Skip to content

SCA-2195: park allowance-held recordings outside active sweeps - #25281

Merged
Git-on-my-level merged 11 commits into
mainfrom
agent/omi-control-codex-sol/ba3ada7ae522
Nov 14, 2026
Merged

Git-on-my-level merged 11 commits into
mainfrom
agent/omi-control-codex-sol/ba3ada7ae522

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

Allowance-exhausted recordings repeatedly cycle through retry and pending-work scans without being eligible to run. This change parks current allowance holds outside active discovery and releases them in capture order after an entitlement generation changes, through normal admission.

Issue: SCA-2195
Failure-Class: new

Published: 209d1147328c4b9d44764df9b983e91a7e304b70 was pushed normally to this PR's existing branch at 2026-11-14 14:50Z using existing authentication. The complete bounded pre-push gate passed on M1 Studio: 48 preflight checks, zero type errors (existing warnings), 795 selected unit passes / 86 existing expected failures, all subsequent hook steps and formatting. No source edits, force push or hook bypass. External CI has started and is pending; no green CI or SHIP is claimed. SCA-2197 round 2 of 2 proceeds on this exact published head with the assigned non-Sol DeepSeek V4.1 Flash reviewer. New commits invalidate its verdict.

Behavior and review scope

  • Current held / allowance_exhausted GPU retries enter allowance_held; recordings, obligations and history remain durable. Fair-use, provider, decisionless, allowed and real worker-failure recovery retain existing behavior.
  • Retry due scans, pending predecessors/fresh selection, retry-age samples, queue-age and timeliness active-state membership exclude parked rows. Held stock has its own hourly leader-only COUNT gauge and census entry, with monitoring exports.
  • Projection assignment/finish/follow-up and privacy projection sweeps already read result receipts that parked jobs have never produced. Quarantine/dead-letter, provider/vendor, record-pending, input-retention and artifact-cleanup sweeps retain their own state predicates. Explicit privacy erasure still includes held recordings.
  • Owner discovery hashes commercial and referral authority, effective entitlement/time transitions, UTC month and the UTC day when the optional backfill daily cap is enabled. Usage counters remain outside the generation. Both transient usage reasons retry before acknowledgement. Durable claims/cursors release oldest first through normal admission.
  • Shared CAS transitions live in the database layer; the controller imports are acyclic and at module scope. Conversation purge decrements/retire held-owner counts transactionally, including shadow refresh and repeat deletion.
  • The candidate integrates main c13e510, preserves owner cursor and allowance maintenance, both index families and metric exports, and regenerates the manifest. Cursor migration is 0007; allowance indexes are 0008. Migration loading is contiguous 1–8.
  • Migration dry-run prints counts only. Apply is resumable, idempotent and rechecks per-row CAS/privacy fences. Full sweep/version/migration details: backend/docs/runbooks/batch-allowance-parking.md.

Kill switch: BATCH_ALLOWANCE_PARK_ENABLED=off on backend-integration and every GPU worker. Default is on unless explicitly off. Rollback restores retry membership and retry clocks in bounded pages; retain the new controller until parked stock reaches zero. Discovery is limited to 20 owners per 30 seconds (about 55 minutes at 2,202 continuously held owners); rollback is gradual at up to 12,000 rows/hour.

Final candidate validation

On 209d1147328c4b9d44764df9b983e91a7e304b70, synthetic data and local stores:

  • Allowance integration with all three stores required: 62 passed, four applicability skips, including all 12 forty-held-row cases, mixed versions, migration resume/CAS/failure and ordered release.
  • Provider proof with simulator, Firestore emulator and real isolated Postgres required: 54 passed, no skips. Both selector modes assert that privacy/predecessor races actually ran.
  • Parked-job purge emulator regression: one passed, including repeat deletion.
  • Allowance authority/reset, measured read budgets, jobstore migration and serving configuration unit suites: 117 passed.
  • Metadata-aware preflight: all 48 checks passed, including all seven Firestore guard files, 588 query-shape cases, changed collection budgets and runtime image contracts.
  • M1 Studio normal publication gate on this exact head: 48 preflight checks passed, including all seven Firestore guard files and 588 query-shape cases; zero type errors (existing warnings); selected unit suites 795 passed / 86 existing expected failures. All post-unit hook steps completed and 38 changed Python files passed the pinned formatter. Git push exited successfully. The worker's three-store and focused receipts above remain earlier exact-head evidence; those integration proofs were not rerun during publication. Full external CI remains pending.

Connector dispositions for independent verification: #4572885182 promotional generation; #4572885186 reverse-layer import; #4572885189 module-scope/cycle; #4573177946 daily reset; #4573177949 transient usage; #4573177954 purge counts. All six have candidate fixes and passing relevant regressions; threads remain open for the independent reviewer.

Dry-run and release gates

Approved ro-prod metadata preview completed 11:53:22Z: 1,027,058 scanned; 998,102 retry/current allowance candidates; 28,956 active retries remain (273 fair-use, 28,683 not currently held); overdue retry would fall from 1,005,149 to 28,939. Merge-pending projects 2,815,875 → 1,817,773. Second local application changes zero; production writes zero. Estimated reads including prior aborted aggregation ceiling: about 1.071M, within approved 2.5M. This paged preview is not atomic; real fences can reduce applies. Eligibility is unchanged, so no duplicate production scan.

Measured release reads are 9/16/24 per row and migration 6/8/12 for no conversation/ordinary/two-redirect profiles. Planning reserve is 64 reads/row, 6,406/page, <65M for a 1M-row release burst plus metadata, and 64M for a separate 1M-row migration; combined <129M. This is headroom, not an enforced maximum. Longer redirects, contention, shadow refresh and repeated/daily bursts require remeasurement and budget acceptance.

Independent exact-head review, required CI, READY indexes and rollout-lead acceptance of the budget/latency/rollback must precede the first default-on deployment or apply. The release owner deploys the backend controller before GPU writers and applies the reviewed migration after explicit go. Never enable BATCH_PIPELINE_PROVIDER_BACKLOG_RELEASE_ENABLED. No merge, deploy, apply, activation or capacity action was performed.

Production acceptance remains open: both serving planes, automatic release for an entitled test owner, and matched full-day retry/requeue, reads per completed audio-hour and over-SLA evidence on SCA-2173. The constructed forty-held-row proof does not clear every production stalled owner; SCA-2015 owns residual head-shape verification.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 14, 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-14T16:25:29.248964Z 5697d47 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: 0b7810475a

ℹ️ About Codex in GitHub

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

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

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

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

def entitlement(uid: str, now: float, previous: str | None) -> tuple[str, bool]:
from database._client import get_data_plane_firestore_client

snapshot = get_data_plane_firestore_client().collection('users').document(uid).get(field_paths=['subscription'])

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 Include promotional entitlement changes in the generation

When the referral campaign is enabled, an owner whose exhausted Free-plan generation has already been acknowledged can claim promotional access without changing subscription: database/referral_campaign.py writes referral_campaign_grant, and get_user_valid_subscription() composes that grant into the effective paid entitlement. This read excludes the grant, so the generation remains unchanged and the early return prevents funded_allowance() from detecting the newly available allowance. Their recordings remain parked until the next UTC month or an unrelated subscription change. Include promotional authority and its time-dependent validity in generation discovery.

Useful? React with 👍 / 👎.

from google.cloud import firestore

from database.batch_pipeline_privacy import BatchPrivacyBlocked
from utils.batch_pipeline.allowance_hold import STATE, enabled, park

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 Remove the migration's reverse-layer dependency

The new database migration imports its state and transition implementation from utils.batch_pipeline.allowance_hold, reversing the explicitly prescribed backend dependency hierarchy. Move the shared persistence transition into the database layer, or put migration orchestration above that layer, so both callers can share the CAS behavior without a database-to-utils dependency. This violates the Import Rules in backend/AGENTS.md.

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

Useful? React with 👍 / 👎.

# indefinitely while a large owner's earlier page drains.
if job['allowance_held_at'] > owner['cutoff']:
return cursor, False
from utils.batch_pipeline.scheduler import Scheduler

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 Restructure the controller to keep imports at module scope

The new release callback imports Scheduler inside the transaction, contrary to the explicit module-scope-only import rule in backend/AGENTS.md; the new entitlement resolver and serving integration also introduce function-scoped imports. Since scheduler.py already imports allowance_hold, simply moving this import upward creates a cycle. Extract the shared release/parking primitives into an acyclic module and use module-level imports instead.

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

Useful? React with 👍 / 👎.

Git-on-my-level and others added 2 commits November 14, 2026 10:35
Address SCA-2197 round-1 findings and connector import-layer findings.
Shared CAS primitives live below scheduler and migration.

Failure-Class: new
Co-authored-by: multica-agent <[email protected]>

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 59f1edf138

ℹ️ 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 +44 to +45
value = [subscription, valid, promotions, grant_authority, effective, clock.strftime('%Y-%m')]
return hashlib.sha256(json.dumps(value, sort_keys=True, default=str).encode()).hexdigest()

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 Account for daily-cap resets before parking allowance refusals

When UNLIMITED_V2_BACKFILL_HOURS_CAP_ENABLED is enabled, batch admission passes backfill=True, and allowance_decision_reason() maps the daily-cap refusal to allowance_exhausted, so these jobs enter the new parked state too. However, this generation changes only at the UTC month boundary, not the daily reset. Discovery also calls funded_allowance() without backfill=True, so it can immediately release and acknowledge the generation while the daily cap is still exhausted; once admission parks the job again, the next day's restored allowance cannot release it. Preserve daily retry semantics for these refusals or track their daily reset separately.

Useful? React with 👍 / 👎.

Comment on lines +208 to +210
if allowance.reason == 'allowance_unavailable':
raise RuntimeError('allowance unavailable')
return current, allowance.managed

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 Retry discovery when usage cannot be trusted

If the first entitlement check after a plan or month change returns usage_invalid, this check treats it as a definitive denial and the controller durably acknowledges the generation. Repairing the usage record then cannot release the held recordings because usage is intentionally excluded from the generation and subsequent checks return early. resolve_transcription_allowance() explicitly includes both usage_invalid and allowance_unavailable in TRANSCRIPTION_ALLOWANCE_TRANSIENT_REASONS; handle both as retryable discovery failures so an untrusted usage lookup cannot strand recordings until another entitlement change.

Useful? React with 👍 / 👎.

Comment on lines +181 to +182
if not row.get('held_count'):
row['active'] = False

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 Update held counts when conversation purges delete parked jobs

When a user deletes a conversation containing parked jobs, purge_batch_owner(..., conversation_id=...) deletes those jobs through _delete_job() without decrementing their owner's held_count. The owner-level allowance_holds document has no conversation identity, so _belongs() excludes it from that purge. Consequently, this retirement check never deactivates the owner even after its last held recording is deleted: empty owners continue consuming metadata reads and slots in the bounded 20-owner discovery queue indefinitely, delaying release for owners that still have recordings. Update the hold count transactionally when purging an allowance_held job.

Useful? React with 👍 / 👎.

Git-on-my-level and others added 2 commits November 14, 2026 12:01
Handle transient usage, daily reset discovery and purge counts; repair provider race proofs and verify deep held predecessors.

Failure-Class: FC-policy-held-work-reenters-active-sweeps
Co-authored-by: multica-agent <[email protected]>
Merge main, preserve both discovery paths and metric exports, move allowance migration to 0008, and declare incremental purge counter reads.

Failure-Class: FC-policy-held-work-reenters-active-sweeps
Co-authored-by: multica-agent <[email protected]>
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Pipeline lead (14:57Z): round 2 was run on the published exact head; full verdict below. Custody, entitlement and migration confirmations requested in that note:

  • Parking never drops or commits a recording. Parking is one state transition (retry → allowance_held): audio_uri, immutable identity, result, attempt history, policy snapshot and obligation are retained, merge_pending is cleared and the live retry clock moved aside; no expiry, no deletion, no result write, no provider route. Integration tests assert the audio URI is unchanged and attempt == 0.
  • A released row re-enters normal admission. Release restores the retry clock, sets state=ready with compute_decision=unattempted and appends through the normal scheduler queue/control, so the worker's current funded_allowance/cap decision still authorizes compute; a still-exhausted owner simply parks again.
  • Migration 0008 is safe to dry-run and to apply in pages. Dry-run prints COUNT aggregations only (no document scan, no checkpoint write). Apply discovers ≤100 IDs per page, rechecks each row transactionally through the same CAS predicate (state retry, decision held/allowance-exhausted, no result/provider route, no live lease), catches privacy fences, and CAS-advances its checkpoint only after the page; a crash replays one page idempotently and a failed page never advances. 0008_allowance_holds.sql is additive indexes only, loaded contiguously after cursor 0007; it applied in the isolated Postgres harness here, and production apply was not executed.

Production acceptance remains outstanding on SCA-2195; SCA-2198 stays parked. The blocking item in §1 needs a corrective commit and a fresh exact-head review (no third round, no verdict carryover).


VERDICT: FIX — exact head 209d1147328c4b9d44764df9b983e91a7e304b70, review round 2 of 2.
Reviewing model: DeepSeek V4.1 Flash (agent M1 Studio OpenCode (DeepSeek V4.1 Flash), provider morph, model ID morph-dsv41flash-1017).

All six connector findings and both round-1 findings are verified fixed in code and in tests. One new blocking defect exists at this exact head: a required CI check fails, caused by the import weight this change adds.

1. Blocking: exact-head CI fails the fast-unit duration guard

gh pr checks on 209d1147 (snapshot 15:06Z): 39 pass, 2 fail, 1 pending (Analyze (python)), 27 skipping. The failures are
Backend unit shard 8/8 and its aggregate Backend unit suite (4 s). Assertion-wise nothing failed; the repo's CPU duration guard did:

  • tests/unit/test_batch_upload_coalescing.py::test_supervisor_drains_existing_holds_while_producer_off[true] — 2.30 s CPU vs the 1.00 s fail limit (call phase; warn 0.10 s). The test PASSED and was then failed by the guard (BACKEND-UNIT-FAILED-FILE).

This is not environment-only. With the guard forced to report (BACKEND_FAST_UNIT_FAIL_SECONDS=0.001) I measured the same node repeatedly:

  • head 209d1147: 1.10 s / 1.14 s / 1.46 s (always over the 1.00 s fail limit)
  • base c13e510: 0.57 s / 0.89 s / 1.11 s

Cause is precise: backend/utils/batch_pipeline/serving.py now imports utils.batch_pipeline.allowance_hold at module scope, and that module imports utils.subscription only for TRANSCRIPTION_ALLOWANCE_TRANSIENT_REASONS. utils.subscription is absent from serving's import graph at base and present at head ('utils.subscription' in sys.modules False → True). Cold import of utils.subscription costs 2.5 s CPU in this environment; the test imports serving inside its call phase, so the file-isolated runner charges that graph to this first test. The new edge tipped a borderline test over the blocking limit.

Narrow remedies (either is sanctioned by the repo):

  • move the two transient reason strings to a light config//policy module and have utils.subscription re-export them, so allowance_hold does not import utils.subscription at module scope (preferred: it restores the pre-change import graph), or
  • record that node ID in backend/tests/fast_unit_duration_allowlist.txt, whose own header covers "first test of a file amortizes that process's module import".

Because the contract has no third round, any corrective commit needs a fresh full exact-head review; the FIX verdict does not carry over.

2. Connector findings — all six fixed

  • #4572885182 promotional entitlement generation — fixed. generation() hashes the commercial subscription, its validity, campaign enablement, the raw grant authority (campaign_id/status/starts_at/ends_at/paid_coverage) and the shared effective_subscription_payload projection plus the UTC reset period; entitlement() projects both subscription and referral_campaign_grant; users.get_user_valid_subscription(include_promotions=True) is the admission authority that composes the grant, so a claim, extension, scheduled start/expiry or paid-coverage edge now changes the generation and releases. Unit tests cover claim release with the real discovery resolver, extension acknowledged once with usage-counter noise excluded, scheduled activation/expiry, and both paid-coverage edges.
  • #4572885186 reverse-layer import — fixed. database/batch_pipeline_allowance_migration.py now imports only google.cloud.firestore and database-layer modules; database/batch_pipeline_allowance_hold.py has no utils import; Scheduler imports the database module. Hierarchy is database → utils, not reversed.
  • #4572885189 function-scoped imports/cycle — fixed. scheduler.py imports the database transition module at module scope; allowance_hold.py imports Scheduler at module scope; serving.py imports both at module scope. The graph is acyclic (database module imports no utils; scheduler does not import utils.batch_pipeline.allowance_hold). Exercised by the suites below. (Its module-scope utils.subscription edge is the blocking import-weight issue above, not a cycle.)
  • #4573177946 daily-cap reset generation — fixed. The reset period is the UTC day when UNLIMITED_V2_BACKFILL_HOURS_CAP_ENABLED is on and the UTC month otherwise, so a re-parked day-cap refusal is released at the next UTC reset; normal admission remains authority and may re-park it once per day. Verified by unit test (test_reparked_daily_cap_refusal_releases_after_utc_reset) and by the generation test. Cap stays default-off; when it is enabled the daily reoffer applies only to cap-refused jobs whose funded allowance is available, and the runbook requires cost remeasurement for repeated daily bursts.
  • #4573177949 transient usage — fixed. entitlement() raises when funded_allowance() returns either TRANSCRIPTION_ALLOWANCE_TRANSIENT_REASONS member (allowance_unavailable, usage_invalid), so no generation is acknowledged and the owner is retried; test proves no acknowledgement then a release on retry.
  • #4573177954 purge held-owner counts — fixed in code. _delete_job reads the owner hold counter inside the same erasure transaction only for allowance_held, decrements it, sets active by the remaining count and refreshes the shadow; purge_batch_owner includes allowance_holds in the owner table walk; a repeated purge returns early on the missing job, so it cannot double-spend. The emulator regression asserts 2 → 1 → 0, active True → False and an idempotent repeat. I did not execute that emulator test myself (see limitations); the head's CI Backend emulator proofs job passed.

3. Round-1 findings

  • P1 referral authority: resolved as above (real grant read + shared effective projection + time transitions).
  • P2 read envelope: resolved as a disclosed planning envelope. Budgets are now 64 reads/row and ≤6,406/page, with the combined release+migration disclosure (<129M). Real FirestoreTransaction/scheduler/flush measurements are 9/16/24 release reads and 6/8/12 migration reads including discovery; I reproduced all six measured cases. These remain planning headroom, not an enforced maximum, and the rollout lead's acceptance is still required.

4. Independent verification on this head

  • Allowance generation + measured-read unit suites: 21 passed (includes the six actual-transaction read cases).
  • Affected batch unit set (scheduler, metrics, pump, capacity, timeliness, lifecycle, monitoring contract, unit policy, terminal poll skip, admission backoff, allowance): 747 passed, 86 xfailed; 4 setup errors only because this review environment lacks the Redis guard's Lua/fakeredis support (environment, not product).
  • Allowance integration with OMI_REQUIRE_STORE_BACKENDS=sim,postgres: 40 passed, 41 skipped (emulator-only). Postgres is a real throwaway cluster created by initdb; all release, parking, kill-switch, mixed-version, privacy-fence and checkpoint cases ran there.
  • Store/recovery conformance (sim + real Postgres): 200 passed, 109 skipped (emulator-only).
  • Firestore query-shape cases: 588 passed.
  • Firestore index/manifest guards: 70 passed.
  • Own probe (not in the repo): release retires the owner (held_count 0, active false, excluded from the due query) and returns rows to ready; with the switch off the rollback restores retry, decrements and retires; an unchanged generation performs no funded-allowance evaluation.
  • Migration loading is contiguous 1–8 (cursor 0007_ready_owners, allowance 0008_allowance_holds); 0008 is additive indexes only and was applied by the Postgres harness.
  • Diff vs main c13e510 is 50 files, all inside the allowance-parking surface, its tests, indexes, budgets, census, metrics/export and runbook. No firmware/CV1 or backfill-hours-cap implementation path; the earlier scope concern is resolved.

5. Reviewed but deliberately unchanged (verified)

Parked rows leave state=retry and merge_pending=true membership, so retry due scans, pending/fresh predecessors, retry-age, queue-age and timeliness active/uncommitted lists cannot see them; the held gauge is a separate hourly leader-only COUNT exported through Cloud Run GMP and both Prometheus bridges. Projection assignment/finish/follow-up and privacy projection walks read result receipts a parked job never produced. Quarantine/dead-letter, provider/vendor, record-pending, retention and artifact sweeps keep their own state predicates; explicit privacy erasure still reaches parked jobs (and now maintains the counter). Release appends through the normal scheduler queue and still requires ordinary admission. Rollback is bounded (100 rows/30 s ≈ 12,000 rows/hour), restores the saved retry clock and keeps a new controller until stock drains; kill switch is off-only parsed ("off" disables, other values keep it on with a warning).

6. Non-blocking residuals (report to pipeline lead)

  1. AllowanceHolds(...).tick() in Serving._maintain is not wrapped in try/except like every neighbouring subsystem. A failing discovery query (index not READY, transient Firestore error) aborts the rest of that maintenance pass and turns /metrics into a 500 for that scrape instead of degrading. READY indexes are a release gate, so planned rollout avoids it; wrapping the call is still the safer shape.
  2. Inactive allowance_holds documents are retained after retirement (no query or read cost; small unbounded metadata growth).
  3. Discovered planning numbers are envelopes: production billing, 55-minute discovery latency, rollback pacing and the 64-read reserve still need the rollout lead's explicit acceptance before default-on deployment or migration apply.

7. Limitations

  • No local Firestore emulator (no Java runtime in this environment): I did not rerun the emulator-only purge-held-count or Firestore migration cases myself; the head's CI Backend emulator proofs job passed, and I verified those paths by code inspection. Migration apply was not executed against production (correctly out of scope).
  • Production reads/billing were not measured; no production writes, index creation, merge, deploy, flag or capacity change, no recording deletion, no entitlement-rule change.
  • Pinned formatting was not re-run here (formatter not installed in this environment); the author's formatter receipt remains author evidence.

Bottom line: the parking/migration design, the six connector fixes and both round-1 fixes hold up on 209d1147, but a required exact-head check fails for a fixable import-weight reason. FIX, and production acceptance remains outstanding on SCA-2195; SCA-2198 stays parked.

VERDICT: FIX 209d114

Reviewing model: DeepSeek V4.1 Flash (M1 Studio OpenCode, provider morph, model ID morph-dsv41flash-1017). Exact head 209d114. Independent review; no code, merge, deploy, migration apply or production write performed.

Git-on-my-level and others added 2 commits November 14, 2026 10:15
…ance-hold tests

entitlement() now imports utils.subscription at its call boundary. The first
test to reach it paid that one-time import (0.66 s locally, 1.11 s under the
pre-push guard) against the 1.00 s per-test CPU budget. Test-only; no budget,
assertion or allowlist change.

Co-Authored-By: Claude Fable 5.2 <[email protected]>

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7bb56987a8

ℹ️ 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 +44 to +46
def migrate(tx):
job = tx.get('jobs', snapshot.id)
return park(tx, job, now)

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 Revalidate historical holds parked after a generation was released

When migration pages for an already-entitled owner overlap controller ticks, the first page can be released and its entitlement generation acknowledged before subsequent pages are parked. Those later rows contain historical allowance refusals, but park() preserves the acknowledged generation, and entitlement() returns early for that same generation without checking available allowance. Consequently, subsequent migrated recordings remain parked until another subscription change or period reset despite the owner having available allowance. A focused reproduction of two migration batches separated by a controller tick leaves the second recording permanently held across subsequent ticks. Distinguish historical migration decisions from fresh refusals so later migration pages receive a current entitlement evaluation.

Useful? React with 👍 / 👎.

Comment on lines +96 to +100
def _revoke(self, segment: str, now: float) -> None:
if not self.store.quarantine_fenced(segment, now):
return

def retire(tx):

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 Retire held-owner counts atomically with privacy quarantine

If the process exits or the retirement transaction fails after quarantine_fenced() commits, the job is already privacy_blocked but its owner's held_count is never decremented. Subsequent allowance pages exclude that job, and conversation purge only decrements counts for jobs still in allowance_held, so neither path repairs the count. A concurrent purge between quarantine and retire() produces the same leak because the job lookup then returns empty. Empty owners consequently remain active indefinitely and consume slots in bounded entitlement discovery. Update the count in the quarantine transaction, or persist a retryable retirement obligation.

Useful? React with 👍 / 👎.

Two union conflicts, both sides kept: .github/firestore-collection-budgets.json
(allowance entries and delivered-share entries) and
backend/database/batch_pipeline_indexes.py (allowance and delivered-share
index requirements). No product logic changed by hand.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@Git-on-my-level

Copy link
Copy Markdown
Member Author

Narrow independent confirmation at the exact head (gpt-6-luna via agentctl review pool) of the three commits after the fully reviewed 209d1147328c (import deferral, a test-only import, merge of main with two union conflicts): no BLOCKER or SHOULD-FIX. VERDICT: SHIP 5697d47abf28. CI at this head: 41 success, 22 skipped, 0 failed after one rerun (first run: three CPU-budget misses at 1.01-1.05 s, two in files this PR does not touch, and one Sync Cloud Tasks Stack Gauntlet timeout). Note for release: the delivered-share metric counts parked allowance_held rows as not delivered.

@Git-on-my-level
Git-on-my-level merged commit 963967a into main Nov 14, 2026
78 of 83 checks passed
@Git-on-my-level
Git-on-my-level deleted the agent/omi-control-codex-sol/ba3ada7ae522 branch November 14, 2026 18:00
Git-on-my-level added a commit that referenced this pull request Nov 14, 2026
…tion (#25268)

Provider backlog release must stay bounded independently of fresh work.
This integrates the existing hourly commit gate with current main,
preserving the merged transactional fresh selection, conditional owner
cursor/revision, stalled-head fallback, privacy/custody fences and
projection predecessor chain.

Integrated head: `e2906c45b3606b175b14dc525bf7562377d4beab`. Main
merged: `c5cf5a2b3dd2c3b3b638a562d066dafd92334753`. Successor of
`7bc3c7299a5e9eb1f2a16a653b819f043cf1910e`; its SHIP/CI do not apply to
this head. The only merge conflict was the flag registry: preserve both
meter and delivered-share entries and record count 285. Delivered-share
code, indexes, serving and dashboards match current main. Feature diff:
213 changed non-test lines. The automated P2 at predecessor 42a7077 is
confirmed and corrected: gate age/reach now sample the injected drain
clock AFTER transactional gate retrieval, on each retry. The predecessor
SHIP does not apply. Pipeline lead extended the cap by one narrow
confirmation and posted gpt-6-luna SHIP at this head. Normal successor
hooks passed; the single CI retry must finish green before readiness.

## Behavior and scope

The default-on meter reads an uncached six-field gate (`state`,
`rate_per_hour`, `reach_seconds`, `window`, `tokens_used`, `updated_at`)
inside the fresh-selection transaction. Missing, malformed, stale (180
seconds), closed, exhausted and out-of-reach gates refuse backlog. Only
the heartbeat determines the budget hour; merge token writes preserve
`updated_at`. Fresh commits neither read the gate nor spend tokens. A
metered result carries `backlog_release: true`.

Merge current main into the existing branch; no rebase. Integration
fixes update the merged flag count and explicitly select legacy
meter-off behavior in rollback/characterization fixtures. New
cross-store conformance covers token/result atomicity, fresh
independence and privacy refusal. Removed unrelated cursor budget
entries so the budget diff covers only the new gate collections. No
controller, heartbeat writer or migration is included: cursor 0007 is
retained; unmerged parking/0008 is separate.

## Service/version contract and release request

Ship CLOSED. Create no gate document, keep
`BATCH_PIPELINE_PROVIDER_BACKLOG_RELEASE_ENABLED=false` on all
committers and do not increase any rate. Absent/closed gate or rate zero
commits no provider backlog. Default-on code enforcement is not
activation.

Readers/writers: `OrderedMerge` on Cloud Run `backend-integration` and
GKE batch worker reads all six fields and updates only window/tokens,
preserving the heartbeat. Firestore/Postgres/simulator generic adapters
transport it. Postgres remains dark; actual Postgres acceptance remains
deferred under SCA-1959. Older versions ignore the document and obey the
legacy release switch. Result projection ignores the new result marker
and retains predecessor/privacy fencing. PR 4 must provide a single
fenced heartbeat writer and preserve current-hour token usage.

Rollback: `BATCH_PIPELINE_BACKLOG_RELEASE_METER_ENABLED=false` restores
the legacy default-off release switch; keep the provider release switch
false throughout rollback to prevent unmetered release. Before any
opening, Release must record actual serving revisions/images for BOTH
committing services. Parent SCA-2015 owns the release request and live
acceptance; this PR does not merge, deploy or authorize opening.

## Cost and limits

One global document serializes backlog commits. Added cost: one uncached
gate read per backlog attempt, one write per released row. For a ready
held head/no fresh rows: nine baseline reads and four writes on release;
seven reads/zero writes on refusal. Add up to two depth watermark reads,
commit-time privacy reads, cursor/owner discovery and transaction
retries. Explicit legacy false skips the gate read. Collection budgets
are planning envelopes, not measured/enforced limits. Observed process
counters may undercount lost replies/exits; durable tokens remain
authoritative. Reach uses capture end; zero is unlimited.

## Validation and confirmation

Pipeline lead's cap extension at17:48Z authorized exactly ONE narrow
independent confirmation, already launched by the lead from m5.
**VERDICT: SHIP e2906c4**, actual model
`gpt-6-luna` via agentctl review pool, posted17:54Z on SCA-2251 comment
`01a1db32-2683-7b10-884d-e94f9e0a50a4`. No BLOCKER or SHOULD-FIX. Narrow
diff `42a7077b35b3..e2906c4`, three files +65/-9. No extra
author-side reviewer or full review launched.

Confirmed by independent reviewer: post-read/post-parse sampling on
every retry; raising clock aborts without token/result; no
wall/monotonic mix; heartbeat-derived budget hour/token preservation;
fresh unchanged. Four new deterministic regressions fail under
predecessor sampling and pass now; reviewer focused suite57 passed.
Author canonical batch691 passed; actual
sim/Firestore-emulator/local-Postgres conformance60 passed, zero skips.
Normal hooks46 checks, zero type errors (existing warnings), push exit0
with zero leftover owned processes. Assertions, timing budgets and
allowlists unchanged.

Change-note assumption (nonblocking reviewer note): elapsed time must
not move backwards between drain start and post-read evaluation.
Production uses `time.monotonic()`, which satisfies it. A synthetic
backwards-moving clock could make a gate appear younger and is outside
this injected-clock contract. Recorded here and in the attached release
change-note addendum; no code/source commit changes the reviewed SHA.

CI disclosure: first attempt had two untouched CPU misses:
upload-coalescing supervisor1.08s and monthly-switch billing1.10s
against unchanged1.00s. Pipeline lead reran the failed job ONCE,
matching the permitted retry. That retry must pass at this exact head
before readiness; no further retry, threshold/assertion/allowlist change
or source edit authorized here. Existing timing-class follow-up is
separate from this PR.

Train2 merge order: #25281 first, then #25268. Any resulting mechanical
main merge needs the lead's confirmation at the new SHA; this SHIP does
not carry to a successor. Existing release request SCA-2262 only.
Provider release stays false, no gate creation/rate change. Actual
serving and live acceptance remain parent/release-owned.

Failure-Class: FC-backlog-release-shares-lane-with-fresh-work
Git-on-my-level added a commit to Git-on-my-level/omi that referenced this pull request Nov 14, 2026
Merges origin/main (27abe5b) into the package C branch of PR BasedHardware#25147.

Three textual conflicts, each resolved by keeping both sides:
- dual_store.py MIRRORED_TABLES: main added allowance_holds (BasedHardware#25281); this
  branch added pull_claims and merge_holds.
- test_store_conformance.py and test_jobstore_protocol_parity.py: both sides
  appended tests at the same place.

The merged tree fails test_every_serving_read_is_in_the_executable_parity_census:
main added Store reads after this branch was cut. The next commit covers them.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Git-on-my-level added a commit to Git-on-my-level/omi that referenced this pull request Nov 14, 2026
…parity and erasure

Main gained Store reads and one mirrored table after package C was cut
(BasedHardware#25281 allowance parking, the fresh gate, ready-owner discovery, the
finish backfill marker). The executable parity census must name every
serving read, and erasure of the Postgres copy must reach every mirrored
table.

- serving_parity: add ready_owners, allowance_owners, allowance_page and
  projection_finish_backfill_complete to the Store census, and
  fresh_first_pending and fresh_first_ready_pending to the transaction
  census. Frozen emulator and Postgres cases compare each one, empty and
  populated, including an allowance-parked row and its owner hold.
- dual_store.owner_rows: erase the owner's allowance_holds row by key, as
  merge_holds already is. The row was found only when the document named
  its owner; the erasure test now uses a hold document that does not.

Verified on this head with a loopback Firestore emulator and a throwaway
Postgres, OMI_REQUIRE_STORE_BACKENDS=all: test_jobstore_purge_postgres,
test_dual_store_firestore_postgres, test_dual_store_postgres,
test_store_conformance and test_recovery_custody_conformance: 423 passed,
7 skipped (cases not applicable to a backend). Unit: test_jobstore_dual_store
and test_jobstore_protocol_parity, 177 passed.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Git-on-my-level added a commit that referenced this pull request Nov 15, 2026
…CA-2288) (#25323)

## Current merge candidate and disposition — 2026-11-15

Current head: `6a0fe352db1220059456488b2ac752420ebd1c44`.

The m5 author remains the sole branch writer. This CI-refresh commit has
the same complete source tree
(`1ff77c8991d37e33879fd78b14717b85b2993155`) as lineage-fix commit
`e9eb225342c66f01cded3c61e4d52372c1955c8e`. The fix normalizes only
table-specific primary-side exceptions and preserves omitted intake
`repair_lineage` as a serving mismatch; its regression covers matching
without lineage and mismatching with it.

SCA-2339's RULING on SCA-2288 at 2026-11-15 00:37:42Z is **fix exactly
this and ship without another review**. It supersedes the older review
requests recorded below; it is not a claim of a new reviewer SHIP at
this head. Local results reported by the author: 824 unit/guard passes;
433 integration passes, 7 skipped. Terminal candidate CI at 04:47Z
passed all eight backend unit shards, the Backend unit suite, emulator
proofs, Hygiene and the configured required checks. Synthetic candidate
`e822681f9bda222a806e926d6d5104b764d354fe` includes repaired main.

This is a dark-mirror source handoff through normal release-owner
merge/train controls. Production admission and activation remain
separate. Copy-TTL retirement and owner-resolved cohort wiring remain
production-readiness requirements; no production namespace is admitted
by this handoff. No live evidence or savings is claimed. All older
commit/test/review receipts below are historical and do not identify the
current candidate.

> Replaces #25147: the same commits on a new branch. #25147 was opened
on 2026-11-12, and the UI author approval guard compares against the
base commit GitHub recorded then; with main merged in, that comparison
exceeds the guard's 300-file limit and fails closed. Against current
main this change is 26 files. Review history and verdicts carry over and
are summarised below.

## What changed and why

SCA-1807 package C extends the dark Firestore-to-Postgres mirror census
to pull claims and merge holds, adds executable comparisons through the
actual serving read methods, and makes cold-copy erasure independent of
mirror mode and namespace admission. Explicit namespace admission
defaults empty; the existing staging fence still refuses production.
Firestore remains the only claimant/writer; no D reverse copier or
serving writer is added.

Query observation is separately opt-in, uses a bounded queue, and emits
counts only. Frozen emulator/PG fixtures cover every serving read, empty
results, ties, null/missing values, cursors, owner-serialized phantoms
and deliberate drift. Capture repair_lineage retains its existing
Firestore-only retention boundary; this is explicitly a full-field
serving gate, not normalized away by the new checker.

## Product invariants affected

none

## How it was verified

- Locked Python 3.11 macOS environment via
backend/scripts/sync-python-deps.sh.
- Design's exact seven-file test.sh unit set: 196 passed; additional
seam/staging/projection and conversation-erasure tests: 123 passed.
- Real loopback Firebase emulator and disposable socket-only Postgres,
OMI_REQUIRE_STORE_BACKENDS=all, exact nine-file design matrix: 490
passed, 10 skipped, 3 strict xfailed, 5 failed. The five failures are
the existing Firestore enrichment outbox timing/coalescing and
wake-exception contract failures; unchanged base
faec7c5 reproduces all five. No
skips/xfails are hidden or changed to pass.
- `make preflight`: all 41 checks passed; the normal push hook also
enforces final-head checks and backend typing.
- Independent review completed in two rounds; round 2 cleared product
commit 7e11cad with no P0/P1/P2
blockers. The subsequent commit classifies both values of the
pure-observation argument in the existing Firestore query test driver
and corrects the instrumentation control’s registry classification to a
permanent configuration switch. The final typing-only follow-up adds a
local alias for the same bounded connection context manager; it changes
no runtime behavior. No third independent review was requested. Final
SHA, terminal logs and preflight result are attached to SCA-1807.

No live shadow evidence, activation, deployment, migration, privacy
serialization proof or savings is claimed. Source savings: $0. SCA-1697
retains D ownership; staging sizing/RC2, production admission, repair
lineage retention, cross-store privacy, full-field live parity and
settled billing remain gates. Details:
backend/docs/jobstore-dark-parity.md.

## Update 2026-11-14: main merged in, new owner (SCA-2288)

This PR now belongs to SCA-2288 (Postgres as a discovery index beside
Firestore; David's ruling of 2026-11-14 is on SCA-1959 and SCA-2288).
SCA-1807 was folded away; the original author no longer pushes here.

Historical integration: two commits on top of previously reviewed commit
`43ddb2ee26a9`:

- `117b10be02b1` merges origin/main (`27abe5bbf8f6`). Three textual
conflicts, each resolved by keeping both sides: `MIRRORED_TABLES` (main
added `allowance_holds` in #25281; this branch added `pull_claims` and
`merge_holds`) and two test files where both sides appended tests.
- `09eb5eab3071` covers what main added after this branch was cut. The
executable parity census gains `ready_owners`, `allowance_owners`,
`allowance_page`, `projection_finish_backfill_complete`,
`fresh_first_pending` and `fresh_first_ready_pending`, each with frozen
emulator and Postgres cases. Erasure of the Postgres copy now removes
the owner's `allowance_holds` row by key; before this it was found only
when the hold document named its owner, and the erasure test now uses a
hold document that does not.

Verified on `09eb5eab3071`, loopback Firestore emulator plus a throwaway
Postgres, `OMI_REQUIRE_STORE_BACKENDS=all`:
`test_jobstore_purge_postgres`, `test_dual_store_firestore_postgres`,
`test_dual_store_postgres`, `test_store_conformance`,
`test_recovery_custody_conformance`: 423 passed, 7 skipped (cases not
applicable to a backend). Unit `test_jobstore_dual_store`,
`test_jobstore_protocol_parity`: 177 passed. The earlier verification
section above describes historical commit `43ddb2ee26a9` and its base,
not the current candidate; the full nine-file design matrix was not
re-run on this head.

Independent review of `09eb5eab3071` (gpt-6-luna, read-only) returned
FIX with three findings, all fixed in `21f3a4f3080d`:

- Erasure of a copy that nothing refreshes re-copied GPU reservation
rows, which name the leased segment until release; such a copy now has
those rows deleted during erasure. A live mirror is unchanged.
- The projection-finish backfill, added on main after this branch was
cut, commits outside `Store.run` and did not refresh the mirror; it now
does.
- The frozen parity fixtures gain a completed backfill marker, a second
ready owner and a second parked row, with cursor cases.

Verified on `21f3a4f3080d`, same setup and the same five integration
files: 427 passed, 7 skipped. Unit (finish backfill, dual store,
protocol parity, shadow seams): 214 passed.

Review round 2 of `21f3a4f3080d` closed the backfill and fixture
findings and kept the GPU one open for a live mirror (a dropped copy of
the release would leave the erased segment's id in Postgres).
`6e0f28ce8783` fixes it at the root: the copy never holds
`gpus.segment_id` (`UNMIRRORED_TABLE_FIELDS`), comparisons compare what
the copy is meant to hold, and the cold-copy special case from
`21f3a4f3080d` is removed.

`22d3e4e792c4` re-pins the reviewed body digest of `backfill_table` (the
pre-push Firestore index guard caught the changed body; the function
still issues no query of its own). `2754ac3b8dd3` narrows a type in the
serving-parity comparison so the backend type check passes; no behaviour
change. Verified for `6e0f28ce8783`: the five integration files, 429
passed, 7 skipped, run before one more fixture case (`get` of a GPU row)
was added; the two files changed after that
(`test_dual_store_firestore_postgres`, `test_jobstore_purge_postgres`)
were re-run on the final tree, 108 passed. Unit (finish backfill, dual
store, protocol parity, shadow seams, postgres locking): 225 passed.

Review round 3 closed the GPU finding and found that the serving-parity
`get` comparison stripped the field from both sides, so a stale Postgres
row would read as a match. `73b4c9799a58` strips the primary side only,
with a frozen case that proves a stale row is a mismatch.

Historical validation on commit `73b4c9799a58`: the five integration
files, 432 passed, 7 skipped. Unit, including the Firestore query-shape
guard: 767 passed.

CI on `73b4c9799a58` failed one unit shard in
`test_reason_label_enums.py`: the serving-parity counter took a plain
string as its outcome label. `ad8c13c81d2c` declares the four existing
outcomes as an enum passed through `reason_label()`; values are
unchanged. The other seven unit shards and the emulator proofs passed on
`73b4c9799a58`.

The board review on SCA-2288 of `ad8c13c81d2c` found that observing
`projection_finish_backfill_complete` went through `PostgresStore.run()`
(its own connection and a `FOR UPDATE` on the control marker).
`b067fc016e8f` reads the marker on the observer's bounded connection
with a plain read, with a unit test that fails on a serving transaction,
a new connection or `FOR UPDATE`. Verified on `b067fc016e8f`: unit and
guard files 824 passed; the five integration files 432 passed, 7
skipped.

The second look on SCA-2288 (Kimi, historical review commit
`b067fc016e8f`) found that the serving-parity `get` comparison also
removed `repair_lineage` from the primary side, so an intake with
lineage compared equal to a copy without it. `e9eb225342c6` takes off
only the GPU reservation's segment id; a frozen case proves the lineage
omission stays a mismatch. Verified on `e9eb225342c6`: unit and guard
files 824 passed; the five integration files 433 passed, 7 skipped.

Still dark: no namespace is admitted by default,
`JOBSTORE_SHADOW_QUERY_PARITY` is off, and nothing here serves a read
from Postgres. Historical review scope (superseded by the SCA-2339
ruling below): the merge delta and the commits after it (`09eb5eab3071`,
`21f3a4f3080d`, `6e0f28ce8783`, `22d3e4e792c4`, `2754ac3b8dd3`,
`73b4c9799a58`, `ad8c13c81d2c`).

## Tests

Regression and frozen-query cases extend
test_dual_store_firestore_postgres.py, test_jobstore_purge_postgres.py
and test_store_conformance.py. Golden harness claim forwarding now
exercises the same mirror seam as production. No authoritative behavior
or golden outputs change.

## UI evidence

UI-Evidence: none -- backend source only

## Failure class

Failure-Class: none
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