Skip to content

SCA-1959: recover D ancestry and bounded privacy/custody repair (incomplete) - #25215

Closed
Git-on-my-level wants to merge 61 commits into
mainfrom
sca-1697-d-g2-dark
Closed

Git-on-my-level wants to merge 61 commits into
mainfrom
sca-1697-d-g2-dark

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

Published recovery: 94f58c176717c5fa38fe89a0265ada338599fa96. Normal merges preserve published b9f707b6ccbfa011e3526cbdf11f72b1fc66a9e8, recovered local 01348656f99cd8e1f843a8bb03720e8dc99a6100, and main 0ce396503a5595975055c44994005db986294060. The recovered owned worktree is clean; original lost dirty/untracked state remains UNKNOWN. Sole source writer: M1 Studio Codex (Sol).

The one authorized bounded round repairs retained import/executor/C1 seams, live privacy checks in completion publication, unsealed recording-wide readmission, per-effect drain rotation, provider lock order and benign token rotation, and isolation of failed committed claims. Main migrations0001–0009 remain byte-identical. Dark0010–0027 preserve prior SQL bodies;0028 and0029 add the readmission and scheduling guards. Existing paid-attempt, unresolved-session and terminal-copy custody semantics remain gates.

Final push: 46 preflight checks PASS; pyright0 errors/96,822 warnings; bounded pre-push gate PASS. Focused source tests:577 unit cases and20 actual loopback Firestore C1 cases pass at01d51dfe; no actual D Postgres execution is claimed. The full push receipts retain their separate applicability skips/xfails. All failed/intermediate attempts are retained.

The smallest two-member D scope panel was unusable, and its single authorized rerun at01d51dfe timed out without a usable terminal answer; exact owned reviewers were cancelled. Neither attempt is a SHIP or final94f review. New exact-head CI is running, not green.

Source readiness remains false. Full G2 rows/P21–P25, all-writer/native/recovery/grouped cohorts, production host/admission/budget policy and unknown-attempt recovery, fleet/hot-owner/million-parked/CAS/counters, remote C4, reverse certificate/cold replay, process-kill matrix, final copy/journal retirement and real bound staging sizing/load remain open. Historical staging/outbox and local harness failures below are not silently retired. Root owns integration/measurements and SQL PG qualification; Release SCA-2283 alone executes production. No activation, production write, provisioning, new spend/access or savings is authorized or claimed here.

Earlier checkpoints and failed/unrequalified evidence (historical):

Current published continuation: 5bf4227fff8941b516e912b169b956a3cef6901a.

The six provider-merge emulator failures are repaired by qualifying both real paths: unchanged legacy race assertions select the legacy probe, while new transactional cases verify privacy refusal, predecessor ordering and common transaction identity for the two bounded fresh reads and result write. Production gate defaults, FIFO/head-wait and privacy semantics are unchanged. The PL-042 strict xfails were removed after the durable wake fix produced actual XPASS; every assertion remains. Pending-deletion fixtures now use actual ClientCustomerData for full Postgres qualification.

Final affected-path evidence: 57 provider-merge + 42 parity/deletion = 99 real-backend cases, zero skips/xfails; 70 merge units pass. Push and final explicit preflight 42 checks each; full pyright 0 errors,87,127 warnings retained. One exact-head CI snapshot: Backend emulator proofs SUCCESS;30success/21skipped/8running, so the whole PR is not called green.

The complete intermediate local emulator lane is retained: it exposed lifecycle_sim rejecting the mandatory nonexistent ADC-disabling path and Dream mark_dirty refusing its synthetic owner. Those two local harness failures remain open. Its two other failed sections were the obsolete strict XPASS markers and real-PG customer fixture mismatch, now repaired and requalified. An initial combined pytest command double-registered tests.conftest; the artifact runner now uses separate invocations like CI, with the failed collection receipt retained.

Production runner/cohort bindings and the broad first P1 remain open. The 37e historical focused349pass/1staging-failure and required431pass/3outbox-failures/9skip/3xfail remain unresolved; neither is reported as a final-head rerun. The prior workloads remain bounded historical evidence. Source readiness is false; no review, merge, serving/copy activation, production flag change or savings is requested.

Earlier source delivery and exact37e evidence follow (historical):

Dark batch job-store source preserves original paid admissions, privacy authority in Firestore, grouped customer completion and original per-record custody across Postgres and Firestore commits. Production selection remains absent: source readiness is false and copying/serving/activation remain held.

The latest integration retains immutable terminal-session evidence in the same SQL commit as fencing and capability retirement, then requires that evidence for mode-independent fenced-result purge. No session URL is copied into receipts or journal. Positive generations use the actual pinned retention delete/absence path; collision outcomes never authorize foreign deletion. Receipt-less originals remain unresolved. Final typed PG/journal retirement is still forbidden pending complete remote proof.

The cold copier validates every original journal version and retains custody before grouping latest images by original recording/admission. Real SDK bulk reads and one conditional commit per recording remove repeated authority reads within the existing 1.5-second page deadline. Separate recordings retain separate admissions; original tokens, epochs, lifetimes, suppression and checkpoint rules remain. Nontransactional enrichment enqueue now preserves its durable obligation on failed task creation through the existing rearm handler; explicit wake errors still propagate.

Exact published head: 37e2d3c3ba9c13e25d2707608a09476cda1933c7. Current main was normally merged; both budget histories and main's stronger workflow assertion are preserved. No applied/live SQL migration was rewritten.

Validation:

  • Focused emulator/private PG: 349 passed, 1 failed, zero skips. All 23 new terminal-receipt cases and 10 grouped-copy cases pass. The unchanged staging before-COMMIT crash replay exhausted its unit deadline before transaction begin; the SDK masked that error with rollback-no-ID. This failure remains unresolved, with its full receipt retained. Six earlier cold-page failures now pass.
  • Required nine-file integration: 431 passed, 3 failed, 9 applicability skips, 3 existing xfails, improved from five failures. Remaining failures concern requested wake time/coalescing versus the first-summary deadline cap. No deadline, retry, hold, refusal assertion or policy was weakened.
  • Required unit set 205, migration/held 11, wake units 24, storage/lake 270, compatibility 2,288, projection/provider 671, actual assignment/deletion integration 100, workflow regression 1, explicit replay-provider lane 31 passed. The replay lane uses unchanged test.sh timing guards and explicitly includes slow-marked cases; earlier deselections are not counted as passes.
  • Contention 2,000/2,000 leased, no double leases/errors. Bounded typed W4 2,000/2,000 settled, correct counters and 200 recording tasks. These are not fleet/budget/RC2 qualification.
  • Push preflight 42 passed; full pyright 0 errors, 87,127 warnings retained. Final explicit preflight also passed42 checks (310.13s) after the authorized locked restore; the prior missing-interpreter subprocess failure receipt is retained. No source changed during qualification.
  • One exact-head CI snapshot: all eight backend unit shards and aggregate succeed; Backend emulator proofs fails six provider-merge race assertions (42 pass). Both tests inject through the old fresh_pending hook; merged main can take the transactional fresh gate first. Path-specific regression repair remains required. No full-green claim or CI watch.

Actual source/runtime inventory and remaining first-review P1 work are recorded in backend/docs/jobstore/d-provider-integration-inventory.md and d-g2-source-checkpoint.md. Production runner/cohort/funding/failover bindings, original intake/staging/late-audio custody, remote C4, all-copy/final journal retirement, reverse certificates, account orchestration, paging/scheduling and full G2/P21–P25/fleet qualification remain open. Local resumable transport is not remote GCS qualification. R14 rollout dates remain conditional forecasts; no savings are booked.

All integration execution disables ambient ADC and remote PG settings and uses the demo loopback Firestore emulator plus private process-owned Unix-socket Postgres. The issue packet retains every failed/intermediate receipt.

Product invariants affected

none

Failure-Class: FC-split-mutation-authority

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-17T10:17:19.644305Z 94f58c1 New commits
ℹ️ About Codex in GitHub

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

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

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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 08e706636a

ℹ️ About Codex in GitHub

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

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

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

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

Comment on lines +80 to +82
from google.cloud import firestore
from database.batch_pipeline_privacy import assert_batch_write_allowed, mint_token, STRUCTURAL_REASONS
from database.batch_privacy_attempt import TOKEN_FIELD, token_version

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Move the new imports to module scope

backend/AGENTS.md explicitly requires “All imports at module top level — never inside functions.” This method introduces three function-local imports, and the new paths in postgres_store.py, pipeline_ledger.py, and testing/jobstore_cutover.py repeat the violation. Move these imports to module scope; where dependencies are circular, extract the shared definitions rather than hiding the cycle with deferred imports.

AGENTS.md reference: backend/AGENTS.md:L168-L174

Useful? React with 👍 / 👎.

settle()
with progress.unit():
purge_jobstore_owner(namespace, uid)
elif phase == 'ledger':

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Add the required conversation-lifecycle change note

This changes conversation-deletion behavior by adding ledger erasure, but the commit contains no note under backend/docs/listen_pusher_pipeline/changes/. backend/AGENTS.md requires a same-PR note for conversation-lifecycle changes. Add a dedicated note describing the purge/observer ordering, the dark rollout state, and the verification evidence; the jobstore checkpoint document does not satisfy the required location.

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

Useful? React with 👍 / 👎.

Comment on lines +126 to +127
except AdmissionChanged:
continue

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Include discovered redirect targets in the next A1 snapshot

When an allowing Firestore walk follows a source to a redirect target whose conversation fence is already closed, while the owner and source fences are open, A2 raises AdmissionChanged because it needs an exclusive lock. However, every retry snapshots the same original keys, which contain only the caller-supplied conversation IDs, so need_x remains false and all three attempts fail identically. This leaves otherwise-allowed work permanently inadmissible through that source even after privacy has been restored. Carry the discovered targets into the next A1 snapshot so a fresh walk can reopen them under an exclusive lock.

Useful? React with 👍 / 👎.

safe = (
value in {'standard', 'enhanced'}
if field == 'data_protection_level'
else value is True if field == 'private_cloud_sync_enabled' else value is None and field in fields

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Recognize map-valued migration status as a narrowing write

With the G2 coordinator installed, the ordinary database/users.py::set_migration_status write is incorrectly classified as non-narrowing: it stores a map, but _value() returns None for map values, making this condition accept it as though it were an explicit null. The live privacy walk rejects every non-null migration_status, whereas existing PG admissions remain usable because no owner fence is closed and check_work_write() does not reread Firestore. This permits work during a protection migration. Check the protobuf value type explicitly and accept only null_value as the safe migration-status value.

Useful? React with 👍 / 👎.

job = self._unit(conn, identity)
if job is None:
raise AuthorityRefused('queried unit disappeared')
self.fence.check_work_write(conn, job['owner_key'], job['admission'])

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Isolate privacy refusals from the rest of a claim batch

If any selected pending unit has an expired admission or a closed privacy fence, check_work_write() raises and rolls back the entire claim transaction, including leases already assigned to unrelated owners. The refused unit remains pending, unheld, and eligible for the same ordered query, so subsequent pulls repeatedly encounter it and can prevent healthy work from being claimed. Admission expiry alone makes this possible after 15 minutes without any deletion. Handle the refused unit separately, retaining its custody while removing it from the actionable pull set or routing it through re-admission, rather than aborting the whole batch.

Useful? React with 👍 / 👎.

Comment thread backend/database/jobstore/units.py Outdated
Comment on lines +48 to +49
acquire(conn, self.ticket)
self.fence.check_work_write(conn, owner, admission)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Make admission and claims acquire locks in the same order

When reopening a closed owner or conversation while pending work for that owner is being claimed, the two paths can deadlock: Fence.admit_from_authority() takes the exclusive owner advisory lock in A2 and then calls its persistence callback, where Units.admit() waits for the namespace authority row; meanwhile, Units.claim() takes that authority row first and then waits for the owner's shared advisory lock in check_work_write(). PostgreSQL must abort one transaction, and neither path retries the resulting database error—the admission loop catches only AdmissionChanged. Establish one lock order across the admission callback and queue operations so concurrent restoration and claiming do not fail this way.

Useful? React with 👍 / 👎.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 28f07cbcb4

ℹ️ About Codex in GitHub

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

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

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

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

Comment on lines +62 to +63
if family != 'users':
return None

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Close the PG fence for privacy-authority narrowing writes

With the G2 coordinator installed, advance_privacy_generation() in backend/database/batch_pipeline_privacy.py still bypasses the PG fence: it writes blocked/purging and advances the generation under batch_pipeline_privacy/{owner_key}, but this branch classifies that collection as non-narrowing. Consequently, purge_batch_owner() can commit its initial invalidation while existing PG admissions continue passing check_work_write(), which neither rereads Firestore nor compares its generation. Handle narrowing writes to this authority collection using its already-hashed owner key, so the existing invalidation API also revokes PG work before its Firestore commit.

Useful? React with 👍 / 👎.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e22cf950bc

ℹ️ About Codex in GitHub

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

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

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

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

Comment on lines +180 to +183
def publish(transaction):
self.authority.check(transaction, phases=('PG_OPEN',))
ref = self.ref('completion', identity)
previous = ref.get(transaction=transaction).to_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 Badge Recheck privacy in the completion publication transaction

With the dark Handoff path explicitly selected, an owner or conversation can be revoked after export() releases its PostgreSQL transaction but before publish() commits. This transaction checks only namespace authority, which remains PG_OPEN during an individual privacy change, so it still creates the completion document containing the old intent and result envelope after revocation. The earlier _guard() cannot fence this cross-store gap. Revalidate the live privacy authority and admission token inside the publishing Firestore transaction, as project() does, so a concurrent narrowing write prevents publication.

Useful? React with 👍 / 👎.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: aa1f38908f

ℹ️ About Codex in GitHub

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

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

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

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

Comment thread backend/database/jobstore/units.py Outdated
Comment on lines +230 to +232
conn.execute(
'UPDATE units SET admission=%s,privacy_generation=%s,hold_reason=%s,'
'lease_token=NULL,lease_until=0,due_at=NULL WHERE namespace=%s AND unit_id=%s',

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Keep provider handoff admissions consistent during restoration

For a Handoff-bound provider unit that expires or becomes privacy-deferred before its first claim, readmit() replaces the unit admission and releases its hold, but leaves queue_handoffs.admission unchanged. The restored unit can then be claimed, yet its final settlement always fails seal_recording()'s admission-equality check, rolling back the terminal result and recording counter. The handoff's original admission is also immutable under migration 0008, so retrying cannot repair this mismatch. Restore the recording-level handoff consistently, or explicitly refuse this unsupported restore before making the unit claimable.

Useful? React with 👍 / 👎.

Comment on lines +392 to +393
"ORDER BY (state='registered') DESC,lease_until,effect_id LIMIT 100",
(owner, conversation, conversation, before_seq, before_seq, janitor),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Rotate unresolved effects out of the bounded drain page

If an owner has 100 registered GCS effects whose terminal/absence proof remains unavailable, this ordering selects those same effects on every drain pass. They remain registered because the GCS branch skips retirement without proof, so later effects—including expired started vector effects—are never visited or converted into residue targets. The janitor's owner-level backoff does not change this within-owner selection. Add per-effect retry scheduling or pagination so unresolved GCS custody is retained without permanently starving other drainable effects.

Useful? React with 👍 / 👎.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 80c0d51859

ℹ️ 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".

queue_guarded = False
if queue is not None:
prepared = CommitRequest(prepared)
queue_guarded = await asyncio.to_thread(queue.prepare, prepared)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Dispatch blocking fence operations through the managed executor

When an authority coordinator is explicitly injected into the async Commit wrapper, this call—and the corresponding privacy prepare/acknowledge calls—runs blocking database operations on asyncio's default executor. backend/AGENTS.md requires awaited blocking work to use run_blocking(executor, fn) and assigns Firestore CRUD to db_executor. Using asyncio.to_thread() bypasses the repository's purpose-specific pool limits, executor observability, and managed shutdown. Route these operations through the prescribed managed executor instead.

AGENTS.md reference: backend/AGENTS.md:L270-L278

Useful? React with 👍 / 👎.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ea9884e97b

ℹ️ 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".

):
raise AuthorityRefused('provider terminal CAS lost')

return self.units.fence.complete(conn, self.owner, self.effect, self.admission, persist)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Use the same lock order for provider START and COMPLETE

In the explicitly injected provider path, a replayed FenceTicket.start() overlapping complete() can deadlock. start() calls _job() first, acquiring the namespace authority and unit row locks, then locks the effect through Fence.start(). This call does the reverse: Fence.complete() locks the effect before invoking persist(), whose _job() waits for the namespace authority. If COMPLETE acquires the effect while the replay acquires the namespace, both transactions wait until PostgreSQL aborts one; neither path retries database errors, so even a valid paid-result settlement can fail. Acquire the namespace/unit/effect locks in the same order on both paths.

Useful? React with 👍 / 👎.

Comment on lines +78 to +82
if (
token_version(token) is None
or (token.to_dict() or {}).get(TOKEN_FIELD) != self.admission['privacy_token']
):
raise AuthorityRefused('provider dispatch token changed')

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Refresh dispatch authorization after benign token rotations

With the provider handoff explicitly selected, any benign privacy-token rotation between admission and START permanently prevents this ticket from dispatching. For example, authority_tokens() rotates the owner's token when a legal hold is written, although Coordinator.classify() deliberately leaves the PG fence open and the live privacy walk still allows work. This comparison nevertheless requires the immutable admission's old token, so every subsequent START fails. Because Units.claim() has already assigned an attempt token, the next claim moves the unit into a vendor hold despite no POST having occurred. Obtain fresh E1 authorization bound to the original PG admission generations, as ProviderProjection._e1_admission() does, rather than requiring the original token to remain unchanged.

Useful? React with 👍 / 👎.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b9f707b6cc

ℹ️ About Codex in GitHub

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

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

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

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

Comment on lines +259 to +260
for claim in claims:
outcome = await run_claimed_provider(

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Isolate individual refusals within the claimed provider batch

With the typed runner explicitly enabled and count > 1, a refusal or transport error from one claim exits this loop before the remaining claims run. Units.claim() has already committed attempt tokens for every claim, so when those untouched units become eligible again, its elif job['attempt_token'] branch puts them into a vendor hold even though they never reached START or sent a POST. A single owner's funding refusal can therefore strand unrelated healthy work. Handle failures per claim, preserving the failed claim's original custody while continuing the rest of the batch.

Useful? React with 👍 / 👎.

Git-on-my-level added a commit that referenced this pull request Nov 15, 2026
…#25360)

Complete the Firestore-authoritative discovery index and its production
copy lifecycle. In explicit index mode, only due
leased/retry/result_ready reads use Postgres hints; Firestore retains
every transaction, claim and privacy decision. Warm SQL/socket
deadlines, first/periodic primary scans and live read/write kills
preserve fallback.

Production copying now resolves a canonical owner at every
current-document reread, applies a deterministic owner cohort and omits
shared control/GPU/pull-claim documents. Excluded, malformed, absent or
newly removed owners retire their copy. Captured reads and convergence
use the same policy. State-specific sampled due parity checks selected
primary-prefix coverage and validates every returned hint against the
current primary; it does not claim complete backlog coverage.

A bounded operator page fills historical copies or rotates through
retained copies after primary TTL deletion, including a dropped expiry
refresh. It never invents a TTL or deletes Firestore state. Explicit
read/statement/row/deadline budgets, warm transport deadlines, atomic
private target-bound checkpoints and a nonblocking single-writer lock
keep retries resumable. Copy retirement and synchronous privacy erasure
remain reachable with mirror mode/admission/write kills off.

## Product invariants affected

none

## Validation

- New cohort/admission unit suite: 256 passed.
- New bounded reconciliation suite: 26 passed; operator/checkpoint
suite: 55 passed.
- Production copy, existing mirror, index selection and seam unit
suites: 148 passed.
- Combined real loopback Firestore and Postgres run: 48 passed, none
skipped, covering production copy/cohort/retirement and sampled parity,
existing index deadlines/stale hints, and account/conversation copy
erasure.
- An initial integration run reproduced a tuple-key encoding defect in
sampled parity; converting the bounded observation to ordered
key/document pairs fixes it. The same real backend cases pass afterward.
- Independent source review found and reproduced mode-off queued upserts
and absent-row parity pollution. Both are fixed with regressions; 210
focused cohort/copy tests and the 48 real backend cases pass afterward.
- Full GitHub CI completed green on
6b1e2bd, including eight unit shards,
guardrails, emulator proofs and hermetic/stack suites. Current main
5b21b67 is integrated at 06b4621; all
43 local manifest checks and 496 focused isolated tests pass, with one
existing deselection, and independent exact-head review is SHIP. Full
substantive GitHub CI completed green on this exact combined head,
including all eight unit shards, guardrails, emulator proofs and
hermetic/stack suites; no failed/cancelled/pending checks in the
readiness snapshot. All 43 prior local manifest checks and normal push
gates passed at 6b1e2bd. Independent exact-head integration verdict on
d433ea5: SHIP; jobstore code, hooks, tests and fences remain unchanged
afterward. The only subsequent delta is the locally reviewed
retention-test import relocation below. Four affected isolated files
pass 185 tests with the timing guard active; the complete clock ratchet
passes 11 tests (overlapping prior sets).
- Repeated CI shard 4 CPU overruns were traced to the retention test
importing shared provider/model helpers inside its measured call. Move
that existing import to collection, preserving every assertion and the
unchanged 1-second guard. The two affected files pass 345 tests through
the CI-style isolated runner; the diagnostic profiled call drops from
1.405s to 0.0021s locally.
- The CI-style isolated 14-file unit runner passed 1205 tests; latest
interface, reconciliation, index and cohort checks passed 324 tests.
These overlap the other sets and are not additive.
- The new operator-only document-id page sites are registered with
reviewed body digests, and their read envelope is declared at the exact
collection site. All prior collection budget values are unchanged; the
1M/day envelope is planning-bound and requires supervisor accounting
before activation.
- Strict changed-file pyright reports zero errors; public bounded helper
contracts replace private cross-module access without suppressions. The
normal full pre-push checks passed on the activation source and are
repeated on the final integration head.
- Third-party image closure passes with the module-specific codec
import, avoiding an unintended package-barrel edge into unrelated
outbox/enrichment dependencies. Worker dependency locks and gate
allowances are unchanged.

## Rollout and rollback

The mirror foundation #25323 is merged. The source does not activate
production. A separately reviewed stdlib operator supervisor enforces a
canonical single-carrier installation, shared target daily reservations
and bounded child-process cleanup; all 45 local packet tests pass. It is
delivered on SCA-2288, with installation and production execution still
pending. The release executor must pin actual writer/deletion revisions
and targets, supervise a bounded rotation outside sweepable worktrees,
set and measure its accepted retirement lag/read/write/connection
budgets, verify backup retention and mode-off erasure, then admit an
initial deterministic cohort in shadow mode. Index ramp is leased,
retry, then result_ready, expanded only with state-specific
traffic/parity, action correctness, sweep freshness, rollback and
net-read evidence. Expansion belongs to the SCA-2288 integration owner
with the existing release executor; the next evidence review and
absolute budgets must be recorded before each activation. No arbitrary
soak interval is required.

Rollback discovery with JOBSTORE_INDEX_READS=off or shadow/firestore
mode; JOBSTORE_SHADOW_WRITES=off also disables index reads. Disable new
production copies with JOBSTORE_PRODUCTION_MIRROR=off. Keep the retained
target and deletion executor access, and continue copy retirement, until
all retained obligations retire. Source merge, runtime acceptance and
settled billing savings remain separate. #25215 stays frozen.

Runbooks: backend/docs/jobstore-discovery-index.md and
backend/docs/jobstore-production-mirror.md. Existing SCA-2288/SCA-2222
retain coordination; no second rollout owner or production authority is
introduced.

## Failure class

Failure-Class: none

This is a new explicitly selected discovery/copy lifecycle on the merged
mirror foundation. Unreviewed discovery methods, including ready_pending
and hold/completion/capacity queries, retain primary semantics. No
workflow, flag-budget policy or baseline allowances change.
@Git-on-my-level Git-on-my-level changed the title SCA-1959: dark G2 and typed queue source checkpoint (incomplete) SCA-1959: recover D ancestry and bounded privacy/custody repair (incomplete) Nov 17, 2026
Git-on-my-level added a commit that referenced this pull request Nov 19, 2026
#25630)

## Summary

Run retained jobstore-copy retirement from the existing Cloud Run
backend-integration Serving supervisor. Migration 0010 stores
target-bound cursors in Postgres; page mutations and locked
version/cursor compare-and-set advancement commit together. One
table/source runs per bounded round-robin tick after critical
maintenance, with a kill switch, shared normal pool, and counts-only
retirement/rotation telemetry.

Prepare the production target/context on the retirement host and every
source deletion executor: Cloud Run backend, backend-sync,
backend-sync-backfill and backend-integration; GKE backend-listen uses
its own backend-listen-runtime DB principal. The GPU
batch-pipeline-worker target uses batch-pipeline-worker, but that
process runs Pump, not Serving. Staging retains its own post-render
bindings without duplicate env names. The co-host env-diff guard
documents the production erasure bindings as listen-only: pusher mounts
no deletion routes or jobstore purge caller. The production-mirror doc
contains the exact caller/deploy inventory and CLI fallback.

## Activation and rollback

Copy and recovery-hint activation remain **off by default**:
JOBSTORE_PRODUCTION_MIRROR=off and BATCH_JOBSTORE_MODE=firestore.
Retirement defaults on only with a complete PG target and valid
data-plane context; it remains independent of copy kills. Mode-off
cohort exclusion can retire all retained copies during rotation. Primary
backfill requires the production mirror configuration. Missing migration
0010 skips safely with a metric; no boot migration occurs.

Release must apply/verify the schema and runtime DML grants separately,
verify actual executor identities/routing and mode-off erasure, measure
a complete rotation/lag and fleet connection budget, then approve mirror
and hint policy cohorts. In particular, verify the
backend-listen-runtime SQL user/grants. No production data/API access,
GCP tier, IAM change, gcloud write, deploy or merge was performed.

Rollback retirement with JOBSTORE_RETIREMENT_ENABLED=off; retain
JOBSTORE_PG_* and synchronous erasure until copies retire. The fallback
reconcile-page CLI keeps private checkpoints. The parked operator track
and PRs #25613/#25215 are unchanged.

## Budgets and state exits

Initial JOBSTORE_RETIREMENT_MAX_ROWS=10, MAX_PRIMARY_READS=20,
MAX_STATEMENTS=500, PAGE_SECONDS=3, INTERVAL_SECONDS=20; total tick
budget is 10 seconds. Before: no in-serving rotation or durable PG
cursor. After: one bounded table/source per supervised leader tick, with
normal-pool warmup outside the page budget and inside the total
allowance. Maximum page time is 3 seconds, well below the 60-second
advisory maintenance lease. Two normal sessions plus the existing
reserved erasure session remain the per-process ceiling; the erasure
connector retains its existing setup behavior.

The new cursor's terminal path is end-of-pass reset to NULL plus
passes/version increments and rotation_completed_at in the page
transaction. Errors roll back page and checkpoint. A failed table
rotates out so it cannot starve other tables. Rows are retired only
after a fresh authoritative absence/cohort exclusion, never by a
clock/lease TTL. Rotation lag is current time minus cursor last-pass
completion (creation before first pass), computed from bounded
cursor-row observations without copy-table scans.

## Product invariants affected

INV-MEM-4: canonical memory admission/promotion authority is unchanged;
the bounded copy and retirement worker never writes Firestore documents
or promotes canonical memory. Firestore remains the sole job
writer/claimant and privacy authority; no customer-facing wire contract
changes.

## Verification

All tests and type checks run through
/Users/dazheng/workspace/omi/bin/omi-heavy with
GOOGLE_APPLICATION_CREDENTIALS and CLOUDSDK_* unset. Local Postgres uses
a disposable Unix-socket test cluster and a synthetic primary.

- Focused pytest selection: **355 passed**, including **7 real-Postgres
tests** covering atomic page/cursor rollback, two overlapping leaders,
CAS refusal, budget rollback and migration idempotency/rollback.
- Unit: cursor scope/CAS/regression, same-transaction callback and SQL
accounting, target/context/kill/backfill gates, one-table fairness,
schema-missing no-op, warm/total budgets, supervisor-only leader
scheduling, private-registry metrics and rotation lag.
- Regression: copy-pool ceilings, production copy/cohort, CLI,
admission, staging fence, source env/flag budgets, query shapes and
deployment rendering.
- backend/scripts/pre-deploy-check.sh: 632 tests passed plus source-only
deploy validations.
- Feature registry, deployment secret boundary and cross-service deploy
contract passed (34 passed, 3 skipped in that source-contract suite).
Full Pyright: **0 errors** across 2317 files (existing warning output
retained). The seven-file Firestore guard set passed, including **608
query-shape tests**; worker runtime **56 passed** and co-host env diff
**92 passed**. **scripts/pr-preflight --pr-body-file passed all 52
checks** before push.


Representative exact commands (all wrapped in omi-heavy; paths from the
task worktree):

```bash
backend/.venv/bin/python -m pytest -q backend/tests/unit/test_jobstore_retirement_cursor.py backend/tests/unit/test_jobstore_retirement.py backend/tests/unit/test_jobstore_retirement_deploy.py backend/tests/unit/test_jobstore_connection_deadline.py backend/tests/unit/test_jobstore_reconcile.py backend/tests/unit/test_jobstore_reconcile_operator.py backend/tests/unit/test_jobstore_copy_connections.py backend/tests/unit/test_jobstore_production_copy.py backend/tests/unit/test_jobstore_migrations.py backend/tests/unit/test_jobstore_production_mirror_admission.py backend/tests/unit/test_staging_fence.py backend/tests/unit/test_runtime_env_sources.py backend/tests/unit/test_batch_stage_env_ratchet.py backend/tests/unit/test_flag_budget.py backend/tests/unit/test_jobstore_index_selection.py backend/tests/unit/test_batch_pipeline_recovery_metrics.py backend/tests/integration/test_jobstore_retirement_postgres.py backend/tests/integration/test_jobstore_migrations_postgres.py
backend/.venv/bin/python -m pytest -q backend/tests/unit/test_batch_pipeline_runtime.py
backend/.venv/bin/python -m pytest -q backend/tests/unit/test_verify_pusher_cohost_env_diff.py
backend/.venv/bin/python -m pyright -p backend/pyrightconfig.json --pythonpath backend/.venv/bin/python --outputjson
# From backend/ with its .venv/bin first on PATH:
bash scripts/pre-deploy-check.sh
# From repository root, using this body file:
scripts/pr-preflight --pr-body-file <body-file>
```

Failure-Class: none

This is a new maintenance/configuration capability, with no incident
failure class claimed.

🤖 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/25630?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/25630?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F25630&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. -->
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Closing under David’s R39 ruling, which retires the Python Postgres jobstore port. Keep the Cloud SQL instance pending review of the SCA-4373 coordination-store proposal. The instance disposition will be decided there.

@github-actions

Copy link
Copy Markdown
Contributor

Hey @Git-on-my-level 👋

Thank you so much for taking the time to contribute to Omi! We truly appreciate you putting in the effort to submit this pull request.

After careful review, we've decided not to merge this particular PR. Please don't take this personally — we genuinely try to merge as many contributions as possible, but sometimes we have to make tough calls based on:

  • Project standards — Ensuring consistency across the codebase
  • User needs — Making sure changes align with what our users need
  • Code best practices — Maintaining code quality and maintainability
  • Project direction — Keeping aligned with our product principles and locked invariants

Before your next PR, please skim:

  • PRODUCT.md — product north star
  • Product invariants — locked rules (shared chat, memory tiers, agent control plane, integrations, brand)

If this was declined for direction or taste, maintainers should cite an invariant ID or open a proposed one — ask if that citation is missing.

Your contribution is still valuable to us, and we'd love to see you contribute again in the future! If you'd like feedback on how to improve this PR or want to discuss alternative approaches, please don't hesitate to reach out.

Thank you for being part of the Omi community!

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