Repository navigation
feat(jobstore): A0/A1 Postgres doc-mode Store, migrations, three-backend Store conformance - #22434
Conversation
…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]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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]>
There was a problem hiding this comment.
💡 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".
| return assert_batch_write_allowed( | ||
| self.customer_client, | ||
| self.customer_client.transaction(), | ||
| uid, |
There was a problem hiding this comment.
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 👍 / 👎.
| 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 |
There was a problem hiding this comment.
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 👍 / 👎.
| generation = self.check_privacy( | ||
| job['owner_id'], | ||
| (job['conversation_id'],) if job.get('conversation_id') else (), | ||
| job.get('privacy_generation'), | ||
| ) |
There was a problem hiding this comment.
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 👍 / 👎.
| yield conn | ||
| except BaseException: | ||
| # A connection that failed mid-flight is not reused. | ||
| if conn is not None: | ||
| try: | ||
| conn.close() |
There was a problem hiding this comment.
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 👍 / 👎.
| _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, | ||
| ) |
There was a problem hiding this comment.
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 👍 / 👎.
| identity = (job['owner_id'], job.get('conversation_id'), job.get('privacy_generation')) | ||
| if identity in guarded: | ||
| continue | ||
| guarded.add(identity) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
💡 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) |
There was a problem hiding this comment.
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 👍 / 👎.
| if not _NAMESPACE.fullmatch(namespace): | ||
| raise ValueError('explicit batch_pipeline_{prod,dev,test_<id>} namespace required') |
There was a problem hiding this comment.
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 👍 / 👎.
| 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') |
There was a problem hiding this comment.
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 👍 / 👎.
| 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') |
There was a problem hiding this comment.
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 👍 / 👎.
| conn = self._idle.get_nowait() | ||
| except queue.Empty: | ||
| conn = self._connect() | ||
| yield conn |
There was a problem hiding this comment.
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 👍 / 👎.
…t ignore to its imports Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
#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]>
There was a problem hiding this comment.
💡 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] |
There was a problem hiding this comment.
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 👍 / 👎.
| if conn is not None and not self._closed: | ||
| self._idle.put(conn) |
There was a problem hiding this comment.
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 👍 / 👎.
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),PostgresStoredoc mode over the batchStoreprotocol (SERIALIZABLE + bounded retry, privacy fence still on Firestore until A5).testing/store_fixtures.py: onestore_backendfixture over sim | Firestore emulator | Postgres (local PG16 on a private unix socket).OMI_REQUIRE_STORE_BACKENDSturns a missing backend into a failure.tests/integration/test_store_conformance.pyruns the same ~27 behaviours on all three; sim gaps are strict-xfailed (noready_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.githubchange (S6), so the postgres param skips there; emulator + sim run ifscripts/run-emulator-proofs.shlists the file (request to its owner).Not in this PR: outbox slice (waits on #22420),
sync_cloud_tasks_stack/run.pyhook (waits on #21932/#20662).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.)