Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions lib/cli/src/crewai_cli/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -1248,6 +1248,22 @@ def flow_add_crew(crew_name: str) -> None:
add_crew_to_flow(crew_name)


@flow.command(name="state")
@click.argument("db_path", type=click.Path(dir_okay=False))
@click.argument("flow_uuid")
@click.argument("record_id", type=click.IntRange(min=1))
@click.option("--json", "as_json", is_flag=True, help="Print the record as JSON.")
def flow_state(db_path: str, flow_uuid: str, record_id: int, as_json: bool) -> None:
"""Show one persisted Flow state from a SQLite flow_states database.

Read-only. These are per-method Flow states, not checkpoints; use
`crewai checkpoint` for those.
"""
from crewai_cli.flow_state_cli import inspect_flow_state

inspect_flow_state(db_path, flow_uuid, record_id, as_json=as_json)


@crewai.group()
def triggers() -> None:
"""Trigger related commands. Use 'crewai triggers list' to see available triggers, or 'crewai triggers run app_slug/trigger_slug' to execute."""
Expand Down
126 changes: 126 additions & 0 deletions lib/cli/src/crewai_cli/flow_state_cli.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
"""Read-only inspection of persisted Flow states.

Reads the ``flow_states`` table that ``SQLiteFlowPersistence`` writes: one row
per completed flow method. These rows are not the full-object checkpoints that
``crewai checkpoint`` browses.

Depends only on the standard library and click, so crewai-cli can read a store
without importing the full crewai framework. The database is opened read-only:
inspection never creates a missing file, writes state, or changes journal
settings.
"""

from __future__ import annotations

from contextlib import closing
import json
from pathlib import Path
import sqlite3
from typing import Any

import click

from crewai_cli.checkpoint_cli import _is_sqlite


STORAGE_KIND = "flow_states"

_SELECT_STATE = """
SELECT id, flow_uuid, method_name, timestamp, state_json
FROM flow_states
WHERE id = ? AND flow_uuid = ?
"""


def _read_only_uri(db_path: str) -> str:
"""Build a SQLite URI that reads the store without leaving files behind.

The store is in WAL mode, where even a read-only connection creates
``-wal`` and ``-shm`` files next to the database. ``immutable=1`` avoids
that, but it also skips a pending ``-wal``, so it is only used when no
``-wal`` file exists and every saved state is already in the main file.
"""
path = Path(db_path).resolve()
query = "mode=ro" if Path(f"{path}-wal").exists() else "mode=ro&immutable=1"
return f"{path.as_uri()}?{query}"


def load_flow_state(
db_path: str, flow_uuid: str, record_id: int
) -> dict[str, Any] | None:
"""Load one persisted state of a flow, scoped to that flow's UUID.

Args:
db_path: SQLite file written by ``SQLiteFlowPersistence``.
flow_uuid: Unique identifier of the flow instance.
record_id: Row id of the saved state in the ``flow_states`` table.
This is not the flow's ``state.id``.

Returns:
The record with its storage kind, source, method name, timestamp and
state, or None when the flow has no state with that row id.

Raises:
click.ClickException: If the file is missing, is not a SQLite database,
has no readable ``flow_states`` table, or holds a state that is not
a JSON object.
"""
if not Path(db_path).is_file():
raise click.ClickException(f"Flow state database not found: {db_path}")
if not _is_sqlite(db_path):
raise click.ClickException(f"Not a SQLite database: {db_path}")

try:
with closing(sqlite3.connect(_read_only_uri(db_path), uri=True)) as conn:
row = conn.execute(_SELECT_STATE, (record_id, flow_uuid)).fetchone()
except sqlite3.Error as exc:
raise click.ClickException(
f"Unsupported flow state database {db_path}: {exc}"
) from exc

if row is None:
return None

row_id, row_uuid, method_name, timestamp, state_json = row
try:
state = json.loads(state_json)
except (TypeError, ValueError) as exc:
raise click.ClickException(
f"Record {record_id} does not hold valid JSON: {exc}"
) from exc
if not isinstance(state, dict):
raise click.ClickException(f"Record {record_id} does not hold a JSON object.")

return {
"storage": STORAGE_KIND,
"db": db_path,
"flow_uuid": row_uuid,
"record_id": row_id,
"method_name": method_name,
"timestamp": timestamp,
"state": state,
}


def inspect_flow_state(
db_path: str, flow_uuid: str, record_id: int, *, as_json: bool = False
) -> None:
"""Print one persisted state of a flow as text, or as JSON for scripts."""
record = load_flow_state(db_path, flow_uuid, record_id)
if record is None:
raise click.ClickException(
f"No state with record id {record_id} for flow {flow_uuid} in {db_path}"
)

if as_json:
click.echo(json.dumps(record, indent=2))
return

click.echo("Storage: flow state history (flow_states), not a checkpoint")
click.echo(f"Source: {record['db']}")
click.echo(f"Flow UUID: {record['flow_uuid']}")
click.echo(f"Record: {record['record_id']}")
click.echo(f"Method: {record['method_name']}")
click.echo(f"Time: {record['timestamp']}")
click.echo("State:")
click.echo(json.dumps(record["state"], indent=2))
224 changes: 224 additions & 0 deletions lib/cli/tests/test_flow_state_cli.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,224 @@
from __future__ import annotations

from contextlib import closing
import json
from pathlib import Path
import sqlite3

from click.testing import CliRunner
import pytest

from crewai_cli.cli import flow_state


FLOW_UUID = "11111111-1111-4111-8111-111111111111"
OTHER_UUID = "22222222-2222-4222-8222-222222222222"

_SCHEMA = """
CREATE TABLE flow_states (
id INTEGER PRIMARY KEY AUTOINCREMENT,
flow_uuid TEXT NOT NULL,
method_name TEXT NOT NULL,
timestamp DATETIME NOT NULL,
state_json TEXT NOT NULL
)
"""


def _create_store(
path: Path, rows: list[tuple[str, str, str, str]] | None = None
) -> Path:
"""Write a flow_states store the way SQLiteFlowPersistence lays it out."""
with closing(sqlite3.connect(path)) as conn, conn:
conn.execute("PRAGMA journal_mode=WAL")
conn.execute(_SCHEMA)
conn.executemany(
"INSERT INTO flow_states (flow_uuid, method_name, timestamp, state_json) "
"VALUES (?, ?, ?, ?)",
rows or [],
)
return path


@pytest.fixture
def store(tmp_path: Path) -> Path:
return _create_store(
tmp_path / "flow_states.db",
[
(
FLOW_UUID,
"draft",
"2026-11-15T10:00:00+00:00",
json.dumps({"id": FLOW_UUID, "topic": "café", "count": 1}),
),
(
OTHER_UUID,
"review",
"2026-11-15T10:05:00+00:00",
json.dumps({"id": OTHER_UUID, "approved": None}),
),
],
)


def _invoke(*args: str) -> tuple[int, str]:
result = CliRunner().invoke(flow_state, list(args))
return result.exit_code, result.output


def test_json_output_is_the_stored_record(store: Path) -> None:
exit_code, output = _invoke(str(store), FLOW_UUID, "1", "--json")

assert exit_code == 0
assert json.loads(output) == {
"storage": "flow_states",
"db": str(store),
"flow_uuid": FLOW_UUID,
"record_id": 1,
"method_name": "draft",
"timestamp": "2026-11-15T10:00:00+00:00",
"state": {"id": FLOW_UUID, "topic": "café", "count": 1},
}


def test_text_output_names_the_storage_kind_and_the_record(store: Path) -> None:
exit_code, output = _invoke(str(store), OTHER_UUID, "2")

assert exit_code == 0
assert "flow state history (flow_states), not a checkpoint" in output
assert f"Source: {store}" in output
assert f"Flow UUID: {OTHER_UUID}" in output
assert "Record: 2" in output
assert "Method: review" in output
assert "Time: 2026-11-15T10:05:00+00:00" in output
assert '"approved": null' in output


def test_record_of_another_flow_is_not_shown(store: Path) -> None:
exit_code, output = _invoke(str(store), FLOW_UUID, "2")

assert exit_code == 1
assert f"No state with record id 2 for flow {FLOW_UUID}" in output
assert "approved" not in output


def test_unknown_record_id_fails(store: Path) -> None:
exit_code, output = _invoke(str(store), FLOW_UUID, "99", "--json")

assert exit_code == 1
assert "No state with record id 99" in output


def test_empty_store_reports_no_state(tmp_path: Path) -> None:
store = _create_store(tmp_path / "empty.db")

exit_code, output = _invoke(str(store), FLOW_UUID, "1")

assert exit_code == 1
assert "No state with record id 1" in output


def test_missing_database_is_not_created(tmp_path: Path) -> None:
missing = tmp_path / "missing.db"

exit_code, output = _invoke(str(missing), FLOW_UUID, "1")

assert exit_code == 1
assert f"Flow state database not found: {missing}" in output
assert list(tmp_path.iterdir()) == []


def test_file_that_is_not_sqlite_is_rejected(tmp_path: Path) -> None:
text_file = tmp_path / "notes.db"
text_file.write_text("not a database", encoding="utf-8")

exit_code, output = _invoke(str(text_file), FLOW_UUID, "1")

assert exit_code == 1
assert f"Not a SQLite database: {text_file}" in output


def test_sqlite_file_without_flow_states_is_unsupported(tmp_path: Path) -> None:
other = tmp_path / "checkpoints.db"
with closing(sqlite3.connect(other)) as conn, conn:
conn.execute("CREATE TABLE checkpoints (id TEXT PRIMARY KEY, data BLOB)")

exit_code, output = _invoke(str(other), FLOW_UUID, "1")

assert exit_code == 1
assert f"Unsupported flow state database {other}" in output
assert "flow_states" in output


@pytest.mark.parametrize("state_json", ["[1, 2]", '"text"', "{broken"])
def test_state_that_is_not_a_json_object_is_rejected(
tmp_path: Path, state_json: str
) -> None:
store = _create_store(
tmp_path / "flow_states.db",
[(FLOW_UUID, "draft", "2026-11-15T10:00:00+00:00", state_json)],
)

exit_code, output = _invoke(str(store), FLOW_UUID, "1", "--json")

assert exit_code == 1
assert "Record 1 does not hold" in output


@pytest.mark.parametrize("record_id", ["0", "-1", "abc", "1.5"])
def test_invalid_record_id_is_a_usage_error(store: Path, record_id: str) -> None:
exit_code, output = _invoke(str(store), FLOW_UUID, "--", record_id)

assert exit_code == 2
assert "RECORD_ID" in output


def test_inspection_leaves_the_store_untouched(store: Path) -> None:
before_bytes = store.read_bytes()
before_files = sorted(path.name for path in store.parent.iterdir())

for args in (
(str(store), FLOW_UUID, "1"),
(str(store), FLOW_UUID, "1", "--json"),
(str(store), FLOW_UUID, "99"),
):
_invoke(*args)

assert store.read_bytes() == before_bytes
assert sorted(path.name for path in store.parent.iterdir()) == before_files
with closing(sqlite3.connect(store)) as conn:
assert conn.execute("PRAGMA journal_mode").fetchone() == ("wal",)


def test_state_still_in_the_write_ahead_log_is_shown(store: Path) -> None:
"""A flow that is still running keeps its newest states in the -wal file."""
with closing(sqlite3.connect(store)) as writer:
writer.execute(
"INSERT INTO flow_states (flow_uuid, method_name, timestamp, state_json) "
"VALUES (?, ?, ?, ?)",
(FLOW_UUID, "publish", "2026-11-15T10:10:00+00:00", '{"count": 2}'),
)
writer.commit()
before_files = sorted(path.name for path in store.parent.iterdir())

exit_code, output = _invoke(str(store), FLOW_UUID, "3", "--json")

assert before_files == [store.name, f"{store.name}-shm", f"{store.name}-wal"]
assert sorted(path.name for path in store.parent.iterdir()) == before_files
assert exit_code == 0
assert json.loads(output)["state"] == {"count": 2}


def test_reads_a_store_written_by_sqlite_flow_persistence(tmp_path: Path) -> None:
sqlite_persistence = pytest.importorskip("crewai.flow.persistence.sqlite")
db_path = tmp_path / "flow_states.db"
persistence = sqlite_persistence.SQLiteFlowPersistence(str(db_path))
persistence.save_state(FLOW_UUID, "draft", {"id": FLOW_UUID, "count": 1})
persistence.save_state(FLOW_UUID, "review", {"id": FLOW_UUID, "count": 2})

exit_code, output = _invoke(str(db_path), FLOW_UUID, "2", "--json")

assert exit_code == 0
record = json.loads(output)
assert record["method_name"] == "review"
assert record["state"] == persistence.load_state_from_history(FLOW_UUID, 2)
Loading