Repository navigation
fix(backend): run ledger drain independently - #12546
Git-on-my-level merged 10 commits into
Conversation
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
Move ledger cutover out of the timed-out maintenance tail into a bounded Cloud Run job with its own cursor and hourly scheduler. Failure-Class: FC-tail-work-starved-by-timeout-predecessor
03a30b1 to
27d7c58
Compare
There was a problem hiding this comment.
All reported issues were addressed across 20 files
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
Git-on-my-level
left a comment
There was a problem hiding this comment.
Thanks for this — clean diagnosis of #12535 (bounded drain code never entered because the 3600s maintenance budget is consumed by serial consolidation) and a well-scoped fix. The core move is sound and the safety invariants survive the extraction. Details below, one blocking item, several non-blocking notes.
Blocking: Backend unit suite fails on the new test file. All 5 tests in tests/unit/test_knowledge_ledger_drain_job.py pass, but test_entrypoint_executes_independent_drain burns 3.41s CPU against the fast-unit duration guard's 1.00s limit (4 passed then BACKEND-UNIT-FAILED-FILE … status 1). The cost is the importlib.util load of the job module inside the timed phase — _load_job() re-executes modal/knowledge_ledger_drain_job.py (which imports firebase_admin and the whole drain module) per test. Please hoist the module load out of the timed call phase (module-level fixture/lazy cache), or trim what the test imports. The repo's timing guard is the gate here, not a production defect.
What I verified and liked, file by file:
backend/utils/memory/knowledge_ledger_drain.py— the heart of the change and it's good:bounded_ledger_drain_inventoryscans a 20-docmemory_state/apply_controlcollection-group page (MAX_LEDGER_DRAIN_UIDS_PER_RUN = 20), skips already-ledger accounts, only picks uptransitioning_to_ledgerrows owned byknowledge-ledger-migration.v1, and_write_cursoris generation-fenced (transactional compare ongeneration) so overlapping executions can't clobber progress.fresh_rollout_authorizerpreserves the per-account/per-row JIT re-authorization exactly as the old cron tail did, publication still requiresremaining_live_legacy_count == 0and no revoked authority. Call sites matchrun_ledger_migration_sweep/publish_ledger_migration_cutoversignatures inknowledge_ledger_migration.py.backend/utils/memory/canonical_short_term_maintenance_cron.py— removal is complete and safe:run_canonical_short_term_maintenance_cronnow returns the maintenance summary directly, and the removed summary fields (ledger_migration_users/ledger_migration_rows) have no remaining consumers (modal/memory_maintenance_job.pyreads onlysummary.errors).backend/modal/knowledge_ledger_drain_job.py+backend/modal/Dockerfile.knowledge_ledger_drain_job— entrypoint mirrors the siblingdaily_memory_sweep_job.pyconventions (same_init_firebase, lazydatabase._client.dbimport, non-zero exit when a page reports errors).COPY backend/ .thenCOPY backend/modal/ .matches the existing image pattern..github/workflows/gcp_daily_memory_sweep_job.ymland..._auto_dev.yml— symmetric additions in both lanes: build → smoke viaruntime_image_contracts.py→ push → render/validate runtime env → deploy the second Cloud Run job → provision + validate the second scheduler. Deploy staysworkflow_dispatch+ admitted-release-SHA gated, which keeps this controlled.backend/deploy/runtime_env.yaml,runtime_env/_base.yaml,dev.overlay.yaml,prod.overlay.yaml—_baseshipsMEMORY_ENABLED: offdefault; overlays enable per stage; task timeout 1200s with--max-retries 1is sensible for a bounded page.backend/scripts/provision_daily_memory_sweep_scheduler.py— theEXPECTED_TARGETSdict generalization is the minimal correct change; identity mismatch still raises.backend/tests/unit/test_knowledge_ledger_drain.py— good contract coverage (cursor independence from the maintenance cursor, no advance before explicit commit, revoked authority never publishes, fail-closed on malformed writer_mode). A follow-up worth adding: a two-page resume test proving the secondbounded_ledger_drain_inventorycall starts after the committedlast_path(your_Queryfake already supportsstart_after).backend/tests/unit/test_legacy_memory_retirement_readiness.py— the new scheduler-args assertion keeps the retained-contract check honest.backend/docs/canonical_memory_architecture.md,backend/docs/runbooks/universal-memory-operations.md,backend/docs/subservice-internals.md— I checked the doc claims against the code (20-doc cap, cursor-after-page-return, per-boundary re-authorization); they're accurate, and the runbook renumbering is correct..github/failure-classes/FC-tail-work-starved-by-timeout-predecessor.json— fits the existing FC corpus schema; the violated-contract statement matches the incident.backend/runtime_images.json— manifest entry wires smoke/probe gates for the new image;smoke_environmentuses the same dummyENCRYPTION_SECRETpattern as siblings.
Non-blocking design notes (maintainer judgment wanted, not necessarily changes):
commit_ledger_drain_inventoryadvances the cursor even whensummary.errorsis non-empty, so accounts that errored this run are only retried after wraparound. Defensible (avoids one broken account poisoning the head of the queue forever) but worth an explicit maintainer nod since the job exits non-zero while still moving the cursor.- Inventory fails the whole run closed on any apply-control doc with a missing/unrecognized
writer_mode. Safe default — just confirm no legacy docs predate the field, or those accounts will block the page until wraparound. - The new scheduler reuses
memory-maintenance-scheduler@…as its target SA. If itsroles/run.invokergrant is scoped todaily-memory-sweep-jobonly,knowledge-ledger-drain-hourlywill 403 on first fire — the grant isn't provisioned anywhere in this diff, so it needs either a project-level grant or an IAM step in the deploy lane before the first prod run. - Unlike
daily-memory-sweep-job(whose prod overlay ships explicit default-off flags), the prod gate for this mutating hourly job is solely the shared JIT authority. That may be exactly right; it's a product call, not a code defect.
One process note: the Hygiene failure (firestore-query-coverage: baseline 62/102 vs inventory 73/113) is a known pre-existing baseline drift unrelated to this PR — no action needed here.
Leaving the workflow/deploy surface and the prod-gate/IAM questions for human maintainer review before merge; the code-level ask is just the test-duration fix.
by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.
…authorized Addresses the review on BasedHardware#12546. The fast-unit duration guard failed on `test_entrypoint_executes_independent_drain` (3.41s > 1.00s). The cost was never `main()` — measured directly, `main()` is 0.000s and executing the job module is 1.52s, since it pulls firebase_admin and the whole drain graph. Loading it at test-module import time moves that out of every phase the guard measures. `commit_ledger_drain_inventory` no longer advances the cursor when the page reported errors, so a failed account is retried on the next run rather than skipped until wraparound. Apply-control rows with no `writer_mode` now read as `compatibility` instead of failing the page closed, so accounts predating the field cannot block the head of the queue. Both deploy lanes grant the scheduler service account `roles/run.invoker` on the drain job before creating or resuming the hourly trigger; without it the first fire 403s. The drain resolves its Firestore client at call time via `get_firestore_client()` rather than binding the module-level client at import. Verification: `BACKEND_UNIT_TEST_FILE_LIST=... bash test.sh` over the three affected files — 15 passed, duration guard clean. `firestore_query_coverage.py --check-ratchet` exits 0 (the earlier failure was a stale baseline; this branch was 69 commits behind and main already carries 113/73). Failure-Class: none
|
Addressed every actionable review item in
Verification after the fixes:
The remaining physical proof is intentionally post-merge/dev-deploy: confirm the hourly trigger can invoke the job, content-free cursor counters advance, and compatibility accounts reach |
|
Both reds are fixed on Duration guard. The diagnosis in the review points at the call phase, but the cost is not there. Measured directly:
Also addressed, with tests:
One thing worth your judgment rather than mine: notes 1 and 2 pull in opposite directions. Not advancing on error is the safer accounting, but it does mean a permanently failing account holds the page until it is fixed. Note 2's default is what keeps that from being reachable through the old-row path; if you would rather have wraparound as the backstop instead, say so and I will flip it back. Verification: 15 passed across the three affected files under |
|
Re-reviewed on Verified on the new head, item by item:
Everything else stands as reviewed before: the maintenance tail removal in Docs note: What remains is judgment, not code: this admits a second mutating hourly Cloud Run Job into both deploy lanes, and in prod the drain's only gate is the shared JIT admission authority ( by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with |
Dismissed: the blocking concern (fast-unit duration guard failing on tests/unit/test_knowledge_ledger_drain_job.py) is verified resolved on b73cfa2 — the job module is loaded once at test-module import, keeping the module-exec cost out of the guarded phases; the three design notes (cursor-on-error, legacy writer_mode, run.invoker grant ordering) are also addressed with contract tests. Current assessment left as a comment on this head.
|
Independent verification pass on Core extraction is faithful. Tail removal is clean. Deploy lane mirrors the existing one. Both Docs note (these steer AI agents in this repo): One non-blocking observation: The remaining proof is the intentional post-merge dev-deploy confirmation of the hourly trigger. This review was produced by David's automated maintainer assistant. by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with |
undivisible
left a comment
There was a problem hiding this comment.
Verdict: APPROVE
Independent ledger drain is the right fix for #12535, and the safety model survives the extraction. Prior cubic / Git-on-my-level items look addressed on b73cfa2. CI is green on this head. I have not submitted merge from this review (lane is review-only / hold for Max’s stack).
What I checked
- Diagnosis matches the code: drain no longer rides
memory-maintenance-job’s 3600s consolidation tail. knowledge_ledger_drain.py: ≤20-doc apply-control inventory, dedicated generation-fenced cursor, commit only whensummary.errorsis empty, missingwriter_mode→ compatibility / invalid explicit → fail closed, JIT re-auth per account and at mutation/publication boundaries, cutover only whenremaining_live_legacy_count == 0.- Maintenance cron removal is complete; ledger summary fields have no remaining consumers in the job path.
- Deploy lane (manual + auto_dev): build/smoke/push → deploy drain job →
roles/run.invokerfor scheduler SA → provision/validate hourly trigger; ordering pinned by unit contract. - Runtime: base
MEMORY_ENABLED: off, overlayson; task timeout1200s,--max-retries 1. - Tests cover resume/wrap, stale generation, retry-same-page-on-error, revoked auth, call-time Firestore client, workflow IAM ordering.
Merge gates (process, not new code defects)
- Rebase (or merge) onto current
mainand re-green CI — branch is ~594 commits behind. Touchedruntime_env*files auto-merge cleanly today, but composed manifest / unit gates should be re-proven on a fresh tip. - Workflow / deploy sign-off — this admits a second mutating hourly Cloud Run Job; prod overlay enables
MEMORY_ENABLED. Labelsneeds-maintainer-review/workflow-reviewstill apply for the ship call. - Deploy ordering — drain removal lives in
gcp_memory_maintenance_job*; drain addition lives ingcp_daily_memory_sweep_job*. Prefer standing up the new job/trigger in the same window as any maintenance image rebuild from this change. (Today’s production behavior is already “drain never runs,” so a brief dual-miss window is not a regression vs #12535, but it should be deliberate.) - Post-merge proof (intentional) — hourly trigger invokes the job; content-free cursor advances; compatibility accounts progress toward
writer_mode=ledger.
Non-blocking follow-ups
- Accounts with remaining live legacy rows (100-mutation cap) do not error, so the cursor advances and they wait for inventory wrap (~20 docs/hour). Consider a sticky “remaining” retry path later if cutover latency matters at fleet scale.
- A permanently failing account pins its page (by design); that is alertable via non-zero job exits — keep an eye on it in the first days after deploy.
Not blocking
transitioning_to_compatibilityrows can be inventoried; publish/sweep owner CAS should fail closed (same class of behavior as the old unfiltered cron tail).
Add a default-off operational gate and require an explicit UID allowlist before the scheduled ledger drain initializes Firebase. Dev reads only the named owner apply-control documents and never advances the global inventory cursor; production remains disabled.\n\nVerification: 154 focused backend tests; runtime env composition and dev/prod workflow validation; backend formatting; compileall; diff check.
Keep the runtime entrypoint imports minimal and retain runtime validation for malformed allowlist values without pyright false positives.
Restrict the development manifest to the single QA owner until an explicit one-shot run is authorized. Keep production disabled and exercise the safe default in the drain manifest test. Failure-Class: none
Document the disabled dev and production defaults, the single QA allowlist, and the explicit one-shot override prerequisite. Failure-Class: none
…12802) ## Summary After an admitted account enters ledger mode, POST /v3/memories currently returns 503 because the manual save is classified as a compatibility writer. Route authenticated explicit user facts through the JIT knowledge ledger with a fresh ingress decision and opaque route capability. Keep external and connector writes on required processing, fence mixed or malformed batches before writes, and prevent closed or rejected retries from being reported as current facts. ## Product invariants affected - INV-MEM-3 - INV-MEM-4 - INV-MEM-1 ## Validation - 111 focused backend unit tests passed. - Firestore emulator direct-user lifecycle proof passed. - Shared backend emulator proof runner passed. - Source pyright passed for changed production modules and emulator script. Failure-Class: new Line-Count-Exception: backend/utils/memory/canonical_memory_adapter.py | 3705 -> 3742 | direct user ledger retry and lifecycle safety boundary plus emulator proof Line-Count-Exception: backend/utils/memory/memory_service.py | 3951 -> 4057 | direct user JIT admission and batch preflight boundary A retry of a closed or rejected content-derived identity returns 503 rather than resurrecting it; explicit reopen remains the lifecycle path. Semantic batch validation occurs before writes, but storage-level batches remain sequential as before. This source change does not enable a cohort or deploy production. It is the manual-write prerequisite for #12546.
Ledger migration currently runs after short-term maintenance, so a maintenance timeout can prevent any account from reaching ledger mode. Move migration into an independent, bounded Cloud Run job with its own scheduler, retryable inventory, fresh JIT authorization at mutation/publication boundaries, and generation-fenced cursor updates.
The job has a dedicated default-off switch and requires an explicit account allowlist. Development reads only the single QA owner account directly; production remains disabled with an empty allowlist. Scoped runs do not advance the shared inventory cursor. The job keeps a 1,200-second timeout, one retry, bounded per-account migration, and the existing cutover/privacy fences.
Validation: focused backend tests, runtime manifest composition, workflow contracts, and repository preflight. Dev deployment and live migration/sweep evidence are verified separately from CI; no production deployment or enablement is included.
Fixes #12535.
Product invariants affected: INV-DATA-1, INV-MEM-1, INV-MEM-4. The drain retains explicit data-plane routing, canonical mutation authority, and bounded migration/cutover checks.
Failure-Class: new
Runtime gate: the job remains disabled by default. Existing development jobs share customer Firestore with production, and both allowlisted identities are used by normal Beta clients. Do not execute migration against either shared account. Runtime proof must use a separately verified isolated dev data plane, include #12802, and pass dev readiness. Source merge does not admit migration work.