Skip to content

fix(harness): weigh media blocks realistically in TokenCounterUtil - #4229

Open
littlebird69 wants to merge 1 commit into
agentscope-ai:2.0.xfrom
littlebird69:fix/4227-media-token-estimate
Open

littlebird69 wants to merge 1 commit into
agentscope-ai:2.0.xfrom
littlebird69:fix/4227-media-token-estimate

Conversation

@littlebird69

Copy link
Copy Markdown
Contributor

AgentScope-Java Version

2.0.5 (branch 2.0.x, 2.0.6-SNAPSHOT)

Description

Fixes #4227.

Background. On the 2.0.x line, TokenCounterUtil charges every media block (ImageBlock, AudioBlock, VideoBlock, DataBlock) a fixed 5 tokens. Image-heavy histories therefore look almost free:

  • token-based compaction triggers never fire for them, and
  • since 2.0.5, ConversationCompactor's size gate (candidateTokens >= totalTokens → reject) compares a text summary — whose wrapper alone is ~130 estimated tokens — against an image prefix estimated at a few tokens, so every summary of an image prefix is rejected as "not smaller than the current N tokens". The rejection happens after summarizePrefix, so callers pay for a discarded summary call on every round above the threshold, and overflow recovery built on compactIfNeeded cannot recover.

Main already fixed this. #3847 moved main's estimate onto ContextTokenEstimator.approximate(), which charges any media block 2048 tokens. This PR backports that weight to 2.0.x as a minimal change, instead of porting the whole #3847 refactor.

Changes (TokenCounterUtil only):

  • Media blocks (the former catch-all) are charged MEDIA_BLOCK_TOKENS = 2048, matching main. Media nested in ToolResultBlock output goes through the same method and is covered too.
  • HintBlock also fell into the old catch-all. It is injected text (e.g. RAG context), not media, so it is now counted by its hint length. Without this, the change above would charge every hint 2048 tokens and trigger compaction early. Note for main: ContextTokenEstimator.approximate() still has no HintBlock case, so it counts hints as 2048 there. I can send a follow-up for main if you want one.

Behavior change to note: on 2.0.x, sessions with many media blocks now reach token-based compaction thresholds earlier. That matches main and reflects their real cost.

Tests

Verification (local, Windows 11 host, JDK 25):

  • mvn spotless:check on agentscope-harness: clean.
  • io/agentscope/harness/agent/memory/compaction/*Test: 64/64 pass.
  • Full agentscope-harness suite: 1623 run, 17 failures. All 17 are pre-existing on this Windows host and reproduce identically (5 failures + 12 errors, same 4 classes) on a clean origin/2.0.x checkout without this change: HarnessAgentTest and SandboxFilesystemIsolationScopeExampleTest (sandbox workspace root "must be an absolute path" with C:\...), MemoryFlushSandboxIndependenceTest ("'other' has different root"), and MemoryConsolidatorCommitGateTest. I did not run the suite on Linux; CI will cover that.

Checklist

  • Code has been formatted with mvn spotless:apply
  • All tests are passing (mvn test): compaction tests pass. The 17 Windows-only failures listed above are pre-existing on clean 2.0.x.
  • Javadoc comments are complete and follow project conventions
  • Related documentation has been updated (e.g. links, examples, etc.): none needed, no public API change
  • Code is ready for review

TokenCounterUtil charged every media block (ImageBlock, AudioBlock,
VideoBlock, DataBlock) a fixed 5 tokens. Image-heavy histories therefore
looked almost free: token-based compaction triggers never fired for them,
and since 2.0.5 the summary size gate rejected every text summary of an
image prefix as "not smaller than the current N tokens" - after the
summarization call had already been paid for.

Charge media blocks 2048 tokens each, the same weight main's
ContextTokenEstimator.approximate() uses since agentscope-ai#3847. Nested media inside
ToolResultBlock output goes through the same path. HintBlock, which also
fell into the old catch-all, is injected text and is now counted by its
hint length instead of being treated as media.

Fixes agentscope-ai#4227
@littlebird69

Copy link
Copy Markdown
Contributor Author

CI note: the red build is not from this change.

  • build (windows-latest) fails in agentscope-core, in SkillBoxTest$UploadContainment.preservesLegacyNamesWithRelativeNonNormalizedWorkDirectory (IllegalArgumentException: 'other' has different root). That is a Windows path-root issue in a module this PR does not touch (core: 3235 run, 0 failures, 1 error).
  • build (ubuntu-latest) was cancelled by matrix fail-fast while the harness tests were still passing.

Locally on Windows the same family of path-root failures reproduces on a clean 2.0.x checkout without this change (listed in the PR description). Could a maintainer re-run the ubuntu job? Contributors cannot re-run CI.

xzxiaoshan added a commit that referenced this pull request Nov 20, 2026
…#4274)

## Background

Swept the last 125 PRs (#4272→#4075) for single-OS CI failures under
`mvn -B -T1C clean verify` (one build OS red, the other green on the
same commit = flake suspect). Cross-PR repeats and main's own red run on
2026-11-19 (ubuntu, run 44516464414) pinpoints four still-broken test
classes; all fixes are test-side only (no `src/main` changes).

## Fixes and evidence

| Test class | Victims | Signature | Fix |
|---|---|---|---|
| `RocketMqExecutionTest` | #4182, #4192, #4103 + main run 44516464414
(2026-11-19, ubuntu) | `turn reaches SUCCEEDED did not become true
within 10s` while the turn kept progressing (modelCalls complete, acks
climbing, lastFailure=none) — deadline breakthrough under starvation,
not a lost turn | shared `waitUntil` deadline 10s→30s (repo tier
#3726/#3774) |
| `AgentScopeAdapterTest` | #4204 (same-commit re-run green = confirmed
flake), #4191, #4246 | `Timed out observing Turn` at 6.7–8.5s elapsed;
resume/recovery one step from terminal | `turn.await(5s)`→30s at all 3
sibling sites via `TURN_DEADLINE`, outer `get` budgets +5s margin |
| `WorkerRuntimeTest` | #4219, #4224, #4255 (windows) | (a) `Worker
lease lost` after 2.4s — 1s claim leases expired between claim and
release; (b) `renewed.await(5s)` missed at 6.5s while the recovery lane
was healthy; (c) `Interrupted sleep interrupted` —
`WorkerRuntime.process()` interrupts the calling thread on lease-renewal
failure and manual `tick()` runs it on the test thread | (a) claim
leases 1s→30s (staleness under test still comes from `release(ZERO)` +
re-claim); (b) latches 5s→30s; (c) raw `Thread.sleep`→interrupt-proof
`pause()` at 5 sites, mirroring the #4176 fix for the same signature in
`ProcessRecoveryTest` |
| `ChatSessionsTest.await` (shared with `ChatControllerTest`) | #4233,
#4182 (stuck-RUNNING at 40.8s/46.4s), #4268, #4163 (poll threw `Durable
database transaction failed`) | two surfaces of one cause: every
snapshot poll opens a writing sqlite transaction contending with the
runtime's own writes, and windows runners starve turns past 30s (same
file already measured 56.6s starvation and uses 120s elsewhere, #3726) |
deadline 30s→120s (aligned tier) + tolerate transient `UNAVAILABLE`
store exceptions while polling; persistent failure rethrows at the
deadline, FAILED-turn fast-fail unchanged |
| `CommandExecutorTest.missingExitCodeIsUnknown` | local -T2C full-repo
stress (2026-11-19; pristine-main baseline of the same class green) |
the 2s network budget fired on scheduler starvation before the instant
fake response was processed, misclassifying the failure as a deadline
miss instead of a missing exit code (2.97s elapsed) | budget 2s→30s for
this non-deadline-semantics test; the two deadline-semantics tests keep
their tight budgets |

## Constraint compliance

- Happy path zero cost: every change only extends failure-path deadlines
or hardens helpers; no new sleeps, no weakened assertions.
- Minimal widening anchored to measured data (each comment cites victims
+ measured values); 30s follows the repo's established deflake tier,
120s follows this file's own previously measured starvation tier.
- Structural hardening preferred: `pause()` helper, transient-lock
retry, lease decoupling from the tested invariant.
- No `src/main` changes.

## Observed but deliberately not fixed here

-
`ProcessRecoveryTest.replacementCollectsOriginalResultWithoutRepeatingEffect`
(#4214: `expected: 2 but was: 3`): recovery-semantics race (model re-run
without effect re-run after abrupt halt) — a product question for the
durable recovery work, not a deadline flake.
-
`JevEvidenceProcessorTest.filterFailureIsWithheldButRankFailureFollowsScoredEvidence`
(#4265: delivered `[]` on a 25×-slowed runner): root cause not
established; single occurrence.
- Already fixed upstream, victims predate the fix:
`AgentScopeAgentExecutorInputRequiredTest` (#4157/#4187/#4152 all
predate #4176's `BaseReActAgentRunner` change), `InboxMiddlewareTest`
(#4093 predates #3738), `HarnessAgentSubagentStreamEventsTest` (#4183
predates #2917).
- `SkillBoxTest$UploadContainment` quartet (#4201/#4202/#4212/#4229):
test does not exist on main (fork stack only); deterministic cross-drive
path bug, not load flakiness.
- #4184/#4185: both-OS compile breaks from dependency major bumps
(dependabot), out of scope.

Also applied during review: sibling sites with the identical measured
mechanism were widened in the same pass — the remaining 1s fixture claim
leases in `WorkerRuntimeTest` (fenced begin/update/release sequences,
same #4219 signature), the start/PAUSED 5s budgets in the same
`AgentScopeAdapterTest` method as the victims, and the 5s/4s observe
budgets in
`completeLocalBackendRunsNativeAgentWhileManagedObserverIsBlocked`.

## Test plan

- [x] Full local `mvn -B -T2C clean verify` green (stricter than CI's
-T1C). Locally excluded, each verified to fail identically on pristine
main on this machine (Windows/git-bash) while passing on CI:
`JsonFileAgentStateStoreTest` (symlink permissions), the
`agentscope-extensions-durable-sandbox` trio plus
`ToolInSandboxExampleTest`/`SandboxRoundTripTest` (sandbox shell heredoc
incompatible with local git-bash python3), and the
`AgentScopeAdapterTest`/`ProcessRecoveryTest`/`HarnessExternalToolProcessRecoveryTest`
trio (durable-adapter classes whose Windows runs are skipped on CI; the
same named tests fail on pristine main locally).
- [ ] CI green on both OS.

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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant