Skip to content

fix(cluster-only): report the cost.json token totals, like update - #5384

Open
neo1777 wants to merge 3 commits into
Graphify-Labs:v8from
neo1777:fix/cluster-only-token-cost-from-ledger
Open

neo1777 wants to merge 3 commits into
Graphify-Labs:v8from
neo1777:fix/cluster-only-token-cost-from-ledger

Conversation

@neo1777

@neo1777 neo1777 commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

Fixes the Token cost line that cluster-only writes, the case I described in #3658. Since #5154, graphify update writes the cost.json totals into the report, and headless extract records its usage there (#1769). cluster-only still reports only its own labeling usage, so on the same graphify-out/ the two commands disagree:

mkdir t && cd t && printf 'def f():\n    return g()\n\ndef g():\n    return 1\n' > a.py
graphify extract . --code-only
python -c "import json;json.dump({'runs':[],'total_input_tokens':12000,'total_output_tokens':3400},open('graphify-out/cost.json','w'))"
graphify cluster-only . --no-label
grep 'Token cost' graphify-out/GRAPH_REPORT.md   # v8: 0 input · 0 output   this branch: 12,000 input · 3,400 output
printf 'def h():\n    return 2\n' >> a.py
graphify update .
grep 'Token cost' graphify-out/GRAPH_REPORT.md   # 12,000 input · 3,400 output on both

The python line stands in for what a paid extract appends to cost.json.

In #3658 I listed three ways to keep a carried-forward value from going stale. #5154 has since settled that: the report line is the cumulative ledger. This PR follows it, so none of those options is needed.

The change:

  • cluster-only and label pass load_report_token_cost(out) to generate(), as watch.py does.
  • When labeling made LLM calls, their usage is printed ([graphify label] labeling tokens: … in / … out) and appended to cost.json with _record_extract_cost (as a run with files: 0), right after the backup_if_protected snapshot and before the Prevent partial-chunk overwrite in --update: pre-build node-count assertion + build_merge() helper #479 guard. So the tokens are recorded even when graph.json is refused, and this report and a later update both count them. _record_extract_cost takes the command name for its two warnings, and now returns whether it wrote the run.
  • If cost.json can't take that run (unreadable or not writable), the file is left alone and this report adds the run's labeling usage to whatever the ledger loader read, so the tokens just spent still show.
  • The aider and devin skills run their own --cluster-only script, which passed a hard-coded {'input': 0, 'output': 0} to generate(). Their fragments (tools/skillgen/fragments/core/aider.md, devin.md) now read the ledger with load_report_token_cost, and tools/skillgen/gen.py gets a sanctioned-change predicate for those lines (_is_cluster_only_ledger_fix_line), as the monolith round-trip requires; the artifacts are regenerated with skillgen.

Type of change

  • Bug fix

Verification & Invariants

Invariant: cluster-only, label, update and the aider/devin --cluster-only scripts report the same token cost for the same graphify-out/, the cost.json totals. This changes what the line means for cluster-only after #1694: it was this run's labeling usage, now it's the ledger total, and the labeling usage is printed on stdout.

  • Read CONTRIBUTING.md.
  • Reproduced the issue and identified the invariant.
  • Smallest fix: one block in cluster-only, a keyword argument and a return value on _record_extract_cost, two lines in each of the aider/devin fragments with their round-trip predicate; no change to report.py.
  • Regression tests in tests/test_labeling.py, next to the other cluster-only/label CLI tests:
    • test_cluster_only_reports_cost_json_totals fails on v8;
    • test_label_adds_labeling_usage_to_cost_json fails on v8;
    • test_cluster_only_without_ledger_reports_zero_and_creates_none passes before and after: with no cost.json and no labeling call, the report stays at 0 and no ledger is created.
    • test_label_reports_its_usage_when_the_ledger_is_unreadable covers the unreadable cost.json case raised in review: it fails on this PR's first commit and passes with the second (on v8 it passes too, since v8 reports only the labeling usage).
    • test_label_records_its_usage_even_when_graph_json_is_refused fails on v8 and on this PR's second commit, and passes with the third.
    • In tests/test_skillgen.py, test_monoliths_read_the_cost_ledger_in_cluster_only checks that both monoliths' --cluster-only script reads the ledger (the round-trip alone would not notice the fix going missing); it fails on the v8 fragments.
  • Description kept in sync with the implementation.
  • Limitations: a cost.json that can't be read or written doesn't get the labeling run (a warning is printed, as for extract), so a later update won't count it; this report still does. Two runs writing cost.json at the same time can still lose one run: that read-modify-write is the one extract already uses, unchanged here, and the skill's own cost.json update has the same race. A lock would have to cover both, so I've left it out of this PR. The cost.json snapshot taken by backup_if_protected is taken before the labeling run is appended. Labeling runs sit in cost.json with files: 0 and no other marker, so the skill's «N runs» line counts them too. As on v8, cluster-only rewrites .graphify_analysis.json without a "tokens" field; nothing reads it now.

How was this tested?

uv run pytest tests/test_labeling.py tests/test_report.py -q   # 70 passed
uv run pytest tests/ -q          # 11328 passed, 379 skipped, 1 xfailed, 17 failed (see below)
uv run python -m tools.skillgen --check   # 134 artifact(s) match
uv run ruff check .              # all checks passed
uv run pyright graphify/cli.py   # same 1 error as on v8 ("Code is too complex to analyze"), none new

The 17 failures are in test_ext_tagged_id_clash.py, test_multilang.py and test_pascal_singleton_resolution.py (the SQL and Pascal grammars aren't installed without --all-extras). They fail identically on a clean v8. I also ran the reproducer above as written, on v8 and on this branch, and the regenerated aider and devin --cluster-only scripts on the same folder: both now write 12,000 input · 3,400 output.

#3681 touches the same report line, for unknown values. This branch doesn't change report.py, and merging #3681's head into it gives the same conflicting files as merging it into v8 at b582ad4 (the aider/devin skill files among them already). #4772, which marks unmeasured skill runs, also writes cost.json: it merges cleanly with this branch and keeps the totals as integers (unmeasured runs are counted apart), which is what load_report_token_cost reads.

The branch is based on v8 at b582ad4 and merges cleanly into v8 at 3671f31. Environment: Python 3.12.3, uv 0.11.23, Linux Mint 22.3.

Graphify-specific checklist

  • Generated skill artifacts regenerated with uv run python -m tools.skillgen --bless from the edited fragments; --check passes.
  • Deterministic: no new dependency on environment variables or global state; cluster-only and label now also append to cost.json, as extract does, and the report reads the same ledger update reads.
  • No unsafe interpolation.
  • No API keys or local-only graph data.
  • AI authorship disclosed in the commit (Co-Authored-By).

After a paid `graphify extract`, `graphify cluster-only` wrote
"Token cost: 0 input · 0 output" in GRAPH_REPORT.md, because it reported
only its own community-labeling usage. `graphify update` on the same
folder reports the cost.json totals since Graphify-Labs#5154, so the two commands
disagreed about the same graph (Graphify-Labs#3658).

- cluster-only and label now pass load_report_token_cost(out) to the
  report, as watch.py does.
- Their labeling usage, when there is any, is appended to cost.json
  first through _record_extract_cost, so this report and a later update
  both count it. The helper takes the command name for its warnings.
- With no cost.json and no labeling call, the report stays at 0 and no
  ledger is created.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@neo1777
neo1777 requested a review from safishamsi as a code owner November 21, 2026 21:41
@github-actions

Copy link
Copy Markdown

Thanks for the pull request, @neo1777. A maintainer will review it soon.

Want to talk it through while it is in review? Come join us on our Discord server. For longer-form discussion there is also GitHub Discussions.

A couple of things that speed up review: make sure the test suite passes on Python 3.11 and 3.13, and that the change keeps extraction deterministic.

@github-actions github-actions Bot added the contributor Pull request from a returning community contributor label Nov 21, 2026

@graphify-labs graphify-labs 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.

Graphify review View in Graphify

Nothing blocking · 6 possible issues to check · Merge confidence 5/5

6 possible issues to check · High impact

The CLI now records community-labeling token usage in cost.json and builds cluster-only reports from the ledger totals.

6 possible issues we couldn't confirm
  • Two runs writing cost.json at the same time can overwrite each other, dropping labeling token counts from the ledger · graphify/cli.py:3406
  • The cluster-only token guard approves removing or adding one line alone, so a partial fix can pass the round-trip check · tools/skillgen/gen.py:1467
  • The cluster-only cost test passes even if the ledger is loaded but its totals are never printed or saved · tests/test_skillgen.py:651
  • +3 more in Graphify

They don't change the score.

What this review covered
  • We didn't review 6 files that aren't source code, such as docs, config, images, or generated or third-party code.
  • 4 of 4 changed files inspected. This is scope, not a correctness guarantee.
Code graph · 1117 functions depend on this change
  • 2 functions became more coupled. render() (17 callers), dispatch_command() (8 callers).
  • 607 of 607 test files are affected by this change.
  • Gate, test list and every flagged function: in the Graphify check.

Reviewed 16e26ce · 2 earlier findings not re-checked · Full report in the Graphify check

Comment thread graphify/cli.py Outdated
Comment on lines +3431 to +3434
if label_token_usage["input"] or label_token_usage["output"]:
_record_extract_cost(out, label_token_usage["input"], label_token_usage["output"],
0, command=cmd)
from graphify.report import load_report_token_cost as _lrtc

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3  A damaged ledger makes the report omit this run’s labeling cost

If cost.json cannot be read or updated, cluster-only can report zero tokens even though its labeling call used tokens.

Include the current run’s labeling usage in cluster-only reports independently of cost.json.

Evidence · checked against the code

Expected: The report should include the current run’s known labeling usage, even if cumulative ledger totals cannot be recovered.
Actually: Ledger recording returns without updating the file, and the report loader supplies zero tokens.

  • Independent source review: Inspected the ledger loader and its tests: malformed or unreadable ledgers return zero, and the tests confirm that behavior. That loader behavior does not preserve the current run’s usage or prevent the cluster-only path from using its zero result. The tests do not exercise the full labeling-to-report failure path.
  • Also reported as: Cluster-only report can drop this run's labeling token cost when cost.json cannot be read or written
Prompt to fix with AI
In graphify/cli.py, dispatch_command (lines 3431-3434):
Problem: A damaged ledger makes the report omit this run’s labeling cost
Expected: The report should include the current run’s known labeling usage, even if cumulative ledger totals cannot be recovered.
Actually: Ledger recording returns without updating the file, and the report loader supplies zero tokens.
Fix it at the cause, and add a test that fails without the fix.

Graphify · Checked against the code · View in Graphify

… take it

If cost.json is unreadable or can't be written, _record_extract_cost
leaves it alone, and the report read only the ledger, so a labeling run
that spent tokens showed none of them. _record_extract_cost now returns
whether it wrote the run; when it didn't, cluster-only/label add this
run's labeling usage to the totals the ledger loader read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Comment thread graphify/cli.py Outdated
Comment on lines +3434 to +3437
# the ledger can't take them, this report still adds them to what it read.
recorded = True
if label_token_usage["input"] or label_token_usage["output"]:
recorded = _record_extract_cost(out, label_token_usage["input"],

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  Concurrent runs can overwrite each other’s token totals

If label and extract run at the same time against the same output directory, the final cost.json can omit one run’s token usage.

Serialize _record_extract_cost read-modify-write updates.

Evidence · checked against the code

Expected: Both runs are recorded and their token usage is reflected in the ledger totals.
Actually: Both can read the prior ledger and then replace it with separate updates; the later write can omit the earlier run and its totals.

  • Independent source review: Checked the helper's atomic-write call and the label and extraction call sites. Atomic replacement does not prevent both callers from reading the old ledger first; no synchronization appears in the inspected helper or call paths. Existing label-ledger tests check sequential totals, not concurrent updates.
Prompt to fix with AI
In graphify/cli.py, _record_extract_cost (lines 3434-3437):
Problem: Concurrent runs can overwrite each other’s token totals
Expected: Both runs are recorded and their token usage is reflected in the ledger totals.
Actually: Both can read the prior ledger and then replace it with separate updates; the later write can omit the earlier run and its totals.
Fix it at the cause, and add a test that fails without the fix.

Graphify · Checked against the code · View in Graphify

…; aider/devin skills read the ledger

- The labeling run is appended to cost.json right after the backup snapshot
  and before the Graphify-Labs#479 guard, so tokens spent on labeling are recorded even
  when graph.json is refused. Its usage is also printed, since the report
  line is now the ledger total rather than this run's labeling cost.
- The aider and devin skills run their own --cluster-only script, which
  reported a hard-coded zero. Their fragments now read the ledger with
  load_report_token_cost, like the CLI. gen.py sanctions those lines for the
  monolith round-trip (_is_cluster_only_ledger_fix_line), a skillgen test
  checks the fix is present, and the artifacts are regenerated with skillgen.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

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

Labels

contributor Pull request from a returning community contributor

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant