Skip to content

feat(cells): cell store and routing directory foundation (CELL_STORE_MODE off) - #24790

Merged
Git-on-my-level merged 5 commits into
mainfrom
pgf/b1-cell-directory-store
Nov 6, 2026
Merged

Git-on-my-level merged 5 commits into
mainfrom
pgf/b1-cell-directory-store

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Nov 6, 2026 •

Copy link
Copy Markdown
Member

Requested by David

Part of the long-term data foundation (space-scoped Postgres cells), wave 1 item B1. Library + migrations + conformance only: CELL_STORE_MODE=off by default, zero serving callers, no pools or connections created at import. Cell-1 and the directory are separate databases intended for the existing prod-jobs instance; nothing here provisions or connects to them.

What changed and why

Add doc-mode cell and routing-directory libraries with separate expand-only migrations and no serving callers. Cell writes commit documents, revisions, the content-free feed, and independent mutation receipts atomically. The directory owns routing/cohort records, memberships, token recycling and public-conversation ownership.

Fix round 1 follows the lead rulings: pull and cursor registration raise typed CursorAhead above the committed head; replay uses mutation_receipts independently of feed compaction; and CELL_STORE_MODE is registered with generated documentation and the required structured ramp (B1 stays library-only; B2 owns gated staging/enrollment). The lead explicitly authorized these two registry paths beyond the original B1 boundary. Since B1 is unmerged, the receipt schema is folded into migration 0001.

Receipt fingerprints hash entity/id/op with the caller fingerprint, preserving reuse detection without content. Receipt PK collisions retry onto the winner's receipt. The old change_log mutation unique index is replaced by the receipt PK so purged receipts cannot cause retry loops against retained feed rows. MUTATION_RECEIPT_RETENTION_SECONDS is 90 days; purge_mutation_receipts removes at most 500 expired receipts per call with a statement timeout, independently of change_log. purge_space removes all five cell tables. Replay protection ends once a receipt is purged; no maintenance scheduler or HTTP mapping is introduced here.

Product invariants affected

none

How it was verified

All commands use this worktree's backend/.venv, with GOOGLE_APPLICATION_CREDENTIALS, all CLOUDSDK_* variables and inherited service-account settings removed. Heavy commands use /Users/dazheng/workspace/omi/bin/omi-heavy run --wait 3600 -- (this checkout has no bin/omi-heavy). Postgres uses private local Unix sockets. GCP tier: none.

Fix-round results: 34 Postgres tests passed in 36.83 s; focused pyright 0 errors, 0 warnings; Black 16 files unchanged. Exact-commit make preflight passed: all 42 selected checks in 655.87 s, with the draft body and BACKEND_UNIT_FILE_BUDGET_SECONDS=900. The first preflight stopped at the structured-ramp requirement on new rollout flags; corrected CELL_STORE_MODE and regenerated docs. The standalone registry checker also passed. Validation applies to local commit 756f7c5980d65de5851590e963e56ce430321b91. Commands:

  • OMI_REQUIRE_STORE_BACKENDS=postgres BACKEND_UNIT_FILE_BUDGET_SECONDS=900 .venv/bin/python -m pytest tests/unit/test_cell_store_conformance.py tests/unit/test_directory_store.py -v (backend directory).
  • .venv/bin/python -m pyright database/cells database/directory config/cell_store.py testing/cells_fixtures.py (backend directory).
  • backend/.venv/bin/python -m black --check --line-length 120 --skip-string-normalization backend/database/cells backend/database/directory backend/config/cell_store.py backend/testing/cells_fixtures.py backend/tests/unit/test_cell_store_conformance.py backend/tests/unit/test_directory_store.py (root).
  • Root: OMI_PR_BODY_FILE= BACKEND_UNIT_FILE_BUDGET_SECONDS=900 make preflight.
  • python3 scripts/render_feature_flag_registry.py regenerates backend/docs/feature-flag-registry.md deterministically, preserving its existing as-of date.

The earlier full backend run is still not green or exhausted: an unchanged admission timing test failed under host load, and passed on an isolated retry without edits. This round reruns the two prescribed B1 suites, not the full backend suite. No remote CI, push, PR, staging or deployment.

Tests

Real Postgres regressions cover future cursors in fresh and populated spaces, head equality, replay after compaction for feed/non-feed writes and deletes, no stale state overwrite, receipt insertion rollback, bounded receipt purge with its exact retention boundary, retained feed independence and complete space purge. Existing ordering, paging, CAS, replay races, coalescing, codec, migrations, import purity and directory conformance remain covered.

UI evidence

UI-Evidence: none -- backend only

Failure class (fixes)

Failure-Class: none

New guards (only when adding a check or ratchet)

No standalone check or ratchet; behavioral regressions use existing conformance discovery.

Scoped cleanups (optional)

CELL_STORE_MODE defaults off; nothing serves cell owners yet. B2 owns admission fencing and writer drain before purge, epoch advancement on re-enrollment, connection-budget and plane-leak gates, and the serving ramp plan. Typed domain adapters/tables and HTTP resync mapping remain assigned to later lanes. Non-blocking review findings are unchanged in this explicitly scoped fix round. The two pre-existing app changes are excluded from commits.

Reviews: Luna and GLM-flash. Blocking findings fixed in 756f7c5 (future cursors rejected with CursorAhead; replay receipts moved to their own 90-day mutation_receipts table so feed compaction cannot drop them; CELL_STORE_MODE registered). Non-blocking follow-ups (purge needs the B2 admission fence and writer drain) are carried to B2.

🤖 Generated with Claude Code

View guided diff Turn on auto-fix

@Git-on-my-level Git-on-my-level self-assigned this Nov 6, 2026

@cubic-dev-ai cubic-dev-ai 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.

9 issues found across 20 files

Confidence score: 2/5

  • backend/database/directory/store.py and its migration treat conversation_id as globally unique, so one user can overwrite another user’s owner and redirect public reads. Use an owner-scoped key for directory rows.
  • backend/database/cells/feed.py checks the cursor floor separately from reading the page, so concurrent compaction can make a client silently miss entries. Keep the check and page read consistent under concurrent compaction.
  • backend/database/directory/store.py leaves a personal owner revoked after a later get-or-create, so that owner can remain unable to access their space. Reactivate the owner row on conflict or reject owner revocation.
  • backend/database/cells/migrations/0001_cells.sql leaves the floor query without an index on space_id and ts, so it scans a space’s full unbounded history. Add a timestamp index for that query.
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="backend/database/cells/store.py">

<violation number="1" location="backend/database/cells/store.py:204">
P2: A concurrent replay can raise `BaseRevisionMismatch` instead of returning the existing receipt because the receipt lookup precedes document locking. Recheck the receipt after acquiring the lock, before enforcing `expected_rev`, so the replay path wins the race.</violation>
</file>

<file name="backend/database/directory/store.py">

<violation number="1" location="backend/database/directory/store.py:90">
P1: This conflict path leaves a revoked personal owner revoked: `revoke_member(space_id=uid, uid=uid)` can create that state, and a later get-or-create does nothing. Reactivate the owner row on conflict, or reject owner revocation, so idempotent enrollment cannot return an unowned personal space.</violation>

<violation number="2" location="backend/database/directory/store.py:201">
P1: `conversation_id` is not globally unique, but this upsert keys the directory row by it and overwrites `owner_space_id`. A second user’s same ID can therefore redirect public reads to the wrong owner; key the index by owner plus ID or reject collisions.</violation>
</file>

<file name="backend/database/cells/migrations/0001_cells.sql">

<violation number="1" location="backend/database/cells/migrations/0001_cells.sql:46">
P2: The unbounded `change_log` has no index for the floor query’s `space_id + ts` predicate, so floor calculation scans a space’s full history instead of the retention window. Add a timestamp index and partial sequence indexes for feed pulls and upsert compaction before this store grows.</violation>
</file>

<file name="backend/testing/cells_fixtures.py">

<violation number="1" location="backend/testing/cells_fixtures.py:37">
P2: Password-authenticated Postgres DSNs lose their password when this fixture rebuilds `target`, so migration and every harness factory fail on the second connection. Preserve `conn.info.password` when it is set before constructing the keyword DSN.</violation>
</file>

<file name="backend/database/directory/migrations/0001_directory.sql">

<violation number="1" location="backend/database/directory/migrations/0001_directory.sql:36">
P2: This check permits active memberships with a non-null `revoked_at`, leaving contradictory lifecycle data that active-membership queries still return. Enforce the timestamp invariant in both directions: active rows require NULL and revoked rows require a timestamp.</violation>

<violation number="2" location="backend/database/directory/migrations/0001_directory.sql:67">
P1: This primary key assumes conversation IDs are globally unique, but existing Firestore discovery explicitly says they are not and fails closed on duplicates. The directory registration path will overwrite the first owner on collision, so key the records by owner as well and make lookup reject ambiguous IDs instead of using `ON CONFLICT (conversation_id) DO UPDATE`.</violation>
</file>

<file name="backend/database/cells/_validation.py">

<violation number="1" location="backend/database/cells/_validation.py:22">
P2: `validate_document` accepts non-string keys in nested maps, but JSON serialization coerces them to strings and changes the document on read. Recursively reject non-string keys, including maps inside lists.</violation>
</file>

<file name="backend/database/cells/feed.py">

<violation number="1" location="backend/database/cells/feed.py:78">
P1: `pull` validates the cursor and reads its page in separate autocommit statements, so concurrent compaction can delete entries after the floor check and make the client silently miss them. Read the floor, log, documents, and head in one repeatable-read transaction.</violation>
</file>

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

)
conn.execute(
"INSERT INTO memberships (space_id, uid, role, created_at) VALUES (%s,%s,'owner',%s) "
'ON CONFLICT (space_id, uid) DO NOTHING',

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: This conflict path leaves a revoked personal owner revoked: revoke_member(space_id=uid, uid=uid) can create that state, and a later get-or-create does nothing. Reactivate the owner row on conflict, or reject owner revocation, so idempotent enrollment cannot return an unowned personal space.

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/directory/store.py, line 90:

<comment>This conflict path leaves a revoked personal owner revoked: `revoke_member(space_id=uid, uid=uid)` can create that state, and a later get-or-create does nothing. Reactivate the owner row on conflict, or reject owner revocation, so idempotent enrollment cannot return an unowned personal space.</comment>

<file context>
@@ -0,0 +1,240 @@
+            )
+            conn.execute(
+                "INSERT INTO memberships (space_id, uid, role, created_at) VALUES (%s,%s,'owner',%s) "
+                'ON CONFLICT (space_id, uid) DO NOTHING',
+                (uid, uid, now),
+            )
</file context>
Suggested change
'ON CONFLICT (space_id, uid) DO NOTHING',
"ON CONFLICT (space_id, uid) DO UPDATE SET role=EXCLUDED.role, state='active', revoked_at=NULL",

self._run(
lambda conn: conn.execute(
'INSERT INTO public_conversations (conversation_id, owner_space_id, visibility, created_at, updated_at) '
'VALUES (%s,%s,%s,%s,%s) ON CONFLICT (conversation_id) DO UPDATE SET '

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: conversation_id is not globally unique, but this upsert keys the directory row by it and overwrites owner_space_id. A second user’s same ID can therefore redirect public reads to the wrong owner; key the index by owner plus ID or reject collisions.

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/directory/store.py, line 201:

<comment>`conversation_id` is not globally unique, but this upsert keys the directory row by it and overwrites `owner_space_id`. A second user’s same ID can therefore redirect public reads to the wrong owner; key the index by owner plus ID or reject collisions.</comment>

<file context>
@@ -0,0 +1,240 @@
+        self._run(
+            lambda conn: conn.execute(
+                'INSERT INTO public_conversations (conversation_id, owner_space_id, visibility, created_at, updated_at) '
+                'VALUES (%s,%s,%s,%s,%s) ON CONFLICT (conversation_id) DO UPDATE SET '
+                'owner_space_id=EXCLUDED.owner_space_id, visibility=EXCLUDED.visibility, updated_at=EXCLUDED.updated_at',
+                (conversation_id, owner_space_id, visibility, now, now),
</file context>

visibility text NOT NULL,
created_at float8 NOT NULL,
updated_at float8 NOT NULL,
PRIMARY KEY (conversation_id),

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: This primary key assumes conversation IDs are globally unique, but existing Firestore discovery explicitly says they are not and fails closed on duplicates. The directory registration path will overwrite the first owner on collision, so key the records by owner as well and make lookup reject ambiguous IDs instead of using ON CONFLICT (conversation_id) DO UPDATE.

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/directory/migrations/0001_directory.sql, line 67:

<comment>This primary key assumes conversation IDs are globally unique, but existing Firestore discovery explicitly says they are not and fails closed on duplicates. The directory registration path will overwrite the first owner on collision, so key the records by owner as well and make lookup reject ambiguous IDs instead of using `ON CONFLICT (conversation_id) DO UPDATE`.</comment>

<file context>
@@ -0,0 +1,71 @@
+    visibility      text NOT NULL,
+    created_at      float8 NOT NULL,
+    updated_at      float8 NOT NULL,
+    PRIMARY KEY (conversation_id),
+    CONSTRAINT public_conversations_visibility_domain CHECK (visibility IN ('shared', 'public')),
+    FOREIGN KEY (owner_space_id) REFERENCES spaces (space_id) ON DELETE CASCADE
</file context>


def floor(self, space_id: str, *, now: float) -> int:
validate_id(space_id)
with self.pool.connection() as 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: pull validates the cursor and reads its page in separate autocommit statements, so concurrent compaction can delete entries after the floor check and make the client silently miss them. Read the floor, log, documents, and head in one repeatable-read transaction.

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/feed.py, line 78:

<comment>`pull` validates the cursor and reads its page in separate autocommit statements, so concurrent compaction can delete entries after the floor check and make the client silently miss them. Read the floor, log, documents, and head in one repeatable-read transaction.</comment>

<file context>
@@ -0,0 +1,147 @@
+
+    def floor(self, space_id: str, *, now: float) -> int:
+        validate_id(space_id)
+        with self.pool.connection() as conn:
+            return _floor(conn, space_id, now)[0]
+
</file context>

for address in sorted(pending):
row = self._lock_read(*address)
expected = pending[address].expected_rev
if expected is not None and (row is None or row[0] != expected):

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: A concurrent replay can raise BaseRevisionMismatch instead of returning the existing receipt because the receipt lookup precedes document locking. Recheck the receipt after acquiring the lock, before enforcing expected_rev, so the replay path wins the race.

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/store.py, line 204:

<comment>A concurrent replay can raise `BaseRevisionMismatch` instead of returning the existing receipt because the receipt lookup precedes document locking. Recheck the receipt after acquiring the lock, before enforcing `expected_rev`, so the replay path wins the race.</comment>

<file context>
@@ -0,0 +1,307 @@
+        for address in sorted(pending):
+            row = self._lock_read(*address)
+            expected = pending[address].expected_rev
+            if expected is not None and (row is None or row[0] != expected):
+                raise BaseRevisionMismatch(self.space_id, row[0] if row is not None else None)
+        if not pending:
</file context>

client_mutation_id text COLLATE "C",
fingerprint text COLLATE "C",
feed boolean NOT NULL DEFAULT true,
ts float8 NOT NULL,

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: The unbounded change_log has no index for the floor query’s space_id + ts predicate, so floor calculation scans a space’s full history instead of the retention window. Add a timestamp index and partial sequence indexes for feed pulls and upsert compaction before this store grows.

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/0001_cells.sql, line 46:

<comment>The unbounded `change_log` has no index for the floor query’s `space_id + ts` predicate, so floor calculation scans a space’s full history instead of the retention window. Add a timestamp index and partial sequence indexes for feed pulls and upsert compaction before this store grows.</comment>

<file context>
@@ -0,0 +1,76 @@
+    client_mutation_id text COLLATE "C",
+    fingerprint        text COLLATE "C",
+    feed               boolean NOT NULL DEFAULT true,
+    ts                 float8 NOT NULL,
+    PRIMARY KEY (space_id, seq),
+    CONSTRAINT change_log_op_domain CHECK (op IN ('upsert', 'delete')),
</file context>

# libpq accepts the last occurrence of a setting. Preserve private
# socket host/port while replacing only the database.
# URI DSNs need a keyword expansion instead of string concatenation.
params = dict(conn.info.get_parameters())

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: Password-authenticated Postgres DSNs lose their password when this fixture rebuilds target, so migration and every harness factory fail on the second connection. Preserve conn.info.password when it is set before constructing the keyword DSN.

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/testing/cells_fixtures.py, line 37:

<comment>Password-authenticated Postgres DSNs lose their password when this fixture rebuilds `target`, so migration and every harness factory fail on the second connection. Preserve `conn.info.password` when it is set before constructing the keyword DSN.</comment>

<file context>
@@ -0,0 +1,95 @@
+                # libpq accepts the last occurrence of a setting. Preserve private
+                # socket host/port while replacing only the database.
+                # URI DSNs need a keyword expansion instead of string concatenation.
+                params = dict(conn.info.get_parameters())
+                params['dbname'] = name
+                target = ' '.join(
</file context>

PRIMARY KEY (space_id, uid),
CONSTRAINT memberships_role_domain CHECK (role IN ('owner', 'member')),
CONSTRAINT memberships_state_domain CHECK (state IN ('active', 'revoked')),
CONSTRAINT memberships_revoked_at_set CHECK (state = 'active' OR revoked_at IS NOT NULL),

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: This check permits active memberships with a non-null revoked_at, leaving contradictory lifecycle data that active-membership queries still return. Enforce the timestamp invariant in both directions: active rows require NULL and revoked rows require a timestamp.

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/directory/migrations/0001_directory.sql, line 36:

<comment>This check permits active memberships with a non-null `revoked_at`, leaving contradictory lifecycle data that active-membership queries still return. Enforce the timestamp invariant in both directions: active rows require NULL and revoked rows require a timestamp.</comment>

<file context>
@@ -0,0 +1,71 @@
+    PRIMARY KEY (space_id, uid),
+    CONSTRAINT memberships_role_domain CHECK (role IN ('owner', 'member')),
+    CONSTRAINT memberships_state_domain CHECK (state IN ('active', 'revoked')),
+    CONSTRAINT memberships_revoked_at_set CHECK (state = 'active' OR revoked_at IS NOT NULL),
+    FOREIGN KEY (space_id) REFERENCES spaces (space_id) ON DELETE CASCADE
+);
</file context>
Suggested change
CONSTRAINT memberships_revoked_at_set CHECK (state = 'active' OR revoked_at IS NOT NULL),
CONSTRAINT memberships_revoked_at_set CHECK ((state = 'active' AND revoked_at IS NULL) OR (state = 'revoked' AND revoked_at IS NOT NULL)),



def validate_document(value: object) -> None:
if not isinstance(value, dict):

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: validate_document accepts non-string keys in nested maps, but JSON serialization coerces them to strings and changes the document on read. Recursively reject non-string keys, including maps inside lists.

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/_validation.py, line 22:

<comment>`validate_document` accepts non-string keys in nested maps, but JSON serialization coerces them to strings and changes the document on read. Recursively reject non-string keys, including maps inside lists.</comment>

<file context>
@@ -0,0 +1,23 @@
+
+
+def validate_document(value: object) -> None:
+    if not isinstance(value, dict):
+        raise TypeError('cell document must be a dict')
</file context>

@Git-on-my-level
Git-on-my-level merged commit c8d822e into main Nov 6, 2026
74 of 76 checks passed
@Git-on-my-level
Git-on-my-level deleted the pgf/b1-cell-directory-store branch November 6, 2026 13:10
Git-on-my-level added a commit that referenced this pull request Nov 7, 2026
…ark) (#24805)

<!-- claude-projects-attribution: {"github_login":"Git-on-my-level"} -->
_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_77757863d2f3cbfc70593225b023691f` is 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:

- Real local Postgres: directory router, cell wipe, directory store and
cell conformance: 68 passed, no skips.
- Cutover foundation and M9 plane probes: 88 passed.
- Runtime deployment validator, including positive/negative binding
fixtures: 198 passed (included in the final 503-test deploy run).
- Registry renderer/checker passed. Final generated output keeps
origin/main's as-of date (2026-11-05), removing unrelated overdue churn;
only B2 entries differ.
- Async blocker scan passed with zero findings.
- Deployment verification passed: 503 deploy tests plus 36
source-admission tests. Backend environment preflight: 17 passed, 9
optional warnings, zero failures.
- Enforced backend typecheck passed: zero errors. Frozen local preflight
passed all 46 checks in 470.69 seconds; the resulting product tree is
committed as 6c194bfa7d35.
- Named witnesses: 3,073 passed, one intentional referral skip; real-PG
conformance is included above. The first full 2,677-file selector had 11
nonzero files. Nine passed guarded replays (259 tests); the remaining
results are an unchanged main-branch monitoring contract failure and the
known 900-second cross-service timeout. The final source selector
covered all 2,677 files (checkpoint 186 + resumed 2,491), verified by
exact path-set equality: 2,670 nonfailing files and seven nonzero files.
Those seven are monitoring contract, executors, fleet deployment,
cross-service timeout, Soniox capture-axis, Soniox wire metrics, and
speaker prompts. The three additional guarded replays passed all 93
tests (24 + 11 + 58), with standard assertions, 100-ms waits, file
isolation and CPU guards intact. No full-suite green claim is made.
- Firestore emulator integration: 107 skipped because no loopback
emulator was available; no deployed acceptance is claimed.

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.md` matches origin/main and is owned by
another PR.

Operations runbook (future authorized provisioning/integration work):

1. B1 (#24790) precedes B2. Deploy B2 with DIRECTORY_ROUTING_MODE off
everywhere. Apply directory and cell migrations, including
cells/0002_write_fence.sql, on staging before enabling routing. Only
enrollment/backfill creates cell heads; writes never auto-create them,
and tombstones cannot be revived.
2. O4: write new-owner-cell1 via backend/scripts/rollout/ramp_set.py
only after every _ramp reader knows the name (backend, backend-listen,
pusher, backend-sync and notifications-job). Older readers reject the
whole document and freeze other ramps at last-known-good.
3. O6: all five plane-aware surfaces must run B2 before the first
enrollment. The provisioning PR must supply reviewed bindings on all
surfaces and pass the new admission validator. W5 adapters/readers,
plane-leak zero, wipe coverage and connection budget must be green
before the first 1% ramp.
4. Connection budget: with pool sizes 2, each instance adds at most 2
directory + 2 cell connections. Incremental fleet bound = `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%.
5. R10/W6: after the cell migration fence, wait
CELL_CUTOVER_QUIESCE_SECONDS (65 seconds, strictly greater than the
60-second idle TTL), and drain admitted writers before backfill/flip.
The W6 driver is outside this PR. Redis loss disables idle publication
and uses authoritative reads; if a write cannot acquire its Redis epoch
fence it refuses to commit. A crashed pending writer leaves caching
disabled until the operator reconciles that marker against authoritative
state; traffic stays authoritative.
6. Rollback before cell serving: routing mode off makes directory rows
inert and the cell wipe step a no-op. Ramp zero stops new cell
enrollment without moving existing rows. After W5 starts serving cell
owners, use its migration ceremony rather than blindly disabling
routing.

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_space` after
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 in `space_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](https://claude.com/claude-code)


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/24805?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="View guided diff"
src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a>
<a
href="https://www.cubic.dev/action/auto-fix/pr/BasedHardware/omi/24805?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F24805&source=description"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"><img
alt="Turn on auto-fix"
src="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
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