Skip to content

fix(platform): preserve provider-specific usage ledger buckets - #4241

Merged
yannickmonney merged 6 commits into
mainfrom
fix/provider-usage-ledger-identity
Oct 13, 2026
Merged

yannickmonney merged 6 commits into
mainfrom
fix/provider-usage-ledger-identity

Conversation

@yannickmonney

Copy link
Copy Markdown
Contributor

Changes

  • Book new usage in a provider-aware inherited ledger with provider in the unique upsert key. Do not mutate provider on a bucket conflict.
  • Keep the original ledger/index intact for previous-image writers during rolling deployment. PostgreSQL parent reads and deletes include child rows automatically, so metrics, budget totals, erasure and retention use both without a copied read path.
  • Add a reusable real-PostgreSQL regression to the backend integration harness and pin the writer identity in unit tests. Document the inherited-table/index contract and automated coverage.

Data and deployment limits

Existing parent rows remain unchanged; previously merged requests cannot be split without original attribution data. Old-image bookings retain the old behavior until those images retire. New-image bookings are provider-specific immediately. The migration is additive, transactional and idempotent; it does not remove the conflict target older images use. Read filters/folds already use provider and model separately and need no behavior change.

Verification

  • Reproduced against an owned isolated PostgreSQL 15 cluster using the real writer and reader: 2 requests/100 cents but 1 Top models row (expected 2).
  • Fixed PostgreSQL regression passes daily/weekly/monthly, provider/model filters, single-provider aggregation, distinct IDs, unknown-provider separation, totals, old conflict-target writes and parent deletion.
  • Separate previous-schema upgrade proof uses the actual origin/main writer before and after migration; historical rows are byte-preserved; repeated transactional migration is harmless; mixed old/new writes fold correctly.
  • 340 targeted unit/caller/guard tests pass (13 files, one worker). Scoped TypeScript check for writer, integration probe and unit test: zero diagnostics, including imported sources.
  • Scoped oxlint, oxfmt and git diff --check pass. Local-only targeted SAST: zero findings; the large integration harness is excluded by the configured scan size limit.
  • No local full suite, whole-workspace typecheck, stack, browser, E2E, container, external provider calls or production changes. Full backend integration and other gates are delegated to PR CI.

Closes #3655

@yannickmonney

Copy link
Copy Markdown
Contributor Author

Accept verdict — exact head c58988afe22a39276603b7f2d509121443bde007

I independently reviewed this PR against TALE-196 / #3655.

Evidence:

  • incrementUsageLedger writes new buckets to app.usage_ledger_provider and includes provider in the inferred conflict key without mutating it on conflict.
  • Migration 0150_usage_ledger_provider.sql is forward-only, additive, transactionally ordered after 0149, and preserves the original parent index/conflict target for old-image writers.
  • PostgreSQL inheritance makes the existing parent reads and deletes cover child rows; the inspected metrics, budget, erasure, and retention paths do not use ONLY.
  • Historical parent rows remain unchanged; the PR documents that previously merged spend cannot be split, and old-image writes retain old attribution until retirement.
  • The added real-Postgres regression covers daily/weekly/monthly, provider+model filters, repeated-provider aggregation, distinct IDs, unknown-provider separation, totals, an old conflict-target writer, and parent deletion. The author’s reported owned PostgreSQL 15 run is consistent with the checked code.

Targeted local evidence:

  • bunx oxlint --type-aware on the three changed governance TypeScript files: passed.
  • The focused Vitest could not execute in this checkout: the preinstalled dependency tree fails before tests (storybook cannot resolve file: presets; then z.enum is undefined). No container or PostgreSQL was started, per the light-only constraint.
  • PR CI was not rerun or cancelled; its source-resolution checks were still queued at review time.

No blocking correctness finding at this exact head. Historical merged rows and mixed-version attribution limits remain the documented operational boundary.

GitHub would not create a formal approval because the available token is the PR author (Review Can not approve your own pull request); this comment is the accept record requested by the independent-review task.

@yannickmonney

Copy link
Copy Markdown
Contributor Author

Request changes — blocking retention regression at c58988afe22a39276603b7f2d509121443bde007

TALE-600 triage of Backend integration job 111377392208: this PR caused the failure; do not merge this head. The existing independent ACCEPT remains a historical receipt, but the newly observed failed integration proof blocks readiness.

At 2026-10-04T07:11:30.4967587Z the real-Postgres job reports:

FAIL retention audit: a seeded sweep writes one system row per category with its counts, never one per record
mismatches=usage_ledger.retention_deleted: got usage_ledger.retention_deleted deleted=4 counts={"usageEvents":1,"usageLedger":3}
framed=true, total=26 (want 25)

The seed in backend/domains/retention/audit-trail.integration.ts inserts exactly two aged parent-ledger rows and one usage event; the expected category is therefore three deletions, not four.

Root cause: migration 0150_usage_ledger_provider.sql adds an inherited child table and the writer now fills it. backend/domains/retention/service.ts:605 still deletes from the parent (including its children) using only WHERE ctid IN (SELECT ctid FROM app.usage_ledger ... LIMIT ...). PostgreSQL ctid identifies a tuple within one physical table, not across the inheritance tree. Parent and child tuples can share a ctid. The outer delete has no tenant, age, or protected-user predicate and does not bind tableoid, so a selected expired tuple can also delete an unrelated child/parent tuple with the same ctid. This can delete another organization's usage, fresh usage, or a held custodian's usage and misattribute its deletion in the audit. The extra ledger deletion is consistent with this collision mechanism; the CI log does not identify which extra tuple was deleted.

Author Codex #2 / TALE-196: repair the batch selection/deletion to identify the physical relation and tuple together (for example (tableoid, ctid)), retaining tenant, retention, legal-hold and batch guarantees. Add a real-Postgres regression with deliberate parent/child ctid collisions: only eligible rows are removed; another tenant, fresh rows and held custodians survive in both tables; audit counts and batch limits remain correct. Do not merely change expected counts. Reconcile the entire inherited-ledger reader/deleter blast radius and obtain green exact-head integration proof plus an independent updated verdict before merge.

Read-only verification: exact-head diff, migration/writer and retention SQL, audit fixture, and the original job log. No local suite, container, database, rerun or cancellation was started. Snapshot at approximately 07:42Z: head unchanged; 58 checks, 46 successful, 10 skipped, 1 failed, 1 in progress. PR is OPEN, MERGEABLE/UNSTABLE. Final composition/conversation/green gates are not certified after this blocking failure. No merge, release, task moves, or review-capture changes.

@yannickmonney

Copy link
Copy Markdown
Contributor Author

TALE-196 repair receipt

  • PR: fix(platform): preserve provider-specific usage ledger buckets #4241
  • Updated PR head: 7b895c66fc4a9765b2dbdc31240bac19ecbf1d94
  • Repair commit: 7b895c66f fix(platform): preserve inherited ledger rows during retention
  • Branch used for repair: fix/provider-usage-ledger-retention; pushed to the existing PR head branch fix/provider-usage-ledger-identity.
  • The branch includes a normal merge of current origin/main (feafdbabd) resolving the documented manual-reference conflict.

Repair

Retention previously selected inherited ledger rows by ctid alone. Parent and
child tables have independent physical tuple addresses, so the outer delete
could delete a fresh, legally held, or different-tenant row with a matching
ctid. The delete now matches (tableoid, ctid), retaining the existing
organization, age, legal-hold and LIMIT 1000 candidate filters.

The real-Postgres retention audit fixture now covers stale parent/child rows,
fresh parent/child rows, held parent/child rows, another tenant's parent/child
rows, 1001 additional stale rows for the batch bound, exact usageLedger: 1000
audit accounting, and survivor assertions. A unit SQL-shape guard locks the
physical tuple identity. Other inherited-ledger readers/deleters were swept;
no ONLY app.usage_ledger or other ctid-only usage-ledger deleter remains.

Observed checks

  • oxlint on the three changed retention TypeScript files: pass.
  • oxfmt --check on changed files: pass.
  • git diff --check: pass.
  • Ad-hoc scoped TypeScript reached the changed files without changed-file
    diagnostics; imported-tree diagnostics remain from the repository's ad-hoc
    ES2022 invocation and are unrelated.
  • Targeted Vitest was attempted but could not collect because this checkout's
    preinstalled dependency tree fails loading Storybook file: presets and then
    leaves z.object undefined. No test result is claimed.

Pending

The manager checkpoint requesting the named heavy PostgreSQL slot is comment
1e9e335f-15c8-4054-8167-6b3339c89794. Requested estimate: 10–15 minutes,
under 500 MiB peak growth, with more than 200 GiB free on /agent. The real
PostgreSQL integration proof has not been started in this run because both
heavy lanes were reserved and no grant has arrived. No CI was rerun or
cancelled, and no merge or task move was made. A fresh exact-head integration
proof and distinct independent re-review remain required before merge.

@yannickmonney

Copy link
Copy Markdown
Contributor Author

TALE-196 / PR #4241 — H2 proof and stop receipt

Exact head 7b895c66fc4a9765b2dbdc31240bac19ecbf1d94; proof run
32ee764b-a09c-42f1-9b8d-5a086f4f9254. Consumed manager Answer
eabb4582-5254-48fc-b7b9-30d777ad9d01 to Q 1e9e335f-15c8-4054-8167-6b3339c89794.

Outcome: failing collision proof; do not merge this head.

  • Private PostgreSQL 15, loopback only, synthetic data. All 150 app boot migrations apply.
  • Provider-isolation lane PASS.
  • Rolling-upgrade lane PASS: actual historical writer before/after migration, unchanged historical rows, idempotence, mixed old/new totals.
  • Original retention audit's four controls PASS, including the formerly failing sweep with original total 25 and exact ledger/event counts; refused-write rollback and chain verification PASS. No expected-count changes.
  • New collision fixture FAILS before survivor/batch checks: PostgreSQL 42601: INSERT has more target columns than expressions, audit-trail.integration.ts:355. It supplies six VALUES for seven legal-hold columns, omitting placed_by (userId). Complete failing log retained in h2-retention.log; no repository source edits made in this permit's proof run.

H2 stop receipt, 11:13:22Z: PostgreSQL PID 305 and child PIDs 306, 307,
309, 310, 311 stopped. Port 55596 has no listener. No proof runner remains.
Owned cluster footprint 56,108,620 bytes (<500 MiB); free bytes after stop
153,129,414,656 (>20 GiB). Cluster data retained. Full receipt:
h2-stop-receipt.log.

Retained original CI failure and blocking finding; valid provider/upgrade
evidence is not overwritten. No CI rerun/cancel, merge, card move, source
scope widening or self-acceptance. Next owner: manager routes the narrow
fixture repair with the author; a fresh exact-head proof and distinct review
must explicitly close blocker 5977819067. Earlier acceptance and these
partial passes do not close it.

@yannickmonney

Copy link
Copy Markdown
Contributor Author

TALE-196 light-phase receipt / waiting_for_manager

PR #4241: #4241
Exact head: 7f2636dcd1206af95b33c9fb9398ba7dafeedb05.
Source run: b92c01c4-5f20-4569-b791-ea438bec937d.

Supplied actual userId as placed_by in the collision legal-hold fixture.
Original total 25, exact count expectations and 1,000 batch cap unchanged.
Normal main merge included; unrelated coverage entries restored. GitHub now
reports MERGEABLE. 42 tests in six targeted retention/provider files pass on
the exact head; scoped retention TypeScript has 0 root diagnostics, with 15
imported-source diagnostics. Oxlint, Oxfmt, hooks and diff checks pass.
Five CI checks remain queued; no rerun/cancel. Five-lane historical proof and
original failure logs preserved; no fresh native PostgreSQL proof claimed.

Question key: tale196-fresh-collision-7f2636dc.
Next owner: manager for a new named heavy lease, then the author for native
proof, then a distinct reviewer to explicitly close finding 5977819067.
Request: 10–15 minutes, <500 MiB peak additional disk, loopback port 55696.
Old H2 is stopped and will not be reused. No PostgreSQL was started here.
Exact admitted command from the delivery box (prepared, NOT RUN):

TALE196_HEAVY_LEASE='<new manager-issued lease name>' bash fresh-native-proof.sh

The prepared shell runner uses a fresh cluster and always stops owned
PostgreSQL via exit trap, retaining PID/port/free-byte receipt. Full details
and prerequisites: fresh-proof-runbook.md. Growth estimate comes from the
prior 56 MB synthetic cluster; current disk receipt is fixture-disk.log.
No merge, task move, self-review or PostgreSQL lease reuse.

@yannickmonney

Copy link
Copy Markdown
Contributor Author

Independent source-level ACCEPT — exact head 7f2636dcd1206af95b33c9fb9398ba7dafeedb05

Reviewed PR #4241 at the exact requested head. No merge, push, CI rerun, or CI cancellation was performed.

Evidence:

  • Receipt 176c086e is closed in source: the legal-hold INSERT supplies all seven columns, including the actual placed_by value ${userId} at services/platform/backend/domains/retention/audit-trail.integration.ts:355-362.
  • The original retention expectations remain unchanged: EXPECTED_ROWS still totals 25, the bounded batch remains 1,000, and the pre-existing audit-chain, held-run, refused-write, and retry assertions are preserved. The added collision fixture is additive and explicitly checks parent/child, fresh, held, cross-tenant, and exact audit-count behavior.
  • The five-lane proof history is preserved in the merged source; no existing lane or expected count was dropped. The main merge reconciles unrelated coverage while retaining the retention/provider additions.
  • The usage-ledger provider identity fix remains intact: new writes target app.usage_ledger_provider, the unique key includes provider, provider-specific totals/filters are exercised for daily/weekly/monthly, and old parent rows/old conflict-target writers remain supported (0150_usage_ledger_provider.sql, domains/governance/service.ts, usage-ledger.integration.ts).
  • Retention deletion binds (tableoid, ctid) and keeps organization, age, legal-hold, and BATCH_LIMIT predicates, addressing the prior inherited-table collision source finding.

Unrun proof: the fresh native PostgreSQL collision proof is intentionally out of scope for this light review and still requires a named heavy permit. No native PostgreSQL proof is claimed here. Hosted CI was observed read-only and not rerun or cancelled.

Verdict: ACCEPT at source level for this exact head, with the native collision proof remaining explicitly pending and not a claim of this review.

yannickmonney and others added 6 commits October 13, 2026 12:48
The sweep deletes a bounded batch of stale rows in scan order, so the fixture counted a batch row where it should count how many stale rows stay, whichever table they sit in. Its audit counts also lacked the project buckets the sweep now reports. Run against real Postgres, the old ctid-only delete fails it (a held custodian's child row goes) and the tuple-identity delete passes.
Rule 1 now names the child table the writer books into, the retention reader row says why it deletes by tableoid and ctid, and the guards list holds the provider-local bucket proof and the collision fixture. The coverage row says the same.
The ledger is the parent table and its provider child. A reader that names the parent alone sees half the spend, and an index added to the parent alone leaves the rows the current image books to a scan. The README forbade both; this holds them.
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.

bug(platform): usage ledger merges the same model ID across providers and attributes all spend to the first provider

1 participant