Skip to content

backend: an over-budget sweep day degrades instead of stalling, and the day's invocation is owned by its window - #14393

Merged
Git-on-my-level merged 5 commits into
mainfrom
fix/sweep-source-window-admission
Sep 17, 2026
Merged

Git-on-my-level merged 5 commits into
mainfrom
fix/sweep-source-window-admission

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Sep 17, 2026 •

Copy link
Copy Markdown
Member

Summary

The daily memory sweep treated a day that was merely too big as a day that was not ready. The completed-day reader returned incomplete when a day had more rows than max_conversations or more summary characters than max_summary_characters; the scheduler reported source_incomplete:<date>, never advanced the cursor, and gave no reason. One over-bound day stopped that user's sweep permanently.

Measured on the isolated JIT QA plane on 2026-09-17: after the fence fix (#14338) the sweep processed 2026-09-10 and 2026-09-11, then stopped for good at 2026-09-12 before any model claim, because an always-running desktop app had cut six four-hour conversations per day against a QA envelope of one. Production has the same shape at its larger bounds.

Fixing that safely turned out to require owning the sweep's at-most-once identity properly, because a bounded selection is a mutable input.

What changed

1. An over-budget day degrades instead of stalling. Eligible rows are ranked (structured summary before raw-transcript fallback, then longer summary, then later started_at, then conversation_id) and taken until the count or character budget binds. The day completes carrying truncated / rows_seen / rows_used / truncation_reason.

2. Eligibility is observed over the whole window, not just a page. A bounded projection scan ordered by started_at then __name__ reads only the eligibility fields for every row in the window before any content is read, so a still-processing row beyond the selection page keeps the day incomplete instead of being silently skipped while the cursor advances. Bounds are 2,000 eligible rows and 100,000 scanned projections plus one overflow probe; the incomplete decision is driven by eligible rows, so a day of mostly-discarded rows cannot stall an account. No new composite index.

3. The invocation identity is owned by the window, not by the selection. A 15-minute admission lease keyed on (uid, window, generations) alone — no dependence on selection, digest, or identity function — is committed before any identity is computed, and the identity is then durably bound for that window. Mutating rows afterwards cannot mint a second invocation. The input digest is bound at claim time, so changed inputs fail closed rather than re-dispatching. Onboarding gets the same treatment: stable source-owned identity, with the transcript digest supplied as input_digest instead of being baked into the id.

4. Locked rows never reach the provider. is_locked is checked in the projection scan and again at full read, and re-checked immediately before dispatch so a row locked between read and dispatch cannot be sent. A fully locked day completes and advances, which is deliberate — see Known gap.

5. Every failure is nameable. Content-free allowlisted reason codes reach the scheduler error and the QA receipt, and the permanent fence states (payload_expired, genuine post-dispatch uncertainty, pre_dispatch_exhausted) are now distinct instead of all collapsing to invocation_indeterminate, because they call for different operator investigations. One operator exit reuses the existing PR #14338 attestation machinery.

Rollout — read this before deploying

The identity function changes, and an old-code worker derives its id from its own snapshot, so it cannot be blocked by any point-in-time check the new code performs: a changed snapshot yields a different, still-absent id. An adversarial review produced that counterexample with a hermetic reproduction against the real old claim function, and an earlier "tombstone the legacy id" design was discarded because of it.

The admission lease gives every version from this one onward a common admission point, so future identity changes are safe by construction. It does not protect against pre-lease binaries. What protects this one transition is deployment evidence:

  • Production has never run this job. gcloud run jobs list --project based-hardware --region us-central1 returns four jobs, none of them sweep jobs; the only prod deploy path is .github/workflows/gcp_daily_memory_sweep_job.yml, which has zero runs ever; and no prod scheduler could trigger it. Prod's first deploy is therefore also the first deploy of the new identity, atomically.
  • Dev must be drained. daily-memory-sweep-job runs from an ENABLED hourly scheduler. Pause it, confirm no execution is in flight, deploy, then resume. A fail-closed startup preflight rejects recent unmarked pending claims as a tripwire, but it cannot see an old worker paused before its first claim — the pause and drain are what make this safe, and the runbook says so.

Known gap, deliberately deferred

A day whose rows are all locked completes and advances. If the user later pays, unlock_all_conversations clears the locks but that day is not revisited, so its content never reaches a summary.

An implementation of paid-unlock replay was written and then removed from this PR. Review found that publishing unlock in 100-row chunks made it non-atomic: with 101 locked rows, batch 1 commits a new source generation and cursor rewind, the hourly sweep dispatches day D, batch 2 commits another generation and rewinds again, and D dispatches a second time under a legitimately different identity — duplicate provider spend the fence cannot prevent by design. It also coupled the payment path to sweep metadata (ZoneInfo on an unvalidated user-supplied time_zone aborting the unlock transaction, leaving a user paid and still locked) and rewound the cursor without an aggregate bound.

Closing a rare correctness gap is not worth a payment-path regression in the same change, so the design is preserved in backend/docs/doc/developer/daily-sweep-admission-and-unlock.md as the starting point for its own PR.

Failure-Class: FC-batch-fault-domain-head-of-line-poison

Line-Count-Exception: backend/utils/memory/daily_memory_sweep.py | 5984 -> 6673 | whole-window eligibility projection scan, the window admission lease and durable identity binding, the locked-row re-check before dispatch, distinct permanent-fence reason codes, and the attested-skip operator exit

Product invariants affected

  • INV-MEM-1
  • INV-MEM-4

Cited because the change edits files those invariants lock. Candidate admission, authority ranking, and memory writes are untouched; the change is confined to which bounded set of finished conversations forms a day's input, how that day's invocation is admitted and identified, and how an incomplete source is named.

Evidence

Hermetic, Google credentials blanked, Python 3.11 via the repo venv:

pytest (7 sweep/agent/repair/operator/job/fixture files)  310 passed
pyright -p pyrightconfig.json                             0 errors
backend/scripts/check_workflow_contracts.py               passed
black --line-length 120 --skip-string-normalization       13 files unchanged
Firestore emulator proof                                  PASS

The emulator proof covers the new transaction shapes: admission, the startup preflight, the attested skip, and the locked-row projection.

Layer measured: unit tests, typecheck, and the Firestore emulator. Not measured: live deployment, provider calls, or production indexes — the QA plane cannot advance past 2026-09-12 until this merges and deploys there, which is the next step.

🤖 Generated with Claude Code

Review in cubic

Git-on-my-level and others added 5 commits September 18, 2026 02:21
…me every source-incomplete reason

A day with more finished conversations or summary characters than the sweep's
bound was reported as source_incomplete forever, with no reason, so one big day
stopped that user's memory sweep permanently. Rank and take a deterministic
bounded subset with visible truncation evidence, keep rows that are still
processing as the only eligibility-based stall, attach a content-free reason to
every incomplete outcome, and size the QA envelope to hold a real day.

Failure-Class: FC-batch-fault-domain-head-of-line-poison

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…urce selector

The workflow-contract gate rejects positional tuples of three or more fields.

Failure-Class: FC-batch-fault-domain-head-of-line-poison

Co-Authored-By: Claude Fable 5.1 <[email protected]>
… invocation by window, not by selection

Review follow-up. A bounded page let unseen unfinished rows slip past the
fail-closed gate while the cursor advanced, and a selection-derived invocation
identity could mint a second dispatch when the day's rows changed after a
possible provider call. Scan the whole window's eligibility fields (2,000-row
ceiling, named reason above it) before reading any content; key the invocation
by uid, window and generations with the input digest bound at claim time, so
changed inputs fail closed after a possible dispatch and only a certified
pre-dispatch release may bind a new selection; exclude locked rows; keep source
truncation evidence out of the agent-owned dictionary; skip oversized rows
anywhere in the ranking; allowlist reason codes.

Failure-Class: FC-batch-fault-domain-head-of-line-poison

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Commit a window admission lease before invocation identity computation, then
retain the bound invocation ID across leases, versions and mutable inputs.
Reject scoped live pre-lock claims at job startup. Onboarding now binds its
input digest separately from its stable source/window identity.

Unlock conversation batches atomically with source generation, cursor rewind
and replay handoff. Preserve historical stages and occupied canonical facts.
Reuse claim-bound repair attestation for skip-only recovery, including returned
and multiple historical owners. Separate eligible/scan ceilings and report
locked/contentless omissions. Document rollout limits and remaining UI-summary
and historical-conflict limitations.

Validation: 291 tests passed across seven sweep/agent/repair/operator unit files;
pyright 0 errors (6014 warnings); workflow contracts passed; Black 9 files clean;
loopback Firestore emulator passed admission, preflight, unlock and skip shapes
plus existing crash, wipe, generation, release and accounting proofs.
All Python used isolated nonexistent Google credentials and timeout 900.
No remote Omi calls, deployment, push or PR.

Invariants: INV-MEM-1, INV-MEM-4
Failure-Class: FC-daily-memory-sweep-fence
Restore conversation unlock exactly to origin/main and remove all sweep replay
handoffs, cache invalidation and canonical replay exceptions. Keep locked days
advancing; document the later-unlock gap and the follow-up design requirements.

Keep the cleared admission and stable-identity core. Make abandonment assert
worker termination and acceptance of lost output without denying past dispatch
or inventing empty accounting. Distinguish expired and exhausted fence states.
Recheck selected source locks at each daily-agent provider boundary, using
content-free projections and the existing claim-local dispatch certificate.

Wire the previously uncalled admission/skip emulator helper into main and
exercise the real Firestore privacy projection. No payment dependency remains.

Validation (invalid Google credentials, timeout 900, shared venv execute-only):
- Seven sweep/job/inventory/agent/repair/operator/strict-transaction unit files:
  310 passed in 17.33s.
- backend/.venv/bin/python -m pyright -p pyrightconfig.json
  --pythonpath .venv/bin/python (from backend): 0 errors, 5988 warnings.
- backend/scripts/check_workflow_contracts.py: passed.
- Black --line-length 120 --skip-string-normalization --check: 13 files clean.
- Firestore emulator localhost proof: passed, including admission overlap,
  pre-lock preflight, single-use abandonment and selected-row lock projection.
  Emulator stopped afterward.
- conversations.py byte-identical to origin/main; payment.py has no diff.
- Rebased offline onto local origin/main 591d701; no remote freshness claim.
- No live payment, provider call, Omi service, deployment, push or PR.

Invariants: INV-MEM-1, INV-MEM-4
Failure-Class: FC-daily-memory-sweep-fence
@Git-on-my-level
Git-on-my-level merged commit 0694d6b into main Sep 17, 2026
64 checks passed
@Git-on-my-level
Git-on-my-level deleted the fix/sweep-source-window-admission branch September 17, 2026 19:54
Git-on-my-level added a commit that referenced this pull request Sep 17, 2026
…sweep code requires (#14402)

#14393 raised QA_SWEEP_MAX_MODEL_CANDIDATES to 3 in both
backend/utils/memory/daily_memory_sweep.py and
backend/scripts/jit_qa_sweep_operator.py, but jit_qa_manual_operator.yml still
hardcoded 1 in the job env block and in the --update-env-vars string.

validate_qa_sweep_environment compares the running job's env against the code
constant, so every sweep-verify dispatch failed before doing any work:

  ValueError: QA sweep requires MEMORY_DAILY_MEMORY_SWEEP_MAX_MODEL_CANDIDATES='3'

Observed on execution daily-memory-sweep-qa-job-8kqzc against the QA plane at
0694d6b. The fail-closed validator worked as designed; this moves the two
stale literals.

check_workflow_contracts.py passed on #14393, so nothing pins this workflow's
sweep env to the code constants. Four values are duplicated between the
validator's required dict and the workflow; deriving them would close the class.

Co-Authored-By: Claude Opus 5 <[email protected]>
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