Repository navigation
Add directory routing, sticky enrollment and fail-closed cell wipe (dark) - #24805
Conversation
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tract Released clients cannot decode a new state value; cell routing is invisible to them, so a migrated record projects as legacy with writes allowed. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Preview deployment for your docs. Learn more about Mintlify Previews.
💡 Tip: Enable Automations to automatically generate PRs for you. |
Codex Review Summary: ✅ CompletedThis 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. |
There was a problem hiding this comment.
22 issues found across 52 files
Confidence score: 2/5
config/deployment-setting-classification.jsontreatsCELLS_PG_DSNandDIRECTORY_PG_DSNas config even though they can contain database passwords. Classify them as secrets and source them from Secret Manager orsecrets.*.background_job_should_skip_accountinbackend/utils/account_cutover/fence.pystill lets migrated owners reach legacy finalization workers, which can write to Firestore after cutover. Fence those jobs for migrated accounts or route them through the new plane.persisted_payload()inbackend/models/account_cutover.pywritesdata_planewithout changingschema_version, while older readers reject unknown fields. Make the schema change backward-compatible or version it so cutover documents remain readable.begin()inbackend/utils/account_cutover/coordinator.pynow defaults to a cell cutover and skips the cohort gate. Require an explicitdata_planeso bare calls retain the documented legacy, cohort-gated behavior.
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name=".agent-artifacts/pgf/b2-result.md">
<violation number="1" location=".agent-artifacts/pgf/b2-result.md:3">
P3: This committed report hard-codes local machine paths, a personal username, and internal ANX links and event IDs. Replace them with repo-relative paths and command names, and drop the internal tracker links, before this artifact is merged.</violation>
</file>
<file name="backend/utils/account_cutover/fence.py">
<violation number="1" location="backend/utils/account_cutover/fence.py:30">
P3: This docstring line describes cell mutation rights that this helper does not grant or check, and 'legacy writes remain fenced' contradicts the next paragraph, which says `rolled_back_stranded` allows new legacy writes. Scope the note to what the helper covers: migrated owners are not covered by this legacy-only fence.</violation>
<violation number="2" location="backend/utils/account_cutover/fence.py:30">
P1: `background_job_should_skip_account` still skips only `migrating` and `new`, so migrated owners pass legacy finalization workers and can write to Firestore. Fence legacy-only jobs in this state or route them through the cell store before admitting them.</violation>
</file>
<file name="config/deployment-setting-classification.json">
<violation number="1" location="config/deployment-setting-classification.json:96">
P1: `CELLS_PG_DSN` and `DIRECTORY_PG_DSN` hold full Postgres connection strings, which typically include the password. Classify both as `secret` and source them from Secret Manager or `secrets.*`, not `config`. The `config` kind allows plain vars and ConfigMaps, so this would expose the credential there.</violation>
</file>
<file name="backend/tests/unit/test_cell_wipe_step.py">
<violation number="1" location="backend/tests/unit/test_cell_wipe_step.py:120">
P2: The `other_worker_cache` dict and its assertion are a no-op, so the test does not check that a stale process cache survives the purge. Drop them and rely on the DB-level fence checks, or seed `router._cache` for a real stale-route check.</violation>
</file>
<file name="backend/database/cells/migrations/0002_write_fence.sql">
<violation number="1" location="backend/database/cells/migrations/0002_write_fence.sql:2">
P3: This comment is inaccurate. `purge.py` `_tombstone` also inserts head rows for missing spaces, so enrollment is not the only creator. `compact()` in `feed.py` also writes without the lock check. Reword it so it describes what the code does.</violation>
</file>
<file name="backend/dependencies.py">
<violation number="1" location="backend/dependencies.py:84">
P3: These four calls reach into a private `_resolve_request_plane_or_503` from another module with no `# pyright: ignore[reportPrivateUsage]`. The repo's strict pyright config will flag them, and other cross-module private calls here carry that ignore. Add the ignore comment, or expose a public name.</violation>
</file>
<file name="backend/config/directory_routing.py">
<violation number="1" location="backend/config/directory_routing.py:28">
P2: Out-of-range ramp percentages are clamped silently, so a typo like `1000` turns into a full 100% enrollment. Reject values outside [0, 100] instead of clamping them.</violation>
</file>
<file name="backend/tests/services/users/test_account_deletion.py">
<violation number="1" location="backend/tests/services/users/test_account_deletion.py:2584">
P3: Add an assertion that the cell purge was actually called, so the test proves the purge failure is what blocks the wipe.</violation>
</file>
<file name=".agent-artifacts/pgf/b2-pr-body.md">
<violation number="1" location=".agent-artifacts/pgf/b2-pr-body.md:7">
P2: This sentence is ungrammatical and embeds an internal event ID (`event:ev_...`) that means nothing to repo readers. Reword it to name what is superseded, for example: "The earlier ANX binding values are superseded by this ruling."</violation>
<violation number="2" location=".agent-artifacts/pgf/b2-pr-body.md:42">
P2: The purge tombstone retains the raw account UID in `space_heads` indefinitely, but this line defers the retention policy to a later gate. Define a retention policy that preserves the stale-writer fence before enrollment is enabled.</violation>
</file>
<file name="backend/database/cells/serving.py">
<violation number="1" location="backend/database/cells/serving.py:20">
P2: If `CELLS_PG_DSN` is set alongside the complete IAM bindings, this silently ignores the IAM path and dials the password DSN. Reject the ambiguous configuration here, and make the deploy validator reject it too.</violation>
</file>
<file name="backend/models/account_cutover.py">
<violation number="1" location="backend/models/account_cutover.py:134">
P2: `persisted_payload()` now writes a `data_plane` key into a document parsed with `extra='forbid'`, and `schema_version` stays 1. A revision without this field rejects every cutover document this code writes, so `/v1/account/cutover/control` returns 503 for those accounts after a rollback. Bump the schema version and make readers tolerate the new key before any write path emits it, or omit the key while it is `None`.</violation>
</file>
<file name="backend/utils/other/plane_routing.py">
<violation number="1" location="backend/utils/other/plane_routing.py:41">
P2: A cache miss or expired entry makes `plane_for` return `'firestore'`, so the leak probe cannot see a cell owner whose entry is absent or expired. The probe then reports zero for those accesses, and `plane_leak_total zero` is not a reliable gate. Consider a tri-state result (cell / firestore / unknown) and count unknown separately, or document that the gate covers only request-warmed owners.</violation>
</file>
<file name="backend/database/cells/feed.py">
<violation number="1" location="backend/database/cells/feed.py:128">
P2: `set_cursor` waits on the space head row lock with no `lock_timeout`, unlike `run()`, which sets `LOCK_TIMEOUT`. During a purge or a stuck transaction, each waiting cursor update can hold a pool slot indefinitely. Set a bounded `lock_timeout` before taking the lock, and map the resulting SQLSTATE 55P03 the way `run()` does.</violation>
</file>
<file name="backend/utils/other/endpoints.py">
<violation number="1" location="backend/utils/other/endpoints.py:61">
P2: Owners whose first authenticated call goes through the readonly or WebSocket dependencies are enrolled without `signup_platform`. The sticky insert uses `ON CONFLICT DO NOTHING`, so the directory row keeps a null platform even when the app sends `X-App-Platform`. Forward the platform on these paths, or defer enrollment until a request that carries it.</violation>
</file>
<file name="config/feature-flags.yaml">
<violation number="1" location="config/feature-flags.yaml:713">
P2: The `_ramp` reader list names `notifications job` but omits `backend-sync-backfill`, which the validator treats as one of the five directory-routing surfaces. Replace `notifications job` with `backend-sync-backfill` so the rollout order covers every reader.</violation>
</file>
<file name="backend/utils/account_cutover/coordinator.py">
<violation number="1" location="backend/utils/account_cutover/coordinator.py:196">
P2: The new `'cell'` default turns a bare `begin(uid)` into a cell cutover that skips the cohort gate. The runbook and the config comment still describe `begin(uid)` as legacy and cohort-gated. Make `data_plane` a required keyword so every caller states the plane explicitly.</violation>
<violation number="2" location="backend/utils/account_cutover/coordinator.py:392">
P2: Nothing stops a cell cutover from finishing as `new` through `complete_to_new`, which would fence the account with `legacy_plane_closed`. Add the reciprocal guard to `complete_to_new` so cell records must complete via `complete_to_migrated`.</violation>
</file>
<file name="backend/utils/account_cutover/access.py">
<violation number="1" location="backend/utils/account_cutover/access.py:115">
P2: This call runs on every product request, and the epoch key it creates in Redis has no TTL. Redis memory grows with every user who ever makes a request. Give `cutover-epoch:{uid}` an expiry in `_READ_CACHE_EPOCH` and `_BEGIN_CACHE_WRITE`, longer than `CUTOVER_IDLE_TTL_SECONDS`. A missing epoch already fails closed in `_PUBLISH_IDLE`.</violation>
</file>
<file name="backend/scripts/runtime_env_validation/manifest.py">
<violation number="1" location="backend/scripts/runtime_env_validation/manifest.py:643">
P2: The DSN check ignores secret bindings, so a Secret Manager-backed DSN is treated as missing and cannot satisfy the advertised DSN option. Resolve secret references as configured without reading or exposing their values.</violation>
</file>
<file name="backend/database/directory/wipe.py">
<violation number="1" location="backend/database/directory/wipe.py:18">
P2: This absent path installs no durable enrollment fence, so an in-flight request can create a directory row after the wipe returns; the later Firestore deletion will leave that row behind. Fence enrollment before treating absence as complete.</violation>
</file>
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
| ], | ||
| "config": [ | ||
| "CELLS_PG_DATABASE", | ||
| "CELLS_PG_DSN", |
There was a problem hiding this comment.
P1: CELLS_PG_DSN and DIRECTORY_PG_DSN hold full Postgres connection strings, which typically include the password. Classify both as secret and source them from Secret Manager or secrets.*, not config. The config kind allows plain vars and ConfigMaps, so this would expose the credential there.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At config/deployment-setting-classification.json, line 96:
<comment>`CELLS_PG_DSN` and `DIRECTORY_PG_DSN` hold full Postgres connection strings, which typically include the password. Classify both as `secret` and source them from Secret Manager or `secrets.*`, not `config`. The `config` kind allows plain vars and ConfigMaps, so this would expose the credential there.</comment>
<file context>
@@ -92,8 +92,21 @@
],
"config": [
+ "CELLS_PG_DATABASE",
+ "CELLS_PG_DSN",
+ "CELLS_PG_HOST",
+ "CELLS_PG_POOL_SIZE",
</file context>
| def legacy_writes_allowed_for_state(state: AccountCutoverState) -> bool: | ||
| """Legacy product mutations are only legal while the account remains legacy. | ||
|
|
||
| Migrated owners may mutate cells; legacy writes remain fenced. |
There was a problem hiding this comment.
P1: background_job_should_skip_account still skips only migrating and new, so migrated owners pass legacy finalization workers and can write to Firestore. Fence legacy-only jobs in this state or route them through the cell store before admitting them.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/utils/account_cutover/fence.py, line 30:
<comment>`background_job_should_skip_account` still skips only `migrating` and `new`, so migrated owners pass legacy finalization workers and can write to Firestore. Fence legacy-only jobs in this state or route them through the cell store before admitting them.</comment>
<file context>
@@ -27,6 +27,8 @@ def __init__(self, message: str = 'account generation mismatch'):
def legacy_writes_allowed_for_state(state: AccountCutoverState) -> bool:
"""Legacy product mutations are only legal while the account remains legacy.
+ Migrated owners may mutate cells; legacy writes remain fenced.
+
``rolled_back_stranded`` restores the legacy data plane for reads and new
</file context>
| monkeypatch.setattr(wipe, 'cell_store', lambda: cell.store) | ||
| # An independent worker keeps this route even when the wiping worker | ||
| # invalidates its own process cache. It outlives the drain and purge. | ||
| other_worker_cache = {uid: 'cell'} |
There was a problem hiding this comment.
P2: The other_worker_cache dict and its assertion are a no-op, so the test does not check that a stale process cache survives the purge. Drop them and rely on the DB-level fence checks, or seed router._cache for a real stale-route check.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/tests/unit/test_cell_wipe_step.py, line 120:
<comment>The `other_worker_cache` dict and its assertion are a no-op, so the test does not check that a stale process cache survives the purge. Drop them and rely on the DB-level fence checks, or seed `router._cache` for a real stale-route check.</comment>
<file context>
@@ -0,0 +1,201 @@
+ monkeypatch.setattr(wipe, 'cell_store', lambda: cell.store)
+ # An independent worker keeps this route even when the wiping worker
+ # invalidates its own process cache. It outlives the drain and purge.
+ other_worker_cache = {uid: 'cell'}
+ assert wipe.purge_owner_planes(uid, now=2) == {'status': 'purged'}
+ assert other_worker_cache[uid] == 'cell'
</file context>
| @@ -0,0 +1,210 @@ | |||
| # B2 fix round 1 implementation result | |||
There was a problem hiding this comment.
P3: This committed report hard-codes local machine paths, a personal username, and internal ANX links and event IDs. Replace them with repo-relative paths and command names, and drop the internal tracker links, before this artifact is merged.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At .agent-artifacts/pgf/b2-result.md, line 3:
<comment>This committed report hard-codes local machine paths, a personal username, and internal ANX links and event IDs. Replace them with repo-relative paths and command names, and drop the internal tracker links, before this artifact is merged.</comment>
<file context>
@@ -0,0 +1,210 @@
+# B2 fix round 1 implementation result
+
+Repository: BasedHardware/omi. Worktree: /Volumes/Ephemeral/scratch/worktrees/omi/omi-lane-pgf-b2-upstream-keep-clean. Branch: lane/pgf-b2. Rebased onto origin/main 4b1c40b5ef03242b82013a64c1dc941728715bab before implementation. No push, PR, deploy, GCP tier or production access. The pre-existing app/analysis_options.yaml and app/pubspec.lock edits are preserved byte-for-byte and uncommitted.
+
+Source implementation is committed at `6c194bfa7d35f410efac6eb03bcbe5731871b750`. Frozen preflight passed all 46 checks on this product tree. Final source selector coverage is exact: 186 checkpointed + 2491 resumed = all 2677 unique selected files, with no omitted or duplicated path. Result: **2670 nonfailing file sessions, 7 nonzero files; resumed runner exit 1**. No full-suite green claim is made. Qualification timestamp: 2026-11-06T21:45:39.447640+00:00.
</file context>
| def legacy_writes_allowed_for_state(state: AccountCutoverState) -> bool: | ||
| """Legacy product mutations are only legal while the account remains legacy. | ||
|
|
||
| Migrated owners may mutate cells; legacy writes remain fenced. |
There was a problem hiding this comment.
P3: This docstring line describes cell mutation rights that this helper does not grant or check, and 'legacy writes remain fenced' contradicts the next paragraph, which says rolled_back_stranded allows new legacy writes. Scope the note to what the helper covers: migrated owners are not covered by this legacy-only fence.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/utils/account_cutover/fence.py, line 30:
<comment>This docstring line describes cell mutation rights that this helper does not grant or check, and 'legacy writes remain fenced' contradicts the next paragraph, which says `rolled_back_stranded` allows new legacy writes. Scope the note to what the helper covers: migrated owners are not covered by this legacy-only fence.</comment>
<file context>
@@ -27,6 +27,8 @@ def __init__(self, message: str = 'account generation mismatch'):
def legacy_writes_allowed_for_state(state: AccountCutoverState) -> bool:
"""Legacy product mutations are only legal while the account remains legacy.
+ Migrated owners may mutate cells; legacy writes remain fenced.
+
``rolled_back_stranded`` restores the legacy data plane for reads and new
</file context>
| Migrated owners may mutate cells; legacy writes remain fenced. | |
| Migrated owners are not covered by this legacy-only fence; cell write rules live elsewhere. |
| @@ -0,0 +1,3 @@ | |||
| -- B2: retain the per-space head as a durable admission tombstone after wipe. | |||
| -- Only enrollment/backfill creates heads; every writer locks and checks this row. | |||
There was a problem hiding this comment.
P3: This comment is inaccurate. purge.py _tombstone also inserts head rows for missing spaces, so enrollment is not the only creator. compact() in feed.py also writes without the lock check. Reword it so it describes what the code does.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/database/cells/migrations/0002_write_fence.sql, line 2:
<comment>This comment is inaccurate. `purge.py` `_tombstone` also inserts head rows for missing spaces, so enrollment is not the only creator. `compact()` in `feed.py` also writes without the lock check. Reword it so it describes what the code does.</comment>
<file context>
@@ -0,0 +1,3 @@
+-- B2: retain the per-space head as a durable admission tombstone after wipe.
+-- Only enrollment/backfill creates heads; every writer locks and checks this row.
+ALTER TABLE space_heads ADD COLUMN tombstoned boolean NOT NULL DEFAULT false;
</file context>
| -- Only enrollment/backfill creates heads; every writer locks and checks this row. | |
| -- Enrollment and purge tombstones create heads; mutating paths lock and check this row before writing. |
| uid = decoded_token["uid"] | ||
| await _enforce_account_deletion_access(uid) | ||
| await _enforce_cutover_access(uid, request) | ||
| await run_blocking(db_executor, auth_endpoints._resolve_request_plane_or_503, uid) |
There was a problem hiding this comment.
P3: These four calls reach into a private _resolve_request_plane_or_503 from another module with no # pyright: ignore[reportPrivateUsage]. The repo's strict pyright config will flag them, and other cross-module private calls here carry that ignore. Add the ignore comment, or expose a public name.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/dependencies.py, line 84:
<comment>These four calls reach into a private `_resolve_request_plane_or_503` from another module with no `# pyright: ignore[reportPrivateUsage]`. The repo's strict pyright config will flag them, and other cross-module private calls here carry that ignore. Add the ignore comment, or expose a public name.</comment>
<file context>
@@ -81,6 +81,7 @@ async def get_current_user_id(
uid = decoded_token["uid"]
await _enforce_account_deletion_access(uid)
await _enforce_cutover_access(uid, request)
+ await run_blocking(db_executor, auth_endpoints._resolve_request_plane_or_503, uid)
return uid
</file context>
| await run_blocking(db_executor, auth_endpoints._resolve_request_plane_or_503, uid) | |
| await run_blocking(db_executor, auth_endpoints._resolve_request_plane_or_503, uid) # pyright: ignore[reportPrivateUsage] |
| monkeypatch.setattr(account_deletion.users_db, 'mark_user_deletion_wipe_failed', MagicMock()) | ||
| monkeypatch.setattr(account_deletion.users_db, 'mark_user_deletion_wipe_completed', MagicMock()) | ||
| assert account_deletion.background_wipe_user_data('uid1') is False | ||
| account_deletion.users_db.mark_user_deletion_wipe_failed.assert_called_once_with('uid1') |
There was a problem hiding this comment.
P3: Add an assertion that the cell purge was actually called, so the test proves the purge failure is what blocks the wipe.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/tests/services/users/test_account_deletion.py, line 2584:
<comment>Add an assertion that the cell purge was actually called, so the test proves the purge failure is what blocks the wipe.</comment>
<file context>
@@ -2566,3 +2572,15 @@ def test_account_wipe_requires_all_retained_vector_copies_to_be_removed(monkeypa
+ monkeypatch.setattr(account_deletion.users_db, 'mark_user_deletion_wipe_failed', MagicMock())
+ monkeypatch.setattr(account_deletion.users_db, 'mark_user_deletion_wipe_completed', MagicMock())
+ assert account_deletion.background_wipe_user_data('uid1') is False
+ account_deletion.users_db.mark_user_deletion_wipe_failed.assert_called_once_with('uid1')
+ account_deletion.users_db.delete_user_data.assert_not_called()
+ account_deletion.users_db.mark_user_deletion_wipe_completed.assert_not_called()
</file context>
| account_deletion.users_db.mark_user_deletion_wipe_failed.assert_called_once_with('uid1') | |
| account_deletion.purge_owner_planes.assert_called_once_with('uid1') | |
| account_deletion.users_db.mark_user_deletion_wipe_failed.assert_called_once_with('uid1') |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 67894e0e15
ℹ️ 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".
| if store.get_space(uid) is None: | ||
| router.invalidate(uid) | ||
| return {'status': 'absent'} |
There was a problem hiding this comment.
Fence absent spaces before completing the wipe
With routing enabled, an in-flight first request can pass deletion admission and pause before resolve() creates its directory row. If the wipe runs at that point, this branch returns without creating a cell tombstone; the request can subsequently create the directory row and enroll a writable cell head, allowing data to be recreated after account deletion. Establish the durable enrollment/write fence even when the directory row is absent, rather than treating absence as proof that no writer can arrive.
Useful? React with 👍 / 👎.
| _enforce_cutover_http_if_request(uid, request) | ||
| _resolve_request_plane_or_503(uid, signup_platform=x_app_platform) |
There was a problem hiding this comment.
Keep cutover control independent of directory resolution
When routing is enabled and neither route cache contains the owner, a directory outage now makes /v1/account/cutover/control return 503 through its Depends(auth.get_current_user_uid) dependency, even when the authoritative cutover document remains available. _enforce_cutover_http_if_request() deliberately exempts this bootstrap route, but the unconditional resolution immediately afterward defeats that exemption. Skip product-plane resolution for the always-reachable control paths so clients can still discover migration and upgrade instructions while product routing is unavailable.
Useful? React with 👍 / 👎.
| from database.cells.serving import cell_store | ||
| from database.directory.store import DirectoryStore, Space | ||
| from database.jobstore.connection import Pool, iam_connector | ||
| from utils.rollout.runtime_percent import ramp_snapshot |
There was a problem hiding this comment.
Preserve the database-to-utils import boundary
The new database router directly imports utils.rollout.runtime_percent, reversing the strict layer hierarchy required by backend/AGENTS.md. This also pulls the rollout coordinator and executor dependencies into every importer of the persistence router, including authentication while routing is off. Obtain the revision through a lower-layer seam or move enrollment orchestration above the database layer instead of introducing this upward dependency.
AGENTS.md reference: backend/AGENTS.md:L168-L174
Useful? React with 👍 / 👎.
| headers=websocket.headers, | ||
| ) | ||
|
|
||
| await run_blocking(db_executor, _resolve_request_plane_ws, uid) |
There was a problem hiding this comment.
Add the required listen/pusher lifecycle change note
The WebSocket authentication changes introduce directory resolution and a new retryable handshake rejection before listen admission, but the commit contains no note under backend/docs/listen_pusher_pipeline/changes/. backend/AGENTS.md explicitly requires a note in the same PR for listen/pusher WebSocket changes; document the activation conditions and HTTP/WS failure behavior there so the operational pipeline history includes this new admission dependency.
AGENTS.md reference: backend/AGENTS.md:L164-L164
Useful? React with 👍 / 👎.
| dsn = value(scope, bindings, f'{prefix}_PG_DSN') | ||
| iam = all(value(scope, bindings, f'{prefix}_PG_{suffix}') for suffix in ('HOST', 'DATABASE', 'USER')) | ||
| if not dsn and not iam: |
There was a problem hiding this comment.
Accept secret-backed DSNs in routing binding validation
When provisioning supplies DIRECTORY_PG_DSN and CELLS_PG_DSN through the manifest's supported secret bindings, this check rejects the configuration even though both serving pool factories accept those runtime environment variables. The validator examines only each host's env mapping, missing Cloud Run's separate secrets mapping, and value() also returns None for GKE env entries backed by a secret. Exercising this validator with secret-backed DSNs on all five surfaces produces ten missing-binding errors. Recognize and validate secret references alongside literal/config-map bindings so the DSN connection option can be deployed without putting credential-bearing DSNs in plaintext configuration.
Useful? React with 👍 / 👎.
| if self.mutations: | ||
| # Also guard replay-only writes; no implicit enrollment on this path. | ||
| lock_writable_space(self.conn, self.space_id) |
There was a problem hiding this comment.
Acquire the space fence in a consistent lock order
When a read-modify-write transaction overlaps a blind write to the same document, the new head lock can deadlock otherwise compatible operations: the first transaction's tx.get() holds the document's FOR UPDATE lock, the blind writer acquires the space-head lock here and waits for that document in _lock_read(), and the first transaction then waits for the head when it flushes. Previously, flush acquired document locks before the head for both paths. PostgreSQL must now abort and retry one transaction, adding lock-wait latency and potentially exhausting the bounded retry budget under contention. Acquire the space fence before invoking transaction bodies, or otherwise preserve one consistent document/head lock order.
Useful? React with 👍 / 👎.
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: 380ebbb02c
ℹ️ 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".
| if directory_routing.routing_active(): | ||
| current_operation = 'cell_directory_purge' | ||
| heartbeat() | ||
| purge_owner_planes(uid) |
There was a problem hiding this comment.
Preserve account deletion for Firestore-routed owners
When routing is enabled, this invokes the cell-only purge for every account, including existing owners and new owners outside the enrollment ramp, which router.resolve() registers with cell='firestore'. purge_owner_planes() explicitly rejects those routes with RuntimeError('cell purge requires explicit directory cell enrollment'), even with the wipe switch enabled. Consequently, these account deletions repeatedly fail before users_db.delete_user_data() runs, after Firebase Auth and other resources have already been deleted. Handle valid Firestore-only directory rows separately so their directory cleanup and normal account deletion can complete without requiring cell enrollment.
Useful? React with 👍 / 👎.
| if ( | ||
| control.client_action == AccountCutoverClientAction.migration_maintenance | ||
| and record.state != AccountCutoverState.rolled_back_stranded | ||
| and (record.state != AccountCutoverState.migrating or mutating) |
There was a problem hiding this comment.
Fence write-producing GET paths during migration
With cutover enforcement enabled, this exemption admits every GET for a migrating account, but existing GET paths perform product writes. For example, GET /v1/folders calls initialize_system_folders() when folders are absent (backend/routers/folders.py:36-38), which writes documents without a cutover check. Additionally, when LOCKED_CONTENT_RESET_RECOVERY_ENABLED=true, the shared authentication dependency runs recover_locked_content() even for GET requests, updating locked memories, action items, and conversations. These requests can therefore mutate the source after the migration fence and backfill, leaving the destination inconsistent. Fence these write-producing paths independently before allowing migrating accounts through the general GET exemption.
Useful? React with 👍 / 👎.
…leted wipe Co-Authored-By: Claude Opus 5.5 <[email protected]>
A wipe interrupted after disabling the route but before the owner tombstone row existed recorded cell='disabled' in the fence and then refused every retry, stranding account deletion before Firestore. A disabled route with a tombstoned cell head is durable proof of an earlier fenced wipe, as it was before the tombstone table; resume the purge from it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
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: 831987467b
ℹ️ 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".
| if is_cutover_control_path(getattr(getattr(request, 'url', None), 'path', '')): | ||
| return |
There was a problem hiding this comment.
Keep bootstrap telemetry from bypassing new-owner enrollment
With routing enabled, a new owner's first request to /v1/account/cutover/control with X-App-Platform skips directory enrollment here, but that route uses get_current_user_uid, which subsequently calls record_user_platform(). That helper merge-creates users/{uid}. On the next product request, router.resolve() therefore sees an existing user and permanently assigns cell='firestore', even at a 100% new-owner ramp. Preserve the control route's directory-outage exemption without creating the user document before enrollment—for example, by keeping its authentication dependency free of registration side effects.
Useful? React with 👍 / 👎.
…imistic mutations (B3) (#24868) <!-- claude-projects-attribution: {"github_login":"Git-on-my-level"} --> _Requested by **David**_ ## What changed and why Add the default-off `/v1/spaces/{sid}/{changes,snapshot,mutations,cursors}` protocol over the cell store. The personal pilot requires `sid == authenticated uid` and an active owner membership. Snapshot starts retain 30/hour while signed continuations use 600/minute; invalid/forged tokens consume the start bucket. The four BYOK policies match the auth dependency. Route admission runs before FastAPI body parsing; cell failures retain safe type-only diagnostics. ## Product invariants affected B3 adds no invariant-globbed paths. B2 (#24805, merged) retains `INV-CUTOVER-1` and `INV-MEM-3`; their existing fences remain authoritative. ## How it was verified Required R3 suites: **278 passed, 0 failed, 1 existing fakeredis/Lua skip**. Environment preflight passed (18 checks, 8 optional warnings), async scan found no blockers, and route-policy baseline/inventory and PR metadata checks passed. **Broader verification is blocked:** repo-wide type checking hit its 1,800-second wall budget without diagnostics; make preflight stopped on a Firestore query-shape file timeout at the unchanged 300-second budget. Two isolated retries also timed out; the diagnostic retry reached 96% with no assertion failure reported. No full preflight/type-check pass or remote CI result is claimed. Credential-scrubbed local Python 3.11, synthetic authentication and private disposable PostgreSQL only; no production access or GCP tier. Exact commands and evidence are in the local lane report `.agent-artifacts/pgf/b3-fix-r3-result.md`. The full backend selector was not executed, per fix-r3. ## Tests Regression tests cover another uid granted the owner role receiving 404 on all four routes, the personal uid still requiring an active owner role, BYOK rejection through the real auth dependency, a >30-page snapshot with the start bucket exhausted, epoch restart charging, invalid and forged token charging, signed-token space/since/address binding, the separate rate budgets and all four BYOK declarations. ## UI evidence UI-Evidence: none -- backend only ## Failure class (fixes) Failure-Class: none ## Scoped cleanups (optional) Reject malformed directory cell values, log unexpected exception types without sensitive details, and document the fingerprint-key divergence. The generated registry retains its owning date per lead direction. Ships dark; rollback is `SPACES_SYNC_API_ENABLED=false`. No client or domain adapter in B3; app-client OpenAPI remains untouched until W7. Pilot policies: changes/cursors 600/minute, snapshot starts 30/hour and continuation pages 600/minute, mutations 120/hour. Personal spaces only until shared-space write policy and cursor namespaces land; snapshot consumers keep page 1's head and restart on epoch changes. Accepted protocol decisions remain: conflicts are recomputed without conflict receipts; fingerprint canonicalization stays isolated from Firestore and uses the `base` key; both 425 recovery conditions use `resync_required` plus `reason`. The personal-space pilot has no entity write allowlist and is owner-only: every route requires `sid == uid` and an active `owner` membership, so another uid (including one with an owner role) or a `member` row grants no sync access until W7 defines shared-space role policy (merge-owner review of cb6f132). Integer revisions are authoritative; datetime tokens provide released-client compatibility. Merge order is B1 → B2 → B3. Deploy dark; enabling the backend flag requires B2's routing, migration, provisioning and admission runbook first. W7 owns the first client ramp under `SUPPORTS_OFFLINE_CACHE`. Rollback disables the flag immediately; previously committed mutations remain ordinary cell data covered by wipe/purge. Long-term data foundation wave B3 (follows #24805). Rebased on main after #24805 merged; focused suites (spaces router, cell conformance, directory store/router, wipe, lifecycle inventory, async boundaries) 1940 passed on the rebased head. Default-off: SPACES_SYNC_API_ENABLED gates every route before body parsing. 🤖 Generated with [Claude Code](https://claude.com/claude-code) ## Review fixes (round 2) - Resolve datetime revisions using database-clock timestamps assigned monotonically under the sequence-allocation lock. Row `updated_at` exposes that same microsecond-stable timestamp for datetime token round trips. Migration `0003_revision_timestamps.sql` preserves change-log event/retention timestamps; older unstamped history requires an integer rebase. - Reject unsupported cell labels before constructing or reading the singleton cell store. - Include feed-shaped deletion `entries` in snapshot pages (including `since`), sharing the row keyset/page budget and suppressing tombstones for recreated rows. - Replay the original receipt revision even after another writer advances or recreates the row. Regression coverage includes confirmed PostgreSQL row-lock contention with reversed caller timestamps, unknown-cell admission on all routes, incremental deletion reconciliation and pagination, and patch/delete replay after a concurrent advance. Fresh round-two required suites: 88 router + 36 cell conformance + 12 directory = 136 passed, zero failed/skipped, on `d2d9fb83434`. Type check (0 errors), async scan (0 findings), and final `make preflight` (44 checks) also pass. Broad selector coverage and the vendor-drill timeout retry are recorded in `.agent-artifacts/pgf/b3-fix-r2-result.md`. ## Review fixes (round 3) - Require sid == authenticated uid AND active owner membership. Another uid with an owner role gets the same 404 as non-membership on all four routes. - Keep snapshot starts and epoch restarts at 30/hour; continuations use 600/minute (up to 300,000 rows/minute at the 500-row page budget). HMAC-SHA256 HTTP tokens bind sid, since and address; invalid/forged tokens consume the start bucket. - Correct all four BYOK declarations to validated_when_headers_present, matching get_current_user_uid and its BYOK validation. The existing generator regenerated the review inventory; no tracked generated policy copy exists. Required R3 suites: **278 passed, 0 failed, 1 existing fakeredis/Lua skip**. Environment preflight passed (18 checks, 8 optional warnings), async scan found no blockers, and route-policy baseline/inventory and PR metadata checks passed. **Broader verification is blocked:** repo-wide type checking hit its 1,800-second wall budget without diagnostics; make preflight stopped on a Firestore query-shape file timeout at the unchanged 300-second budget. Two isolated retries also timed out; the diagnostic retry reached 96% with no assertion failure reported. No full preflight/type-check pass or remote CI result is claimed. Credential-scrubbed local Python 3.11, synthetic authentication and private disposable PostgreSQL only; no production access or GCP tier. ## Review fixes (round 4) - Encode binary values recursively in changes, snapshots and mutation-conflict rows as the cell codec's reserved singleton `{"$bytes": "<base64>"}`. The OpenAPI field descriptions specify this wire convention; nested objects/lists, empty bytes and UTF-8 bytes use the same reversible encoding. - Decode tagged mutation fields before applying them, retain native bytes through the route, and use the existing cell JSON codec for stable mutation fingerprints. Invalid tags return 422 before cell I/O; the existing 128 KiB limit measures the encoded operation. - Reproduced the original failure in all three response shapes before fixing it (3 failing regressions). Post-fix spaces HTTP suite: **114 passed**; cell conformance: **36 passed**, zero failures/skips. The new tests return each response document through mutation input and assert exact stored bytes, idempotent replay, and changed-byte mutation-ID conflicts. Shared codec verification and metadata checks are recorded in `.agent-artifacts/pgf/b3-fix-r4-result.md`. R4 uses credential-scrubbed Python 3.11 and private disposable PostgreSQL only. No production access or GCP tier. Full selector, full preflight and repo typecheck are deliberately deferred to the lead push gate per the R4 brief; this round makes no new claim about those gates or remote CI.
…ple and task workflows (A2b) (#24870) <!-- claude-projects-attribution: {"github_login":"Git-on-my-level"} --> _Requested by **David**_ ## What changed and why Compose conformance-only typed cell adapters for folders, people, action items, goals and workstreams over the existing cell UoW, with expand-only query columns and shared simulator/Firestore/Postgres contracts. Restore legacy IDs from document keys without rewriting payloads, use keys for retirement and replacement, and preserve UTC goal-history fallback for falsy or invalid timezones. No serving selectors or configuration change; enrollment remains outside this PR. Firestore folder/event serving behavior and read costs remain unchanged. The earlier legacy person identity recovery remains: `FirestorePeople` receipt replay of a legacy person document stored without an `id` field now returns the document key as `id` (previously the replayed dict had no `id`); stored payloads are not rewritten. Covered by the shared ID-less conformance cases. ## Product invariants affected none ## How it was verified Round-1 conformance passed all 186 cases on required simulator, Firestore emulator and disposable local Postgres backends. Six focused/failed-file replays passed all 206 cases, including the corrected fingerprint and timeout fixture, strict port contracts, cell migration contracts, and unchanged speaker timing tests. The full 2,677-file unit command exited 1: 65,732 passed / 4 failed, plus one file timed out. The corrected and timing-sensitive cases passed serialized replay; the unchanged deploy-contract fixture still timed out at 900 seconds in both bulk and isolated runs. Its diagnostic stack was parsing AST import closures. No whole-suite green is claimed. The async scanner and expanded typecheck passed (0 type errors); frozen preflight passed all 43 checks. Metadata validation passed all 4 checks. No production access or GCP tier was used. ## Tests Shared regressions read ID-less documents across all five domains, check mutation-return IDs and key-based retirement/replacement, and verify projections do not add IDs to stored legacy payloads. Goal progress history covers valid, null, empty and invalid timezones through both append and update APIs. Existing migration contracts now reject destructive DDL; the import-only guard permits 120 seconds for process startup under load. ## UI evidence UI-Evidence: none -- backend only ## Failure class (fixes) Failure-Class: none ## Review fixes (round 17) - Goal focus enumerates the focus set, which locks it sorted, before it reads the requested goal. Folder reorder locks its ids sorted before it checks them. The cross-domain lock-order test now covers focus and reorder. - Lock order is a latency property here, not a correctness one. Every body read is `SELECT ... FOR UPDATE`, and some bodies are data-dependent: `append_progress_event` locks the goal, then `goal_history/<goal>/<day>`, and the day comes from `users/profile`. Those bodies cannot always lock in flush order. Correctness rests on the store treating `40P01` as retryable (`store.py:326`, bounded and jittered, whole-body replay). New test `test_inverted_lock_order_deadlock_is_detected_and_retried` uses two real connections that lock `a,b` and `b,a`. PostgreSQL aborts one, the retry commits it, and both increments land. 25 related files pass under test.sh. ## Review fixes (round 16) - Cross-domain bodies take row locks in flush's sorted `(entity, id)` order, so a concurrent raw write cannot deadlock them. Goal lifecycle detach locks linked tasks before the goal, then workstreams. Folder delete locks conversations before folders, and locks the deleted folder and its target in sorted order. Folder moves lock conversations sorted and refresh counts in sorted folder order. `_lock_in_order` moves from `WorkflowRepo` to `Repo` so the folder adapter can use it. - Sweep: `import_task_goal_links` already locked in order. `resolve_work_intent` touches only brand-new rows after the task and goal, and the other single-collection paths go through sorted queries. Test: `test_cross_domain_bodies_lock_in_flush_order` fails on 9e19c3f. 25 related files pass under test.sh. ## Review fixes (round 15) - A goal update now rejects `id`, `goal_id` and `account_generation`. Before, the patch was copied whole, so it could change identity or generation past the generation checks. Routers pass typed models without these fields. Test: `test_goal_update_rejects_identity_and_generation_fields[backend x field]`. - A `people.create` replay whose person was deleted returns the receipt id, as the Firestore path does, instead of raising `KeyError`. Test: `test_person_create_replay_survives_deleted_person[postgres|sim]`. - Sweep: every other `if prior is not None` replay in the cell adapters returns a stored id or reads through `.get`. Workstream and folder updates use typed patch models, so they cannot carry identity fields. Both fixes are mirrored in the sim twin. All 8 new cases fail on a1def7b, and the file passes 71/71. ## Review fixes (round 14) - A saved `None` mutation result now replays. `receipt()` returned `None` both when there was no receipt and when the saved result was `None`, so a missing-goal update that was retried after the goal appeared applied the old patch. `_idempotent` now checks whether a receipt exists (`receipt_entry`), in the adapter and in its sim twin. Test: `test_goal_update_replays_saved_none_after_goal_appears[postgres|sim]`, which fails on the previous head. - Merged origin/main to pick up the #24950 registry-gate fix. The flake-fix conflict in `test_qualify_parakeet_route.py` took main's version (#24948). The `domain_sim/store.py` baseline moved to 1511 -> 1619. ## Scoped cleanups (optional) Cell-native creates retain redundant IDs as a documented metadata exception to payload byte parity. Before W5 enrollment, integrate the Firestore-owned profile timezone source and confirm the naive legacy timestamp policy before serving those paths. Round 5 verifies the list indexes; round 6 aligns raw and typed writer lock ordering. No edits under `.github/`, `backend/database/jobstore/` or `backend/testing/store_fixtures.py`. Line-Count-Exception: backend/testing/domain_sim/store.py | 1511 -> 1625 | Shared legacy identity, timezone, chat snapshot, lifecycle, malformed-event, jsonb key-order and typed-generation conformance requires independent simulator behavior in the existing reference adapter. ## Housekeeping Removes lane working notes (`.agent-artifacts/pgf/{a2a,b2,merge-owner-fix}-*`) that merged with #24852 and #24805. One test-only isolation fix in `test_qualify_parakeet_route.py` (timeout injection leaked across cases under load). Long-term data foundation wave A2b (follows #24852). Rebased on main after #24852 merged. ## Review fixes (round 7) - Object- and array-valued legacy folder `order` values sort by PostgreSQL `jsonb::text` (keys by length, then bytes) in the cell cursor and the simulator, matching the SQL order function and index; regression case `[{'b': 0}, {'aa': 0, 'z': 0}]` across limits and pending/committed rows. ## Review fixes (round 8) - `account_generation` filters in cell action-item idempotency and workstream lists compare typed JSON (`coalesce(doc->'account_generation','0')=to_jsonb(gen)`): missing is 0, wrong-typed legacy values are nonmatches instead of a failing bigint cast; regression test for string, boolean, numeric-string and null values. ## Review fixes (round 9) - Python mutation guards (`CellWorkstreams._require`, action-item document reuse) use `generation_matches`, the twin of the typed SQL filter: a missing field is 0, only JSON numbers match, booleans/strings/null are refused; regression test for update on wrong-typed rows. 🤖 Generated with [Claude Code](https://claude.com/claude-code) ## Review fixes (round 2) The immutable timestamp decoder now treats PostgreSQL timezone displacement errors (SQLSTATE 22009) as NULL, alongside malformed dates and datetime overflow. Real PostgreSQL regressions cover positive and negative +99:99/+24:00 equivalents in both plain strings and codec-tagged timestamps, including STORED-column writes. Migration 0003 remains expand-only and its checksum is re-pinned before enrollment. The cell action-item update enforces the same encoded before-state comparison and after-state result as Firestore. Shared conformance covers stale snapshots for changed and no-op patches, rejection without writes or receipts, matching snapshots, and successful receipt replay. The independent simulator is corrected too. The mutation fingerprint is unchanged because Firestore excludes expected_chat_state. The full shared run also exposed a cell folder-deletion parity defect: rehoming overwrote folder_user_set instead of preserving the stored marker. The one-line cell correction follows Firestore and the independent simulator; the existing shared parametrized regression covers absent, false and true markers, with and without a default folder, inside and outside a UoW. Round-2 focused regressions passed all 14 cases, and the final required simulator/Firestore-emulator/Postgres conformance plus migration run passed all 225 cases with no skips. Full backend typecheck passed with zero errors. At the round-2 handoff the full selected unit run was still in progress; its unchanged timeout-probe and Opus-discovery failures both pass isolated replay (16 and 68 tests respectively). No whole-suite green is claimed; terminal counts and preflight results will be recorded before handoff. ## Review fixes (round 3) Cell and simulator now preserve terminal/paused/background goals on unfocus, reject invalid relationship dispositions, and apply the same strict workstream patch schema as Firestore so identity and account generation cannot change through update. Shared tests assert no writes on rejection and that rejected requests do not consume idempotency keys. Round 4 restores `backend/database/{folders,goals,workstreams}.py` and `test_firestore_query_contract.py` exactly to their pre-round-3 contents (61e183e). Firestore folder/event serving behavior and read costs stay unchanged. Cell and simulator exclude missing or null discarded fields from default folder listings, matching Firestore's server-side `discarded == False` predicate before pagination. Include-discarded behavior and the historical post-pagination deleted filter are preserved. Cell event queries keep a guarded numeric cast and apply stored-type ordering and the query limit before validating the existing Firestore presentation model; malformed rows consume window slots and are then dropped. Workstream numeric inequality excludes nonnumeric stored types; goal ordering includes them. Valid integer strings above bigint range remain readable, with no bigint cast. Oversized doubles consume their query slot and are then dropped, matching Pydantic's existing float-to-int range check; the cell accounts for JSONB decoding integral doubles as Python integers. Shared cases cover malformed strings, null, objects, arrays, fractional/zero/negative/boolean/timestamp sequences, a one-row window consumed by malformed parent IDs/kinds/summaries, missing ordered fields, numeric versus string ordering, and document-key tiebreaks. People name lookup remains string-only in cell and simulator. Migration 0003 adds all ten generated columns with one ALTER TABLE, preventing repeated table rewrites. Its name remains 0004_task_workflow_typed.sql for lead-owned merge-time renumbering, and the checksum and migration contract are updated. Round-4 validation supersedes the earlier round-3 result: required simulator/Firestore-emulator/Postgres shared conformance and cell migration tests passed all 327 cases without failures or skips. All 17 focused unit files passed 1,036 cases, including all 50 restored query-contract cases; the standard unit runner deselected one slow query-shape sentinel. The full preflight then included that sentinel and passed all 840 Firestore guard cases and all 39 checks (550.42 seconds). Environment preflight passed 17 checks with 9 optional warnings and 0 failures. Canonical full backend typecheck passed with 0 errors / 76,784 warnings. The initial preflight timed out the query-shape file at its default 300-second budget; the retry used the supported 1,800-second local per-file override, with no assertion, repository timeout or guard changes. An ad hoc typecheck omitted --pythonpath and reported missing dependencies; the canonical backend/scripts/typecheck.sh invocation explicitly bound this worktree's Python and passed. A conservative 2,694-file unit attempt was stopped after focused coverage passed, following the lead's earlier publication-gate scope. No full-unit-suite or CI green is claimed. No GCP tier, production access, push or PR creation was used. ## Known parity differences No unavoidable bigint-range result difference is known for Firestore-storable values: shared tests require identical accepted large integer strings and rejection of oversized doubles. Firestore does not store integer-typed values outside signed 64-bit range. Cell numeric fields outside that range are dropped after LIMIT, matching the only Firestore-storable numeric representation (double); integer strings are preserved without that bound. This PR does not enroll or serve cell owners. ## Review fixes (round 5) Cell folder pagination now returns the exact SQL ordering key as JSONB text with each row and uses that text unchanged in the next cursor. This removes Python repr differences for legacy objects and arrays, preserves SQL numeric precision, and works for persisted rows and pending UoW writes. PostgreSQL regressions put page boundaries on arrays and non-datetime objects, including equal values with document-key tiebreaks and page sizes one and two. Migration 0003 retains its filename and one ALTER TABLE for all ten generated columns, with its checksum re-pinned. The folder list and expression index share the immutable cell_folder_order_key(q_order) function. The action-item list index matches the query's coalesced completion, due-null marker, due epoch, negative created epoch, and document-key expressions. Explicit UTC extraction makes the epoch expressions immutable without changing ordering. EXPLAIN regressions inspect the actual adapter queries and require their named indexes with no Sort or Incremental Sort. Before the fix, all ten new regressions failed: eight pagination cases skipped rows and both index cases required a sort. After the fix, all 31 migration/typed-cell tests passed. No production access, GCP tier, push, PR creation, main merge, full selector, full preflight or repository typecheck was used in round 5; the lead owns the publication gate. Round-5 terminal validation: required shared simulator/Firestore-emulator/Postgres conformance passed all 306 cases with no skips, and the nine directly related file-isolated unit suites passed all 167 cases. Together with the 31 migration/typed-cell cases, all 504 focused cases passed. Firestore emulators shut down normally; all verification commands and the task-owned heartbeat are stopped. Commit: 7a15c78. ## Review fixes (round 6) Raw and typed cell writers now take document/missing-key locks before the admission/sequence head. The typed UoW retains its per-space advisory serialization, but no longer locks space_heads before the body; raw flush locks all buffered addresses before checking the writable-space fence and replay receipts. The fence, sequence allocation, change log and receipt writes remain in the same transaction through commit. Four two-connection PostgreSQL regressions cover existing and missing rows, raw read-before-write and buffered-only writes, with a one-second lock_timeout and retries disabled. Each verifies distinct connection PIDs, both commits, the final shared row and the sequence head. The shared event decoder rejects numeric values below -9223372036854775808 as well as above 9223372036854775807. Eight real JSONB round-trip cases verify both numeric bounds, integral doubles losing their float type, and preservation of integer strings outside the numeric range. Migration 0004_task_workflow_typed.sql is unchanged. The pre-fix regression run reproduced six failures (four lock-order cases and two lower-bound cases), with six passing boundary controls. After the fix, the complete migration/typed-cell and raw-cell suites passed all 71 cases with no skips. No full selector, full preflight or repository typecheck was run in round 6; the lead owns the publication gate. No production access, GCP tier, push, PR creation or main merge was used. Round-6 terminal validation: all 547 focused cases passed with no failures or skips (71 migration/raw-cell cases, 306 required simulator/Firestore-emulator/Postgres shared cases, 170 directly related file-isolated unit cases). Backend Pyright scoped to the four changed Python files passed with zero errors / 733 warnings. The initial typecheck identified the regression's deliberate protected-method instrumentation; its single targeted annotation documents that test seam. The pinned formatter left all four files unchanged, and git diff --check passed. All verification commands and disposable stores have stopped, and the task-owned heartbeat was verified by PID/parent and terminated. Code commit: cf43cce. No artifacts were committed. ### Review fixes (round 10) - **Strict generation checks on link paths.** `resolve_work_intent`, `import_task_goal_links` and `validate_task_relationship` compared generations with Python equality, so a boolean `false`/`true` passed the generation 0/1 guards. They now use the typed `generation_matches` helper, which reads the raw row (the entity model would coerce a boolean to an int). The simulator twin gets the same checks, including its create-reuse, document-id and `list_open` paths. - `test_wrong_typed_generation_refuses_task_goal_links` covers boolean, string and fractional generations; it fails on the previous head. - Verified: 15 cells, workstream, goal, action-item and cell-store conformance suites, 321 passed. ### Review fixes (round 11) - **Key projections keep the JSON type.** `q_conversation_id`, `q_idempotency_key` and `q_goal_id` in migration 0004 now project only JSON strings, so a legacy numeric `idempotency_key: 123` no longer matches a request for `"123"`. The simulator already compared typed values. `q_status` is unchanged, since a NULL there would read as `active`. The pinned 0004 checksum in the migration test is updated (0004 has never been applied outside tests). - `test_numeric_legacy_idempotency_key_does_not_match_string_request` fails on the previous migration and passes now. - Verified: the same 15 suites, 322 passed. ### Review fixes (round 12) - **Pending overlay matches migration 0004.** The read-your-writes overlay in `space_store.py` now projects `q_conversation_id`, `q_idempotency_key` and `q_goal_id` as string-only, exactly like the generated columns, so a numeric legacy key edited in the same unit of work no longer matches a string request. `test_pending_overlay_keeps_numeric_idempotency_key_typed` fails on the previous head. - The same rule now covers the two remaining id lookups this PR adds: folder conversations by `folder_id` and workstream artifacts by `workstream_id` match only string-valued ids, as the simulator's typed equality does. - Verified: the workflow, cells and conformance suites (323 passed) plus 12 folder test files run one per process (99 passed). ### CI fix (round 12b) - **Migration 0004 on a fresh PostgreSQL 17 database.** CI failed `test_cell_wipe_step`, `test_directory_router` and `test_cell_store_conformance` at collection time with `function cell_query_timestamp(jsonb) does not exist`. PostgreSQL 17 builds expression indexes under `search_path = pg_catalog, pg_temp`, so the SQL `cell_folder_order_key` could not resolve the decoder while building `cell_docs_folder_order`. The function now pins `SET search_path FROM CURRENT`. Reproduced locally on a fresh database: the old migration fails a `REINDEX` under the restricted path, and the new one passes. `test_folder_order_index_rebuilds_under_restricted_search_path` covers it. The pinned 0004 checksum is updated. ### Review fixes (round 13) - **Consistent row-lock order.** `delete_batch`, `get_by_ids` and `import_task_goal_links` read (and so lock) rows in caller order, while buffered raw writes lock in sorted `(entity, entity_id)` order at flush; two such transactions could deadlock. A new `_lock_in_order` helper reads the ids sorted first, in flush's entity order (action items, then goals, then workstreams), before the body runs. `test_multi_row_bodies_lock_rows_in_flush_order` fails on the previous head. - Verified: workflow, cells and conformance suites, 325 passed.
Requested by David
What changed and why
Add sticky directory enrollment before signup telemetry, fail-closed HTTP/WS plane resolution, generation-zero cell cutovers, and the required cell/directory account-wipe step. Routing ships off; this PR authorizes no cell serving or positive enrollment ramp.
Round-1 review fixes prevent stale open cutover reads from publishing an idle cache entry and prevent stale routes from recreating wiped cell data. Redis epochs plus a pending-writer guard protect both Firestore write seams; the cell space-head lock guards mutation/replay, cursor, epoch, enrollment and purge paths. Wipe retains a content-free tombstone and retries safely after fencing.
D5 waiver (lead fix-r1 ruling): B2 ships dark with no runtime_env PG bindings. Exact host/database/IAM identities belong to the provisioning PR, gated on the N2 connection-budget measurement. The deploy validator now rejects partial enablement across backend, backend-sync, backend-sync-backfill, backend-listen and pusher. DIRECTORY and CELLS bindings are required on every surface because every enrollment dependency can initialize a cell head; backend also runs account wipe. DSN or complete IAM bindings and explicit pool sizes 1..2 are supported. No infrastructure values were guessed. The earlier ANX values ask
event:ev_77757863d2f3cbfc70593225b023691fis superseded by this ruling.Product invariants affected
INV-CUTOVER-1, INV-DATA-1, INV-MEM-3. Extend the existing cutover control record rather than introducing another authority. Bridge generation fencing, auth/control reachability and destination-binding honesty remain intact. Migrating allows reads and denies mutations; migrated allows cell traffic at generation zero while legacy writes remain fenced. Cell/directory wipe failures remain required failures before Firestore deletion. The lead owns the separate locked-invariant revision note for migrated; invariant files are unchanged.
How it was verified
Local tests only, with GOOGLE_APPLICATION_CREDENTIALS and every CLOUDSDK_* variable unset (also SERVICE_ACCOUNT_JSON and FIREBASE_AUTH_CREDENTIALS_PATH). Python is this worktree's backend/.venv (3.11.15); heavy runs use omi-heavy. No GCP tier, production access, or api.omi.me calls. Current round-1 results:
The monitoring failure is on the pinned qualification base
4b1c40b5ef03; PR #24804 fixed it on main while the final replay waited. No second rebase was performed after freezing the qualified product tree.Exact commands and counts:
.agent-artifacts/pgf/b2-result.md..agent-artifacts/pgf-result.mdmatches origin/main and is owned by another PR.Operations runbook (future authorized provisioning/integration work):
4 * sum(max instances for the five surfaces), plus existing clients. Cell pools open for cell enrollment or wipe. Fleet maxima and database max_connections have not been measured here; N2 must establish headroom or a pooler before 1%.W5 gates recorded without code changes (flash NB2/NB3/NB6): bind the plane for the lifetime of WebSocket sessions; require auth resolution before relying on plane_for's missing/partial-module fallback; evaluate a short negative cache for rejected uid inputs if metrics justify it. No domain adapter or traffic migration is included here.
Round-2 review dispositions (lead): cell cutovers now reject any explicit generation change (regression added). Recorded W5/W6 gates, no code here: (1) before any route flip (W6), route changes must be observable across workers (route version check, or a verified quiesce longer than both the 300 s process cache and the Redis TTL), with a two-resolver flip test; (2) move
lock_writable_spaceafter pending-address locks so lock order stays docs then heads (deadlock retries at W5 volume); (3) wipe completeness while routing is rolled back to off (purge sweep at flip-off); (4) retention policy for purge tombstones inspace_heads(raw uid); (5) the provisioning PR must use literal/env_var bindings or extend the validator's binding grammar; (6) feed pulls for unenrolled spaces return retryable unavailable, not empty; (7) mixed-version serving after the first real cutover write needs fleet-wide B2+ builds.Tests
Deterministic regressions interleave stale read → epoch INCR/Firestore commit/idle DEL → refused late cache publication → denied next mutation, for both write seams. Additional tests cover in-flight/crashed writers, Redis outages and key loss, upgrade/generation checks, and quiesce > TTL. Real Postgres tests cover an independent-process stale writer after purge, a resolver paused across the fence, crash-after-tombstone retry, and no implicit enrollment from mutation/cursor/epoch operations. Deployment fixtures cover both environments, all five surfaces, IAM/DSN/ConfigMap bindings, missing bindings, invalid modes, dark manifests, inherited shared-ConfigMap activation, activation from other environment surfaces, and the actual deploy-validator entrypoint.
UI evidence
UI-Evidence: none -- backend only
Failure class (fixes)
Failure-Class: none
New guards (only when adding a check or ratchet)
The PGF B2 round-1 D5 review identified incomplete deployment admission following B1 #24790 and M9 #24778. This extends the existing runtime-env validation primitive with fleet-wide binding admission and positive/negative fixtures; it adds no parallel checker or workflow.
🤖 Generated with Claude Code