Skip to content

fix(training): key saved call inputs by call scope, not agent id - #3457

Open
wahllllll wants to merge 2 commits into
agentscope-ai:mainfrom
wahllllll:fix/training-router-per-call-inputs
Open

wahllllll wants to merge 2 commits into
agentscope-ai:mainfrom
wahllllll:fix/training-router-per-call-inputs

Conversation

@wahllllll

@wahllllll wahllllll commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Symptom

TrainingRouter saves each call's input messages during PreCallEvent and reads them back during PostCallEvent, so it can hand them to the selection strategy and to the shadow run. That hand-off is keyed by agent id:

private final Map<String, List<Msg>> callInputs = new ConcurrentHashMap<>();
// PreCall:  callInputs.put(agentId, event.getInputMessages());
// PostCall: List<Msg> inputs = callInputs.remove(agentId);

An agent id is shared by every concurrent call on that agent, and AgentBase#callSerializationKey only serializes calls that belong to the same session — calls in different sessions overlap by design (that is the stated intent of that method: "ReActAgent returns its (userId, sessionId) slot key so same-session calls do not corrupt shared conversation state while distinct sessions run in parallel").

So for two overlapping calls A and B on one agent:

step state of callInputs
A's PreCall agentId -> inputsA
B's PreCall agentId -> inputsB (overwrites)
A's PostCall removes inputsB → A is trained on B's messages
B's PostCall removes nothing → logs No input messages found for agent and skips training

Neither path raises. The training data is attributed to the wrong request, and one call in the pair is silently dropped.

This is the exact anti-pattern AgentBase warns about in its own javadoc for beforeAgentExecution: returning the per-call scope through the Reactor Context rather than a separate accessor exists "to avoid any window in which a concurrent call could overwrite a shared field between construction and capture".

Fix

Key the map by the per-call scope the framework already publishes on the Reactor Context under AgentBase#CALL_SCOPE_KEY — the same value ReActAgent.scopeFrom reads. handlePostCall was already inside Mono.deferContextual(ctx -> …), so the context was in hand and simply unused.

private static Object callKey(Agent agent, ContextView context) {
    Object scope = context.getOrDefault(AgentBase.CALL_SCOPE_KEY, null);
    return scope != null ? scope : agent.getAgentId();
}

Agent types that keep no per-call scope (beforeAgentExecution returns null) fall back to the agent id, so their behaviour is unchanged. When neither is available — only reachable with an agent that has no id at all, e.g. a test double — the key is null and the map operation is skipped, since a ConcurrentHashMap cannot hold a null key.

One follow-on is needed. With a per-call key, an entry is no longer overwritten by the next call, so a call that fails before PostCallEvent fires would leave its entry behind for the life of the JVM. ErrorEvent is now handled to drop it. (AgentCloner only supports ReActAgent, so the scope is always present on the path this module actually uses.)

Tests

Added shouldTrainEachCallWithItsOwnInputs: two PreCallEvents on the same agent with different call scopes (the two-session overlap above), then the first call's PostCallEvent, asserting the selection strategy receives the first call's messages.

Verified the test pins the behaviour — with the production change reverted it fails exactly on the wrong pairing:

TrainingRouterTest.shouldTrainEachCallWithItsOwnInputs:201
  the first call must be trained on its own inputs, not on a later call
  ==> expected: <first-call> but was: <second-call>
Tests run: 8, Failures: 1, Errors: 0, Skipped: 0

With the fix the same class is green (8/8), and spotless:apply reports no further changes.

Note on the integration path

This module integrates through the Hook / HookEvent API, which is @Deprecated(forRemoval = true, since = "2.0.0") — MiddlewareBase replaces it. I deliberately kept this a minimal, mechanical fix to the shipped behaviour rather than porting the router to Middleware: the bug is live and affects data correctness today, and the port is a design decision (which middleware hook points map to PreCallEvent / PostCallEvent, where the shadow run belongs) that deserves its own discussion. Happy to do that port separately if you would prefer the module moved onto Middleware rather than patched.

No database migration and no configuration change.


Fixes #3499

TrainingRouter keeps the PreCall inputs in a map so PostCall can hand them to
the selection strategy and to the shadow run. The map was keyed by the agent id,
which an agent shares with every concurrent call on it: AgentBase#
callSerializationKey only serializes calls that belong to the same session, so
two calls on one agent in different sessions overlap by design.

Overlapping calls then raced on that single entry. Whichever PreCall ran last
won, so the earlier call's PostCall handed the later call's messages to the
selection strategy -- training data attributed to the wrong request -- while the
later call's own PostCall found nothing and logged "No input messages found",
dropping that call from training entirely. Neither path raises.

Key the map by the per-call scope the framework publishes on the Reactor Context
under AgentBase#CALL_SCOPE_KEY (the same value ReActAgent.scopeFrom reads),
falling back to the agent id for agent types that keep no scope. Contexts that
yield no key at all -- only reachable with an agent that has no id -- skip the
map instead of failing the hook, since a ConcurrentHashMap rejects a null key.

Because a per-call key is never overwritten by a later call, an entry would now
outlive a call that fails before PostCall fires, so ErrorEvent is handled to
drop it.

All changes are confined to agentscope-extensions-training.
@codecov

codecov Bot commented Oct 9, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 79.16667% with 5 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...gentscope/core/training/runner/TrainingRouter.java 79.16% 2 Missing and 3 partials ⚠️

📢 Thoughts on this report? Let us know!

…llback

Pin the two behaviours the previous commit added without tests: an ErrorEvent
drops the inputs saved by PreCall so a late PostCall has nothing to train on,
and an agent that exposes no id is tolerated rather than failing the hook on a
null map key.
@wahllllll

Copy link
Copy Markdown
Contributor Author

@jujn — #3457 is the oldest thing I have open (30 days) and has never been looked at, so I am not sure whether it is queued or whether the shape is wrong.

It fixes #3499: TrainingRouter keys saved call inputs by agent id, so two concurrent calls on the same agent read each other's inputs — the second call can be trained against the first call's prompt. The fix keys them by call scope instead; two commits, +149/−10, checks green, merges cleanly onto main.

If it needs a different shape I would rather redo it now than leave it sitting for another month, and I am happy to do that work. If it is simply queued, a word that it is on the list would be enough — I will stop bumping it.

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

P3 不重要不紧急

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: TrainingRouter keys saved call inputs by agent id, so overlapping calls on one agent train on each other's messages

2 participants