Skip to content

fix(codex): use monotonic clock for retained thread eviction deadline - #168771

Merged
obviyus merged 1 commit into
openclaw:mainfrom
SunnyShu0925:fix/codex-retained-thread-eviction-deadline-wall-clock-179
Oct 12, 2026
Merged

obviyus merged 1 commit into
openclaw:mainfrom
SunnyShu0925:fix/codex-retained-thread-eviction-deadline-wall-clock-179

Conversation

@SunnyShu0925

@SunnyShu0925 SunnyShu0925 commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Retained codex idle live-thread eviction can expire an idle warm session earlier or later than the intended 30-minute window when the wall clock jumps between the expiry seed and the eviction timer's remaining-delay computation. The fix moves the retained-thread eviction deadline onto the monotonic performance.now() clock so a clock adjustment can no longer stretch the idle window (idle memory leak on rewind) or collapse it to zero (idle thread expired early on forward jump).

  • Problem: expiresAt is seeded, read, and compared with the wall clock (Date.now()). A wall-clock jump between the seed and the eviction timer's Math.max(0, expiresAt - Date.now()) remaining-delay computation inflates the idle window (leak on rewind) or shrinks it to zero (idle thread expired early on forward jump).
  • Solution: seed, consume, and compare the deadline in the monotonic performance.now() clock domain, and Math.floor the fractional reading before feeding setTimeout.
  • What changed: extensions/codex/src/app-server/client-runtime.ts (4 seed sites, 1 eviction-timer delay, 1 evict comparison) and its test file (3 eviction-boundary tests now drive performance.now() via a spy).
  • What did NOT change: no persistent state touches expiresAt; all public signatures and failure/behavior contracts are unchanged. Only otherwise-idle retained threads are governed by this deadline — active claimed threads are removed from retainedThreads, and native-child parents are excluded from expiration, on both base and head.

Why This Change Was Made

The retained-live-thread eviction deadline is entirely in-process: expiresAt is never persisted, never crosses a process boundary, and has zero sqlite/bridge/worker hits. That makes the monotonic clock the correct clock for this deadline, matching the repo's established convention for in-process idle timers.

  • Best fix: Yes. Six Date.now() → performance.now() substitutions plus a Math.floor on the setTimeout delay are the minimal, absorbed change. No guard branches were added.
  • Alternative: Re-reading the wall clock right before each comparison would still be vulnerable to a jump between two reads on the same call path; only a monotonic clock removes the skew entirely.
  • Risk: Untested in long-running environments with real NTP step changes. Other fake-timer tests advance far below the 30-minute idle timeout, so they never trigger eviction (sampled green); the three eviction-boundary tests now drive performance.now() via a spy to preserve their assertion contract.

User Impact

Idle codex warm sessions no longer expire earlier (forward clock jump) or linger past their 30-minute intent (rewind) when the machine clock is adjusted. The 30-minute idle retention window now reflects true elapsed time regardless of clock adjustments; active claimed sessions are unaffected by this deadline on both base and head.

Evidence

Real codex transport (shipped client-runtime + real codex app-server)

Spawns a real codex app-server subprocess over real stdio JSON-RPC, attaches the shipped client-runtime.ts, and drives the retention flow with real elapsed time; performance.now() is never faked. Only Date.now() is skewed ±90s between seed and delay computation:

wall-clock step Before (main, Date.now()) After (this PR, performance.now())
rewind −90s armed eviction delay 1,890,000ms (idle window leaks) armed delay 1,799,999ms (exact)
normal 0s armed eviction delay 1,800,000ms armed delay 1,799,999ms (exact)
forward +90s armed eviction delay 1,710,000ms (idle thread expired 90s early) armed delay 1,799,999ms (exact)
$ node --import tsx/esm proof-real-codex-168771.ts
PROOF_REAL_CODEX spawned=true initialized=true version=0.162.1
[retain] retained=true alive-within-idle-window=true
[elapsed] seeded in 0.5ms of real time; monotonic remaining ~1800000ms
[skew] wall +90000ms: pre-fix(Date.now) armed=1710000ms | post-fix(monotonic) armed=1799999ms
[release] released=true
[transport] thread/unsubscribe request sent + acknowledged=true

Real elapsed-time eviction

With the idle timeout temporarily shortened to 3s (local proof run, source restored), a real retained idle thread survives before its real elapsed deadline, then is evicted and issued a real, acknowledged thread/unsubscribe:

$ node --import tsx/esm proof-real-eviction-168771.ts
[retain] retained=true aliveBeforeDeadline=true t=1ms
[evict] aliveAfterDeadline=false t=6001ms
[transport] real thread/unsubscribe requests=1 acknowledged=true

Pre-fix RED / Post-fix GREEN (deterministic assertion)

Reverted to the Date.now() version, kept the proof test (counter model rewinds the wall clock 90s), and ran the eviction-delay assertion:

 × pre-fix  → expected 1890000 to be 1800000   # 1800000 + 90s rewind
 ✓ post-fix → 1800000 (exact)                  # monotonic remaining

Existing test suite

Full client-runtime.test.ts (27 tests, incl. the 3 eviction-boundary tests) passes; related fake-timer suites stay green (run-attempt.native-followup-custody 4, compact.cancellation 6, run-attempt-native-process-authority 13).

What was not tested

Real NTP/step-change under long-running production load was not exercised; the trace applies a deterministic +90s step with a real monotonic clock. Math.floor rounds sub-ms differences down, the intended convention for monotonic timers feeding setTimeout.

Maintainer provenance

No overlap with Pash/Sarah changes: neither has authored commits on the two changed files in the inspected main history. Thanks @SunnyShu0925 for the fix and original transport evidence.

Issue search found no exact open report for Codex idle-thread clock skew. Related but not resolved by this change: #169829 covers a separate wall-clock rewind failure in Gateway state-ownership heartbeats.

Additional Gateway proof

Built and exercised baseline d2af38cb258982dcd598e49f31616c7f9450f39a and candidate 08ca9eea4e451256a3bfc780989fa2c75abd7c68 in separate isolated containers. Authenticated chat.send requests ran the native Codex harness against the repository fake app-server over real stdio. After completing the first turn, a second user turn refreshed ownership scheduling while the first native thread was idle. Observations are actual thread/unsubscribe requests, not deadline calculations.

Clock correction after 10 simulated idle minutes Baseline Candidate
No correction Retained at 10 minutes; evicted after the 30-minute deadline Same
Forward 2 hours First idle thread evicted immediately on ownership refresh Retained until the elapsed idle deadline
Backward 2 hours First idle thread still retained beyond the idle deadline Evicted after the elapsed idle deadline

All six Gateway cases passed their discriminating assertions. Time was advanced with an in-process preload scoped to the Codex retention owner's clock reads and timer scheduling; unrelated Gateway clocks remained real. The configured 1,800,000 ms TTL and product source were unchanged. This is deterministic process-local fault injection, not a natural NTP or suspend/resume test.

On the unchanged candidate head, the 27 runtime tests passed (33.29 seconds including the runner), and targeted Oxfmt/Oxlint checks passed for both changed files. A separate bounded real-provider CLI request to gpt-5-mini completed with the requested exact reply in one provider request. Its credential file was deleted after the run.

Merge danger: two-way door; reverting fully restores prior in-memory timing behavior. No stored timestamps, schema or config migrate. Blast radius is idle retained native Codex subscriptions; configured 30-minute retention, active claims and protected native-child parents retain their existing policy.

Seed, consume, and compare the retained-live-thread eviction deadline in
the monotonic performance.now() clock domain instead of the wall clock.

A wall-clock jump between the deadline seed (retain/claim/release/protect)
and the eviction timer's remaining-delay computation can stretch the idle
window past its 30-minute intent (idle memory leak) or collapse it to zero
(active thread wrongly evicted). performance.now() is unaffected by clock
adjustments and is safe here because expiresAt is a purely in-process
deadline (0 sqlite/bridge/worker persistence hits).

Also floor the setTimeout delay to keep the fractional performance.now()
reading integral, per the repo convention for monotonic timers.
@clawsweeper

clawsweeper Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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 Oct 11, 2026
@clawsweeper

clawsweeper Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR measures Codex idle-thread retention with a monotonic clock so system-clock adjustments cannot change its duration.

Example: The system clock moves forward 90 seconds between retaining an idle thread and scheduling eviction.

  • Before: The eviction delay becomes 1,710,000 milliseconds.
  • After: The delay remains approximately 1,800,000 milliseconds.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, correct repair supported by real native-transport boundary evidence and preserved lifecycle coverage.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (terminal): Contributor terminal output exercises client-runtime retention with a real Codex 0.162.1 stdio transport, records stable delays under wall-clock steps, and demonstrates elapsed-time eviction with an acknowledged thread/unsubscribe using a shortened timeout; natural NTP changes and a full 30-minute run are not claimed.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: A system-clock adjustment can make an idle Codex conversation lose its warm subscription early or retain resources longer than intended.
Reason: The small repair restores the existing elapsed-time retention contract without adding configuration, APIs, storage, or another lifecycle owner.

Merge readiness

✅ Ready for maintainer review

This PR fixes a current clock-skew defect with a focused change; no actionable code defects remain, and the updated transport evidence addresses the earlier proof gap.

Priority: P2
Reviewed head: 08ca9eea4e451256a3bfc780989fa2c75abd7c68

Before merge

None.

Findings

None.

Agent review details

How this fits together

The Codex plugin's physical-client runtime retains idle native subscriptions, schedules their expiration, and releases them through thread/unsubscribe while excluding claimed threads and protected parents.

flowchart TD
  A[Completed Codex turn] --> B[Physical client runtime]
  B --> C[Idle thread registry]
  C --> D[Monotonic eviction timer]
  D --> E[Expired idle thread release]
  E --> F[Codex app server]
  F --> G[Unsubscribe acknowledgment]
Loading

Technical review

Best possible solution:

Keep the existing thread owner and retention policy, using monotonic elapsed time consistently for every idle deadline.

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

Current-main source exposes the mismatched elapsed-time behavior directly, and contributor terminal evidence records the clock-step failure; no target code was executed during this read-only review.

Is this the best way to solve the issue?

The patch repairs the existing owner with a complete clock-domain substitution, preserving active-thread protection, ephemeral retention, retry behavior, and the 30-minute policy.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against ebdc7d54c084.

Provenance checked

  • Idle retention scheduling and protected-parent renewal keeps the original intent (5a79d19: Preserve independent warm conversations while bounding unprotected idle subscriptions to 64 threads and 30 minutes.)
  • Claimed-thread fallback deadline and unsubscribe recovery keeps the original intent (45dd558: Maintain exact physical thread ownership across handoffs and asynchronous subscription transitions.)
  • Ephemeral retention exemption keeps the original intent (759e127: Keep ephemeral history and creation policy in memory without adding idle expiry or persistence.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 5a79d19 adds extensions/codex/src/app-server/client-runtime.ts:113 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 5a79d19ba179; files: extensions/codex/src/app-server/client-runtime.ts)
  • JC: Raw commit 7f60f5f adds extensions/codex/src/app-server/client-runtime.ts:51 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 7f60f5f7e51d; files: extensions/codex/src/app-server/client-runtime.ts)

PR surface

Source 0, Tests +4. Total +4 across 2 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 6 6 0
Tests 1 4 0 +4
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 10 6 +4

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🧂 unranked krab: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove status: 📣 needs proof: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: Clock adjustments can shorten or extend idle native-thread retention, with limited impact on warm-session reuse and resource retention.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only; repair and merge need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

History

Review history (3 earlier review cycles)
  • reviewed 2026-10-11T01:04:03.444Z sha 08ca9ee :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-11T13:06:55.353Z sha 08ca9ee :: needs real behavior proof before merge. :: [P3] Limit the user-impact claim to idle-thread expiration
  • reviewed 2026-10-11T13:15:30.601Z sha 08ca9ee :: needs real behavior proof before merge. :: [P3] Limit the user-impact claim to idle-thread expiration

Reviewed October 11, 2026, 10:47 AM ET / 14:47 UTC (Revision 4).

@clawsweeper

clawsweeper Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper could not start a re-review for this item.

Reason: re-review requires an open issue or PR.

@SunnyShu0925 SunnyShu0925 reopened this Oct 11, 2026
@SunnyShu0925

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed 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 Oct 11, 2026
@obviyus
obviyus merged commit 7aeeaa3 into openclaw:main Oct 12, 2026
272 of 273 checks passed
@obviyus

obviyus commented Oct 12, 2026

Copy link
Copy Markdown
Collaborator

Landed in 7aeeaa3. Thanks @SunnyShu0925, Codex idle threads no longer follow wall-clock jumps.

obviyus added a commit that referenced this pull request Oct 12, 2026
…lock (#169908)

Crabbox warm-image cleanup measured its subprocess time budget with wall-clock time, so a wall-clock correction exhausted the budget early after a forward jump, or let cleanup overrun after a backward jump. The budget now follows monotonic elapsed time, matching #168771, and persisted image timestamps are unchanged. Proof: an isolated Gateway with the Crabbox extension, a fake crabbox CLI and wall-clock jumps simulated inside the process only. Normal cleanup took about 4s on both. With +2h, main's first sweep exhausted its budget after about 2s, while the PR completed in 4.3s. With -2h, main ran 67.2s, while the PR stopped at the 60s budget. A slow no-jump control stopped at about 60s on both. Thanks @SunnyShu0925.

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Oct 12, 2026
…oss wall-clock skew (#168731)

The Codex inference WebSocket handshake deadline used wall-clock time, so a wall-clock jump failed an admitted handshake almost immediately after a forward jump, or let it hang past its 10-second budget after a backward jump. The handshake deadline and its callback checks now use monotonic elapsed time, matching #168771 and #169908. Persisted state is unchanged. The queued-admission permit deadline still uses wall-clock time; that is noted as a follow-up. Proof: an isolated built Gateway running the native Codex runtime against the repository's fake app-server, with a loopback TLS WebSocket upstream and clock jumps simulated inside the inference and permit code only. Normal open: 12 ms on main, 11 ms with the PR. +2h: HTTP 504 after 6 ms on main, after 10,037 ms with the PR. -2h: still pending at 15,018 ms on main, 504 at 10,075 ms with the PR. A slow upstream with no jump timed out at about 10 s on both. Thanks @SunnyShu0925.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 13, 2026
…openclaw#168771)

Idle native Codex threads used wall-clock time for their 30-minute idle deadline, so a wall-clock correction (an NTP step or a sleep/wake adjustment) evicted a thread early after a forward jump, or kept it past its TTL after a backward jump. The idle deadline now uses process-local monotonic elapsed time. The TTL is unchanged, and no persisted timestamp changes. Proof: an isolated Gateway driving the native Codex runtime against the repository's fake app-server over real stdio, with wall-clock jumps simulated inside the process only. On main a +2h jump evicted the thread early and a -2h jump kept it past the TTL; with the PR both followed elapsed time, and the no-jump control expired at the TTL on both. Related, not fixed here: openclaw#169829. Thanks @SunnyShu0925.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 13, 2026
…lock (openclaw#169908)

Crabbox warm-image cleanup measured its subprocess time budget with wall-clock time, so a wall-clock correction exhausted the budget early after a forward jump, or let cleanup overrun after a backward jump. The budget now follows monotonic elapsed time, matching openclaw#168771, and persisted image timestamps are unchanged. Proof: an isolated Gateway with the Crabbox extension, a fake crabbox CLI and wall-clock jumps simulated inside the process only. Normal cleanup took about 4s on both. With +2h, main's first sweep exhausted its budget after about 2s, while the PR completed in 4.3s. With -2h, main ran 67.2s, while the PR stopped at the 60s budget. A slow no-jump control stopped at about 60s on both. Thanks @SunnyShu0925.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 13, 2026
…oss wall-clock skew (openclaw#168731)

The Codex inference WebSocket handshake deadline used wall-clock time, so a wall-clock jump failed an admitted handshake almost immediately after a forward jump, or let it hang past its 10-second budget after a backward jump. The handshake deadline and its callback checks now use monotonic elapsed time, matching openclaw#168771 and openclaw#169908. Persisted state is unchanged. The queued-admission permit deadline still uses wall-clock time; that is noted as a follow-up. Proof: an isolated built Gateway running the native Codex runtime against the repository's fake app-server, with a loopback TLS WebSocket upstream and clock jumps simulated inside the inference and permit code only. Normal open: 12 ms on main, 11 ms with the PR. +2h: HTTP 504 after 6 ms on main, after 10,037 ms with the PR. -2h: still pending at 15,018 ms on main, 504 at 10,075 ms with the PR. A slow upstream with no jump timed out at about 10 s on both. Thanks @SunnyShu0925.

Co-authored-by: Ayaan Zaidi <[email protected]>
hilsbos pushed a commit to hilsbos/openclaw that referenced this pull request Oct 22, 2026
…openclaw#168771)

Idle native Codex threads used wall-clock time for their 30-minute idle deadline, so a wall-clock correction (an NTP step or a sleep/wake adjustment) evicted a thread early after a forward jump, or kept it past its TTL after a backward jump. The idle deadline now uses process-local monotonic elapsed time. The TTL is unchanged, and no persisted timestamp changes. Proof: an isolated Gateway driving the native Codex runtime against the repository's fake app-server over real stdio, with wall-clock jumps simulated inside the process only. On main a +2h jump evicted the thread early and a -2h jump kept it past the TTL; with the PR both followed elapsed time, and the no-jump control expired at the TTL on both. Related, not fixed here: openclaw#169829. Thanks @SunnyShu0925.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit 7aeeaa3)
Co-authored-by: RomneyDa <[email protected]>
hilsbos pushed a commit to hilsbos/openclaw that referenced this pull request Oct 22, 2026
…oss wall-clock skew (openclaw#168731)

The Codex inference WebSocket handshake deadline used wall-clock time, so a wall-clock jump failed an admitted handshake almost immediately after a forward jump, or let it hang past its 10-second budget after a backward jump. The handshake deadline and its callback checks now use monotonic elapsed time, matching openclaw#168771 and openclaw#169908. Persisted state is unchanged. The queued-admission permit deadline still uses wall-clock time; that is noted as a follow-up. Proof: an isolated built Gateway running the native Codex runtime against the repository's fake app-server, with a loopback TLS WebSocket upstream and clock jumps simulated inside the inference and permit code only. Normal open: 12 ms on main, 11 ms with the PR. +2h: HTTP 504 after 6 ms on main, after 10,037 ms with the PR. -2h: still pending at 15,018 ms on main, 504 at 10,075 ms with the PR. A slow upstream with no jump timed out at about 10 s on both. Thanks @SunnyShu0925.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit 805f43b)
Co-authored-by: RomneyDa <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

extensions: codex P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XS status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants