Skip to content

Sqlite

File-backed storage for sessions shared by workers on one machine.

SQLiteSessionStorage

Persist snapshots in a local database. Workers share the same file path.

Source code in src/openai_agents/codex/sqlite.py
class SQLiteSessionStorage:
    """Persist snapshots in a local database. Workers share the same file path."""

    def __init__(self, path: str | os.PathLike[str]) -> None:
        if os.fspath(path) == ":memory:":
            raise ValueError("Use InMemorySessionStorage for sessions in memory")
        self._path = Path(path).resolve()
        self._locks = self._path.with_name(self._path.name + ".locks")

    @staticmethod
    def _release(gate: sqlite3.Connection, lock: sqlite3.Connection, path: Path) -> None:
        # Keep other workers from opening the file between close and unlink.
        try:
            gate.execute("BEGIN EXCLUSIVE")
        finally:
            lock.close()
        path.unlink()

    def _load(self, stack: ExitStack, key: str) -> StoredConversation:
        self._locks.mkdir(mode=0o700, exist_ok=True)
        path = self._locks / hashlib.sha256(key.encode()).hexdigest()
        # Serialize file creation and removal. Only the per-ID lock spans the turn.
        gate = stack.enter_context(
            closing(sqlite3.connect(self._locks / "gate", check_same_thread=False))
        )
        with gate:
            gate.execute("BEGIN EXCLUSIVE")
            lock = sqlite3.connect(path, timeout=0, check_same_thread=False)
            try:
                lock.execute("BEGIN EXCLUSIVE")
            except sqlite3.Error as error:
                lock.close()
                if str(error) == "database is locked":
                    raise _busy(key) from error
                raise
            stack.callback(self._release, gate, lock, path)

        try:
            self._path.touch(mode=0o600, exist_ok=False)
        except FileExistsError:
            pass
        with closing(sqlite3.connect(self._path)) as db:
            db.execute(
                "CREATE TABLE IF NOT EXISTS agents_codex_conversations "
                "(conversation_id TEXT PRIMARY KEY, snapshot TEXT NOT NULL)"
            )
            row = db.execute(
                "SELECT snapshot FROM agents_codex_conversations WHERE conversation_id = ?",
                (key,),
            ).fetchone()
        return StoredConversation(ConversationState.from_json(row[0]) if row else None)

    def _save(self, key: str, state: ConversationState) -> None:
        snapshot = state.to_json()
        with closing(sqlite3.connect(self._path)) as db, db:
            db.execute(
                "INSERT INTO agents_codex_conversations (conversation_id, snapshot) VALUES (?, ?) "
                "ON CONFLICT (conversation_id) DO UPDATE SET snapshot = excluded.snapshot",
                (key, snapshot),
            )

    @asynccontextmanager
    async def lock(self, conversation_id: str) -> AsyncIterator[StoredConversation]:
        _validate_id(conversation_id)
        stack = ExitStack()
        try:
            record = await run_sync(lambda: self._load(stack, conversation_id))
            yield record
            state = record.state
            if state is not None:
                await run_sync(lambda: self._save(conversation_id, state))
        finally:
            await run_sync(stack.close)