Skip to content

Agent re-executes the previous turn's instruction, creating a duplicate node (cross-turn; the per-turn duplicate guard cannot catch it) #1780

Closed

Description

@malibio

Surfaced by the #1775 matrix re-run (run 3, rebased onto the #1778 runner). Distinct from #1775, which was about argument construction and error reporting.

Symptom

The agent completes a create instruction correctly, then re-executes it during the next turn, writing a second identical node.

From the daemon log (chat group 8c → 8d):

17:43:45  create_node  is_error=true   args={}                  <- reported as unparseable (#1775 fix)
17:43:46  create_node  is_error=false  {"content":"Kind of Blue by Miles Davis",
                                        "node_type":"album_to_listen"}  -> f1f25564
17:43:47  iteration=3  response="I have added \"Kind of Blue\"..."      <- 8c ends, correctly, ONE node

17:43:49  iteration=0  search_nodes {"node_type":"venue_booking",...}   <- 8d turn begins
17:43:50  iteration=1  create_node  {"content":"Kind of Blue by Miles Davis",
                                     "node_type":"album_to_listen"}     -> 0bbcb76b   <- DUPLICATE
17:43:53  iteration=3  create_node  {"content":"the Blue Note [email protected]",
                                     "node_type":"venue_booking"}       <- 8d actual work

Two nodes now exist for one user request. A later search_nodes in the same run confirms it: Found 2 nodes matching "Kind of Blue".

Why the existing guard misses it

packages/agent/src/local_agent/agent_loop.rs has a duplicate-call guard, but seen_calls is scoped to a single run_turn and starts empty each turn. The repeat happens in the next turn, so there is nothing to match against. The guard is working as designed; its design does not cover this.

Note the iteration counter restarting at 0 in the log above — that is the turn boundary, and it is exactly where the guard resets.

Why the eval under-reports it

toolOnce counts tool names scraped per chat node. Because 8c and 8d share a chat, the single stray call is attributed to both, so 8c and 8d each report "got 2" from one extra write. Reading the assertion alone suggests two separate defects; the log shows one.

Not a regression from #1775

In all three #1775 runs the argument error is reported correctly, and in this run the model recovers from that message and creates the node successfully on the next call. The duplicate is a separate behavior that runs 1 and 2 happened not to exhibit — the matrix has large run-to-run variance (see the caveats in scripts/results-e4b.json).

Investigation notes

Acceptance criteria

  • Root-cause why the next turn re-executes the previous turn's create instruction (with a captured prompt dump, not inference)
  • A completed create instruction is not re-executed on a subsequent turn
  • A regression test covers the cross-turn case specifically — the existing per-turn guard tests do not
  • State whether the eval should attribute tool calls per turn rather than per chat node, so one stray call stops failing two scenarios

Activity

  1. added
    bug
    on Jul 28, 2026
  2. malibio commented on Jul 28, 2026

    @malibio
    CollaboratorAuthor

    Baseline (worktree issue-1780-cross-turn-duplicate, from 7dcae76): Frontend: 170 test files passed, 4104 tests passed.

  3. malibio commented on Jul 28, 2026

    @malibio
    CollaboratorAuthor

    Root cause (verified in code, not inferred)

    The session does not persist across turns, and the persistence round-trip drops every trace of tool activity. Turn N+1 sees no evidence the work was done.

    1. A brand-new ephemeral session is built for every turn.
    packages/daemon/src/services/local_agent_service.rs:341 run_ai_chat_turn:

    • :343 let history = load_node_history(...) — re-read from the DB node
    • :363 let prior_history: Vec<ChatMessage> = history[..history.len()-1].to_vec();
    • :373 service.create_session(None, prior_history) — new session each turn
    • :435 service.end_session(&session_id) — destroyed at turn end

    So seen_calls is not merely turn-scoped by choice; the whole session object is gone. There is nothing to widen the guard's scope onto without changing what is persisted.

    2. The persisted message shape has nowhere to put tool calls.
    AiChatMessage (packages/core/src/models/ai_chat_node.rs:38-52) is only:

    pub struct AiChatMessage { role: String, content: String, timestamp: Option<String>, reasoning: Option<String> }

    No tool_calls, no tool_call_id, no name.

    append_assistant_message (local_agent_service.rs:619) writes only the final prose result.response — the assistant tool-call message and every tool result are never persisted at all.

    3. Reload discards anything that is not user/assistant text.
    load_node_history (local_agent_service.rs:1342-1356):

    let role = match m.role.as_str() {
        "user" => Role::User,
        "assistant" => Role::Assistant,
        _ => return None,          // any "tool" role discarded
    };
    let mut msg = ChatMessage::text(role, m.content);  // tool_calls = vec![], tool_call_id = None

    ChatMessage::text (packages/nlp-engine/src/chat/types.rs:145-154) hard-codes tool_calls: Vec::new().

    4. The in-loop message that would carry the evidence is deliberately content-free.
    agent_loop.rs:717-722 pushes assistant_with_tool_calls(String::new(), tool_calls) — empty content by design (so the chat template stays clean). That message is in-memory only.

    Why this produces the duplicate

    On turn 8d the model's history is:

    • user: "add Kind of Blue…" ← the instruction, fully present
    • assistant: "I have added "Kind of Blue"…" ← prose claim, no node id, no tool call
    • user: (the 8d request)

    The create_node call, its arguments, and the returned node id f1f25564 are all absent. The only evidence the instruction was satisfied is an unverifiable prose sentence. A model that treats its own prior prose as less authoritative than the explicit user instruction still visible above it re-executes the instruction. That is a soft, probabilistic cue — which is exactly why this reproduced in 1 of 3 runs rather than deterministically.

    This also means a cross-turn seen_calls set is not implementable as stated in the issue: there is no cross-turn state to hold it. The durable fix is to persist tool-call evidence so the next turn can see its own completed work.

    Eval attribution (acceptance criterion 4)

    The issue's premise here is incorrect — attribution is already per-turn, not per-chat-node.

    scripts/aichat.ts:145-151 captures NS_LOG byte size before the send; reportTurnLog(logSize) (:111-137) then tails only the bytes appended during that turn and emits one [tool] line per "Tool executed". runner.ts:71-99 runTurn scrapes those into one TurnRecord per send.

    So each stray call is attributed to exactly one turn. The reason 8c and 8d both failed is different: agent-matrix.ts:240 flattens across turns for the verdict —

    const toolsCalled = turns.flatMap((t) => t.toolsCalled);

    Scenarios 8c and 8d are separate scenarios that share a chat and are scored over the flattened turn list, so a toolOnce count of 2 surfaces in both. No runner change is needed; if the double-reporting is worth removing, the change belongs in how matrix scenarios sharing a chat are scored, not in per-turn attribution.

  4. malibio commented on Jul 28, 2026

    @malibio
    CollaboratorAuthor

    Acceptance criterion 4 — eval attribution: no change needed

    I said in my earlier comment that the double-reporting came from agent-matrix.ts:240 flattening across turns. That was wrong, and I'm correcting it: attribution is already strictly per-turn at every layer.

    1. scripts/aichat.ts:145-151 records the NS_LOG byte offset before the send; reportTurnLog(logSize) (:111-137) tails only bytes appended during that turn, emitting one [tool] line per "Tool executed".
    2. runner.ts:71-99 runTurn scrapes those into one TurnRecord per send.
    3. runner.ts:337 scores with [scored] only — the scenario's own turn. Prior context turns (:330-332) are collected separately and explicitly "never scored". The flatMap at agent-matrix.ts:240 therefore runs over a single-element array.

    So one stray call cannot be counted against two scenarios. The issue's stated explanation ("because 8c and 8d share a chat, the single stray call is attributed to both") does not hold.

    What actually happened in that run is that there were two separate stray create_node calls, one in each turn — consistent with the daemon log, where the duplicate fires at 8d iteration=1 and 8d also does its own legitimate create_node at iteration=3 for the venue booking. 8c reported 2 for its own reason; 8d reported 2 because it genuinely made two create_node calls in its own turn (the repeat of 8c's instruction plus its own work).

    Since attribution is already per-turn, I have made no eval change. The toolOnce assertion is measuring the right thing; the duplicate write it caught was real.

  5. self-assigned this
    on Jul 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

backendbug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions