Skip to content

feat(jobstore): A0/A1 Postgres doc-mode Store, migrations, three-backend Store conformance - #22434

Merged
Git-on-my-level merged 7 commits into
integration/legacy-retirefrom
lr/12-postgres
Oct 19, 2026
Merged

Git-on-my-level merged 7 commits into
integration/legacy-retirefrom
lr/12-postgres

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Oct 19, 2026 •

Copy link
Copy Markdown
Member

Lane 12, A0/A1 slice 1 (swarm plan, workstream A). Targets integration/legacy-retire. Nothing is wired to a runtime; no deploy.

  • database/jobstore/: bounded pool (<= 4), expand-only versioned migrations (checksums, advisory lock, contract-marker lint), PostgresStore doc mode over the batch Store protocol (SERIALIZABLE + bounded retry, privacy fence still on Firestore until A5).
  • testing/store_fixtures.py: one store_backend fixture over sim | Firestore emulator | Postgres (local PG16 on a private unix socket). OMI_REQUIRE_STORE_BACKENDS turns a missing backend into a failure.
  • tests/integration/test_store_conformance.py runs the same ~27 behaviours on all three; sim gaps are strict-xfailed (no ready_predecessor, no priority validation, accepts conversation put/patch, no projection scan).

Verified (local m5): firebase emulators:exec + OMI_REQUIRE_STORE_BACKENDS=all: 80 passed, 3 skipped by design, 4 xfailed. Postgres cannot run in GitHub CI without an unnamed .github change (S6), so the postgres param skips there; emulator + sim run if scripts/run-emulator-proofs.sh lists the file (request to its owner).
Not in this PR: outbox slice (waits on #22420), sync_cloud_tasks_stack/run.py hook (waits on #21932/#20662).

View guided diff Turn on auto-fix

Product invariants affected: INV-DATA-1. The job store is not wired into any production-family artifact or runtime selector; nothing here routes Stable, mobile or Beta to development or staging. Test data lives only in batch_pipeline_test_* namespaces on a loopback emulator, a private-socket local Postgres, or the operator's own staging database.

Failure-Class: none
(No fix in this PR; any fix: subject in the range arrives through the integration merge.)

Git-on-my-level and others added 3 commits October 19, 2026 13:19
…end Store conformance

Adds database/jobstore (connection pool capped at 4, expand-only versioned
migrations with checksum + advisory lock, PostgresStore over the batch Store
protocol, SERIALIZABLE with bounded retry), testing/store_fixtures.py (the
store_backend fixture over sim, Firestore emulator and Postgres, local PG16
on a private unix socket) and tests/integration/test_store_conformance.py.
Postgres in CI needs an unnamed .github change (S6), so the postgres
parameter skips in GitHub CI and is proven locally.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…he modules reachable

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 19, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-19T09:00:51.001602Z 7a88857 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

…sor, validation, conversation writes and projection scan

Closes the four gaps the Store conformance suite had strict-xfailed.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a00257fe4a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +302 to +305
return assert_batch_write_allowed(
self.customer_client,
self.customer_client.transaction(),
uid,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Run privacy checks in an active Firestore transaction

When customer_client is a real Firestore client, transaction() only creates a transaction object; it is not active until begun by Firestore's transaction machinery. Passing this inactive transaction to assert_batch_write_allowed() makes its document reads fail with ValueError: Transaction not in progress, so every jobs/results flush and explicit privacy check fails before reaching PostgreSQL. Run the helper inside a real Firestore transaction and cover the Postgres-plus-Firestore path with an emulator-backed test instead of the permissive simulator customer fake.

AGENTS.md reference: backend/AGENTS.md:L225-L225

Useful? React with 👍 / 👎.

Comment on lines +19 to +23
def _psycopg():
try:
import psycopg
except ImportError as exc: # pragma: no cover - exercised only where the driver is absent
raise RuntimeError('psycopg 3 is required to use the Postgres job store') from exc

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Package the Postgres driver with the backend

When this backend is selected in the deployed backend image, the first call to _psycopg() raises because psycopg is absent from backend/requirements.txt and every checked-in backend lock, including the runtime lock installed by backend/Dockerfile. The new tests conceal this by skipping the Postgres backend when the module is unavailable, so add the driver to the requirements input and regenerate the locks before this store can run.

AGENTS.md reference: backend/AGENTS.md:L18-L22

Useful? React with 👍 / 👎.

Comment on lines +119 to +123
generation = self.check_privacy(
job['owner_id'],
(job['conversation_id'],) if job.get('conversation_id') else (),
job.get('privacy_generation'),
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Make the privacy fence atomic with PostgreSQL writes

Even after the Firestore transaction is started correctly, the privacy check completes independently of the surrounding PostgreSQL transaction. If an account-deletion marker or privacy generation changes after this read but before write_doc() commits, the stale job/result is still persisted; unlike FirestoreStore, no transaction conflict can abort it. Do not enable this backend until the fence is mirrored into PostgreSQL or another protocol makes the privacy decision and state write atomic, and cover this cross-store contention window explicitly.

AGENTS.md reference: backend/AGENTS.md:L225-L225

Useful? React with 👍 / 👎.

Comment on lines +52 to +57
yield conn
except BaseException:
# A connection that failed mid-flight is not reused.
if conn is not None:
try:
conn.close()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve pooled connections after application exceptions

Any exception raised by the transaction callback—including expected BatchPrivacyBlocked, validation failures, and the write-budget error—is caught around the pool's yield and treated as a broken connection. Those paths therefore close a healthy connection, so repeated rejected jobs continually redial PostgreSQL and can create the connection storms this pool is meant to prevent. Discard only connections with an actual connection/SQL failure, while returning healthy connections after the transaction context has rolled back application errors.

Useful? React with 👍 / 👎.

Comment on lines +20 to +23
_CONTRACTING = re.compile(
r'\b(DROP\s+(TABLE|COLUMN|INDEX|SCHEMA|CONSTRAINT)|RENAME\s+(TO|COLUMN)|ALTER\s+COLUMN\s+\w+\s+(TYPE|SET\s+NOT\s+NULL)|TRUNCATE)\b',
re.IGNORECASE,
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject all destructive DROP statements in migration lint

The expand-only check allows destructive forms such as DROP VIEW, DROP TYPE, DROP SEQUENCE, and DROP MATERIALIZED VIEW without the required contract marker because only the listed object kinds match this expression. A future migration can therefore remove a schema object during the expand train while still passing load(), defeating the rollout safeguard; match destructive DROP forms comprehensively or explicitly enumerate every supported PostgreSQL object kind.

Useful? React with 👍 / 👎.

Comment on lines +115 to +118
identity = (job['owner_id'], job.get('conversation_id'), job.get('privacy_generation'))
if identity in guarded:
continue
guarded.add(identity)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Stamp every deduplicated job with the checked generation

When one transaction inserts multiple jobs for the same owner and conversation with no privacy_generation—the normal multi-segment admission shape—the first job adds the identity to guarded and receives the generation, but every subsequent job hits this continue and is written without one. Later updates to those jobs pass expected_generation=None, so after a protection migration finishes they can resume under a newer privacy generation instead of being rejected as stale. Cache the generation per identity and assign it to every new job even when the Firestore fence read is deduplicated.

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c2507655f7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

def _jsonb(value: dict):
from psycopg.types.json import Jsonb

return Jsonb(value)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve Firestore timestamp values when encoding JSONB

When a store transaction contains a Firestore-style datetime value, Psycopg's default Jsonb encoder delegates to standard JSON serialization and raises TypeError: Object of type datetime is not JSON serializable. This occurs on existing pipeline paths such as batch_pipeline_intake.cache_completed(), which writes an expires_at datetime into intakes, and admission writes datetime fields into content in harness mode, so the Postgres implementation cannot satisfy the claimed document-store contract for real pipeline documents. Add an explicit timestamp codec with a matching decoder, and include datetime round trips in the backend conformance suite.

Useful? React with 👍 / 👎.

Comment on lines +145 to +146
if not _NAMESPACE.fullmatch(namespace):
raise ValueError('explicit batch_pipeline_{prod,dev,test_<id>} namespace required')

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Reject runtime stages that do not match the namespace

When a dev process is accidentally configured with batch_pipeline_prod—which is also the chart's default namespace—this regex accepts it regardless of OMI_ENV_STAGE, allowing the process to read and write production-scoped rows if it reaches a shared database. FirestoreStore explicitly rejects this mismatch in _require_stage(), so selecting the Postgres implementation removes the existing fail-closed stage boundary; apply the same stage-to-namespace validation here before the backend is enabled.

Useful? React with 👍 / 👎.

Comment on lines +215 to +217
local = 'host=/' in dsn or 'localhost' in dsn or '127.0.0.1' in dsn
if not local and os.getenv('OMI_TEST_POSTGRES_ALLOW_REMOTE') != '1':
raise BackendUnavailable('remote OMI_TEST_POSTGRES_DSN needs OMI_TEST_POSTGRES_ALLOW_REMOTE=1')

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Parse the DSN host before granting loopback privileges

When a remote DSN contains the text localhost or 127.0.0.1 anywhere—for example host=notlocalhost.example.com or an application_name=localhost parameter—this substring test classifies it as local and bypasses the required OMI_TEST_POSTGRES_ALLOW_REMOTE=1 opt-in. The fixture then connects and immediately runs schema migrations on that remote database; parse the DSN and validate the actual host as a loopback address or Unix socket instead.

Useful? React with 👍 / 👎.

Comment on lines +19 to +22
conn.execute('CREATE SCHEMA IF NOT EXISTS mig_test')
conn.execute('SET search_path TO mig_test')
yield conn
conn.execute('DROP SCHEMA mig_test CASCADE')

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Isolate each migration test in a unique schema

When two test invocations share an OMI_TEST_POSTGRES_DSN, or that database already has a mig_test schema, every fixture reuses the same schema and teardown unconditionally drops it with CASCADE. Concurrent runs can therefore modify or delete each other's migration tables, and a pre-existing schema can lose unrelated objects; generate a per-fixture schema name and drop only that schema.

Useful? React with 👍 / 👎.

Comment on lines +49 to +52
conn = self._idle.get_nowait()
except queue.Empty:
conn = self._connect()
yield conn

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Normalize injected connections to autocommit mode

When the documented connect= seam returns a normal Psycopg connection, its default is autocommit=False, unlike dial(). A nontransactional helper such as due() then returns that connection to the pool with an implicit transaction still open; the next run() nests a savepoint in that transaction and its SET TRANSACTION ISOLATION LEVEL SERIALIZABLE can no longer establish the required isolation, while test cleanup writes may never commit at all. Set or validate autocommit=True when accepting newly injected connections so all pool sources have the transaction semantics assumed by PostgresStore.

Useful? React with 👍 / 👎.

Git-on-my-level added a commit that referenced this pull request Oct 19, 2026
#22440)

Lane 12 (Postgres A0/A1, #22434) imports psycopg 3 lazily in database/jobstore/connection.py;
runtime use needs it locked. Lane 1 owns the locks in the legacy-retire swarm.

Added to requirements.txt and spliced into the five backend pylocks from
scripts/update-python-lock.sh output: only the psycopg and psycopg-binary blocks. The regenerate
also floated gitpython, pyjwt and tornado; those unrelated upgrades are deliberately left out.

Verified: uv pip install 'psycopg[binary]==3.2.10' into the backend venv; `import psycopg` ->
3.2.10, pq impl binary.

Co-authored-by: Claude Opus 5.5 <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7a88857596

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".


def _jsonb(value: dict):
# psycopg joins the lockfile separately; until then pyright cannot resolve it.
from psycopg.types.json import Jsonb # pyright: ignore[reportMissingImports]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Move the psycopg import to module scope

_jsonb() adds a function-local import, and the same pattern appears in _psycopg() and several new fixture helpers, but backend modules require all imports at module scope. Move these imports to the top level while keeping connection and client construction lazy so the new persistence path follows the repository's import contract.

AGENTS.md reference: backend/AGENTS.md:L163-L163

Useful? React with 👍 / 👎.

Comment on lines +64 to +65
if conn is not None and not self._closed:
self._idle.put(conn)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Synchronize connection returns with pool shutdown

When close() runs concurrently with a checked-out connection being returned, this path can observe _closed == False, be preempted while close() marks the pool closed and drains the empty idle queue, and then enqueue the connection after that drain. That connection is never closed, and later calls can also continue opening connections after shutdown; synchronize the closed-state check and idle-queue update and reject new checkouts once closure begins.

Useful? React with 👍 / 👎.

@Git-on-my-level
Git-on-my-level merged commit 60f13ba into integration/legacy-retire Oct 19, 2026
24 checks passed
@Git-on-my-level
Git-on-my-level deleted the lr/12-postgres branch October 19, 2026 09:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant