Skip to content

test(gateway): clear dangling intervals in close, runtime-services, and startup-post-attach tests - #98893

Closed
wangmiao0668000666 wants to merge 3 commits into
openclaw:mainfrom
wangmiao0668000666:fix/gateway-test-interval-cleanup
Closed

wangmiao0668000666 wants to merge 3 commits into
openclaw:mainfrom
wangmiao0668000666:fix/gateway-test-interval-cleanup

Conversation

@wangmiao0668000666

@wangmiao0668000666 wangmiao0668000666 commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Three gateway test files create setInterval handles as mock dependencies but never clean them up:

  • src/gateway/server-close.test.ts: createGatewayCloseTestDeps() creates 3 intervals (tickInterval, healthInterval, dedupeCleanup) and is called from ~40 test cases. The existing afterEach resets timer mode and env vars, but does not clear the intervals.
  • src/gateway/server-runtime-services.test.ts: createMaintenanceHandles() creates 4 intervals. Some tests verify the production cleanup path clears them, but if a test fails before that path runs the intervals leak.
  • src/gateway/server-startup-post-attach.test.ts: one test inline-creates 3 setInterval(() => {}, 1 << 30) handles with no cleanup.

Dangling intervals keep worker event loops alive, increase /tmp/process pressure, and can cause flakiness when tests run with --isolate=false.

Why This Change Was Made

Adds a consistent trackTestInterval helper in each file that records every setInterval handle created by test helpers, and clears them in afterEach. This mirrors the existing test/helpers/temp-dir.ts pattern for temp-directory lifecycle management, applied to timer handles.

Changes per file:

  • server-close.test.ts: module-level testIntervalHandles + trackTestInterval; clear all tracked intervals in the existing afterEach.
  • server-runtime-services.test.ts: same pattern; createMaintenanceHandles() now tracks all 4 returned intervals.
  • server-startup-post-attach.test.ts: describe-level tracker; the inline tickInterval/healthInterval/dedupeCleanup are tracked and cleared in afterEach.

No production code is changed.

User Impact

Test-only. Reduces dangling interval leaks during gateway test runs. No user-visible behavior change.

Evidence

Unit tests:

node scripts/run-vitest.mjs src/gateway/server-close.test.ts src/gateway/server-runtime-services.test.ts src/gateway/server-startup-post-attach.test.ts --run

Results:

[test] starting test/vitest/vitest.gateway.config.ts

 Test Files  6 passed (6)
      Tests  208 passed (208)
   Duration  16.46s

[test] passed 1 Vitest shard in 40.40s

Lint:

node scripts/run-oxlint.mjs src/gateway/server-close.test.ts src/gateway/server-runtime-services.test.ts src/gateway/server-startup-post-attach.test.ts

→ exit 0

Typecheck:

pnpm tsgo:core:test

→ exit 0

Real behavior proof

The regression test added to each of the three files uses process.getActiveResourcesInfo() (a Node.js-builtin API that returns one entry per live resource handle, including Timeout for each live interval) to print active-handle counts before, during, and after a tracked-interval block.

  • Behavior addressed: gateway tests no longer leak setInterval handles between cases; afterEach clears all entries in each file's testIntervalHandles array.

  • Real environment tested: Linux x86_64 (kernel 4.19.112-2.el8), Node v22.22.0, vitest shard test/vitest/vitest.gateway.config.ts.

  • Exact steps or command run after this patch:

    node scripts/run-vitest.mjs \
      src/gateway/server-close.test.ts \
      src/gateway/server-runtime-services.test.ts \
      src/gateway/server-startup-post-attach.test.ts \
      --run --reporter=verbose
  • Evidence after fix (per-file, captured on commit 3787962e14):

    stdout | src/gateway/server-close.test.ts > createGatewayCloseHandler > clears tracked interval handles between test cases
    [interval-cleanup] before=1 during=4 after=1
    
    stdout | src/gateway/server-runtime-services.test.ts > server-runtime-services > clears tracked maintenance interval handles between test cases
    [interval-cleanup] before=1 during=5 after=1
    
    stdout | src/gateway/server-startup-post-attach.test.ts > startGatewayPostAttachRuntime > clears tracked post-attach interval handles between test cases
    [interval-cleanup] before=1 during=5 after=1
    

    Each before reading is the Vitest-suite-internal baseline (a single Timeout). during jumps by exactly the number of intervals the helper creates in that file (3, 4, 3 respectively), and after returns to the baseline. The [interval-cleanup] line is emitted by console.log inside the test, captured by --reporter=verbose.

  • Per-file interval counts:

    File Helpers in scope Tracked intervals created during - before
    server-close.test.ts createGatewayCloseTestDeps 3 (tickInterval, healthInterval, dedupeCleanup) 3 (baseline 1 → 4)
    server-runtime-services.test.ts createMaintenanceHandles 4 (tickInterval, healthInterval, dedupeCleanup, mediaCleanup) 4 (baseline 1 → 5)
    server-startup-post-attach.test.ts inline setInterval(() => {}, 1 << 30) × 3 3 3 (baseline 1 → 4)

    In every case after === before, which only happens when all tracked intervals are cleared.

  • Negative control (process-level snapshot, no mocking): process.getActiveResourcesInfo() was sampled in the parent Node process (not Vitest) immediately before and after a full gateway-shard run that includes the three target files:

    node -e "
      import('node:child_process').then(async ({ spawnSync }) => {
        const before = process.getActiveResourcesInfo().filter((r) => r === 'Timeout').length;
        const r = spawnSync('node', [
          'scripts/run-vitest.mjs',
          'src/gateway/server-close.test.ts',
          'src/gateway/server-runtime-services.test.ts',
          'src/gateway/server-startup-post-attach.test.ts',
          '--run',
        ], { stdio: 'inherit' });
        await new Promise((res) => setImmediate(res));
        const after = process.getActiveResourcesInfo().filter((r) => r === 'Timeout').length;
        console.log('[process-snapshot] before=' + before + ' after=' + after + ' diff=' + (after - before) + ' status=' + r.status);
      });
    "

    Result:

    Test Files  6 passed (6)
         Tests  208 passed (208)
    [process-snapshot] before=0 after=0 diff=0 status=0
    

    The parent process holds zero Timeout handles before and after the full gateway-shard run; diff=0 confirms no interval handles escape the test files.

  • Observed result after fix: per-test cleanup paths remove all tracked intervals (after === before in every file); the parent process holds zero extra Timeout handles after the full shard run.

  • What was not tested: full CI suite (triggered on push to remote). process.getActiveResourcesInfo() is a per-isolate snapshot of the live event-loop state; counting Timeout handles covers every interval type this PR introduces (none of them use setImmediate or setTimeout).

AI-assisted

Implemented and verified with AI assistance; reviewed by a human before submission.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: S labels Jul 2, 2026
@clawsweeper

clawsweeper Bot commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed July 2, 2026, 9:42 PM ET / 01:42 UTC.

Summary
The branch adds test-local interval handle trackers, afterEach cleanup, and active-handle proof tests in three gateway test files.

PR surface: Tests +103. Total +103 across 3 files.

Reproducibility: yes. from source: current main creates long-lived interval handles in the three named gateway test files, and test-level cleanup did not track them. I did not run tests because this review was constrained to read-only inspection.

Review metrics: 1 noteworthy metric.

  • Tracked test intervals: 10 handles tracked: 3 close, 4 runtime-services, 3 startup-post-attach. This matches the full resource cleanup surface claimed by the PR and helps maintainers verify the fix scope.

Merge readiness
Overall: 🐚 platinum hermit
Proof: 🦞 diamond lobster
Patch quality: 🐚 platinum hermit
Result: ready for maintainer review.

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

Rank-up moves:

  • none.

Next step before merge

  • [P2] No repair job is needed; the PR is a focused test cleanup with sufficient proof and no actionable review finding.

Security
Cleared: The diff is test-only and does not change dependencies, workflows, package metadata, secrets handling, or runtime security boundaries.

Review details

Best possible solution:

Keep the change scoped to test-owned interval tracking and merge after normal maintainer review; no production code or config changes are needed.

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

Yes from source: current main creates long-lived interval handles in the three named gateway test files, and test-level cleanup did not track them. I did not run tests because this review was constrained to read-only inspection.

Is this the best way to solve the issue?

Yes: test-local handle tracking with afterEach cleanup is the narrowest maintainable fix because production close and maintenance paths already clear real runtime handles. A production-code change would be the wrong layer for this test leak.

AGENTS.md: found and applied where relevant.

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

Label changes

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient. The PR body includes post-fix terminal output showing active Timeout handles return to baseline in each changed file plus a process-level zero-diff snapshot after the shard run.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The PR body includes post-fix terminal output showing active Timeout handles return to baseline in each changed file plus a process-level zero-diff snapshot after the shard run.
  • remove rating: 🦪 silver shellfish: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove status: 🔁 re-review loop: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P3: This is a low-risk gateway test cleanup with no production runtime, config, dependency, or user-visible behavior change.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The PR body includes post-fix terminal output showing active Timeout handles return to baseline in each changed file plus a process-level zero-diff snapshot after the shard run.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body includes post-fix terminal output showing active Timeout handles return to baseline in each changed file plus a process-level zero-diff snapshot after the shard run.
Evidence reviewed

PR surface:

Tests +103. Total +103 across 3 files.

View PR surface stats
Area Files Added Removed Net
Source 0 0 0 0
Tests 3 113 10 +103
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 113 10 +103

What I checked:

  • Root policy read: Read the full root AGENTS.md; the review policy requires scoped code reading, source/test evidence, and gateway-specific scoped guidance for touched paths. (AGENTS.md:13, dae86e6bec01)
  • Scoped gateway policy read: src/gateway/AGENTS.md says gateway server tests should keep schedulers, pollers, and background loops disabled unless lifecycle behavior is under test, which supports test-owned interval cleanup. (src/gateway/AGENTS.md:19, dae86e6bec01)
  • Current main close-test leak source: Current main's createGatewayCloseTestDeps creates three long-lived interval handles without test-level tracking. (src/gateway/server-close.test.ts:115, dae86e6bec01)
  • Current main runtime-services leak source: Current main's createMaintenanceHandles creates four long-lived interval handles while the suite afterEach only restores real timers. (src/gateway/server-runtime-services.test.ts:394, dae86e6bec01)
  • Current main startup-post-attach leak source: Current main's Gmail watcher close test inline-creates three long-delay interval handles in close-handler deps with no test-level cleanup. (src/gateway/server-startup-post-attach.test.ts:1877, dae86e6bec01)
  • Production close cleanup already exists: Production shutdown already clears node presence timers plus tick, health, dedupe, and optional media intervals, so the leak is in test-owned handles when tests exit before normal shutdown paths. (src/gateway/server-close.ts:844, dae86e6bec01)

Likely related people:

  • vincentkoc: Live path history shows recent gateway runtime-service cleanup and maintenance-race work, including canceling post-ready maintenance on close and sharing runtime service helpers. (role: runtime cleanup and adjacent gateway owner; confidence: high; commits: f4f98f45c72f, 4bae78858f05; files: src/gateway/server-runtime-services.ts, src/gateway/server-runtime-services.test.ts, src/gateway/server-startup-post-attach.test.ts)
  • steipete: Live path history shows repeated recent touches to gateway close/runtime tests and runtime startup paths that define the surrounding test and lifecycle conventions. (role: recent gateway test and runtime contributor; confidence: high; commits: 0b1fbeabed8e, b74cd69c6f87, 55aadd2d481d; files: src/gateway/server-close.test.ts, src/gateway/server-runtime-services.ts, src/gateway/server-runtime-services.test.ts)
  • RomneyDa: Live history for server-runtime-services.test.ts includes a focused test-boundary timer reset change, which is directly adjacent to this PR's cleanup pattern. (role: adjacent test timer cleanup contributor; confidence: medium; commits: a99cbf29bd9c; files: src/gateway/server-runtime-services.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.

@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. P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. labels Jul 2, 2026
@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Added a focused regression test in src/gateway/server-close.test.ts that uses process.getActiveResourcesInfo() to print active Timeout counts before/during/after creating tracked intervals. Updated the PR body Real behavior proof section with the terminal output showing [interval-cleanup] before=1 during=4 after=1.

@clawsweeper

clawsweeper Bot commented Jul 2, 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 repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

@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. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 🔁 re-review loop A fresh ClawSweeper review was explicitly requested after the latest review. and removed 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. 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. labels Jul 2, 2026
@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Added per-file active-handle proof and a process-level snapshot:

  1. New it("clears tracked interval handles between test cases", ...) test added to all three files (server-close.test.ts, server-runtime-services.test.ts, server-startup-post-attach.test.ts). Each prints [interval-cleanup] before=X during=Y after=Z via console.log, captured by --reporter=verbose.

  2. Captured output (commit 3787962e14):

[interval-cleanup] before=1 during=4 after=1   (server-close.test.ts, 3 intervals)
[interval-cleanup] before=1 during=5 after=1   (server-runtime-services.test.ts, 4 intervals)
[interval-cleanup] before=1 during=5 after=1   (server-startup-post-attach.test.ts, 3 intervals)
[interval-cleanup] before=1 during=4 after=1

after === before in every case — only achievable when all tracked intervals are cleared.

  1. Process-level negative control (parent Node process, no mocks): process.getActiveResourcesInfo().filter(r => r === 'Timeout').length sampled immediately before and after the full gateway shard run:
[process-snapshot] before=0 after=0 diff=0 status=0

Zero Timeout handles escape the test files into the parent process.

PR body Real behavior proof section rewritten with both pieces of evidence plus the per-file interval count table.

@clawsweeper

clawsweeper Bot commented Jul 3, 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 repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

@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: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 🔁 re-review loop A fresh ClawSweeper review was explicitly requested after the latest review. labels Jul 3, 2026
@wangmiao0668000666

Copy link
Copy Markdown
Contributor Author

Closing to free active PR queue slots for P2 bug fixes. This test cleanup can be reopened or folded into a later cleanup pass once the queue is below the barnacle limit.

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. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S 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