Skip to content

perf: maintain idempotent monthly usage totals - #23397

Merged
Git-on-my-level merged 17 commits into
mainfrom
lane/fs-p3
Oct 24, 2026
Merged

Git-on-my-level merged 17 commits into
mainfrom
lane/fs-p3

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Oct 23, 2026 •

Copy link
Copy Markdown
Member

What changed and why

Monthly allowance refreshes repeatedly scan hourly_usage (caller #6, about 42M reads/day in the sprint's latest-hour snapshot). Maintain five monthly counters and daily subtotals in the same transaction as hourly usage and its existing once/partial receipt. Warm full-month and since-day lookups read one document. Absolute history overwrite, admin reset and historical deletion atomically invalidate the total; first use rebuilds from hourly source rows. Legacy anomalies retain the existing query.

Every new aggregate creator binds erasure authority to publication: ordinary, once-key, absolute, admin and migration writers use the existing external_write_fence and require a user root inside their transaction. Authority reads precede all receipt/source/total writes. Rejected publication leaves receipts untouched. Existing batch projection completion/partial transactions reuse their deletion/root/privacy checks. Lead approved this strengthening in ANX event:ev_5e7c48e900024551f307ab9c3e254fd7.

Usage publication refusals are non-fatal to user-facing pipelines. The shared utils.analytics.record_usage composition boundary catches the refusal outside the transaction: conversation/transcript/audio processing completes while hourly/monthly counters and the once receipt remain uncommitted. A typed missing-root refusal is distinct from a deletion/destructive-operation refusal in omi_fallback_total and matching fixed-field logs (component=usage_publication, from_mode=publish, to_mode=skip, outcome=degraded, reason usage_root_missing or usage_fence_blocked); no UID, content or exception text enters labels/logs. All user-facing source writes use this helper. Direct admin/migration operations keep their refusal semantics. Cold reader rebuild already returns to the hourly query on root absence; no other production user path gains a root dependency in this PR.

Hermetic regressions cover a root absent before sync admission, root removal immediately before publication, pending/completed deletion and ordinary live-account once replay. They require completed sync, the persisted conversation/transcript, no aggregate/usage receipt on refusal and an incremented bounded counter. Deletion still returns 403 for HTTP polling. The Firestore fake now preserves subcollections during root deletion, matching Firestore; a harness self-test checks repeated deletion without recreating the root.

Rollout and rollback

Writer maintenance ships ON. Reader usage_month_total remains 0 because mixed-version writers can undercount paid/Free allowance. Lead owns merge, deploy and ramp. Target writer train: 2026-10-24 08:00Z, cutoff 07:30Z. Deploy every writer (listen → pusher → Cloud Run → desktop-backend, plus operator/migration tooling); verify actual serving identities/traffic and drain old jobs. Choose a common FSR_USAGE_MONTH_TOTAL_EPOCH, then 5% for two hours with zero synthetic parity mismatches, no p95/5xx regression and no contention errors. Lead/reads loop expands to 100%.

The original 08:00Z full-ramp deadline conflicts with an 08:00Z writer train plus the required hold. Proposed replacement: 2026-10-24 12:00Z, pending lead acceptance. Report any writer/parity blocker. Details: backend/docs/monthly-usage-totals.md.

Kill switch: usage_month_total:0, preserving other levers. Writers continue maintenance. After rollback to any old writer, change the epoch on all readers before re-enabling. Epoch wiring uses existing manifests/renderers; no new workflow.

Attribution and net economics

Origins: job:usage_month_total_read, job:usage_month_total_rebuild, job:usage_month_total_fallback. Grade all three alongside original monthly and writer caller origins. Up to 40M/day gross reader reduction is modeled, not measured. Previously unfenced writer/replay attempts now add three point reads (deletion marker, destructive gate, root) per commit attempt. If their daily count is W, subtract 3W plus cold-seed scans/point reads and fallbacks from gross reduction; account separately for one added total write per accounting commit. Retries and existing outer fences may add further reads. Example: W=1M/day implies at most 37M/day before those other costs. W and realized net saving remain unmeasured. Funded read_month and plan/shadow readers retain their existing paths.

Product invariants affected

INV-MEM-4: backend/deploy/runtime_env.yaml wires the epoch; canonical memory intake/promotion keeps its authority. Existing deletion fences are strengthened by transaction-bound reuse under the lead's explicit ruling. Free-plan allowance policy, authorization, transcripts and speaker labels retain their behavior.

Validation

  • Latest integration head 9efacbc5723b866a598c061986d8718d960071d6 includes main 0d302a99fe (perf(memory): reuse atomically versioned released query projections #23402) and 251892e223 (perf(sync): reuse snapshots within read-only operations #23393). Only adjacent feature declarations conflicted. All monthly/snapshot/released-memory declarations and query proof registry entries are preserved; the feature registry keeps its existing 2026-10-22 date. The reviewed safety code and regressions are unchanged from safety commit 162181c8d8.
  • Normal integrated-head commit/push hooks passed; evidence nonfatal-main2-push.log. No workflow, timing budget, test selection, skip hatch or force-push change. Live exact-head checks are authoritative: require every expected backend check, all six unit shards and aggregate gate, full Hermetic E2E and merge gate, emulator proofs, guardrails, source closure, static contracts, metadata, hygiene and formatting to be present and successful before merge. The final gate certificate belongs to the lane handoff; no stale-head or check-presence-only certification.
  • Safety delta local evidence: 165 focused unit passes (47 sync-two-lane, 24 monthly total, 60 usage units, 34 user usage), 24 targeted hermetic passes, and 56 loopback monthly Firestore emulator passes. Eight ordinary/once refusal cases prove zero writes/committed usage receipt, exact bounded reason counter/log, and unrelated errors still propagate. Real finalize cases include a root absent before admission, root removed immediately before accounting, pending/completed deletion and live once replay; the job and persisted decoded conversation/transcript complete. Evidence: nonfatal-unit2.log, nonfatal-unit3.log, nonfatal-hermetic2.log, nonfatal-emulator2.log.
  • Full Hermetic E2E on predecessor f05a38addd: 135 passed, 3 skipped, 2 xfailed, 110.56s (job); emulator, other five shards and stack checks also passed. That head was not green: its first shard-3 attempt passed all 66 runtime-image assertions but failed a 1.17s / 1.00s CPU guard; one bounded same-head retry passed all test files and the CPU guard but failed the unchanged 723s / 720s wall gate. Earlier safety head 162181c8d8 failed wall 733s / 720s. No further identical reruns are queued. Main perf(memory): reuse atomically versioned released query projections #23402 then advanced and caused a real merge conflict; the latest head integrates that changed source/test input. Timing evidence: nonfatal-final-unit3-failure.log, nonfatal-final-unit3-retry-failure.log, card:fs-p3-ci-unit-wall-budget.
  • One requested safety delta Luna review: SHIP, no P0/P1, execution exec-express-mask-gap-tennis-atom-bundle; static production/caller review, nonfatal-luna-review.md. Later changes only corrected test setup/fake deletion semantics and integrated already-reviewed main. No review loop.
  • Earlier writer proof remains: fake 744 source reads to 1 warm read, identical five-field/day-cutoff results, three writer authority reads and one added total write. Monthly emulator proofs include all original creator erasure cases, receipt rollback/retry/replay and racing root/deletion inventories. Four historical broader projection failures also reproduced on then-main 4d236fd94e, tracked on card:fs-p3-projection-emulator-baseline; the broader suite was not rerun after the latest upstream integration.

All local checks use omi-heavy at nice 19 with targeted FILE_LIST or hermetic -k. No full local backend unit suite, production data, GCP or deploy action. Reader remains off until lead-owned writer/epoch gates; realized net savings are unmeasured.

UI evidence

UI-Evidence: none -- backend accounting/read-path change.

Failure class (fixes)

Failure-Class: none

The erasure defect was found within this unmerged feature; no shipped incident is classified. ANX owner/evidence: card:fs-p3, card:p88-monthly-usage-cold-seed-erasure.

🤖 Generated with Claude Code

Reuse hourly accounting commits and sync receipts for monthly/day totals.
Invalidate absolute corrections and reconstruct a cold baseline transactionally.
Gate readers until the fleet has the writer contract; retain hourly fallback
and an epoch for old-writer rollback recovery.
Materialization writes derived user data, so reuse the existing transaction
fence and require an existing user root before seeding. Preserve the old
read-only query when authority blocks materialization. Cover pending/completed
deletion, destructive gates, missing roots and a racing wipe inventory on the
Firestore emulator; the pre-fix snapshot fails both erasure regression cases.

@Git-on-my-level Git-on-my-level left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

FIX — Sol / P88, round 1, exact head dc362fc2166bf88503edcc3ba807b8731027eb74.

[P1] Fence cold-seed publication against account erasure — backend/database/monthly_usage_totals.py:123 (authority reads must precede the scan at :87). A monthly-cache miss now turns a previously read-only usage lookup into a write, but _rebuild reads only the monthly document and hourly rows before transaction.set(ref, data). It never reads account_deletions/{uid} or the existing destructive-operation gate. Therefore an already-admitted request can initialize this collection after deletion intent is persisted; if the recursive eraser has already inventoried or walked the total collection, the new usage metadata survives account erasure. The same problem exists when the parent document is absent: Firestore allows child documents below a deleted parent.

Reuse the existing account/destructive-operation fence inside the seeding transaction before any writes, and prove that pending/deleted intent and a live destructive gate prevent publication. Add a deletion-inventory race regression (including root-missing cleanup); keep the existing source fallback and authority policy. Ordinary hourly writers and accounting/receipt semantics need not change for this finding.

Reviewed the atomic counter/receipt maintenance, warm 744→1 read proof, day-cutoff parity, late/duplicate/partial/retry/reset and Free/paid resolver cases. Those establish the intended accounting mechanism, but do not cover this new reader-created write boundary. Reader rollout still requires the documented all-writer coverage and epoch gate; no fleet savings are established.

No merge performed. Re-review should cover only the fix delta.

Git-on-my-level and others added 6 commits October 23, 2026 13:54
Update the legacy sync fake with a canonical hour and user reference. Assert the receipt, hourly source and monthly increment are staged in the same transaction, and replay remains a no-op.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Bind existing deletion/destructive authorities and user-root existence to
the source, receipt and monthly total commit in every new aggregate creator.
Keep bounded corrections atomic and reuse projection session authority.
Cover rejected writes, receipt replay, SDK retry, rollback and wipe inventory
races with the loopback emulator. Include added authority reads in economics.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reuse the single-attempt serialized transaction fixture for cache invalidation
tests and enforce read-before-write ordering. Clarify the increment helper's
caller authority contract; writer economics include authority reads.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Hermetic dev-token authentication did not persist the account root required
by the approved transactional erasure fence. Seed a live account explicitly
for sync lifecycle and Watch recovery coverage, preserving the production
fence. Exercise actual finalization usage and once replay, then prove pending
and completed deletion and a root erased immediately before usage cannot
publish counters or commit the usage receipt.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Refresh the repaired main baseline before final sync regression validation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Git-on-my-level
Git-on-my-level marked this pull request as ready for review October 23, 2026 20:13
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-24T00:18:13.456068Z 76725e1 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.

Git-on-my-level and others added 4 commits October 23, 2026 16:19
Memory deletion leaves a completed destructive-operation authority outside
the user subtree. Remove that synthetic gate during per-test cleanup so the
live sync finalization cases actually start without authority markers, as
their assertions require. Preserve all production erasure checks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Refresh the repaired main baseline before final sync regression validation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Refresh the repaired main baseline before final sync regression validation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Catch erasure-fence refusals at the shared analytics boundary after the
accounting transaction aborts. Distinguish absent roots from deletion gates
with bounded fallback telemetry while preserving counters and once receipts.

Prove sync completion and retained conversation transcripts for root-less
accounts and deletion transitions. Match Firestore root deletion semantics
in the hermetic fake so child documents survive root removal.

Co-Authored-By: Claude Opus 5.5 <[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: 162181c8d8

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

from database._client import get_firestore_client
from database.firestore_read_origin import read_origin
from database.legal_holds import DestructiveOperationInProgress, external_write_fence
from utils.observability.fallback import record_fallback

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 Keep fallback composition out of the database layer

The new database module imports utils.observability.fallback, reversing the dependency hierarchy explicitly required by backend/AGENTS.md. Keep the accounting implementation in the database layer and compose fallback telemetry in a higher-level caller, or move the shared telemetry primitive into an allowed lower-level module while preserving its existing instrumentation contract.

AGENTS.md reference: backend/AGENTS.md:L163-L169

Useful? React with 👍 / 👎.

batch_size = 400
batch_size = 200 # hourly set + monthly invalidation, below the 500-write limit
items: List[Tuple[datetime, Dict[str, Any]]] = list(hourly_updates.items())
user_ref = db.collection('users').document(uid)

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 Resolve and inject the client in the converted batch writer

This transaction conversion adds new persistence code using the legacy db proxy without adding a keyword-only firestore_client parameter. backend/AGENTS.md explicitly requires converted database helpers to resolve get_firestore_client() at call time and support client injection; the new tests instead have to monkeypatch user_usage.db. Resolve one client at the helper boundary and use it consistently for the user reference, transaction, and publication fence.

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

Useful? React with 👍 / 👎.

if not plan.doc_ids:
return
from database.fsr_read_cache import writing
from database.monthly_usage_totals import commit_fenced

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 newly added imports to module scope

The new commit_fenced import is inside apply_reset, contrary to the explicit module-scope-only import rule in backend/AGENTS.md. The script's existing preference for deferred imports does not override that scoped guide. Move this newly introduced import to module scope; the same correction applies to the newly added function-local imports in the monthly-usage tests.

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

Useful? React with 👍 / 👎.

Include #23393 sync read-only snapshots and preserve both snapshot and monthly
epoch declarations. Regenerate the feature registry at its existing date.
The non-fatal usage publication safety delta is unchanged.

Co-Authored-By: Claude Opus 5.5 <[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: f05a38addd

ℹ️ 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 +156 to +157
class Transaction(Batch):
"""Single-attempt serialized writes; retry/erasure semantics use the emulator."""

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 Reuse the required strict Firestore transaction fixture

The new monthly-accounting unit tests exercise document reads and transactional writes through this bespoke fake, but backend/AGENTS.md explicitly requires tests.unit.fixtures.strict_firestore_transaction.StrictFirestore for that boundary. This implementation is not bound to an owning store and accepts references from unrelated stores, bypassing the shared fixture's client/reference consistency checks. Reuse the required fixture and extend it only for capabilities established by the emulator tests rather than introducing a parallel transaction implementation.

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

Useful? React with 👍 / 👎.

Git-on-my-level and others added 2 commits October 23, 2026 18:25
Include #23402 released memory projections and retain its declarations beside
the monthly epoch and sync snapshot contracts. Regenerate the registry at its
existing date. The reviewed non-fatal usage publication fix is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Git-on-my-level
Git-on-my-level merged commit 4d3c06c into main Oct 24, 2026
60 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/fs-p3 branch October 24, 2026 00:28
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