Skip to content

fix(agent): make --preview apply the same selection the review applies - #801

Merged
lizhengfeng101 merged 3 commits into
alibaba:mainfrom
zmwangx:fix/preview-selection-parity
Sep 11, 2026
Merged

lizhengfeng101 merged 3 commits into
alibaba:mainfrom
zmwangx:fix/preview-selection-parity

Conversation

@zmwangx

@zmwangx zmwangx commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Description

--preview applied only the static file filters, but a real review applies one more gate before it freezes coverage: any diff whose token count exceeds 80% of max_tokens is dropped. That gate runs before the selected set is sealed, so a file could be listed under "Will review" and then never be reviewed. Preview could not apply it even in principle — runPreview never passed a template, so the limit was zero on that path.

Rather than teach preview the size check separately — which would just let the two drift again — this turns the deterministic pre-dispatch selection into one operation both paths consume:

  • internal/agent/selection.go holds selectFiles, which takes the changed diffs and returns a decision per file: the exclusion reason, or none. It is pure — no output, no mutation, no git or LLM access — so it can run in a preview that builds none of the review runtime.
  • Run and Agent.Preview both call it. The three independently implemented decisions it replaces — the static filter, the size filter, and the reviewable count — are gone; the run's skip logging, its file counts, and preview's entries are all derived from the same decisions.
  • The size gate moves from dispatch into shared selection. It still runs before coverage is sealed, while preview now consumes the identical decision.
  • The token limit is an input to selection (Args.Template.MaxTokens), and zero disables the gate — which is how delegate preview opts out.

The net guarantee: preview's will_review set is the set a fresh, non-resumed, unbudgeted run registers as selected coverage.

User-visible changes:

  • Oversized diffs are reported with a new too_large exclusion reason, in the human view and in --format json.
  • Preview resolves the real per-file limit (--max-tokens, then the saved max_tokens, then the template) without building an LLM runtime, so it still needs no provider and no API key.
  • The run's N file(s) changed, reviewing M line no longer counts files the size gate is about to drop.
  • Run-level telemetry gains review.skipped, carrying the cause as an attribute. no.files.changed fires exactly where it did before, so existing consumers are unaffected.
  • The skip line for an emptied selection names the count instead of claiming "All changed files", which was wrong whenever the static filters had already removed some.
  • ocr delegate preview is deliberately unchanged: the host agent reviews with its own context window, not OCR's max_tokens.

Out of scope because they are execution-specific or unavailable to preview: aggregate --max-tokens-budget exhaustion, resume reuse (--preview cannot be combined with --resume), and LLM failures. The commit message covers the design and the trade-offs in detail.

Type of Change

  • Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Refactoring (no functional changes)
  • Documentation update
  • CI / Build / Tooling

How Has This Been Tested?

  • make test passes locally
  • Manual testing (describe below)

The repro from #782: one commit adding a single ~186 KB file, whose diff exceeds 80% of the default max_tokens. No real API key is needed: preview initializes no provider, and the full run uses dummy endpoint settings that are never contacted because the size gate exits before any request.

mkdir repro && cd repro && git init -q .
git config user.email t@t && git config user.name t
printf 'package main\n\nfunc main() {}\n' > seed.go
git add -A && git commit -qm init

{ echo "package huge"; for i in $(seq 1 4000); do echo "func Hn$i(a int) int { return a * $i }"; done; } > huge.go
git add -A && git commit -qm "add one large file"

Before — preview promises a review that never happens:

$ ocr review --commit HEAD --preview

Preview: 1 file(s) changed  |  +4001  -0

Will review (1):
  [A]  huge.go              +4001 -0

$ OCR_LLM_URL=https://api.invalid.test/v1 OCR_LLM_TOKEN=dummy OCR_LLM_MODEL=fake-model ocr review --commit HEAD
[ocr] 1 file(s) changed, reviewing 1 in /tmp/repro
[ocr] Skipping huge.go (~70047 tokens exceeds 80% of max_tokens(58888))
[ocr] Pre-filtered 1 file(s) exceeding 80% of max_tokens
[ocr] All changed files exceeded the token size limit. Skipping review.
[ocr] Summary: 0 file(s) reviewed, 0 comment(s), ~0 token(s) used, 0s elapsed
Review skipped: no items were selected.

After — preview reports the drop, and the run's own count agrees with it:

$ ocr review --commit HEAD --preview

Preview: 1 file(s) changed  |  +4001  -0

Excluded from review (1):
  [A]  huge.go              (too_large)

$ OCR_LLM_URL=https://api.invalid.test/v1 OCR_LLM_TOKEN=dummy OCR_LLM_MODEL=fake-model ocr review --commit HEAD
[ocr] 1 file(s) changed, reviewing 0 in /tmp/repro
[ocr] Skipping huge.go (~70047 tokens exceeds 80% of max_tokens(58888))
[ocr] Pre-filtered 1 file(s) exceeding 80% of max_tokens
[ocr] 1 file(s) exceeded the token size limit; nothing left to review. Skipping review.
[ocr] Summary: 0 file(s) reviewed, 0 comment(s), ~0 token(s) used, 0s elapsed
Review skipped: no items were selected.

A regression test pins the property directly: preview's will_review set equals the set the run registers as selected coverage, over a changeset that mixes reviewable, extension-filtered, deleted and oversized files.

Checklist

  • My code follows the project's coding style (go fmt, go vet)
  • I have performed a self-review of my code
  • I have added tests that prove my fix is effective or my feature works
  • New and existing unit tests pass locally with my changes
  • I have updated the documentation accordingly (if applicable)
  • I have signed the CLA

Related Issues

Closes #782.


Disclosure: PR authored by AI with human guidance and careful review.

@github-actions

github-actions Bot commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

✅ OpenCodeReview: Review complete: 0 finding(s) across 7 selected item(s).

@lizhengfeng101

Copy link
Copy Markdown
Contributor

@zmwangx Right fix — one selectFiles for both paths kills the drift at the source. Please add a test asserting previewMaxTokens resolves the same value the real run applies (that's the one seam left), and rebase onto main. 👍

`--preview` applied only the static file filters, but a real review also
ran filterLargeDiffs before it froze coverage, dropping any diff whose
token count exceeded 80% of max_tokens. That filter ran before
registerCoverage sealed the selected set, so a file could be listed
under "Will review" and then never be reviewed — and preview could not
apply the gate even in principle, because runPreviewContext passed no
Template and Template.MaxTokens was therefore zero on that path.

Extract the deterministic pre-dispatch selection into one pure
operation, selectFiles, that returns every input diff with a decision
and a stable reason. Preview and Run both consume it, so neither can
re-derive the rules on its own: reimplementing the size check inside
preview would just let the two drift again. Run keeps its previous log
output by reporting the static exclusions and the size exclusions as two
groups.

Add too_large as the exclusion reason for an oversized diff, so
consumers need not reproduce the tokenizer or the 80% threshold to
explain the drop. The human preview renders it through the existing
reason column.

Give preview the real limit without initializing a provider:
resolveMaxTokens needs only AppCfg, which loads independently of
llm.ResolveEndpointWithOptions, so preview still requires no API key.
`ocr scan --preview` already resolved its limit this way, through
resolveScanPreviewMaxTokens; that helper had the same body as
previewMaxTokens, so scan now calls previewMaxTokens instead.
`ocr delegate preview` passes no template and keeps the gate
disabled — the host agent reviews with its own context window, not
OCR's max_tokens.

One behavior delta beyond the fix: a deletion is decided before the size
gate, so an oversized deletion now stays in the working diff set instead
of being dropped by filterLargeDiffs. It was never dispatched or
registered either way, and it now behaves like any other deletion.

ResolveIdentity, the resume pre-flight, must hash the same selection
the run records in source_artifact_sha256, so it now replays
selectFiles as well. That digest skips deletions, so the delta above
does not move it.

The skip line for an emptied selection now names the count and drops its
"All changed files" claim, which was wrong whenever the static filters
had already removed some.

Selection also decides the run-level skip signal now. review.skipped
carries the cause in an attribute — too_large, deleted or
no_supported_files, most actionable first — and is keyed on the
selected set, the same quantity registerCoverage seals, so a
deletion-only run counts as skipped too. Two judgement calls there:
no.files.changed keeps firing exactly where it did, so existing
consumers are unaffected, and a deletion-only run emits review.skipped
before review.started rather than suppressing review.started, which
would drop a signal main emits. An oversized changeset used to emit
review.started with a review.count that included the files it then
dropped, and no skip event at all.

Deliberately out of scope because the outcomes are execution-specific
or unavailable to preview: aggregate --max-tokens-budget exhaustion,
resume reuse and LLM failures.

The regression test pins that equality directly: preview's will_review
set equals the set a fresh, non-resumed, unbudgeted run registers as
selected coverage, over a changeset that mixes reviewable,
extension-filtered, deleted and oversized files, asserting each of those
outcomes is really represented. The CLI test covers both sources of the
limit, since --max-tokens short-circuits config resolution; the
all-oversized case drives Run, which is where the gate now runs; and the
model constant table pins too_large's wire value. The unit tests that
covered filterDiffs / filterLargeDiffs / countReviewable now cover the
one selection they were folded into.

Update architecture and review-rule docs for selection.go and the two
post-gate outcomes, add too_large to the FAQ, and document the new
review.skipped telemetry event in every locale.

Fixes alibaba#782
Selection is one operation that preview and the run both consume, but
each resolves the max_tokens it hands selection on its own path: the run
from the app config its LLM runtime loaded, preview through
previewMaxTokens, which loads the config without building a runtime. A
source or precedence change on either path alone would put preview's
will_review set out of step with the run again, with nothing failing.

Drive a real review through the CLI for each source of the limit — the
template default, the saved max_tokens, --max-tokens, and the flag
overriding a saved value — and assert previewMaxTokens returns what the
run handed its agent. The change set holds only a file the static gates
exclude, so the run skips before any LLM request.

Read the run's value off agent.Args through a newReviewAgent variable
rather than recomputing it in the test, so the assertion follows what
executeReviewContext actually applies instead of restating its
precedence.
@zmwangx
zmwangx force-pushed the fix/preview-selection-parity branch from 2ffd46e to 455cf91 Compare September 10, 2026 15:39
@zmwangx

zmwangx commented Sep 10, 2026

Copy link
Copy Markdown
Contributor Author

@lizhengfeng101 Cool, done. I had to introduce a test hook for agent.New in order to test this, which to me is a bit of a smell, haven't thought this through.

Assert previewMaxTokens parity by calling resolveMaxTokens directly (the
same function the run uses) instead of monkeypatching agent.New through a
package-level var that leaked into review_cmd.go. Removes global mutable
test state and the production indirection.
@lizhengfeng101

Copy link
Copy Markdown
Contributor

Pushed a small follow-up (a7fa1e4): I think this smell is worth removing before merge. Dropped the newReviewAgent package var and asserted the max_tokens parity by calling resolveMaxTokens directly — the same function the run uses — instead of monkeypatching agent.New. Same parity property, no global mutable test state, and the seam no longer leaks into review_cmd.go. make check + make test green. Feel free to adjust or revert if you'd rather keep it.

@lizhengfeng101 lizhengfeng101 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM

@lizhengfeng101
lizhengfeng101 merged commit 152cc6d into alibaba:main Sep 11, 2026
15 checks passed
@zmwangx
zmwangx deleted the fix/preview-selection-parity branch September 11, 2026 06:12
Githab-capibara added a commit to Githab-capibara/open-code-review that referenced this pull request Sep 17, 2026
alibaba#801)

* fix(agent): make --preview apply the same selection the review applies

`--preview` applied only the static file filters, but a real review also
ran filterLargeDiffs before it froze coverage, dropping any diff whose
token count exceeded 80% of max_tokens. That filter ran before
registerCoverage sealed the selected set, so a file could be listed
under "Will review" and then never be reviewed — and preview could not
apply the gate even in principle, because runPreviewContext passed no
Template and Template.MaxTokens was therefore zero on that path.

Extract the deterministic pre-dispatch selection into one pure
operation, selectFiles, that returns every input diff with a decision
and a stable reason. Preview and Run both consume it, so neither can
re-derive the rules on its own: reimplementing the size check inside
preview would just let the two drift again. Run keeps its previous log
output by reporting the static exclusions and the size exclusions as two
groups.

Add too_large as the exclusion reason for an oversized diff, so
consumers need not reproduce the tokenizer or the 80% threshold to
explain the drop. The human preview renders it through the existing
reason column.

Give preview the real limit without initializing a provider:
resolveMaxTokens needs only AppCfg, which loads independently of
llm.ResolveEndpointWithOptions, so preview still requires no API key.
`ocr scan --preview` already resolved its limit this way, through
resolveScanPreviewMaxTokens; that helper had the same body as
previewMaxTokens, so scan now calls previewMaxTokens instead.
`ocr delegate preview` passes no template and keeps the gate
disabled — the host agent reviews with its own context window, not
OCR's max_tokens.

One behavior delta beyond the fix: a deletion is decided before the size
gate, so an oversized deletion now stays in the working diff set instead
of being dropped by filterLargeDiffs. It was never dispatched or
registered either way, and it now behaves like any other deletion.

ResolveIdentity, the resume pre-flight, must hash the same selection
the run records in source_artifact_sha256, so it now replays
selectFiles as well. That digest skips deletions, so the delta above
does not move it.

The skip line for an emptied selection now names the count and drops its
"All changed files" claim, which was wrong whenever the static filters
had already removed some.

Selection also decides the run-level skip signal now. review.skipped
carries the cause in an attribute — too_large, deleted or
no_supported_files, most actionable first — and is keyed on the
selected set, the same quantity registerCoverage seals, so a
deletion-only run counts as skipped too. Two judgement calls there:
no.files.changed keeps firing exactly where it did, so existing
consumers are unaffected, and a deletion-only run emits review.skipped
before review.started rather than suppressing review.started, which
would drop a signal main emits. An oversized changeset used to emit
review.started with a review.count that included the files it then
dropped, and no skip event at all.

Deliberately out of scope because the outcomes are execution-specific
or unavailable to preview: aggregate --max-tokens-budget exhaustion,
resume reuse and LLM failures.

The regression test pins that equality directly: preview's will_review
set equals the set a fresh, non-resumed, unbudgeted run registers as
selected coverage, over a changeset that mixes reviewable,
extension-filtered, deleted and oversized files, asserting each of those
outcomes is really represented. The CLI test covers both sources of the
limit, since --max-tokens short-circuits config resolution; the
all-oversized case drives Run, which is where the gate now runs; and the
model constant table pins too_large's wire value. The unit tests that
covered filterDiffs / filterLargeDiffs / countReviewable now cover the
one selection they were folded into.

Update architecture and review-rule docs for selection.go and the two
post-gate outcomes, add too_large to the FAQ, and document the new
review.skipped telemetry event in every locale.

Fixes alibaba#782

* test(cli): pin preview's max_tokens to the value the run applies

Selection is one operation that preview and the run both consume, but
each resolves the max_tokens it hands selection on its own path: the run
from the app config its LLM runtime loaded, preview through
previewMaxTokens, which loads the config without building a runtime. A
source or precedence change on either path alone would put preview's
will_review set out of step with the run again, with nothing failing.

Drive a real review through the CLI for each source of the limit — the
template default, the saved max_tokens, --max-tokens, and the flag
overriding a saved value — and assert previewMaxTokens returns what the
run handed its agent. The change set holds only a file the static gates
exclude, so the run skips before any LLM request.

Read the run's value off agent.Args through a newReviewAgent variable
rather than recomputing it in the test, so the assertion follows what
executeReviewContext actually applies instead of restating its
precedence.

* test(review): drop agent.New seam from max-tokens parity test

Assert previewMaxTokens parity by calling resolveMaxTokens directly (the
same function the run uses) instead of monkeypatching agent.New through a
package-level var that leaked into review_cmd.go. Removes global mutable
test state and the production indirection.

---------

Co-authored-by: kite <[email protected]>
kall added a commit to kall/open-code-review that referenced this pull request Sep 28, 2026
…merge

Update two learnings whose references drifted when v1.12.9 landed:

- cross-engine-review-exposes-file-filter-blind-spots: add the secret
  gate to the coreFilterReason decision order (user exclude no longer
  beats everything), list the current ExcludeReason constants, note
  that provider_directory and too_large never appear in core diff
  output, 31 -> 97 default exclude globs, vendor/ -> apps/ in the
  parity example, re-point moved line citations (selection.go,
  scan/agent.go, shared_flags.go, core_cmd.go), mark alibaba#782 closed by
  alibaba#801, and describe the cited commits as fork-branch commits now that
  they are pushed.
- clean-merge-does-not-prove-branch-only-files-compile: re-point moved
  citations (review_cmd.go:136, shared.go:132-135, system_rules.go,
  agent_test.go:238), and state that build/vet/test is necessary but
  not sufficient when the branch holds copies of upstream logic, with
  a link to the new parity learning.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
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.

--preview reports files as "Will review" that the real run drops pre-dispatch

2 participants