Skip to content

Keep sessions_send delivery pending after wait timeout - #58133

Closed
medusa527 wants to merge 3 commits into
openclaw:mainfrom
medusa527:codex/sessions-send-timeout
Closed

medusa527 wants to merge 3 commits into
openclaw:mainfrom
medusa527:codex/sessions-send-timeout

Conversation

@medusa527

Copy link
Copy Markdown

Summary

  • treat sessions_send wait timeouts as pending delivery instead of an immediate hard failure
  • keep the agent-to-agent announce flow alive so delayed replies can still be surfaced
  • add regression coverage for the delayed-reply timeout path

Problem

sessions_send currently returns status: "timeout" as soon as the initial agent.wait times out. In the agent-to-agent path, that can be premature: the target run may still finish moments later, but the calling agent has already received a hard timeout and may emit a user-facing failure like DELEGATION_FAILED:socrates:timeout.

Reproduction

  1. Use sessions_send from one agent to another with timeoutSeconds > 0.
  2. Let the target run exceed the initial wait window but still complete shortly after.
  3. Observe that the caller receives a timeout immediately even though the target eventually produces a valid reply.

Expected

If the target run is still in flight after the initial wait window, sessions_send should keep delivery pending and allow the follow-up announce flow to finish when the delayed reply arrives.

Actual

The tool returned status: "timeout" right away, which encouraged the caller to post a failure even though the target reply could still be delivered successfully.

Fix

When the initial agent.wait times out, keep the tool result in accepted/pending-delivery state and start the existing announce flow with the in-flight runId. The announce flow performs its own follow-up wait and can still fetch and relay the delayed reply.

The same pending-delivery treatment now also applies when the wait RPC itself hits a gateway timeout after the target run has already started.

Validation

  • vitest --root /tmp/openclaw-sessions-send-timeout run src/agents/openclaw-tools.sessions.test.ts -t "sessions_send keeps delayed announce delivery alive after a wait timeout"
  • vitest --root /tmp/openclaw-sessions-send-timeout run src/agents/openclaw-tools.sessions.test.ts

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: M labels Mar 31, 2026
@byungsker

This comment was marked as spam.

@medusa527

Copy link
Copy Markdown
Author

Thanks for the careful read.

I pushed a small follow-up in 5add7048e7 to make the upper bound explicit:

  • added a short implementation comment in runSessionsSendA2AFlow() clarifying that the delayed-delivery path does a single follow-up agent.wait, then exits if that also times out or yields no reply
  • added a second test that covers that edge case and asserts we stop after the initial wait plus one delayed wait, with no announce delivery sent

On the first point: the existing delayed-timeout test was already asserting that the delivery channel receives the final announced content via expect(announceDeliveredMessage).toBe("announce-ready"), but I agree the bounded-path behavior was worth making more explicit in code and test coverage.

@medusa527
medusa527 marked this pull request as ready for review April 2, 2026 02:08
@medusa527
medusa527 requested a review from a team as a code owner April 2, 2026 02:08
@greptile-apps

greptile-apps Bot commented Apr 2, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR changes sessions_send to treat agent.wait timeouts (both status-level and gateway-level) as pending delivery instead of hard failures, then delegates to the existing A2A announce flow which performs one bounded follow-up wait. The fs changes add an expectedSize guard with backup/restore logic to catch silent write truncation across both the Python and JS write helpers.

Confidence Score: 5/5

  • Safe to merge; the core sessions-send fix is correct and well-tested, and the only finding is a P2 edge case in a rarely-used fallback path.
  • The primary timeout-to-pending change and the A2A follow-up wait are logically sound and covered by new regression tests. The fs size-verification logic is correct for both the Python subprocess and JS fallback paths. The only finding is an unlikely TOCTOU state inconsistency in runPinnedWriteFallback that could surface the wrong error message; it is P2 and does not block merge.
  • src/infra/fs-pinned-write-helper.ts — the hadExistingTarget reset in the ENOENT fallback catch
Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/infra/fs-pinned-write-helper.ts
Line: 371-376

Comment:
**`hadExistingTarget` not reset on TOCTOU-ENOENT**

If `fs.stat(targetPath)` succeeds (setting `hadExistingTarget = true`) but then `fs.link` or `fs.copyFile` throws `ENOENT` (e.g. file deleted between stat and link), the outer catch swallows the ENOENT without resetting `hadExistingTarget`. The code then continues with `hadExistingTarget = true` but no backup on disk. Later, if a size mismatch occurs, `fs.rename(backupPath, targetPath)` on line 382 throws `ENOENT` — raising the wrong error and leaving the new-but-wrong-size content in place rather than surfacing a clean `write size mismatch`.

This only triggers in an extremely rare TOCTOU race and is limited to the JS fallback path (`runPinnedWriteFallback`), but the fix is straightforward:

```suggestion
  } catch (error) {
    if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
      await fs.rm(tempPath, { force: true }).catch(() => {});
      throw error;
    }
    hadExistingTarget = false;
  }
```

How can I resolve this? If you propose a fix, please make it concise.

Reviews (1): Last reviewed commit: "Clarify bounded follow-up wait in sessio..." | Re-trigger Greptile

Comment thread src/infra/fs-pinned-write-helper.ts Outdated
Comment on lines +371 to +376
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
await fs.rm(tempPath, { force: true }).catch(() => {});
throw error;
}
}

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.

P2 hadExistingTarget not reset on TOCTOU-ENOENT

If fs.stat(targetPath) succeeds (setting hadExistingTarget = true) but then fs.link or fs.copyFile throws ENOENT (e.g. file deleted between stat and link), the outer catch swallows the ENOENT without resetting hadExistingTarget. The code then continues with hadExistingTarget = true but no backup on disk. Later, if a size mismatch occurs, fs.rename(backupPath, targetPath) on line 382 throws ENOENT — raising the wrong error and leaving the new-but-wrong-size content in place rather than surfacing a clean write size mismatch.

This only triggers in an extremely rare TOCTOU race and is limited to the JS fallback path (runPinnedWriteFallback), but the fix is straightforward:

Suggested change
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
await fs.rm(tempPath, { force: true }).catch(() => {});
throw error;
}
}
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
await fs.rm(tempPath, { force: true }).catch(() => {});
throw error;
}
hadExistingTarget = false;
}
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/infra/fs-pinned-write-helper.ts
Line: 371-376

Comment:
**`hadExistingTarget` not reset on TOCTOU-ENOENT**

If `fs.stat(targetPath)` succeeds (setting `hadExistingTarget = true`) but then `fs.link` or `fs.copyFile` throws `ENOENT` (e.g. file deleted between stat and link), the outer catch swallows the ENOENT without resetting `hadExistingTarget`. The code then continues with `hadExistingTarget = true` but no backup on disk. Later, if a size mismatch occurs, `fs.rename(backupPath, targetPath)` on line 382 throws `ENOENT` — raising the wrong error and leaving the new-but-wrong-size content in place rather than surfacing a clean `write size mismatch`.

This only triggers in an extremely rare TOCTOU race and is limited to the JS fallback path (`runPinnedWriteFallback`), but the fix is straightforward:

```suggestion
  } catch (error) {
    if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
      await fs.rm(tempPath, { force: true }).catch(() => {});
      throw error;
    }
    hadExistingTarget = false;
  }
```

How can I resolve this? If you propose a fix, please make it concise.

@medusa527
medusa527 force-pushed the codex/sessions-send-timeout branch from 5add704 to f64211f Compare April 3, 2026 13:57
@medusa527
medusa527 force-pushed the codex/sessions-send-timeout branch from f64211f to 76796dc Compare April 12, 2026 06:33
@medusa527

Copy link
Copy Markdown
Author

Just rebased onto current main to clear the merge conflicts — the upstream refactor of sessions_send (moving gateway-timeout handling into waitForAgentRunAndReadUpdatedAssistantReply / waitForAgentRun) let me simplify the patch: the old inline try/catch for gateway timeouts is gone, and the two delivery-pending branches now just fall through to startA2AFlow. All 16 tests in openclaw-tools.sessions.test.ts pass locally. Could a maintainer take a look? Thanks!

@medusa527
medusa527 force-pushed the codex/sessions-send-timeout branch from 76796dc to a0351b3 Compare April 22, 2026 08:52

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a0351b3871

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines 377 to +381
if (result.status === "timeout") {
startA2AFlow(undefined, runId);
return jsonResult({
runId,
status: "timeout",
error: result.error,
status: "accepted",

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.

P1 Badge Treat terminal wait timeouts as failures, not accepted

agent.wait uses status: "timeout" for both “still running past caller timeout” and terminal aborted runs (see src/gateway/server-methods/agent-job.ts where aborted end events map to timeout). This branch now converts every timeout into status: "accepted" and starts delayed announce flow, so a run that has already ended with timeout is reported as pending success and never produces the expected follow-up delivery. In practice, when the target agent run times out/aborts, callers can get a misleading accepted result instead of a failure signal.

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8676fd294b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

});

if (result.status === "timeout") {
startA2AFlow(undefined, runId);

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.

P1 Badge Pass baseline when deferring timed-out waits to A2A flow

This timeout branch now starts delayed announce delivery with startA2AFlow(undefined, runId) but drops the pre-run snapshot captured in baselineReply. The delayed path in runSessionsSendA2AFlow then calls readLatestAssistantReply(...) (src/agents/tools/sessions-send-tool.a2a.ts) and treats that as the run reply, which can be an old assistant message when the timed-out run finishes without emitting new assistant text. In that case, sessions_send may announce stale content from earlier history to the requester channel, which is a new regression introduced by enabling timeout-to-announce flow here.

Useful? React with 👍 / 👎.

@medusa527

Copy link
Copy Markdown
Author

CI is now fully green (94/94) after the rebase onto current main + a small type-narrowing fix in openclaw-tools.sessions.test.ts for call.params.runId access. The boundary-lint failures from the previous run were pre-existing on main at my original base and were fixed upstream in b78713a3 and ccbef550, which the rebase picked up. Patch is unchanged in behavior; all 16 sessions tests still pass. Could a maintainer take a look when there's a spare moment? Thanks!

@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Apr 30, 2026
@clawsweeper

clawsweeper Bot commented May 1, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: found issues before merge.

Summary
This branch changes sessions_send to return accepted/pending delivery and start delayed A2A announce delivery after an initial wait timeout, with bounded-follow-up comments and regression tests.

Reproducibility: yes. Current main can be reproduced with a mocked sessions_send path where agent returns a run id and the first nonzero-timeout agent.wait returns status: "timeout"; the code returns a hard timeout before any delayed announce path. The PR regressions are reproducible with mocked terminal-aborted timeout and stale-history/no-new-reply cases.

Next step before merge
Manual review is next because #68196 proposes a different timeout compensation contract and this branch has P1 semantics findings that should be resolved in one chosen design.

Security
Cleared: The diff changes agent runtime logic and focused tests/comments only, with no concrete security or supply-chain concern found.

Review findings

  • [P1] Do not mark terminal timeouts as accepted — src/agents/tools/sessions-send-tool.ts:380-383
  • [P1] Pass the baseline into delayed A2A reads — src/agents/tools/sessions-send-tool.ts:380
  • [P3] Add the required changelog entry — src/agents/tools/sessions-send-tool.ts:383
Review details

Best possible solution:

Land one consolidated fix that distinguishes soft wait-window expiry from terminal run timeout, preserves the baseline reply guard for delayed reads, keeps announce delivery alive only for proven in-flight accepted runs, and adds the required changelog entry.

Do we have a high-confidence way to reproduce the issue?

Yes. Current main can be reproduced with a mocked sessions_send path where agent returns a run id and the first nonzero-timeout agent.wait returns status: "timeout"; the code returns a hard timeout before any delayed announce path. The PR regressions are reproducible with mocked terminal-aborted timeout and stale-history/no-new-reply cases.

Is this the best way to solve the issue?

No. The direction is valid for soft wait-window expiry, but this implementation is not the safest fix because it treats all timeout results as accepted and reads delayed replies without the pre-run baseline; #68196 should be considered during consolidation.

Full review comments:

  • [P1] Do not mark terminal timeouts as accepted — src/agents/tools/sessions-send-tool.ts:380-383
    agent.wait can return status: "timeout" for both caller wait-window expiry and already-ended aborted runs. This branch converts both cases into accepted pending delivery, so terminal failures lose their failure signal and callers can wait for an announce that will never arrive.
    Confidence: 0.9
  • [P1] Pass the baseline into delayed A2A reads — src/agents/tools/sessions-send-tool.ts:380
    The normal wait path captures baselineReply so old assistant history is not reused as the new run reply, but the timeout branch calls startA2AFlow(undefined, runId). The delayed A2A flow then reads the latest assistant reply without that baseline and can announce stale history.
    Confidence: 0.89
  • [P3] Add the required changelog entry — src/agents/tools/sessions-send-tool.ts:383
    This changes the user-visible sessions_send status and delivery contract, but the PR does not update CHANGELOG.md. Add a single-line active-version entry with appropriate human contributor credit before merge.
    Confidence: 0.86

Overall correctness: patch is incorrect
Overall confidence: 0.92

What I checked:

  • current-main-hard-timeout-path: Current main starts the target run, waits with waitForAgentRunAndReadUpdatedAssistantReply, and immediately returns status: "timeout" when that helper reports timeout; it does not start delayed A2A delivery in that branch. (src/agents/tools/sessions-send-tool.ts:423, 929df0f5567f)
  • pr-timeout-branch-change: The PR patch changes the timeout branch to call startA2AFlow(undefined, runId) and return status: "accepted" with pending delivery for every result.status === "timeout". (src/agents/tools/sessions-send-tool.ts:375, 8676fd294bd9)
  • timeout-status-is-ambiguous: Gateway lifecycle end events with aborted normalize to status: "timeout", and waitForAgentRun also returns timeout for agent.wait timeout responses and gateway-timeout errors, so the PR cannot treat all timeout results as still in flight. (src/gateway/server-methods/agent-job.ts:145, 929df0f5567f)
  • baseline-protection-current: The normal reply read compares the latest assistant reply fingerprint against the pre-run baseline, preventing stale assistant history from being reused as the new run reply. (src/agents/run-wait.ts:205, 929df0f5567f)
  • delayed-a2a-read-lacks-baseline: The delayed A2A path waits once on waitRunId and then reads the latest assistant reply directly without any baseline parameter, so the PR's startA2AFlow(undefined, runId) path can announce old content. (src/agents/tools/sessions-send-tool.a2a.ts:48, 929df0f5567f)
  • overlapping-open-pr: Related fix(agents): post-timeout compensation in sessions_send #68196 is open and proposes a different post-timeout compensation contract in run-wait.ts and sessions-send-tool.ts, so this PR should not be treated as the sole repair path. (6c42105c1ec3)

Likely related people:

  • steipete: Recent GitHub commit history shows repeated maintenance of sessions-send-tool.ts, sessions-send-tool.a2a.ts, and run-wait.ts, including the run-wait helper extraction and current sessions_send routing fixes. (role: recent maintainer and central feature-history owner; confidence: high; commits: 8daf0124c93e, 49be9a15fe10, c5c08c074a44; files: src/agents/tools/sessions-send-tool.ts, src/agents/tools/sessions-send-tool.a2a.ts, src/agents/run-wait.ts)
  • scotthuang: Recent commits changed the A2A skip behavior in sessions-send-tool.ts, which is part of the same delivery and follow-up announce path touched by this PR. (role: adjacent sessions_send A2A maintainer; confidence: medium; commits: 8a7c21407ae3, 1c3fbbd72a01; files: src/agents/tools/sessions-send-tool.ts)
  • jalehman: Commit history shows prior work on sessions-send-tool.a2a.ts for sessions_send announce delivery, including Telegram thread delivery behavior in the same helper. (role: adjacent announce-delivery owner; confidence: medium; commits: 8359e5f584d3; files: src/agents/tools/sessions-send-tool.a2a.ts)
  • ZiPengWei: Recent history on run-wait.ts includes recovery behavior for interrupted subagent waits, adjacent to the timeout and transport semantics this PR changes. (role: adjacent wait/recovery maintainer; confidence: low; commits: 845040214e13; files: src/agents/run-wait.ts)

Remaining risk / open question:

  • The desired post-timeout contract is unsettled because fix(agents): post-timeout compensation in sessions_send #68196 proposes a compensation-based behavior instead of always keeping delayed announce pending.
  • The PR head predates several current-main sessions_send changes, so maintainers should rebase or consolidate before relying on CI from the older head.

Codex review notes: model gpt-5.5, reasoning high; reviewed against 929df0f5567f.

@openclaw-barnacle openclaw-barnacle Bot removed the stale Marked as stale due to inactivity label May 1, 2026
@medusa527

Copy link
Copy Markdown
Author

Closing in favor of #68196, which addresses both P1 findings the reviewer raised here (distinguishes terminal aborts from soft wait-window expiry, and threads a baseline through the late-reply read). Thanks @glfruit.

@medusa527 medusa527 closed this May 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling size: M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants