Skip to content

fix(agents): prevent native hook failures during overlapping Codex runs - #134346

Closed
esqandil wants to merge 1 commit into
openclaw:mainfrom
esqandil:fix/native-hook-relay-lifecycle-upstream
Closed

esqandil wants to merge 1 commit into
openclaw:mainfrom
esqandil:fix/native-hook-relay-lifecycle-upstream

Conversation

@esqandil

@esqandil esqandil commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes an issue where Codex sessions with overlapping runs could lose native hook routing mid-turn and fail closed with native hook relay bridge stale registration or not found errors. A new turn, nested run, or bound-thread resume reused the session's stable relay identifier and replaced a still-live registration.

Why This Change Was Made

Tracks live registrations per relay identifier and routes each invocation to the newest registration matching its generation. The loopback bridge and SQLite locator remain shared until the final registration exits; renewals cover non-current siblings; retained relays remain valid across sibling churn; and the bounded registration cap rejects a newcomer instead of evicting active work.

The implementation preserves exact-generation fail-closed behavior and upgrades shared state created by older module copies in place.

User Impact

Overlapping Codex runs in the same session can continue using PreToolUse and related native hooks without one run invalidating another. Stale or unknown generations remain rejected.

Evidence

  • 158/158 focused relay tests passed on the current head (src/agents/harness/native-hook-relay.test.ts, src/gateway/server-methods/native-hook-relay.test.ts, extensions/codex/src/app-server/native-hook-relay.test.ts), including new regression coverage for: an invocation binding to the registration that claimed the payload turn; unclaimed hooks rejected while multiple live registrations contest one generation; a steered/duplicate turn/start claim refused instead of transferring hook ownership; an open-foreground unclaimed direct child parking in admission-wait and resolving on claimDirectChild; and closed-foreground unknown children still rejected.
  • Reverting the fix (tests kept) makes the new tests fail for the intended reasons: the cross-bind cases route to the wrong sibling and the admission-wait case hard-blocks.
  • Core and extension TypeScript checks passed; oxlint, formatting, max-lines, and assertion-safety checks passed. The earlier CHANGELOG.md edit is removed per review.
  • Codex-side contract verified against the sibling codex-rs source: turn/start is start-or-steer (app-server/src/request_processors/turn_processor.rs — a steered start returns the live sibling's turn id in the same TurnStartResponse shape), and every hook payload carries a mandatory turn_id set from the active turn (core/src/hook_runtime.rs, hooks/src/schema.rs). The turn-claim registry therefore keys on a selector that is always present, and a steered turn/start can no longer silently transfer hook ownership: a turn id already claimed by a live sibling is refused, and a double-claimed turn id fails closed (block/deny) rather than routing to the newest registration.
  • Live behavior proof (equivalent lifecycle semantics deployed against a v2026.7.1 gateway, journal excerpts redacted to markers): fresh native session NATIVE_HOOK_SMOKE_OK; two simultaneous overlapping native sessions in one Codex thread completed OVERLAP_A_OK / OVERLAP_B_OK with zero native hook relay not found / stale-registration errors over the observation window, where the pre-fix build reproducibly failed mid-turn.
  • Fail-closed posture unchanged on every rejection path: stale, unknown, contested, or capped registrations produce a block/deny at the hook boundary with no gateway fallback (src/cli/native-hook-relay-cli.ts), and the cap rejects the newcomer instead of evicting live work.

@clawsweeper

clawsweeper Bot commented Aug 31, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime agents Agent runtime and tooling size: XL labels Aug 31, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. 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. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Aug 31, 2026
@clawsweeper

clawsweeper Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed August 31, 2026, 6:10 PM ET / 22:10 UTC.

ClawSweeper review

What this changes

The PR tracks concurrent native-hook relay registrations, shares one loopback bridge between them, and binds Codex hook traffic to the provider turn that owns it.

Merge readiness

⛔ Blocked until stronger real behavior proof is added - 5 items remain

Keep open: the per-registration routing direction addresses the reported overlap, but legacy/current module coexistence still tears down a live relay and the exported SDK handle gains a required field that breaks structural consumers.

Priority: P1
Reviewed head: 65b6654b3085093e882759bdc10e7fa803744942

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The intended owner-boundary repair has useful focused coverage, but two concrete correctness blockers and uninspectable exact-head runtime proof prevent merge readiness.
Proof confidence 🦪 silver shellfish (2/6) Needs stronger real behavior proof before merge: Authority-chain proof required: the PR body asserts redacted v2026.7.1 markers, but supplies no inspectable exact-head trace. Provide a redacted run of two overlapping real Codex turns showing each reaches its own policy owner, plus duplicate/stale-turn rejection before tool I/O. 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.
Patch quality 🦐 gold shrimp (3/6) 2 actionable review findings remain.

Verification

Check Result Evidence
Real behavior Needs proof Needs stronger real behavior proof before merge: Authority-chain proof required: the PR body asserts redacted v2026.7.1 markers, but supplies no inspectable exact-head trace. Provide a redacted run of two overlapping real Codex turns showing each reaches its own policy owner, plus duplicate/stale-turn rejection before tool I/O. 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 7 items Introduced lifecycle change: The PR creates a tracked registration set, adds only the new registration, then replaces the legacy shared-map entry.
Legacy registration compatibility path: The new code explicitly describes registrations from older module copies as living only in the shared relays map, but its teardown condition treats an empty tracked set and absent shared-map entry as no live registration.
Pre-change behavior: The parent implementation maintained one shared relay entry and refused an old registration’s cleanup once that entry had been replaced, establishing the mixed-module lifecycle that the new compatibility code claims to support.
Findings 2 actionable findings [P1] Reconcile legacy registrations before replacing the shared slot
[P1] Keep the exported registration-handle shape source-compatible
Security None None.

How this fits together

Codex starts create native-hook relay registrations, while hook subprocesses send payloads through a shared loopback bridge. The relay selects the owning run’s policy context and returns the resulting allow/block response to the native client.

flowchart LR
  A[Codex turn start] --> B[Relay registration]
  B --> C[Shared loopback bridge]
  D[Native hook payload] --> E[Turn and generation routing]
  E --> F[Run policy context]
  F --> G[Gateway hook result]
Loading

Before merge

  • Add real behavior proof - Needs stronger real behavior proof before merge: Authority-chain proof required: the PR body asserts redacted v2026.7.1 markers, but supplies no inspectable exact-head trace. Provide a redacted run of two overlapping real Codex turns showing each reaches its own policy owner, plus duplicate/stale-turn rejection before tool I/O. 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.
  • Reconcile legacy registrations before replacing the shared slot (P1) - A legacy module-copy registration exists only in relays; this insertion adds only the new registration to the slot map and overwrites that entry. Its later unregister empties the map and deletes relays, so teardown removes the bridge and relay-wide state although the older run is still live. The legacy test covers isolation, not this overlapping lifecycle.
  • Keep the exported registration-handle shape source-compatible (P1) - claimTurn is required on a handle type re-exported through the plugin SDK. Structural consumers that construct a handle now fail to compile; this branch's Codex mock needed the new member for that reason. Keep this additive or internal, and add compatibility coverage for SDK consumers.
  • Resolve merge risk (P1) - The PR adds production +783/-306 (net +477); its lifecycle split should be simplified where the two compatibility repairs permit it.
  • Resolve merge risk (P1) - The asserted Codex turn contract cannot be independently checked because the required sibling source is unavailable in this review environment.

Findings

  • [P1] Reconcile legacy registrations before replacing the shared slot — src/agents/harness/native-hook-relay.ts:194-196
  • [P1] Keep the exported registration-handle shape source-compatible — src/agents/harness/native-hook-relay-types.ts:98-109
Agent review details

Security

None.

PR surface

Source +477, Tests +1079. Total +1556 across 10 files.

View PR surface stats
Area Files Added Removed Net
Source 7 783 306 +477
Tests 3 1192 113 +1079
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 10 1975 419 +1556

Review metrics

Metric Value Why it matters
Production versus test delta production +783/-306; tests +1192/-113 The bug fix has net +477 production lines across relay ownership and bridge lifetime, so the compatibility fixes should avoid retaining unnecessary lifecycle surface.

Merge-risk options

Maintainer options:

  1. Repair shared lifecycle and SDK contract (recommended)
    Reconcile legacy shared-map entries with slot-tracked registrations, keep the exported handle structurally compatible, and add the mixed-lifecycle and consumer-compatibility regressions.
  2. Pause unsupported compatibility
    If old and new module copies are intentionally not supported together, pause this change until an owner approves removing that compatibility claim and its associated runtime path.

Technical review

Best possible solution:

Adopt or retain a legacy shared-map registration for the full overlapping lifecycle, preserve the prior SDK handle shape, and prove exact-head overlapping turns and rejection paths at the final hook boundary.

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

Yes, from source: register a legacy shared-map relay, register a slot-tracked sibling on its relay ID, then unregister the sibling; the old live relay is no longer represented and its bridge is torn down.

Is this the best way to solve the issue?

No: the central ownership direction is sound, but it must preserve the claimed mixed-module lifecycle and the existing public structural SDK contract.

Full review comments:

  • [P1] Reconcile legacy registrations before replacing the shared slot — src/agents/harness/native-hook-relay.ts:194-196
    A legacy module-copy registration exists only in relays; this insertion adds only the new registration to the slot map and overwrites that entry. Its later unregister empties the map and deletes relays, so teardown removes the bridge and relay-wide state although the older run is still live. The legacy test covers isolation, not this overlapping lifecycle.
    Confidence: 0.96
  • [P1] Keep the exported registration-handle shape source-compatible — src/agents/harness/native-hook-relay-types.ts:98-109
    claimTurn is required on a handle type re-exported through the plugin SDK. Structural consumers that construct a handle now fail to compile; this branch's Codex mock needed the new member for that reason. Keep this additive or internal, and add compatibility coverage for SDK consumers.
    Confidence: 0.9

Overall correctness: patch is incorrect
Overall confidence: 0.93

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add merge-risk: 🚨 compatibility: A required member was added to a type exported through the plugin SDK, which can break structural plugin consumers on upgrade.
  • add merge-risk: 🚨 availability: The legacy/current coexistence path can remove the shared bridge and fail hooks for a still-live registration.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦐 gold shrimp.
  • remove rating: 🧂 unranked krab: Current PR rating is rating: 🦪 silver shellfish, so this older rating label is no longer current.
  • remove merge-risk: 🚨 security-boundary: Current PR review merge-risk labels are merge-risk: 🚨 compatibility, merge-risk: 🚨 availability.

Label justifications:

  • P1: A live native run can lose its bridge when a newer slot-tracked sibling exits, causing hook failures during an active turn.
  • merge-risk: 🚨 compatibility: A required member was added to a type exported through the plugin SDK, which can break structural plugin consumers on upgrade.
  • merge-risk: 🚨 availability: The legacy/current coexistence path can remove the shared bridge and fail hooks for a still-live registration.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦐 gold shrimp.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs stronger real behavior proof before merge: Authority-chain proof required: the PR body asserts redacted v2026.7.1 markers, but supplies no inspectable exact-head trace. Provide a redacted run of two overlapping real Codex turns showing each reaches its own policy owner, plus duplicate/stale-turn rejection before tool I/O. 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

Acceptance criteria:

  • [P1] node scripts/run-vitest.mjs src/agents/harness/native-hook-relay.test.ts.
  • [P1] node scripts/run-vitest.mjs src/gateway/server-methods/native-hook-relay.test.ts.
  • [P1] node scripts/run-vitest.mjs extensions/codex/src/app-server/native-hook-relay.test.ts.
  • [P1] git diff --check.

What I checked:

Likely related people:

  • Peter Steinberger: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Reproduce and fix the mixed legacy/current registration lifecycle.
  • Make the SDK handle change additive or internal and cover a structural consumer.
  • Attach redacted exact-head overlapping-turn and rejection-path evidence.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
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.

Workflow

  • 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.

History

Review history (2 earlier review cycles)
  • reviewed 2026-08-31T18:03:01.079Z sha 853cbeb3a907a43a82c7494f5203ca04941952d1 :: needs real behavior proof before merge. :: [P1] Bind hooks to the originating live registration
  • reviewed 2026-08-31T18:19:55.443Z sha d9f490b4868a45027fbb9fa0625d288a2d0f4198 :: needs real behavior proof before merge. :: [P1] Bind each hook to its originating registration | [P3] Remove the release-owned changelog entry

@esqandil
esqandil force-pushed the fix/native-hook-relay-lifecycle-upstream branch from 853cbeb to d9f490b Compare August 31, 2026 18:10
Codex native runs share one stable per-session relayId, and the single
registration slot let an overlapping sibling run (new turn, nested run,
or bound-thread resume reusing the persisted generation) evict the
active registration at register time. Every later PreToolUse hook of the
still-live run then failed closed with the stale-registration error
mid-turn, and a retained relay guarding direct-child hooks could be torn
down by the next turn's registration on the same session.

Track every live registration per relayId in registration order and
route invocations to the newest registration matching the presented
generation, falling back to the current registration only for the
bootstrap generation-mismatch grace. Unregister now removes only the
caller's own registration; relayId-wide state (loopback bridge, SQLite
locator record, invocation history, approval and permission state) is
torn down only when the last registration goes. The bridge is reused
across overlapping registrations, its record expiry covers the
longest-lived registration, and renew works for non-current siblings so
long turns no longer lose their relay at the original TTL.
Retained-relay and foreground liveness checks key off slot membership
instead of map currency, so a sibling registering or unregistering
cannot invalidate an in-flight invocation binding.

Registrations are capped per relayId, and at the cap the new
registration is rejected instead of evicting a live sibling.
Exact-generation authorization is preserved: a generation that was
unregistered or expired still fails closed with the stale registration
error. Shared-state objects written by older module copies are upgraded
in place, and their relays-only registrations stay routable, expirable,
and sweepable.

Slot bookkeeping, lifetime teardown, and invocation-binding resolution
move to native-hook-relay-registrations.ts to keep the relay facade
under the max-lines cap.
@esqandil
esqandil force-pushed the fix/native-hook-relay-lifecycle-upstream branch from d9f490b to 65b6654 Compare August 31, 2026 21:59
@esqandil

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. labels Aug 31, 2026
@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 Sep 15, 2026
@openclaw-barnacle

Copy link
Copy Markdown

Closing due to inactivity.
If you believe this PR should be revived, post in #clawtributors on Discord to talk to a maintainer.
That channel is the escape hatch for high-quality PRs that get auto-closed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling extensions: codex gateway Gateway runtime merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: XL stale Marked as stale due to inactivity 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.

1 participant