Skip to content

Postgres

Postgres storage for conversation snapshots. Requires psycopg >= 3.2.

PostgresConversationStore

Share snapshots across workers using one database transaction per lock.

Source code in src/openai_agents/codex/postgres.py
class PostgresConversationStore:
    """Share snapshots across workers using one database transaction per lock."""

    def __init__(self, conninfo: str) -> None:
        self._conninfo = conninfo

    @asynccontextmanager
    async def _transaction(self) -> AsyncIterator[AsyncConnection[Any]]:
        connection = await AsyncConnection.connect(self._conninfo, autocommit=True)
        try:
            # Read the snapshot in a fresh statement *after* acquiring ownership.
            await connection.set_isolation_level(IsolationLevel.READ_COMMITTED)
            async with connection.transaction():
                yield connection
        finally:
            await connection.close()

    async def initialize(self) -> None:
        """Create the table in the current schema. Safe to call from each worker at startup."""
        async with self._transaction() as conn:
            await conn.execute(
                "SELECT pg_advisory_xact_lock(hashtextextended('agents_codex_sdk:setup', 0))"
            )
            await conn.execute(
                """
                CREATE TABLE IF NOT EXISTS agents_codex_conversations (
                    conversation_id text COLLATE "C" PRIMARY KEY,
                    snapshot text NOT NULL
                )
                """
            )

    @asynccontextmanager
    async def lock(self, conversation_id: str) -> AsyncIterator[StoredConversation]:
        """Hold the ID until commit or rollback. Raise conversation_busy on contention."""
        _validate_id(conversation_id)

        async with self._transaction() as conn:
            # An advisory lock also covers the first turn, before the row exists.
            cursor = await conn.execute(
                'SELECT pg_try_advisory_xact_lock(hashtextextended(%s COLLATE "C", 0))',
                (f"agents_codex_sdk:conversation:{conversation_id}",),
            )
            if await cursor.fetchone() != (True,):
                raise _busy(conversation_id)

            cursor = await conn.execute(
                "SELECT snapshot FROM agents_codex_conversations WHERE conversation_id = %s",
                (conversation_id,),
            )
            row = await cursor.fetchone()
            conversation = StoredConversation(ConversationState.from_json(row[0]) if row else None)
            yield conversation
            if conversation.state is not None:
                await conn.execute(
                    """
                    INSERT INTO agents_codex_conversations (conversation_id, snapshot)
                    VALUES (%s, %s)
                    ON CONFLICT (conversation_id) DO UPDATE SET snapshot = EXCLUDED.snapshot
                    """,
                    (conversation_id, conversation.state.to_json()),
                )

initialize async

initialize() -> None

Create the table in the current schema. Safe to call from each worker at startup.

Source code in src/openai_agents/codex/postgres.py
async def initialize(self) -> None:
    """Create the table in the current schema. Safe to call from each worker at startup."""
    async with self._transaction() as conn:
        await conn.execute(
            "SELECT pg_advisory_xact_lock(hashtextextended('agents_codex_sdk:setup', 0))"
        )
        await conn.execute(
            """
            CREATE TABLE IF NOT EXISTS agents_codex_conversations (
                conversation_id text COLLATE "C" PRIMARY KEY,
                snapshot text NOT NULL
            )
            """
        )

lock async

lock(
    conversation_id: str,
) -> AsyncIterator[StoredConversation]

Hold the ID until commit or rollback. Raise conversation_busy on contention.

Source code in src/openai_agents/codex/postgres.py
@asynccontextmanager
async def lock(self, conversation_id: str) -> AsyncIterator[StoredConversation]:
    """Hold the ID until commit or rollback. Raise conversation_busy on contention."""
    _validate_id(conversation_id)

    async with self._transaction() as conn:
        # An advisory lock also covers the first turn, before the row exists.
        cursor = await conn.execute(
            'SELECT pg_try_advisory_xact_lock(hashtextextended(%s COLLATE "C", 0))',
            (f"agents_codex_sdk:conversation:{conversation_id}",),
        )
        if await cursor.fetchone() != (True,):
            raise _busy(conversation_id)

        cursor = await conn.execute(
            "SELECT snapshot FROM agents_codex_conversations WHERE conversation_id = %s",
            (conversation_id,),
        )
        row = await cursor.fetchone()
        conversation = StoredConversation(ConversationState.from_json(row[0]) if row else None)
        yield conversation
        if conversation.state is not None:
            await conn.execute(
                """
                INSERT INTO agents_codex_conversations (conversation_id, snapshot)
                VALUES (%s, %s)
                ON CONFLICT (conversation_id) DO UPDATE SET snapshot = EXCLUDED.snapshot
                """,
                (conversation_id, conversation.state.to_json()),
            )