Skip to content

Feature/Fix: Validate and optimize lineage token accounting#2158

Open
iam-brain wants to merge 28 commits into
steipete:mainfrom
iam-brain:iam-brain/lineage-validation-and-performance
Open

Feature/Fix: Validate and optimize lineage token accounting#2158
iam-brain wants to merge 28 commits into
steipete:mainfrom
iam-brain:iam-brain/lineage-validation-and-performance

Conversation

@iam-brain

@iam-brain iam-brain commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

Stack dependency

This is PR 4 of 4. It follows PR #2157; review and merge that PR first.

Summary

Adds the final validation, diagnostic, and performance slice for the shadow-lineage rearchitecture.

  • provides an opt-in aggregate-only replay over frozen local histories
  • diagnoses reset-epoch and post-branch fingerprint theories without feeding speculative estimates into accounting
  • records stage-level timing and bounded family metrics
  • removes repeated copy-on-write growth and redundant timestamp parsing
  • hashes JSONL during parsing to reduce mutation-check reads
  • adds a bounded two-million-observation regression test
  • keeps legacy removal blocked and the rollback path intact

The scanner is materially closer to OpenAI's finalized UTC totals, but it is not exact and further real-world validation remains necessary.

Final UTC comparison

Positive percentages are overcounts versus OpenAI; negative percentages are undercounts.

UTC day Live app cache vs OpenAI Partial fix vs OpenAI Reviewed scanner vs OpenAI OpenAI official
2026-07-09 976,079,823 +14.47% 764,026,920 -10.40% 808,692,108 -5.16% 852,682,935
2026-07-10 7,456,347,992 +371.86% 1,438,632,374 -8.96% 1,625,777,248 +2.88% 1,580,199,588
2026-07-11 98,382,045,260 +7,708.15% 846,608,173 -32.81% 1,375,236,113 +9.15% 1,259,990,957
Aggregate 106,814,473,075 +2,792.45% 3,049,267,467 -17.43% 3,809,705,469 +3.16% 3,692,873,480

Sources and interpretation

  • Live app cache: historical totals retained by the installed CodexBar cache, not a recomputed legacy scan.
  • Partial fix: scanner after the interleaved-cost containment fix already landed upstream.
  • Reviewed scanner: the lineage selector after addressing review feedback with copy-stable event identity and physical-parent discovery.
  • OpenAI official: finalized UTC daily totals used during validation.

The aggregate is much closer than the partial fix, but day-level residuals remain significant. This does not claim exact parity or support removing the legacy fallback.

Performance

The cold retained-data replay used the same 616-document, 918,677-observation corpus for both paths.

Calculation path Total Change vs legacy
Legacy scanner 212.269 s baseline
Reviewed lineage scanner 182.249 s -30.020 s (-14.14%)

The lineage time breaks down as follows (minor rounding and timer-boundary overhead account for the remainder):

Lineage phase Time Share of lineage total
Bounded discovery, including referenced-parent lookup 82.903 s 45.49%
Ledger document loading and hashing 81.754 s 44.86%
Family reconciliation and deduplication 17.512 s 9.61%
Family preparation, composition, and timer overhead 0.080 s 0.04%

The ledger held at most one family at a time: 39 families total, 355,168 observations in the largest family, and 856,177 duplicate observations suppressed. This shows that discovery and repeated JSONL loading—not the lineage calculation itself—are the remaining performance targets.

Validation

  • opt-in frozen UTC replay with aggregate-only output
  • two-million-observation regression test
  • 48 focused lineage tests after review fixes
  • make check
  • full suite: 650 selections across 55 groups; no failures, retries, or timeouts
  • repository review gate: no material findings after fixes

Related investigation: #2037.

@clawsweeper clawsweeper Bot added proof: sufficient Contributor real behavior proof is sufficient. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Jul 14, 2026
@clawsweeper clawsweeper Bot added status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. P2 Normal priority bug or improvement with limited blast radius. merge-risk: 🚨 compatibility 🚨 Merging this PR could break existing users, config, migrations, defaults, or upgrades. labels Jul 14, 2026
@clawsweeper

clawsweeper Bot commented Jul 14, 2026

Copy link
Copy Markdown

Codex review: needs maintainer review before merge. Reviewed July 14, 2026, 9:38 AM ET / 13:38 UTC.

Summary
Adds lineage-based Codex token-accounting validation, diagnostics, bounded replay coverage, performance instrumentation, parser hashing, and guarded authority-selection infrastructure.

Reproducibility: yes. at the source-and-corpus level: the PR documents a frozen retained-history replay where retained totals massively overcount and the current partial scanner still differs from finalized UTC totals. The private corpus was not independently rerun during this review.

Review metrics: 3 noteworthy metrics.

  • Patch surface: 24 files; +5,978 / -21. This is a substantial accounting rearchitecture rather than a narrow validation-only change.
  • Implementation and tests: 13 source files and 11 test files. The branch adds ten lineage modules plus scanner integration and extensive focused coverage.
  • Measured replay: 616 documents; 918,677 observations; 14.14% faster. The real retained-data replay materially supports both behavior and performance assessment.

Root-cause cluster
Relationship: fixed_by_candidate
Canonical: #2037
Summary: The open issue is the canonical user problem, and this PR is the final validation and performance slice of its four-PR candidate fix stack.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge readiness
Overall: 🐚 platinum hermit
Proof: 🦞 diamond lobster
Patch quality: 🐚 platinum hermit
Result: ready for maintainer review.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • After the prerequisites land, rerun frozen-history and fresh-install versus upgrade/cache validation on the exact rebased head before enabling lineage authority.

Risk before merge

  • [P1] The three prerequisite draft PRs remain open, so this final slice should not be evaluated or landed independently of the exact stacked merge result.
  • [P1] Individual finalized UTC days still differ by as much as about 9%, so enabling lineage authority prematurely could replace a known overcount with material undercount or overcount on some histories.
  • [P1] The PR base predates current main; exact-head cache invalidation, upgrade behavior, and integration should be refreshed after the prerequisites land.
  • [P1] Although legacy remains the default, a future caller supplying lineage mode and authorization can materially change historical totals, making the authority boundary compatibility-sensitive.

Maintainer options:

  1. Land only as guarded infrastructure (recommended)
    Merge after the prerequisite stack and exact-head upgrade validation while preserving legacy defaults, cache isolation, and rollback.
  2. Pause until parity improves
    Leave the stack unmerged until daily residuals and upgrade behavior are validated across more real histories.

Next step before merge

  • Review the prerequisite stack in order, refresh it against current main, and decide whether the guarded accounting architecture should enter the product.

Maintainer decision needed

  • Question: Should CodexBar land this default-off lineage accounting architecture now despite the remaining day-level residuals, or defer the architecture until parity evidence is stronger?
  • Rationale: The implementation appears technically guarded and well proven, but accepting a substantial parallel accounting model and its ongoing maintenance cost cannot be resolved from correctness tests alone.
  • Likely owner: steipete — The repository owner is the best available owner for the product boundary and long-term accounting-direction decision.
  • Options:
    • Land guarded infrastructure (recommended): Merge the prerequisite stack in order, retain legacy authority and rollback, and require fresh evidence before any lineage promotion.
    • Defer the architecture: Keep the current file-local containment and revisit lineage accounting after broader real-history parity and upgrade evidence exists.

Security
Cleared: The diff adds no dependency, workflow, secret-access, permission, or downloaded-code changes, and its local replay is designed for aggregate-only output.

Review details

Best possible solution:

Land the stack only in dependency order as default-off infrastructure, preserve legacy authority and whole-scan rollback, and require exact-head upgrade testing plus broader ordinary-day parity evidence before any production promotion.

Do we have a high-confidence way to reproduce the issue?

Yes at the source-and-corpus level: the PR documents a frozen retained-history replay where retained totals massively overcount and the current partial scanner still differs from finalized UTC totals. The private corpus was not independently rerun during this review.

Is this the best way to solve the issue?

Yes for a default-off, reversible infrastructure path; no for promoting lineage accounting to authority yet, because individual UTC days still differ materially from the reference.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against c61e01e774c4.

Label changes

Label justifications:

  • P2: This is a normal-priority improvement to incorrect local Codex accounting with a guarded and reversible rollout path.
  • merge-risk: 🚨 compatibility: Activating the new authority can materially change historical token totals and cache behavior, so upgrade and promotion boundaries must remain explicit.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The PR body provides after-fix frozen-history replay results against finalized UTC totals and cold-run performance measurements on the changed accounting path.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body provides after-fix frozen-history replay results against finalized UTC totals and cold-run performance measurements on the changed accounting path.
Evidence reviewed

What I checked:

Likely related people:

  • steipete: Adopting a new accounting architecture and deciding when it may become authoritative are repository-level product and maintenance-boundary choices. (role: repository owner and likely decision owner; confidence: high; files: Sources/CodexBarCore/Vendored/CostUsage/CostUsageScanner.swift, Sources/CodexBarCore/Providers/Codex)
  • Zihao-Qi: Authored the merged interleaved-accounting containment and provenance work that established the current baseline and explicitly deferred the cross-file lineage ledger. (role: introduced current-main containment behavior; confidence: high; commits: c852c135e10c; files: Sources/CodexBarCore/Vendored/CostUsage/CostUsageScanner.swift, Tests/CodexBarTests)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

How this review workflow works
  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.
Review history (8 earlier review cycles)
  • reviewed 2026-07-14T01:46:27.389Z sha c01c5a8 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-14T10:57:17.122Z sha 0b5a00e :: needs maintainer review before merge. :: none
  • reviewed 2026-07-14T11:16:47.820Z sha 0b5a00e :: needs maintainer review before merge. :: none
  • reviewed 2026-07-14T11:43:03.121Z sha 0b5a00e :: needs maintainer review before merge. :: none
  • reviewed 2026-07-14T12:04:33.944Z sha 0b5a00e :: needs maintainer review before merge. :: none
  • reviewed 2026-07-14T12:30:23.672Z sha 0b5a00e :: needs maintainer review before merge. :: none
  • reviewed 2026-07-14T12:57:28.168Z sha 0b5a00e :: needs maintainer review before merge. :: none
  • reviewed 2026-07-14T13:16:36.798Z sha 5be1a78 :: needs maintainer review before merge. :: none

@iam-brain iam-brain force-pushed the iam-brain/lineage-validation-and-performance branch from 19ed384 to 0b5a00e Compare July 14, 2026 04:52
@iam-brain iam-brain marked this pull request as ready for review July 14, 2026 15:23

@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: b1cb89f8b1

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +2882 to +2884
static func codexAccountingProducerKey(mode: CodexLineageAccountingMode) -> String {
let base = CostUsageCacheIO.currentProducerKey(provider: .codex) ?? "codex"
return mode == .legacy ? base : base + ":" + mode.producerKeySuffix

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 Include authorization state in lineage cache identity

When .lineage is run with a promotion authorization, the promoted lineage totals are saved under the same producer key used for .lineage without authorization. If authorization is later removed, makeCodexRefreshPlan can decide shouldRefresh == false, so the cached lineage-authoritative days are returned without re-running select and the reversible switch does not fall back to legacy totals until a refresh or force rescan. Include the authorization state in the cache identity or force a refresh when it changes.

Useful? React with 👍 / 👎.

Comment on lines +2960 to +2961
if selection.usedLineageAuthority {
cache.days = selection.days

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 Preserve retained days when publishing lineage totals

In authorized .lineage mode, selection.days is computed only from files, which is limited to the current scan window, but just above this block the cache may intentionally retain a wider retainedSinceKey/retainedUntilKey. A refresh for a narrowed date range can therefore replace the whole cache with only the narrowed window while still saving the wider scan bounds, causing later queries inside that retained window to return missing lineage history instead of triggering a rebuild. Recompute over the retained window or merge unchanged retained days when publishing lineage authority.

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

merge-risk: 🚨 compatibility 🚨 Merging this PR could break existing users, config, migrations, defaults, or upgrades. P2 Normal priority bug or improvement with limited blast radius. proof: sufficient Contributor real behavior proof is sufficient. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant