Skip to content

fix(tool-search): recall tools for Chinese queries via Han character bigrams - #4147

Open
birdie7761 wants to merge 1 commit into
agentscope-ai:mainfrom
birdie7761:fix/toolsearch-cjk-bigram-recall
Open

birdie7761 wants to merge 1 commit into
agentscope-ai:mainfrom
birdie7761:fix/toolsearch-cjk-bigram-recall

Conversation

@birdie7761

Copy link
Copy Markdown
Contributor

AgentScope-Java Version

2.1.0-SNAPSHOT (based on main @ c8875287f)

Description

The default KeywordToolSearchStrategy splits queries on [^\\p{L}\\p{N}]+. CJK characters are
letters, so a natural Chinese query survives splitting as one long term — and matching is
whole-phrase contains(). A tool described 搜索并读取文件内容 can never be recalled by the query
帮我搜索文件内容: the 7-character phrase does not appear verbatim anywhere. For deployments
whose tools carry Chinese names/descriptions, tool search returns an empty result set for exactly
the queries users send.

The fix adds the overlapping Han-character bigrams of every term carrying 3+ Han code points
(kept alongside the full term):

  • long CJK queries regain substring recall (搜索 / 文件 / 内容 windows all hit the example
    description above);
  • windows are built from code points — supplementary-plane Han (two UTF-16 chars) neither
    splits into invalid surrogate strings nor degrades to single-character matching;
  • windows only form between two adjacent Han code points — Latin fragments of a mixed term
    (inbox inside 帮我找inbox邮件) never become matching units that could outrank the tool the
    Chinese part describes;
  • two-Han terms are already the smallest matching unit — semantics unchanged, pinned by a
    test;
  • non-CJK terms never expand — Latin/numeric matching is byte-for-byte the previous behaviour,
    pinned by the existing keywordRankingLimitsAndEmptyResults;
  • dependency-free by design (the class's stated contract): a hand-rolled Character.UnicodeScript
    check, no tokenizer.

The docs/v2 EN/ZH tool pages describe the strategy's CJK matching behaviour (per the
user-visible-change rule).

Scoring treats each bigram like any other term (name hit +3, description hit +1), so more overlap
still ranks higher; common-word bigrams can add ranking noise among Chinese-described tools, which
is the accepted trade-off of a recall-first fix (an exact-semantic matcher remains a pluggable
ToolSearchStrategy away).

Compatibility

  • Behaviour change is confined to queries containing a 3+ character Han-script term: previously
    those queries could only match a verbatim phrase (in practice: nothing); now they can also match
    overlapping 2-character windows. No term that matched before can stop matching (the full term is
    kept).
  • No public signatures, state formats, or event payloads change.

Tests

Four new cases; red-verified pre-fix — verbatim failure output:

ToolSearchTest.cjkQueriesRecallToolsDescribedWithShorterChinesePhrases
  actual: [] ==> expected: <[read_cn]> but was: <[]>
ToolSearchTest.mixedScriptQueriesDoNotRecallToolsThroughLatinFragments
  actual: [install_plugin, mail_cn] ==> expected: <[mail_cn]>
ToolSearchTest.supplementaryPlaneHanTermsMatchOnAdjacentCodePoints
  a different ext-B character must not match through a split surrogate pair, actual: [ext_doc]
Test Asserts
cjkQueriesRecallToolsDescribedWithShorterChinesePhrases a natural Chinese query recalls the tool whose description shares its phrases, not unrelated Chinese- or English-described tools
twoCharacterCjkQueriesKeepExactSubstringSemantics two-character CJK queries match as before, and unrelated short queries still recall nothing
mixedScriptQueriesDoNotRecallToolsThroughLatinFragments a mixed CJK/Latin query recalls only through its Han windows — Latin fragments (in, bo from inbox) never match unrelated English-described tools
supplementaryPlaneHanTermsMatchOnAdjacentCodePoints ext-B terms match on adjacent code-point windows, and a query mentioning a different ext-B character must not match through a split surrogate pair

Regression: full agentscope-core suite — only the pre-existing
JsonFileAgentStateStoreTest.sessionOperationsShareLocksThroughRootSymlink env-specific errors
(Windows symlink through root, brought by #4048, untouched by this diff; passes or aborts cleanly
on CI); spotless:check clean.

…bigrams

A natural Chinese query survives the term splitter as one long Han-script
term (CJK letters are not separators), so whole-phrase contains() never
matches a catalog entry described with a shorter Chinese phrase - the
default strategy returns an empty result set for exactly the queries CJK
deployments send. Terms carrying three or more Han code points now also
match on their overlapping Han-character bigrams:

- windows are built from code points, so supplementary-plane Han (two
  UTF-16 chars) neither splits into invalid surrogate strings nor degrades
  to single-character matching;
- windows only form between two adjacent Han code points, so Latin
  fragments of a mixed term never become matching units;
- two-Han and non-CJK terms keep their exact-substring semantics.

Dependency-free by design, matching the class's contract.

Red-verified pre-fix: "帮我搜索文件内容" returned no tools against a tool
described "搜索并读取文件内容"; a mixed query recalled "install_plugin"
through Latin character pairs; a query naming a different ext-B character
matched through a split surrogate pair.
@mintlify

mintlify Bot commented Nov 12, 2026

Copy link
Copy Markdown

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit 80a0999.

Approve preview

xzxiaoshan added a commit that referenced this pull request Nov 12, 2026
#4149)

## Summary

Scanned the last 5 pages of PRs (#3941–#4147, 125 PRs): 14 had red CI,
and 9 of those failed on exactly one OS while the other OS stayed green
on the same commit — the classic `-T1C` parallel-build starvation
signature (the both-OS failures were compile/spotless issues and are out
of scope). This PR fixes every distinct flaky test class found that way,
plus two narrowly-scoped hardenings the fixes depend on.

| Test / class | Failed OS | Victim PRs | Evidence | Fix |
|---|---|---|---|---|
| `AguiMvcControllerTest#eventStreamSignals…` | ubuntu ×2 | #4112, #4143
| 5s latch deadline hit while sibling tests in the class ran 5–9s under
the same load | shared 30s await constant (all waits in the class share
the same executor starvation exposure) |
| `SubagentRunIdChainTest` (both methods) | windows ×3 | #4091, #4025,
#4142 | blocking read starved just past 10s (10.04–10.84s elapsed); same
test 0.414s on ubuntu | block budget 10s → 30s |
| `InboxMiddlewareTest#notificationReaches…` | ubuntu ×2 | #3991, #4093
| assertion matched the memory-consolidation prompt instead of the
reasoning request | `MockModel` recordings made thread-safe (see below)
|
| `GatewayEventsWebSocketTest#sameOrigin…` | windows ×2 | #4072, #4094 |
~0.1s clean close with no frames; job log shows the preceding 403'd
upstream upgrade left a dying pooled socket (`Connection prematurely
closed BEFORE opening handshake is complete`) that the next proxied
socket reused | stand-in control plane now answers rejected upgrades
with `Connection: close` so the gateway pool discards the socket |
| `TurnLeaseServiceTest#heartbeatErrors…` | windows | #4075 |
`await(70ms) isFalse` anchored to when the starved test thread resumes,
not to lease acquisition | bounds re-anchored to
elapsed-time-since-acquisition (fires within 2s, not before 120ms;
deadline 150ms, ticks 50ms) |
| `SandboxConnectorRedirectTest#commandWaits…` | windows | #4058 |
capability probe inherited the 200ms command-transport budget and died
at 199ms before any command was submitted | probe budget floor (see
CommandExecutor below) |
| `GracefulShutdownManager` singleton leak | local | found during
verification | `resetForTesting()` reset every field except `config`, so
a `PT0.1S` config leaked across tests and failed `defaultConfig`
whenever filesystem class order placed it after `shutdownTimeoutSignal`
| reset now also restores `GracefulShutdownConfig.DEFAULT` |

## Shared test-util fix

`MockModel` recorded calls from whichever thread drives the agent — the
turn thread and background memory maintenance — into a plain `ArrayList`
plus unsynchronized `int`/`last*` fields. Two concurrent adds race the
`elementData[size] / size++` update and can silently drop an entry; that
is exactly the #4093/#3991 signature (the reasoning request vanished,
only the post-call consolidation request survived). Recordings are now a
`CopyOnWriteArrayList` with `AtomicInteger`/`volatile` siblings —
order-preserving, atomic per add, stable to iterate while a call is in
flight. Complements the iteration fix proposed in #4133.

## Non-test changes (called out explicitly)

- **`CommandExecutor`** — the `/capabilities` pre-flight probe now uses
`max(configured per-attempt, 2s)` for its budgets. Strictly a widening:
identical for default (60s) and ≥2s configurations; only sub-2s configs
change, and only for the probe — command exchanges keep the configured
budget. Side benefit: the old code passed the same 200ms as the shared
exchange deadline, which made the intended `CAPABILITY_MAX_ATTEMPTS = 3`
retry dead code; the floor lets the retry actually run. The test-only
alternative (raising the test's 200ms config and the server delays to
match) would add ~1.5–2s of real test wall time, so the 2-line
production fix is the smaller change.
- **`GracefulShutdownManager.resetForTesting`** — one added line
restoring `config` to default, inside a method documented "Intended for
testing and demo purposes only" (no production callers; production code
never calls `setConfig`).

## Constraint compliance

- **No happy-path slowdown:** every widened number is a failure-path
deadline only; all awaits/latches return the moment the signal arrives,
and no sleeps were added (`TurnLeaseServiceTest` actually drops a forced
70ms wait).
- **Minimal widenings, anchored to measurements:** 5s→30s (deadline hit
twice; repo precedent from #3726 for CI-starvation waits), 10s→30s (3×
the observed 10.04–10.84s), probe floor 2s (10× the 199ms miss),
TurnLease window [120ms, 2s] (bug population ~50ms vs legitimate
≥150ms).

## Test plan

- [x] Full reactor `mvn -B -T2C clean verify` green locally (4m38s wall
clock; all seven fixed areas' suites green)
- [x] `JsonFileAgentStateStoreTest` (8 symlink cases) excluded locally
only — pre-existing Windows-symlink-privilege limitation, reproduced
identically on a pristine `main` baseline, unrelated to this diff
- [ ] CI on both OSes

Follow-up noted during review: the production control-plane hub behind
`/api/v1/events` lives outside this repo; if it also answers rejected
upgrades with a keep-alive 403 and closes, the gateway can still poison
a subsequent proxied socket in production — worth checking against the
real hub separately.
@jujn jujn added the P2 重要不紧急 label Nov 16, 2026

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

P2 重要不紧急

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants