Skip to content

fix(trace): follow Black's trailing commas through refactors - #58

Merged
Sym-jay merged 2 commits into
Sym-jay:mainfrom
Sandro850:fix/refactor-trailing-commas-47
Nov 29, 2026
Merged

Sym-jay merged 2 commits into
Sym-jay:mainfrom
Sandro850:fix/refactor-trailing-commas-47

Conversation

@Sandro850

Copy link
Copy Markdown
Contributor

Addresses #47.

Summary

Add a conservative historical tracing fallback for Black-style
trailing-comma changes in Python keyword arguments.

Exact matches retain priority. On an exact miss at an indexed refactor,
the fallback verifies historical correspondence using diff anchors,
structural AST position, equivalent file ASTs, compilable syntax,
and ordered call tokens.

Ambiguous or insufficiently verified matches are rejected.
Verified predecessor text is carried into subsequent historical hops.

The full KeptLines matcher is intentionally not reused because
preservation during an edit and historical equivalence have different
requirements, particularly given the useful warnings lost in #44.

Flask reproduction

At the parent of c2705ffd:

Line Before After
request=self.request, e08bcf9 e08bcf9
session=self.session, 025589ee e08bcf9 via 025589ee

The session argument now traces through Black's formatting commit
to the original fix (#2935), at flask/ctx.py:333.

The existing useful replay warning is preserved, and the subsequent
semantic rewrite remains attributed to c2705ffd.

Labelled replay

Baseline: 5845a10. All five reference repositories were evaluated
at their pinned heads using the 500-commit labelled replay.

Repository Before precision After precision
Flask 4/4 (100%) 5/5 (100%)
Requests 2/10 (20.0%) 2/10 (20.0%)
Express 5/9 (55.6%) 5/9 (55.6%)
Django 49/71 (69.0%) 49/71 (69.0%)
React 9/31 (29.0%) 9/31 (29.0%)
Total 69/125 (55.2%) 70/126 (55.6%)

Across 2,478 checked commits:

  • All 125 previous warnings remain identical, including locations,
    historical citations and hop chains.
  • All 69 previously useful warnings are preserved.
  • One new useful Flask warning is emitted.
  • No new noise or unlabelled warnings remain.

The new warning occurs in c17f37939 at src/flask/ctx.py:354,
citing e08bcf9 through 025589ee.

The edit switches from the session property to its backing field
to avoid access tracking while preserving the current-session
propagation introduced by fix #2935.

Although the change preserves the original fix's behaviour,
reviewing that guarantee is useful. The corresponding edit in
c2705ffd provides an existing labelled precedent.

The new warning is labelled in bench/labels/pallets-flask.json.

Historical regression recall

All 137 historical regression pairs reproduced their baseline evidence.

  • Overall on-target recall: 12/71 (16.9%), unchanged.
  • Within-model recall: 12/27 (44.4%), unchanged.
  • Elsewhere hits: 9, unchanged.

Performance

Same-machine measurements using Python 3.12.3 and Git 2.43.0.
Warm workloads used two discarded warm-ups and eight measured runs.

Operation Baseline median Candidate median
Cold indexing 467.5 ms 445.8 ms
Warm Flask check 128.0 ms 129.6 ms
Warm Flask map 638.5 ms 637.4 ms
Targeted trace function (interleaved) 35.1 ms 49.5 ms
Total labelled replay 343.36 s 340.49 s

Instrumentation recorded two eligible fallback attempts among
1,836 exact misses. Both recovered the intended historical origin.

The rare path adds approximately 14 ms to the targeted trace,
including verification and an additional successful historical hop.

A first verification of a revision/path pair can require three
additional Git calls. Exact matches incur no additional source
reads or parsing.

With simulated latency of 40 ms per tracer Git call, the targeted
trace increased from 122.9 ms to 304.0 ms. This is a sensitivity
experiment, not a real cross-platform measurement.

A large-file probe measured approximately 300 ms of CPU and
49 MB peak memory for verification of a 405K-character Python file.

Validation

  • pytest: 249 passed, 1 skipped.
  • blot bench: 33/33 cases correct.
  • git diff --check: clean.
  • The primary regression fails on baseline code and passes
    with the candidate.
  • Mutation tests detect deliberately broken historical
    correspondence safeguards and cache eviction policies.

The final Flask replay was rerun after adding its new label.
The other four replays and historical recall results come from
the byte-identical production implementation before the final
test and label additions.

Limitations

The fallback deliberately covers only the narrow trailing-comma
case on the last keyword argument of a Python call, with an
unchanged closing parenthesis on its own line.

General multiline re-wraps (#48), simultaneous renames, and
arbitrary cosmetic changes are not handled.

Whole-file AST comparison and ordered token verification can
decline valid formatting hops involving docstring changes,
quote-style changes, type comments, or shifted type-ignore
directives. These cases fail closed.

Local execution was limited to Python 3.12. Other supported
Python versions were not tested locally.

Further Git-read optimisations and broader cosmetic equivalence
rules are intentionally left outside this PR.

@Sym-jay

Sym-jay commented Nov 28, 2026

Copy link
Copy Markdown
Owner

Thanks Sandro! I re-ran everything on your branch and got the same numbers: 70/126, one new useful Flask warning, recall unchanged. Nice work on the measurements.

One thing though: it's ~150 lines in trace.py for one extra warning, and everything goes through that file. Could you try a simpler version? On an exact miss, just look up the line with the trailing comma added or removed in the existing RefactorOrigins index, and keep your checks (keyword-arg line, single candidate, same file). I don't think the AST/tokenize part adds much, since the hop only runs on refactor commits anyway.

If the simple version gets the same results, let's go with that and keep your tests. If it breaks something, show me the case and I'm happy to take this one as is.

@Sandro850

Copy link
Copy Markdown
Contributor Author

Thanks for the suggestion! I tried the index-only version and several intermediate designs. The experiments also exposed a correctness issue in the currently published implementation.

I'd recommend replacing it with a smaller, revised AST-based fallback.

Comparison

Implementation Net production code lines Extra Git calls per verification Counterexamples
Index-only 20 0 Incorrect cross-call attribution
Diff anchoring 66 1 Accepts some semantic changes
AST position only 53 2 Incorrect attribution when identical calls move
Published PR 119 3 Also fails when identical calls move
Revised AST approach 93 2 Passes all demonstrated counterexamples

All five implementations reproduce the same benchmark results:

  • 70/126 useful warnings, with identical replay findings.
  • 12/71 overall recall and 12/27 within model.
  • All 137 historical regression pairs unchanged.
  • 33/33 scripted benchmark cases.

The differences become apparent in adversarial Git histories.

1. Index-only counterexample

Consider two calls to the same function:

Before formatting After formatting
First call, introduced by a feature session=(current_session) session=current_session,
Second call, introduced by a fix session=current_session session = current_session

For the first call, exact lookup misses. Toggling the comma finds exactly one deleted candidate in the same file, but it belongs to the second call.

Editing only the first call then produces a false severity-2 removed-fix warning citing the second call's fix.

2. Counterexample affecting the published PR

While investigating smaller alternatives, I found that the published implementation also produces an incorrect historical attribution when two structurally identical calls exchange positions.

Equal ASTs, matching tokens and diff positions do not necessarily establish historical identity.

The following self-contained reproduction demonstrates the problem on the published commit (f4bf20a).

#!/bin/sh
# Usage: sh repro.sh [PYTHON]
# PYTHON must be able to import blot.

set -eu
py=${1:-python3}
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT

export GIT_CONFIG_NOSYSTEM=1
export GIT_CONFIG_GLOBAL=/dev/null
export GIT_AUTHOR_DATE=2026-01-01T00:00:00Z
export GIT_COMMITTER_DATE=2026-01-01T00:00:00Z

cd "$work"
git init -q -b main .
git config user.email test@example.com
git config user.name Test

commit() {
    printf "$2" > ctx.py
    git add ctx.py
    git commit -qm "$1"
}

commit "Fix crash in the billing handler (fixes #1)" \
  '# billing\nmake(\n    session=current\n)\n'

commit "Add preview handler" \
  '# billing\nmake(\n    session=current\n)\n# preview\nmake(\n    session=(current)\n)\n'

commit "Reformat and reorder documented handlers" \
  '# preview\nmake(\n    session=current,\n)\n# billing\nmake(\n    session = current\n)\n'

# Change only the preview call.
printf '# preview\nmake(\n    session=other,\n)\n# billing\nmake(\n    session = current\n)\n' > ctx.py

git add ctx.py
"$py" -m blot why ctx.py:3
"$py" -m blot check || true

The published PR attributes the preview argument to the billing fix:

explained by 3334bce4 Fix crash in the billing handler
traced past 1f61a9c5 Reformat and reorder documented handlers

blot: 1 warning

! removed-fix ctx.py:3

The revised implementation stops at the refactor and emits no warning.

Proposed replacement

The revised fallback:

  • Keeps the existing exact-match priority.
  • Uses the existing index to find a unique comma-toggled candidate in the same file.
  • Compares equivalent, compilable ASTs and corresponding keyword nodes.
  • Verifies the actual physical source lines.
  • Rejects structurally duplicate calls where historical correspondence is ambiguous.
  • Preserves type-comment handling and bounded caching.

It removes tokenization and the additional diff read, reducing the production code from 119 to 93 net code lines and the verification path from three additional Git calls to two.

Validation

  • pytest: 274 passed, 1 skipped.
  • Scripted benchmark: 33/33.
  • All 126 replay findings preserved individually.
  • All 137 historical regression pairs unchanged.
  • All demonstrated cross-call counterexamples rejected.
  • No incorrect comma-fallback pairings observed across 597 generated Git histories.

The new regression tests cover three layouts of identifying comments around relocated identical calls. The comment-above variant fails on the published PR and passes with the revised implementation.

Two existing test expectations change to accept additional verified formatting-only cases.

Performance

Operation Published PR Revised version
Warm check 136.7 ms 135.0 ms
Warm map 645.9 ms 646.7 ms
Targeted Flask trace 50.0 ms 48.0 ms

Measured locally using Python 3.12.3 and Git 2.43.0.

Limitations

The fallback remains conservative. It declines ambiguous duplicate calls, files with differing ASTs, unsupported source layouts or encodings, files over 512 KiB, and certain type-comment or type-ignore cases.

The existing exact-text hop has a related historical attribution weakness that predates this PR. I have deliberately left it unchanged, as it is outside #47.

The safety argument is supported by regression tests, historical benchmarks and generated histories, rather than a formal proof.

I agree that the original fallback was heavier than necessary. The revised implementation is smaller, preserves the measured results and addresses the newly discovered correctness issue.

The replacement is prepared and validated locally. I've left the published branch unchanged for now.

If you're happy with this direction, I'll push the revised implementation to this PR.

@Sym-jay

Sym-jay commented Nov 29, 2026

Copy link
Copy Markdown
Owner

Wow, good catch on the swapped-calls bug. I ran your script on f4bf20a and got the same wrong warning. Go ahead and push the revised version. Smaller and correct beats smallest. Once it's up I'll re-run the replays and merge.

Could you also open an issue for the exact-hop weakness you mentioned? Better to track it separately than grow this PR.

@Sym-jay Sym-jay left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Re-ran everything on f6b8358: same 70/126, recall unchanged, bench 33/33, and your repro now stays quiet. Merging, thanks Sandro! Don't forget the issue for the exact-hop weakness when you get a chance.

@Sym-jay
Sym-jay merged commit b363061 into Sym-jay:main Nov 29, 2026
7 checks passed
@Sandro850

Copy link
Copy Markdown
Contributor Author

Thanks for the review and for encouraging the simplification! I've already opened #59 with a self-contained reproduction of the exact-hop weakness, including the distinction from git blame's move detection. I'd be happy to investigate that one next.

Sym-jay added a commit that referenced this pull request Nov 29, 2026
* Docs after #58: precision 70/126, record the trailing-comma hop

* CLAUDE.md: no Claude attribution in PRs, issues or comments
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.

2 participants