Skip to content

refactor(agent,scan): share one 80% token threshold - #421

Merged
lizhengfeng101 merged 1 commit into
alibaba:mainfrom
chethanuk:refactor/token-threshold-const
Jul 21, 2026
Merged

lizhengfeng101 merged 1 commit into
alibaba:mainfrom
chethanuk:refactor/token-threshold-const

Conversation

@chethanuk

Copy link
Copy Markdown
Contributor

Description

The "80% of max_tokens" prompt ceiling had two encodings that could drift apart.

tokenWarningThreshold = 0.80 is defined at internal/llmloop/compression.go:19, but it
is unexported — so the four call sites outside llmloop could not reach it and each
hardcoded * 4 / 5 instead. This adds a small exported helper so every site shares the
single definition.

graph LR
  subgraph before["before — two encodings, six sites"]
    A1["agent.go:594<br/>maxAllowed * 4 / 5"]
    A2["agent.go:789<br/>MaxTokens * 4 / 5"]
    A3["scan/agent.go:321<br/>MaxTokens * 4 / 5"]
    A4["scan/agent.go:555<br/>maxAllowed * 4 / 5"]
    A5["compression.go:101<br/>int(float64(x)*tokenWarningThreshold)"]
    A6["loop.go:440<br/>int(float64(x)*tokenWarningThreshold)"]
  end
  subgraph after["after — one"]
    H["llmloop.PromptTokenLimit(maxTokens)"]
    C["tokenWarningThreshold = 0.80<br/>compression.go:19"]
    H --> C
  end
  A1 --> H
  A2 --> H
  A3 --> H
  A4 --> H
  A5 --> H
  A6 --> H
Loading

All six sites now route through the helper. loop.go:439's softLimit is left inline
because it uses the separate tokenSoftThreshold (60%) constant, which has a single
consumer and stays unexported.

Behaviour is unchanged

The replaced integer form x * 4 / 5 and the helper's int(float64(x) * 0.80) agree
across every reachable input. 0.80 in float64 is 0.80000000000000004…, i.e. strictly
above exact 4/5, so for positive x the product never rounds below the exact value and
truncation lands on the same integer. Brute-forced over x ∈ [-5_000_000, +5_000_000]:
zero divergences. Negatives agree too, since Go integer division truncates toward zero.
The first divergence is at x = 2^52 (~4.5 quadrillion tokens).

The float form is also the more robust of the two at extremes: x * 4 overflows int64
above MaxInt64/4, where the old expression silently returned 0 — i.e. "no limit".

MaxTokens is validated > 0 at internal/config/template/template.go:189 and :203
before any agent is constructed, so the non-positive case is unreachable in production;
the existing _ZeroMaxTokens / _NoLimit tests still pin the guards for direct
construction.

Out of scope

Left alone deliberately, to keep this a mechanical refactor: the literal 80 in
user-facing message strings and doc comments (agent.go:596,788,800,809;
scan/agent.go:319,330,338,557; llmloop/loop.go:434-435), and the * 4 / 5 example in
pages/src/content/docs/{en,zh,ja}/architecture.md. Those are display copy and prose, not
the arithmetic this issue targets. Glad to follow up separately if wanted.

One observation, no change made: Template.MaxTokens is also sent to the provider as the
output cap (internal/llm/client.go:493 MaxCompletionTokens,
internal/llm/responses_client.go:188 MaxOutputTokens), so this helper is really "80%
of the output cap, used as a prompt budget". That conflation predates this PR — I kept the
existing semantics rather than changing them, but if you'd prefer the helper named
WarnTokenLimit to tie it to the constant rather than implying a prompt/completion
distinction the config doesn't make, that's a one-line change.

AI assistance: Claude Code helped implement and verify this change. I reviewed the full
diff and take responsibility for it.

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 (full suite, -race, 23 packages, zero failures)
  • Manual testing:
    • make fmt, make vet, make check — clean
    • make coverage — 81.5%, above the 80% gate; PromptTokenLimit itself at 100%
    • go test ./internal/llmloop/ -run TestPromptTokenLimit -v — 8 subtests + parity test pass
    • go test ./internal/agent/ ./internal/scan/ -run 'FilterLarge' -v — 6/6 pass
    • grep -rn "4 / 5" --include="*.go" . — empty

Mutation-tested the new boundary tests

The pre-existing TestFilterLargeDiffs / TestFilterLargeScans use margins wide enough
to pass at any threshold, so before this PR nothing actually pinned 80%. I verified the
new tests close that gap by mutating the constant in both directions:

Test 0.80 0.75 0.85
TestFilterLargeDiffs PASS PASS PASS
TestFilterLargeDiffs_Boundary PASS FAIL FAIL
TestFilterLargeScans PASS PASS PASS
TestFilterLargeScans_Boundary PASS FAIL FAIL

Both new tests are two-sided mutation killers; the pre-existing ones survive both mutants.

Tests added

  • TestPromptTokenLimit — table-driven, expectations hand-computed rather than derived
    from the implementation (which would tautologically pass). The maxTokens: 5 row is the
    load-bearing one: the exact product is 4.000000000000000222, and the half-ULP at 4.0
    makes it round down to exactly 4.0 and truncate to 4, not 3.
  • TestPromptTokenLimitMatchesReplacedExpression — parity with the removed x*4/5 form.
    Documented as specific to 0.80, to be deleted rather than "fixed" if the threshold moves.
  • TestFilterLargeDiffs_Boundary / TestFilterLargeScans_Boundary — with MaxTokens=100
    the limit is 80, so an exactly-80-token input is kept and an exactly-81-token one is
    dropped. Fixtures are built through llm.CountTokens — the same function the code under
    test uses — and t.Fatalf if the tokenizer ever disagrees, so drift fails loudly rather
    than quietly weakening the assertion.

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 (not applicable)
  • I have signed the CLA

Related Issues

Closes #417

tokenWarningThreshold = 0.80 is defined in internal/llmloop, but it is
unexported, so the four call sites outside that package could not reach
it and each hardcoded '* 4 / 5' instead. The 80% policy therefore had two
encodings that could silently drift apart.

Add llmloop.PromptTokenLimit and route all six sites through it:

  internal/agent/agent.go:594, 790
  internal/scan/agent.go:321, 555
  internal/llmloop/compression.go:99
  internal/llmloop/loop.go:440

loop.go:439's softLimit stays inline; it uses the separate 60%
tokenSoftThreshold, which has a single consumer and stays unexported.

Behaviour is unchanged. 0.80 in float64 is strictly above exact 4/5, so
for positive x the product never rounds below the exact value and
truncation lands on the same integer; verified over
x in [-5_000_000, 5_000_000] with zero divergences. The float form is
also the more robust of the two: x*4 overflows int64 above MaxInt64/4,
where the old expression silently returned 0 (i.e. no limit).

The <= 0 guards stay at the call sites. filterLargeDiffs/filterLargeScans
treat a non-positive limit as keep-everything, while the pre-flight gates
treat it as a ceiling that rejects every prompt, so the helper does not
special-case it.

Tests: TestPromptTokenLimit pins the arithmetic with hand-computed
expectations, and new boundary tests pin the threshold itself - with
MaxTokens=100 an exactly-80-token input is kept and an 81-token one
dropped. The pre-existing filter tests survive mutating the constant to
both 0.75 and 0.85; the new ones fail on both.

Closes alibaba#417
@github-actions

Copy link
Copy Markdown
Contributor

✅ OpenCodeReview: No comments generated. Looks good to me.

@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 9ab0616 into alibaba:main Jul 21, 2026
2 checks passed
Githab-capibara added a commit to Githab-capibara/open-code-review that referenced this pull request Sep 17, 2026
tokenWarningThreshold = 0.80 is defined in internal/llmloop, but it is
unexported, so the four call sites outside that package could not reach
it and each hardcoded '* 4 / 5' instead. The 80% policy therefore had two
encodings that could silently drift apart.

Add llmloop.PromptTokenLimit and route all six sites through it:

  internal/agent/agent.go:594, 790
  internal/scan/agent.go:321, 555
  internal/llmloop/compression.go:99
  internal/llmloop/loop.go:440

loop.go:439's softLimit stays inline; it uses the separate 60%
tokenSoftThreshold, which has a single consumer and stays unexported.

Behaviour is unchanged. 0.80 in float64 is strictly above exact 4/5, so
for positive x the product never rounds below the exact value and
truncation lands on the same integer; verified over
x in [-5_000_000, 5_000_000] with zero divergences. The float form is
also the more robust of the two: x*4 overflows int64 above MaxInt64/4,
where the old expression silently returned 0 (i.e. no limit).

The <= 0 guards stay at the call sites. filterLargeDiffs/filterLargeScans
treat a non-positive limit as keep-everything, while the pre-flight gates
treat it as a ceiling that rejects every prompt, so the helper does not
special-case it.

Tests: TestPromptTokenLimit pins the arithmetic with hand-computed
expectations, and new boundary tests pin the threshold itself - with
MaxTokens=100 an exactly-80-token input is kept and an 81-token one
dropped. The pre-existing filter tests survive mutating the constant to
both 0.75 and 0.85; the new ones fail on both.

Closes alibaba#417
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.

refactor(agent): replace hardcoded * 4 / 5 token threshold with a named constant

2 participants