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
15 changes: 15 additions & 0 deletions docs/edge/ar/concepts/flows.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -477,6 +477,21 @@ flow_2.kickoff(restore_from_state_id=flow_1.state.id)

إذا لم يطابق `restore_from_state_id` المقدم أي حالة مستمرة، يعود kickoff بصمت إلى السلوك الافتراضي — نفس سلوك `inputs["id"]` عند عدم العثور عليه. الجمع بين `restore_from_state_id` و `from_checkpoint` يطلق `ValueError`؛ اختر مصدر ترطيب واحدًا. تثبيت `inputs["id"]` أثناء التفرع يشارك مفتاح الاستمرارية مع تدفق آخر — عادةً ما تريد استخدام `restore_from_state_id` فقط.

### فحص سجل الحالة

يحتفظ `SQLiteFlowPersistence` بكل لقطة يحفظها، بينما يعيد `load_state` أحدثها فقط. استخدم `list_state_history` للتنقل بين صفحات بيانات اللقطات الوصفية للتدفق — `id` الصف و `method_name` و `timestamp` — دون تحميل حمولات الحالة. تُرتَّب السجلات من الأقدم إلى الأحدث حسب `id` الصف؛ يجب أن تكون قيمة `limit` بين 1 و `MAX_HISTORY_LIMIT` (1000) وأن تكون قيمة `offset` غير سالبة. قيمة `id` في السجل هي معرّف صف في التخزين وليست `state.id` الخاص بالتدفق — لا يمكن تمريرها إلى `restore_from_state_id`. لأدوات الفحص مثل CLI، تفتح `SQLiteFlowPersistence.read_history` قاعدة البيانات للقراءة فقط وتعيد قائمة فارغة عندما لا يكون ملف قاعدة البيانات أو الجدول أو التدفق موجودًا. لا تنشئ قاعدة البيانات أو جداولها أبدًا، لكن قراءة قاعدة بيانات بوضع WAL قد تنشئ أو تترك ملفات جانبية `-wal`/`-shm` بجوارها، ويُطلَق `sqlite3.OperationalError` إذا تعذّر إنشاء هذه الملفات. يمكن للواجهات الخلفية الأخرى تجاوز `list_state_history`؛ التنفيذ الأساسي يطلق `NotImplementedError`.

```python
from crewai.flow.persistence import SQLiteFlowPersistence

persistence = SQLiteFlowPersistence("flows.db")
for record in persistence.list_state_history(flow.state.id, limit=20, offset=0):
print(record.id, record.method_name, record.timestamp)

# Read-only: never creates the database or tables, never changes schema or data
records = SQLiteFlowPersistence.read_history("flows.db", flow.state.id)
```

### كيف تعمل

1. **تعريف الحالة الفريد**
Expand Down
15 changes: 15 additions & 0 deletions docs/edge/en/concepts/flows.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -480,6 +480,21 @@ flow_2.kickoff(restore_from_state_id=flow_1.state.id)

If the supplied `restore_from_state_id` does not match any persisted state, the kickoff falls back silently — same as the existing `inputs["id"]` resume not-found behavior. Combining `restore_from_state_id` with `from_checkpoint` raises a `ValueError`; pick one hydration source. Pinning `inputs["id"]` while forking shares a persistence key with another flow — usually you want only `restore_from_state_id`.

### Inspecting State History

`SQLiteFlowPersistence` keeps every snapshot it saves, while `load_state` returns only the latest. Use `list_state_history` to page through a flow's snapshot metadata — row `id`, `method_name`, and `timestamp` — without loading the state payloads. Records are ordered oldest first by row `id`; `limit` must be between 1 and `MAX_HISTORY_LIMIT` (1000) and `offset` must be non-negative. A record's `id` is a storage row ID, not a flow `state.id` — it cannot be passed to `restore_from_state_id`. For inspection tools such as the CLI, `SQLiteFlowPersistence.read_history` opens the database read-only and returns an empty list when the database file, table, or flow does not exist. It never creates the database or its tables, though reading a WAL-mode database may create or leave behind `-wal`/`-shm` sidecar files next to it, and raises `sqlite3.OperationalError` if those files cannot be created. Other backends may override `list_state_history`; the base implementation raises `NotImplementedError`.

```python
from crewai.flow.persistence import SQLiteFlowPersistence

persistence = SQLiteFlowPersistence("flows.db")
for record in persistence.list_state_history(flow.state.id, limit=20, offset=0):
print(record.id, record.method_name, record.timestamp)

# Read-only: never creates the database or tables, never changes schema or data
records = SQLiteFlowPersistence.read_history("flows.db", flow.state.id)
```

### How It Works

1. **Unique State Identification**
Expand Down
15 changes: 15 additions & 0 deletions docs/edge/ko/concepts/flows.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -470,6 +470,21 @@ flow_2.kickoff(restore_from_state_id=flow_1.state.id)

제공된 `restore_from_state_id`가 어떤 영속 상태와도 일치하지 않으면, kickoff는 조용히 기본 동작으로 폴백됩니다 — 기존 `inputs["id"]`의 미발견 동작과 동일합니다. `restore_from_state_id`를 `from_checkpoint`와 결합하면 `ValueError`가 발생합니다; 하나의 하이드레이션 소스를 선택하세요. 포크 중 `inputs["id"]`를 고정하면 다른 플로우와 영속 키를 공유하게 됩니다 — 일반적으로 `restore_from_state_id`만 사용하는 것이 좋습니다.

### 상태 기록 조회

`SQLiteFlowPersistence`는 저장한 모든 스냅샷을 보관하지만, `load_state`는 최신 스냅샷만 반환합니다. `list_state_history`를 사용하면 상태 페이로드를 로드하지 않고 플로우 스냅샷의 메타데이터(행 `id`, `method_name`, `timestamp`)를 페이지 단위로 조회할 수 있습니다. 레코드는 행 `id` 기준으로 오래된 순서대로 정렬되며, `limit`은 1에서 `MAX_HISTORY_LIMIT`(1000) 사이여야 하고 `offset`은 음수가 아니어야 합니다. 레코드의 `id`는 저장소의 행 ID이며 플로우의 `state.id`가 아니므로 `restore_from_state_id`에 전달할 수 없습니다. CLI와 같은 조회 도구에서는 `SQLiteFlowPersistence.read_history`가 데이터베이스를 읽기 전용으로 열고, 데이터베이스 파일이나 테이블 또는 플로우가 없으면 빈 리스트를 반환합니다. 데이터베이스나 테이블을 생성하지는 않지만, WAL 모드 데이터베이스를 읽으면 옆에 `-wal`/`-shm` 사이드카 파일이 생성되거나 남을 수 있으며, 이 파일을 생성할 수 없으면 `sqlite3.OperationalError`가 발생합니다. 다른 백엔드는 `list_state_history`를 재정의할 수 있으며, 기본 구현은 `NotImplementedError`를 발생시킵니다.

```python
from crewai.flow.persistence import SQLiteFlowPersistence

persistence = SQLiteFlowPersistence("flows.db")
for record in persistence.list_state_history(flow.state.id, limit=20, offset=0):
print(record.id, record.method_name, record.timestamp)

# Read-only: never creates the database or tables, never changes schema or data
records = SQLiteFlowPersistence.read_history("flows.db", flow.state.id)
```

### 작동 방식

1. **고유 상태 식별**
Expand Down
15 changes: 15 additions & 0 deletions docs/edge/pt-BR/concepts/flows.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -470,6 +470,21 @@ flow_2.kickoff(restore_from_state_id=flow_1.state.id)

Se o `restore_from_state_id` informado não corresponder a nenhum estado persistido, o kickoff retorna silenciosamente ao comportamento padrão — o mesmo comportamento do `inputs["id"]` quando não encontrado. Combinar `restore_from_state_id` com `from_checkpoint` lança um `ValueError`; escolha uma única fonte de hidratação. Fixar `inputs["id"]` durante o fork compartilha uma chave de persistência com outro flow — geralmente você quer apenas `restore_from_state_id`.

### Inspecionando o Histórico de Estado

O `SQLiteFlowPersistence` mantém todos os snapshots que salva, enquanto `load_state` retorna apenas o mais recente. Use `list_state_history` para paginar os metadados dos snapshots de um flow — `id` da linha, `method_name` e `timestamp` — sem carregar os payloads de estado. Os registros são ordenados do mais antigo para o mais recente pelo `id` da linha; `limit` deve estar entre 1 e `MAX_HISTORY_LIMIT` (1000) e `offset` não pode ser negativo. O `id` de um registro é um ID de linha do armazenamento, não o `state.id` do flow — ele não pode ser passado para `restore_from_state_id`. Para ferramentas de inspeção como a CLI, `SQLiteFlowPersistence.read_history` abre o banco de dados somente para leitura e retorna uma lista vazia quando o arquivo do banco de dados, a tabela ou o flow não existem. Ele nunca cria o banco de dados nem suas tabelas, embora ler um banco em modo WAL possa criar ou deixar arquivos auxiliares `-wal`/`-shm` ao lado dele, e lança `sqlite3.OperationalError` se esses arquivos não puderem ser criados. Outros backends podem sobrescrever `list_state_history`; a implementação base lança `NotImplementedError`.

```python
from crewai.flow.persistence import SQLiteFlowPersistence

persistence = SQLiteFlowPersistence("flows.db")
for record in persistence.list_state_history(flow.state.id, limit=20, offset=0):
print(record.id, record.method_name, record.timestamp)

# Read-only: never creates the database or tables, never changes schema or data
records = SQLiteFlowPersistence.read_history("flows.db", flow.state.id)
```

### Como Funciona

1. **Identificação Única do Estado**
Expand Down
16 changes: 14 additions & 2 deletions lib/crewai/src/crewai/flow/persistence/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,21 @@
This module provides interfaces and implementations for persisting flow states.
"""

from crewai.flow.persistence.base import FlowPersistence
from crewai.flow.persistence.base import (
DEFAULT_HISTORY_LIMIT,
MAX_HISTORY_LIMIT,
FlowPersistence,
FlowStateHistoryRecord,
)
from crewai.flow.persistence.decorators import persist
from crewai.flow.persistence.sqlite import SQLiteFlowPersistence


__all__ = ["FlowPersistence", "SQLiteFlowPersistence", "persist"]
__all__ = [
"DEFAULT_HISTORY_LIMIT",
"MAX_HISTORY_LIMIT",
"FlowPersistence",
"FlowStateHistoryRecord",
"SQLiteFlowPersistence",
"persist",
]
51 changes: 50 additions & 1 deletion lib/crewai/src/crewai/flow/persistence/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@
from __future__ import annotations

from abc import ABC, abstractmethod
from datetime import datetime
from typing import TYPE_CHECKING, Any

from pydantic import BaseModel, Field
from pydantic import BaseModel, ConfigDict, Field


if TYPE_CHECKING:
Expand All @@ -14,6 +15,27 @@

_persistence_registry: dict[str, type[FlowPersistence]] = {}

DEFAULT_HISTORY_LIMIT = 50
MAX_HISTORY_LIMIT = 1000


class FlowStateHistoryRecord(BaseModel):
"""Metadata for one persisted state snapshot of a flow.

Attributes:
id: Stable ID of the snapshot within the backend; increases with each
save. This is not the flow's ``state.id`` and cannot be passed to
``kickoff(restore_from_state_id=...)``.
method_name: Name of the flow method that produced the snapshot.
timestamp: When the snapshot was saved.
"""

model_config = ConfigDict(frozen=True)

id: int
method_name: str
timestamp: datetime


class FlowPersistence(BaseModel, ABC):
"""Abstract base class for flow state persistence.
Expand All @@ -25,6 +47,9 @@ class FlowPersistence(BaseModel, ABC):
- save_pending_feedback(): Saves state with pending feedback context
- load_pending_feedback(): Loads state and pending feedback context
- clear_pending_feedback(): Clears pending feedback after resume

Backends that retain every saved snapshot can optionally override
list_state_history() to expose paginated snapshot metadata.
"""

persistence_type: str = Field(default="base")
Expand Down Expand Up @@ -67,6 +92,30 @@ def load_state(self, flow_uuid: str) -> dict[str, Any] | None:
The most recent state as a dictionary, or None if no state exists
"""

def list_state_history(
self,
flow_uuid: str,
*,
limit: int = DEFAULT_HISTORY_LIMIT,
offset: int = 0,
) -> list[FlowStateHistoryRecord]:
"""List metadata for persisted state snapshots of a flow.

Optional override for backends that retain snapshot history. The
default raises ``NotImplementedError``.

Args:
flow_uuid: Unique identifier for the flow instance
limit: Maximum number of records to return (1 to ``MAX_HISTORY_LIMIT``)
offset: Number of records to skip

Returns:
Records ordered oldest first.
"""
raise NotImplementedError(
f"{type(self).__name__} does not support listing state history"
)

def save_pending_feedback(
self,
flow_uuid: str,
Expand Down
112 changes: 111 additions & 1 deletion lib/crewai/src/crewai/flow/persistence/sqlite.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,12 @@
from pydantic import BaseModel, Field, PrivateAttr, model_validator
from typing_extensions import Self

from crewai.flow.persistence.base import FlowPersistence
from crewai.flow.persistence.base import (
DEFAULT_HISTORY_LIMIT,
MAX_HISTORY_LIMIT,
FlowPersistence,
FlowStateHistoryRecord,
)


if TYPE_CHECKING:
Expand All @@ -25,6 +30,7 @@

_SQLITE_BUSY_TIMEOUT_SECONDS = 30.0
_SCHEMA_RETRY_DELAY_SECONDS = 0.05
_SQLITE_MAX_INTEGER = 2**63 - 1


def _json_default(obj: Any) -> Any:
Expand Down Expand Up @@ -246,6 +252,110 @@ def load_state(self, flow_uuid: str) -> dict[str, Any] | None:
return result if isinstance(result, dict) else None
return None

def list_state_history(
self,
flow_uuid: str,
*,
limit: int = DEFAULT_HISTORY_LIMIT,
offset: int = 0,
) -> list[FlowStateHistoryRecord]:
"""List metadata for every persisted state snapshot of a flow.

Delegates to :meth:`read_history` with this instance's ``db_path``.

Args:
flow_uuid: Unique identifier for the flow instance.
limit: Maximum number of records to return (1 to ``MAX_HISTORY_LIMIT``).
offset: Number of records to skip.

Returns:
Records ordered oldest first by row ID.

Raises:
ValueError: If ``limit`` or ``offset`` is out of range.
"""
return self.read_history(self.db_path, flow_uuid, limit=limit, offset=offset)

@staticmethod
def read_history(
db_path: str | Path,
flow_uuid: str,
*,
limit: int = DEFAULT_HISTORY_LIMIT,
offset: int = 0,
) -> list[FlowStateHistoryRecord]:
"""List state snapshot metadata without modifying the database.

This needs no persistence instance, so no database file or table is
created and no schema or journal mode is changed. The database is opened with ``mode=ro``, which makes it
safe for inspection tools such as the CLI. Reading a WAL-mode database
may create ``-wal``/``-shm`` sidecar files next to it; if they cannot
be created, the ``sqlite3.OperationalError`` is raised.

Args:
db_path: Path to a ``SQLiteFlowPersistence`` database file.
flow_uuid: Unique identifier for the flow instance.
limit: Maximum number of records to return (1 to ``MAX_HISTORY_LIMIT``).
offset: Number of records to skip.

Returns:
Records ordered oldest first by row ID, or an empty list if the
database file, table, or flow does not exist.

Raises:
ValueError: If ``limit`` or ``offset`` is out of range.
sqlite3.DatabaseError: If the database cannot be read.
"""
if (
not isinstance(limit, int)
or isinstance(limit, bool)
or not 1 <= limit <= MAX_HISTORY_LIMIT
):
raise ValueError(
f"limit must be an integer between 1 and {MAX_HISTORY_LIMIT}, "
f"got {limit!r}"
)
if (
not isinstance(offset, int)
or isinstance(offset, bool)
or not 0 <= offset <= _SQLITE_MAX_INTEGER
):
raise ValueError(
f"offset must be an integer between 0 and {_SQLITE_MAX_INTEGER}, "
f"got {offset!r}"
)
path = Path(db_path)
if not path.exists():
return []
uri = f"{path.resolve().as_uri()}?mode=ro"
try:
with closing(
sqlite3.connect(uri, uri=True, timeout=_SQLITE_BUSY_TIMEOUT_SECONDS)
) as conn:
rows = conn.execute(
"SELECT id, method_name, timestamp FROM flow_states"
" WHERE flow_uuid = ? ORDER BY id ASC LIMIT ? OFFSET ?",
(flow_uuid, limit, offset),
).fetchall()
except sqlite3.OperationalError as exc:
if "no such table" in str(exc).lower():
return []
raise

# Older releases wrote naive UTC timestamps; normalise them to aware
# UTC so records from one database always compare with each other.
records: list[FlowStateHistoryRecord] = []
for row_id, method_name, ts in rows:
timestamp = datetime.fromisoformat(ts)
if timestamp.tzinfo is None:
timestamp = timestamp.replace(tzinfo=timezone.utc)
records.append(
FlowStateHistoryRecord(
id=row_id, method_name=method_name, timestamp=timestamp
)
)
return records

def load_state_from_history(
self, flow_uuid: str, record_id: int
) -> dict[str, Any] | None:
Expand Down
Loading