Skip to content

test(gateway): consolidate server-close.test.ts - #166014

Merged
steipete merged 1 commit into
mainfrom
steipete/deslop-restart-t-server-close-20261006
Oct 6, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/deslop-restart-t-server-close-20261006

Conversation

@steipete

@steipete steipete commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

server-close.test.ts repeats Gateway fixtures and assertions across related shutdown scenarios. Consolidate those cases while keeping the distinct lifecycle, persistence, and transport contracts visible.

User Impact

No user-visible change. This is a test-only lane: production LOC delta is 0, as required by the campaign. No production files or shared support files change.

Why This Change Was Made

The file falls from 2,432 to 2,157 lines: -275 (-11.3%). The shared support file has other consumers and remains unchanged. Local factories now compose the existing close fixture, create typed controller records, and supply HTTP callback stubs. Outcome assertions replace duplicate warning strings; trace-format assertions and the recent restart count-format regression remain.

Original case(s) Remaining coverage
completes clean shutdown and clears the process-root registry and lifecycle state; records subsystem shutdown warnings without aborting later cleanup; uses caller-provided channel ids instead of the local channel registry completes %s teardown and clears registry and lifecycle state: clean, subsystem-failure, and explicit-channel rows retain exact warnings, stop order, state clearing, and registry lookup exclusion.
drains active sessions for $reason (timed out: $timedOut); drains pending restart replies before emitting session-end hooks drains active sessions after replies for %s (...): all three original drain inputs plus the original 123 ms restart/100 ms drain-budget ordering input.
keeps post-terminal caller work in restart drain and recovery; preserves terminal recovery until persistence is settled (%s) preserves terminal recovery until persistence and caller work settle (%s): post-terminal, untracked, settled, and pending rows preserve their original IDs, flags, candidate contents, and cancellation assertions.
starts bundle MCP and LSP runtime disposal concurrently continues independent teardown while $label cleanup is pending, bundle-MCP row: LSP must start before the fake clock advances through MCP grace, while MCP is still blocked.
forces lingering HTTP connections closed and records a timeout warning; attempts every listener and later cleanup before rejecting stuck HTTP close (multiple: %s) forces lingering HTTP close (settles: $settles, multiple: $multiple): forced success and stuck single/multiple-listener rows retain the force count, exact rejection, sibling attempt, timer cleanup, and later Tailscale cleanup.
Duplicate timeout/failure log assertions The same retained tests assert warnings together with cancellation, disposal, listener completion, or rejection. Logging-specific trace assertions remain.
Repeated per-runtime disposal counts disposes Code Mode runs before agent and bundle runtimes during shutdown keeps the exact ordered event array, which also detects missing or duplicate disposal.

The 35% reduction target is not met. This uses the campaign's coverage-preserving escape hatch. Within the remaining createGatewayCloseHandler block:

  • Registry/SQLite/SDK cases retain actual databases, concurrent owners, delayed cleanup, failure aggregation, retry, and final retirement. Their setup represents different owners and resources, not interchangeable mock boilerplate.
  • Process cases retain real descendants, TERM resistance, immediate extinction on return, and replacement after a concurrent adapter startup failure.
  • Restart/cancellation cases retain per-Gateway isolation, captured-operation identity, terminal persistence states, recovery-before-abort ordering, session-ID rotation, hidden/completed/stale exclusions, and marker failures.
  • Plugin/transport cases retain strict-stop failure, late cleanup, admission-versus-callback failure, independent runtime progress, and different HTTP/WebSocket deadlines.

The issue-numbered #112681 rows and the relevant #165574, #165670, and #165980 regressions remain. No new skipped tests, snapshots, production changes, or dependencies. The existing Windows exclusion on POSIX process-tree proof is unchanged. The validation scan found one unrelated unused production export, OUTBOUND_GREETING_FALLBACK_MS in extensions/voice-call/src/webhook/realtime-call-session-control.ts. Its value is used internally; removing its export is outside this test-only lane.

Evidence

Provider: blacksmith-testbox, profile openclaw-check, lease tbx_01m4836q24694xbvb19gv0m4yh (stopped after validation). Development checks ran on the lease, with synchronized source hashes checked before execution. Its initial pnpm install --frozen-lockfile completed before baseline timing. No local suites, builds, or typechecks ran.

pnpm test src/gateway/server-close.test.ts --maxWorkers=1 passed 72 baseline / 71 consolidated cases. Three alternating warm pairs gave:

Round Before wall time After wall time
1 16.46 s 16.59 s
2 17.12 s 17.40 s
3 18.62 s 16.69 s
Median 17.12 s 16.69 s

Median wall time is down 0.43 s (2.5%); the sum of individual test timings also fell from 7.521 s to 7.388 s (medians). Individual pairs vary, so this is evidence of no aggregate cost growth, not a throughput claim. Initial cold baseline: 40.38 s, including 18.95 s of worker compilation. Initial warm baseline: 17.81 s; the earlier candidate: 19.14 s. The table above measures the candidate after its review repair; the only later edit adds lint-required braces to the HTTP fixture.

Validation results:

  • Focused before/after suite: all runs passed, as measured above.
  • Shared-support consumers: node scripts/run-vitest.mjs src/gateway/server-close.agent-databases.test.ts src/gateway/server-close.cleanup-scope.test.ts src/gateway/server-close.incognito-pending-history.test.ts src/gateway/server-close.queued-heartbeat.test.ts src/gateway/server-restart-heartbeat.test.ts — 5 files / 14 tests passed, 87.40 s runner wall time.
  • node scripts/check-changed.mjs --dry-run selected the Gateway-server test graph and targeted lint. node scripts/check-changed.mjs passed its first 22 gates, including formatting, all ratchets, plugin boundaries, and Gateway-server typechecking (39.1 s), then failed at the unrelated existing dead-export scan for extensions/voice-call/src/webhook/realtime-call-session-control.ts: OUTBOUND_GREETING_FALLBACK_MS.
  • Baseline attribution: restored the exact original 2,432-line test file from base 58163bdb326f371bac41d98a45f68239e6add238 on the same lease and ran node --import tsx scripts/check-deadcode-exports.mts. Both production and full-tree scans reproduced the identical unused export. The voice-call file has no lane diff; its bytes also match inspected origin/main. This gate remains red and is not claimed as passing.
  • Because the gate stopped before its final targeted lint, node scripts/run-oxlint.mjs --tsconfig config/tsconfig/oxlint.core.json src/gateway/server-close.test.ts passed separately: 0 warnings / 0 errors, 9.7 s. The first lint pass caught missing braces in the HTTP fixture; the final pass includes that mechanical correction.
  • Mutation sanity passed: three isolated production mutations, each run with pnpm test src/gateway/server-close.test.ts --maxWorkers=1. Each produced exactly 1 failed / 70 passed; source bytes were restored and hashes verified after each.
Temporary mutation Catching consolidated test
Invoke periodic maintenance cleanup without joining it waits for in-flight stopPeriodicTasks cleanup before shared state closes (shared-store close called prematurely)
Leave fulfilled terminal persistence marked unpersisted preserves terminal recovery until persistence and caller work settle (settled) (unexpected recovery candidate)
Treat ERR_SERVER_NOT_RUNNING as an HTTP close failure classifies unbound HTTP listener close callbacks (unexpected warning)
  • Independent autoreview: the first pass found an early-assertion race introduced while replacing polling. Fixed with a fake-clock scheduling barrier while cleanup remains held; fresh P0–P2 review is scoped-clean. The periodic-maintenance mutation verifies the repaired assertion detects the broken join. Exact-head CI run 37436063535 passed for 2466d6f64d32703554a6ba03cbdc61d3613a7dd8; all PR checks are passing or skipped. CI job wall times: checks-node-changed 125 s, checks-node-changed-compact-small-8 132 s, and checks-node-changed-boundary 112 s (job durations, not isolated test time).

This PR is for lead review; do not merge or enable auto-merge from this lane.

@clawsweeper

clawsweeper Bot commented Oct 6, 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.

@steipete
steipete marked this pull request as ready for review October 6, 2026 08:25
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: XL labels Oct 6, 2026
@clawsweeper clawsweeper Bot added P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. 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. labels Oct 6, 2026
@clawsweeper

clawsweeper Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 6, 2026, 4:42 AM ET / 08:42 UTC (Revision 2).

ClawSweeper review

What this changes

This PR consolidates Gateway shutdown tests with local fixtures and parameterized cases while retaining cleanup, restart recovery, and transport assertions.

Merge readiness

✅ Ready for maintainer review

Keep open: the consolidation remains distinct from current main, and inspection found no blocking coverage regression. The retained scenarios and reported mutation checks support preserving this useful maintainer-authored cleanup.

Priority: P3
Reviewed head: 2466d6f64d32703554a6ba03cbdc61d3613a7dd8

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, well-validated test consolidation with no blocking defect found.
Proof confidence 🌊 off-meta tidepool Not applicable: The verified repository administrator's PR changes only tests around the existing Gateway close owner; contributor runtime proof is not required. Reported before/after suite runs and mutation checks support coverage preservation. No stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The verified repository administrator's PR changes only tests around the existing Gateway close owner; contributor runtime proof is not required. Reported before/after suite runs and mutation checks support coverage preservation. No stored-data contract changes.
Evidence reviewed 9 items Pinned introduction and merge scope: The complete introduced diff changes only the shutdown test file. Raw test-merge parents match the pinned base followed by the exact PR head; its result likewise changes only that test file.
Retained shutdown contracts: The consolidated rows retain exact warning outcomes, explicit channel selection, cleanup joins, recovery candidate contents, marker-before-cancellation ordering, concurrent bundle disposal, and forced HTTP completion or rejection. The cleanup scheduling barrier advances the fake clock while cleanup remains held.
Production boundary: The unchanged shared fixture composes the real preparation and completion owners. The production close owner joins cleanup before shared-state retirement, and the run-shutdown owner preserves terminal persistence and recovery ordering. The Code Mode disposal mock targets OpenClaw's own implementation; this patch supplies no Codex dependency signal.
Findings None None.
Security None None.

How this fits together

The Gateway shutdown owner receives stop or restart requests, drains active work, and closes runtimes, listeners, and shared state. These tests protect the ordering, recovery, and failure handling of that process.

flowchart TD
  A[Stop or restart request] --> B[Gateway shutdown preparation]
  B --> C[Drain work and record recovery]
  C --> D[Close runtimes and listeners]
  D --> E[Join cleanup and retire shared state]
  E --> F[Completion or failure]
  G[Consolidated shutdown tests] --> B
  G --> F
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Tests -275. Total -275 across 1 file.

View PR surface stats
Area Files Added Removed Net
Source 0 0 0 0
Tests 1 452 727 -275
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 1 452 727 -275

Review metrics

Metric Value Why it matters
Reported focused test cost Warm median 17.12 s → 16.69 s across 3 paired runs The reported measurements support no aggregate test-cost growth without establishing a throughput improvement.
Reported mutation sensitivity 3 of 3 mutations caught Retained tests reportedly detect broken cleanup joining, terminal-persistence handling, and unbound HTTP-close classification.

Technical review

Best possible solution:

Keep shared shutdown setup concise while preserving distinct tests for cleanup joins, recovery ordering, process extinction, and transport completion.

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

Not applicable: this PR consolidates existing tests rather than fixing a reported runtime defect; the captured body supplies focused before/after validation.

Is this the best way to solve the issue?

Yes: local fixture composition and parameterized cases reduce repetition without changing production APIs or discarding the distinct shutdown contracts inspected.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

No label changes.

Label justifications:

  • P3: This is test maintenance with no production or user-visible behavior change.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The verified repository administrator's PR changes only tests around the existing Gateway close owner; contributor runtime proof is not required. Reported before/after suite runs and mutation checks support coverage preservation. No stored-data contract changes.

Evidence

What I checked:

  • Pinned introduction and merge scope: The complete introduced diff changes only the shutdown test file. Raw test-merge parents match the pinned base followed by the exact PR head; its result likewise changes only that test file. (src/gateway/server-close.test.ts:168, 2466d6f64d32)
  • Retained shutdown contracts: The consolidated rows retain exact warning outcomes, explicit channel selection, cleanup joins, recovery candidate contents, marker-before-cancellation ordering, concurrent bundle disposal, and forced HTTP completion or rejection. The cleanup scheduling barrier advances the fake clock while cleanup remains held. (src/gateway/server-close.test.ts:799, 2466d6f64d32)
  • Production boundary: The unchanged shared fixture composes the real preparation and completion owners. The production close owner joins cleanup before shared-state retirement, and the run-shutdown owner preserves terminal persistence and recovery ordering. The Code Mode disposal mock targets OpenClaw's own implementation; this patch supplies no Codex dependency signal. (src/gateway/server-close.test-support.ts:22, 2466d6f64d32)
  • Still necessary on current main: Current main's close owner and test file are unchanged from the pinned introduction base, so this consolidation is not already implemented there. The latest release has a different earlier test blob; no shipped-fix claim is made for this unmerged test cleanup. (src/gateway/server-close.test.ts, d3c121c23788)
  • Reported validation and sensitivity: The captured PR body reports 72 baseline versus 71 consolidated passing cases, three alternating timing pairs, passing shared-support consumers, and three isolated mutations each caught by a retained test. It explicitly attributes the local dead-export failure to unchanged production code. These are contributor-reported results; this read-only review ran no tests. (2466d6f64d32)
  • Verified exact-head CI: GitHub reports successful completed CI for the exact reviewed head at https://github.com/openclaw/openclaw/actions/runs/37436063535. (2466d6f64d32)

Likely related people:

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

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 (1 earlier review cycle)
  • reviewed 2026-10-06T08:31:30.865Z sha 2466d6f :: needs maintainer review before merge. :: none

@steipete
steipete merged commit c2ea557 into main Oct 6, 2026
187 of 188 checks passed
@steipete
steipete deleted the steipete/deslop-restart-t-server-close-20261006 branch October 6, 2026 08:46
@steipete

steipete commented Oct 6, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

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

Labels

gateway Gateway runtime P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XL 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.

1 participant