Skip to content

fix: preserve same-session hook bursts - #110575

Merged
steipete merged 4 commits into
mainfrom
codex/fix-same-session-hook-queue
Jul 18, 2026
Merged

steipete merged 4 commits into
mainfrom
codex/fix-same-session-hook-queue

Conversation

@steipete

@steipete steipete commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

Closes #110109

What Problem This Solves

Fixes an issue where multiple /hooks/agent events targeting the same underlying agent session could race the cron session lifecycle claim and lose later events.

Why This Change Was Made

Agent hook dispatch now canonicalizes the target agent and session when the hook is accepted, then uses a per-session FIFO inside tracked detached gateway work. Alias forms such as main and agent:main:main share one queue. Different sessions remain parallel. Runtime settings are refreshed when queued work starts, while the accepted target identity remains stable across config reloads. Failed runs and config-load failures preserve detached error reporting and do not block later queue entries.

The isolated-agent module load is shared so independent session queues can start concurrently.

AI-assisted maintainer fix.

User Impact

Webhook bursts for one session no longer drop loser events as non-retryable CronSessionLifecycleClaimError failures. Operators retain normal parallelism across unrelated sessions without lowering global cron concurrency.

Evidence

  • corepack pnpm test src/gateway/server/hooks.agent-trust.test.ts — 15/15 passed on Blacksmith Testbox tbx_01kxv49hrwfwb5jr1xx0cqdj1t.
  • corepack pnpm test src/gateway/server/hooks.agent-trust.test.ts src/gateway/server.hooks.test.ts — 40/40 unit and HTTP integration tests passed on fresh Testbox tbx_01kxv6v2pjbwmgd48atbwh8y7x.
  • Same focused suite repeated 50 consecutive times — all passed (650 test executions at that revision).
  • corepack pnpm check:changed -- src/gateway/server/hooks.ts src/gateway/server/hooks.agent-trust.test.ts — passed, including core/core-test typechecks, lint, format, boundaries, import cycles, and gateway guards.
  • Live OpenAI QA scenario cron-model-created-one-shot-recurring passed in 4m42s with an isolated random-port gateway: model-authored one-shot ran once and was deleted; recurring ran repeatedly, survived restart, and retained a future next run.
  • $autoreview --mode branch --base origin/main plus focused follow-up reviews — no accepted/actionable findings.
  • PR head: 249ca7e62727.

@steipete steipete added the P1 High-priority user-facing bug, regression, or broken workflow. label Jul 18, 2026
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: M maintainer Maintainer-authored PR labels Jul 18, 2026
@steipete
steipete force-pushed the codex/fix-same-session-hook-queue branch from 8224b10 to ba40f9f Compare July 18, 2026 08:47

@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: 8224b101f5

ℹ️ 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 thread src/gateway/server/hooks.ts Outdated
runId,
jobId,
void runWithGatewayIndependentRootWorkContinuation(() =>
enqueueHookAgentDispatch(sessionKey, async () => {

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 Badge Queue by the canonical cron session key

When hook requests use different aliases for the same target session, such as configured/default main and an explicit agent:main:main (or configured mainKey aliases), this queue treats them as separate keys and lets both runs start in parallel. The cron runner canonicalizes input.sessionKey later via resolveCronAgentSessionKey before lifecycle claiming (src/cron/isolated-agent/run.ts:645), so those aliases still collide on the same persisted session and can hit the same CronSessionLifecycleClaimError burst loss this change is meant to prevent; the queue key needs to be the same canonical session key the cron run will claim.

Useful? React with 👍 / 👎.

@steipete
steipete force-pushed the codex/fix-same-session-hook-queue branch 2 times, most recently from 72851b8 to 6087e9d Compare July 18, 2026 09:03

@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: 6087e9d558

ℹ️ 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 thread src/gateway/server/hooks.ts Outdated
runId,
jobId,
void runWithGatewayIndependentRootWorkContinuation(() =>
enqueueHookAgentDispatch(sessionKey, async () => {

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 Badge Include the target agent in hook queue keys

When hooks are enabled for multiple agents and callers use an unscoped key such as the default main, normalizeHookDispatchSessionKey leaves the key unscoped while the run is still targeted via job.agentId. Queueing only by sessionKey means a slow or stuck hook for one agent now blocks hooks for another agent with the same unscoped key, even though downstream session resolution scopes those runs by agent. Key the FIFO by the effective/canonical agent session identity so only truly shared sessions serialize.

Useful? React with 👍 / 👎.

@steipete
steipete force-pushed the codex/fix-same-session-hook-queue branch from 6087e9d to e308bb4 Compare July 18, 2026 09:10
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Jul 18, 2026
@clawsweeper

clawsweeper Bot commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed July 18, 2026, 5:55 AM ET / 09:55 UTC.

Summary
The branch serializes detached /hooks/agent dispatches per effective session and adds coverage for ordered same-session bursts and failure continuation.

PR surface: Source +25, Tests +86. Total +111 across 2 files.

Reproducibility: no. high-confidence live reproduction was performed in this review. The linked report provides a concrete current-style scenario—send three same-session agent hooks while cron concurrency exceeds one—and the source path supports that race model.

Review metrics: none identified.

Root-cause cluster
Relationship: fixed_by_candidate
Canonical: #110109
Summary: This PR is the active candidate fix for the documented same-session hook event-loss race.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge readiness
Overall: 🧂 unranked krab
Proof: 🧂 unranked krab
Patch quality: 🦐 gold shrimp
Result: blocked until real behavior proof is added.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • [P1] Add a redacted live gateway transcript or logs showing multiple same-session hooks complete in arrival order.
  • Show that alias and multi-agent queue identity follows the effective cron session identity, or document why those paths are intentionally distinct.

Proof guidance:

  • [P1] Needs real behavior proof before merge: Tests and changed-file checks are useful supplemental validation, but the PR body does not show an after-fix real gateway run that sends a same-session hook burst and observes ordered completion. Add a redacted terminal transcript, runtime logs, or recording; redact private endpoints, IP addresses, tokens, and other sensitive details. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Risk before merge

  • [P1] The correctness of this fix depends on queue keys remaining aligned with cron’s canonical agent-session identity; aliases or cross-agent unscoped session keys must not either race or become unnecessarily serialized.
  • [P1] There is no contributor-supplied after-fix run through a real gateway that demonstrates a same-session hook burst completing in arrival order.

Maintainer options:

  1. Prove and confirm the queue boundary (recommended)
    Before merge, provide redacted live gateway evidence for a same-session burst and confirm that queue keys use the same canonical effective agent-session identity as cron lifecycle claiming.
  2. Pause for concurrency-policy direction
    Pause this PR if maintainers want lifecycle-claim retry semantics rather than per-session serialization as the permanent behavior.

Next step before merge

  • [P1] The remaining merge gate is contributor-supplied real behavior evidence plus maintainer confirmation of the canonical session-key boundary; this is not a safe automated repair task.

Maintainer decision needed

  • Question: After real gateway burst evidence is added, does the maintainer want to accept this per-session serialization boundary as the canonical hook-delivery behavior?
  • Rationale: The PR changes concurrency behavior around persisted cron session lifecycle ownership, and the protected label requires explicit maintainer judgment on the intended queue identity and operational tradeoff.
  • Likely owner: steipete — The current implementation contributor is the best available routing candidate in the supplied evidence, though broader ownership history was not available.
  • Options:
    • Accept canonical per-session FIFO (recommended): Approve once a redacted live gateway burst proves ordered delivery and the maintainer confirms the queue key follows the effective cron agent-session identity.
    • Prefer a retry policy: Replace or supplement serialization with bounded lifecycle-claim retries if the intended product behavior is to preserve concurrency for aliases that resolve to one session.

Security
Cleared: The two-file patch changes in-process hook scheduling and focused tests; the supplied diff context shows no dependency, workflow, secret, permission, or supply-chain change.

Review details

Best possible solution:

Keep one FIFO queue per canonical effective agent-session identity, retain independent parallelism for distinct sessions, and add a redacted real gateway burst transcript showing all events are processed in order.

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

No high-confidence live reproduction was performed in this review. The linked report provides a concrete current-style scenario—send three same-session agent hooks while cron concurrency exceeds one—and the source path supports that race model.

Is this the best way to solve the issue?

Unclear: a FIFO is the narrow maintainable shape if its key is the same canonical effective agent-session identity claimed by cron, but real gateway evidence and maintainer confirmation of that boundary are still needed.

AGENTS.md: unclear because the file could not be read completely.

Codex review notes: model internal, reasoning high; reviewed against fcdf06ed2944.

Label changes

Label changes:

  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦐 gold shrimp.
  • remove rating: 🦪 silver shellfish: Current PR rating is rating: 🧂 unranked krab, so this older rating label is no longer current.

Label justifications:

  • P1: This PR addresses dropped same-session hook events that can break active user automation workflows.
  • merge-risk: 🚨 session-state: The patch changes ordering around hook runs that append to and claim the same persisted cron session.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦐 gold shrimp.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: Tests and changed-file checks are useful supplemental validation, but the PR body does not show an after-fix real gateway run that sends a same-session hook burst and observes ordered completion. Add a redacted terminal transcript, runtime logs, or recording; redact private endpoints, IP addresses, tokens, and other sensitive details. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed

PR surface:

Source +25, Tests +86. Total +111 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 89 64 +25
Tests 1 87 1 +86
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 176 65 +111

What I checked:

  • Linked bug and intended behavior: The PR explicitly addresses the reported race where concurrent same-session hooks lose later events after a cron session-lifecycle claim conflict; the linked report supplies a concrete three-request reproduction and expects ordered processing or retry. (src/gateway/server/hooks.ts:125, e308bb4af3bb)
  • Current runtime boundary: Current main dispatches the resolved hook session key into runCronIsolatedAgentTurn, while the cron runner canonicalizes its agent session identity before resolving the persisted cron session. The queue must preserve that same identity invariant. (src/cron/isolated-agent/run.ts:3378, fcdf06ed2944)
  • Prior review continuity: The previous completed ClawSweeper cycle found no patch defect but required a real after-fix gateway burst proof. The current PR body still lists focused tests, changed-file checks, and autoreview only; it contains no live gateway transcript, runtime log, recording, or comparable after-fix behavior evidence. (src/gateway/server/hooks.agent-trust.test.ts:192, e308bb4af3bb)
  • Existing review concerns: Earlier review comments correctly identified that queue identity must match the canonical cron session and include agent scope; the branch was updated after those comments, but the supplied review context does not contain sufficient current-head source detail to re-raise either as a confirmed line-level regression. (src/gateway/server/hooks.ts:174, e308bb4af3bb)

Likely related people:

  • steipete: Authored the single current-head commit that changes the hook dispatch path and its focused regression coverage; broader feature-history attribution could not be completed because read-only shell inspection was unavailable. (role: current gateway-path contributor; confidence: low; commits: e308bb4af3bb; files: src/gateway/server/hooks.ts, src/gateway/server/hooks.agent-trust.test.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

How this review workflow works
  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.
Review history (1 earlier review cycle)
  • reviewed 2026-07-18T09:12:28.281Z sha e308bb4 :: needs real behavior proof before merge. :: none

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Jul 18, 2026
@steipete
steipete force-pushed the codex/fix-same-session-hook-queue branch from e308bb4 to 988a1db Compare July 18, 2026 18:11

@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: 988a1db193

ℹ️ 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".

// settings. Otherwise reload can move one FIFO entry to another session.
job.agentId = agentId;
void runWithGatewayIndependentRootWorkContinuation(() =>
enqueueHookAgentDispatch(queueKey, async () => {

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 Badge Avoid serializing detached hook runs

When multiple hooks reuse a normal key such as hook:ingress or agent:main:main, this queues every later request for the full duration of the preceding agent turn. However, each hook job still has sessionTarget: "isolated" (src/gateway/server/hooks.ts:168), so runCronIsolatedAgentTurn replaces every non-cron base key with the unique cron:${job.id} before lifecycle admission (src/cron/isolated-agent/run.ts:642-653). These runs therefore do not claim the same runtime session, and the new FIFO needlessly converts webhook bursts into a potentially minutes-long serial backlog; queue only targets that actually share a lifecycle key, or use a non-detached job target if shared-session execution is intended.

Useful? React with 👍 / 👎.

@steipete
steipete force-pushed the codex/fix-same-session-hook-queue branch from 988a1db to 249ca7e Compare July 18, 2026 18:44

@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: 249ca7e627

ℹ️ 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".

return runId;
}
const agentId = value.agentId ?? resolveDefaultAgentId(dispatchCfg);
const queueKey = resolveCronAgentSessionKey({

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 Badge Preserve agent scope in global-session queue keys

When session.scope is "global" and hooks target different agents, resolveCronAgentSessionKey canonicalizes each agent's main alias to the same literal global, so the process-wide queue makes a slow hook for one agent block hooks for every other agent. Those runs remain agent-scoped because runCronIsolatedAgentTurn receives the resolved agentId and resolveCronSession selects an agent-specific store path. Fresh evidence beyond the earlier agent-key comment is the global-scope canonicalization in src/config/sessions/main-session.ts combined with the agent-specific store selection in src/cron/isolated-agent/session.ts; retain the agent dimension in the queue key even when the canonical session component is global.

Useful? React with 👍 / 👎.

try {
// Agent hooks run after the HTTP response path has returned, so failure
// handling must record a system event instead of throwing to the caller.
const cfg = getRuntimeConfig();

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 Badge Keep reload-time routing aligned with the fixed queue key

When session.mainKey or session.scope changes while a same-key hook is waiting, its queue key remains canonicalized with the acceptance-time config, but this fresh config causes the runner to recanonicalize the original sessionKey under the new routing contract. A hook accepted after the reload uses the new queue and can therefore start alongside the older waiting hook even though both resolve to the same execution-time session identity, defeating the FIFO guarantee and reopening the race this change is intended to prevent.

Useful? React with 👍 / 👎.

@steipete
steipete merged commit f669fb9 into main Jul 18, 2026
124 checks passed
@steipete
steipete deleted the codex/fix-same-session-hook-queue branch July 18, 2026 18:53
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 19, 2026
* fix(gateway): serialize same-session agent hooks

* fix(gateway): canonicalize queued hook sessions

* fix(gateway): preserve hook runner routing contract

* docs(gateway): explain hook reload identity
zooqueen pushed a commit to zooqueen/openclaw that referenced this pull request Sep 11, 2026
* fix(gateway): serialize same-session agent hooks

* fix(gateway): canonicalize queued hook sessions

* fix(gateway): preserve hook runner routing contract

* docs(gateway): explain hook reload identity
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: M status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Concurrent same-session hook events race on the cron session-claim; losers dropped as non-retryable CronSessionLifecycleClaimError

1 participant