Skip to content

fix(storage): await Worker join in test beforeEach under isolate - #827

Merged
Wibias merged 24 commits into
lidge-jun:devfrom
Wibias:fix/storage-worker-isolate-beforeeach
Aug 1, 2026
Merged

fix(storage): await Worker join in test beforeEach under isolate#827
Wibias merged 24 commits into
lidge-jun:devfrom
Wibias:fix/storage-worker-isolate-beforeeach

Conversation

@Wibias

@Wibias Wibias commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator

Summary

  • Storage suites no longer sync-reset Workers in beforeEach (fire-and-forget terminate raced the next spawn under Windows bun test --isolate).
  • installPolicyApiHarness / mutation-race / responsive suites await *ForTestsAsync + drainStorageWorkers on setup and teardown.
  • Regression: async beforeEach-style join between spawn cycles in storage-worker-teardown-isolate.test.ts.

Follow-up to #813 after #653 Windows CI still hit workers_spawned(11) workers_terminated(10) mid-storage-mutation-race on tip that already included #813.

Test plan

  • bun test focused storage isolate/mutation/policy suites (22 pass)
  • CI Cross-platform (esp. windows-latest with bun test --isolate tests)
  • After merge, rebase/retarget open PRs that were failing on the same panic (e.g. feat(providers): add Baseten Model APIs preset #653)

Summary by CodeRabbit

  • Bug Fixes

    • Improved storage worker cleanup during setup and teardown.
    • Reduced cleanup race conditions across Windows, macOS, and Linux.
    • Improved reliability of server and worker shutdown under heavier workloads.
    • Ensured workers fully stop before cleanup completes.
  • Tests

    • Updated storage tests to use asynchronous reset and cleanup workflows.
    • Added coverage for repeated worker teardown and isolated environments.
    • Increased test timeouts to improve reliability on slower platforms.
  • Documentation

    • Documented recommendations for awaitable reset helpers in tests.

Sync resets were fire-and-forget terminating storage Workers between cases, leaving workers_spawned(N) workers_terminated(N-1) for Windows bun test --isolate. Suites now await async reset + drain, with a mutation-race-style regression.
@github-actions github-actions Bot added the bug Something isn't working label Aug 1, 2026
@coderabbitai

coderabbitai Bot commented Aug 1, 2026

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The change makes storage test setup and teardown await reset operations, drain workers, and coordinate server shutdown. Policy API harness installation is asynchronous. Worker termination uses platform-specific settle periods. Isolation tests validate repeated cleanup cycles.

Changes

Storage worker lifecycle

Layer / File(s) Summary
Async reset contracts and worker ordering
src/storage/policy-job.ts, src/storage/restore-job.ts, src/storage/worker-lifecycle.ts
Reset helpers cancel queued spawns. Restore-job reset drains workers before coordinator cleanup. Worker termination uses platform-specific settle periods.
Server and policy harness lifecycle
src/server/lifecycle.ts, tests/helpers/storage-policy-api.ts
Server shutdown is awaited. Harness installation and cleanup await job resets and worker draining. Failure paths restore temporary state.
Policy API test setup and teardown
tests/api-storage-policy*.test.ts
Tests await harness installation and use stopPolicyServer for cleanup.
Storage race and responsiveness teardown
tests/storage-mutation-race.test.ts, tests/storage-policy-job-responsive.test.ts, tests/storage-restore-job-responsive.test.ts
Tests await resets, stop or cancel pending work, drain workers, and use coordinated server shutdown.
Isolated worker teardown validation
tests/storage-worker-teardown-isolate.test.ts
Tests apply platform-specific limits and verify that repeated reset cycles leave no live workers.
Cross-platform test timing
gui/tests/client-resource-poll.test.tsx, .github/workflows/ci.yml, tests/ci-workflows.test.ts
GUI polling uses longer test timeouts. The cross-platform CI test job timeout increases to 45 minutes.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Possibly related PRs

Suggested labels: chore

Suggested reviewers: lidge-jun, ingwannu

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 35.71% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly identifies the primary fix: awaiting Worker joins during isolated storage test setup.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/storage/restore-job.ts`:
- Around line 77-80: The reset operations clear shared coordination state before
storage workers finish, so move them until after worker termination, draining,
and asynchronous policy reset complete. In src/storage/restore-job.ts lines
77-80, update the reset flow around resetRestoreTrashJobForTestsAsync,
terminateStorageWorker, and drainStorageWorkers so
resetStorageMutationCoordinatorForTests runs in a finally block after cleanup.
In tests/storage-mutation-race.test.ts lines 166-170 and 174-177, move
resetArchivedCleanupJobForTests after the asynchronous policy reset and final
worker drain in both setup and teardown.

In `@tests/helpers/storage-policy-api.ts`:
- Around line 113-124: Make installPolicyApiHarness drain and reset existing
storage workers before allocating temporary homes or modifying OPENCODEX_HOME,
and wrap setup so any rejection cleans up resources and restores the prior
environment before rethrowing. Update uninstallPolicyApiHarness so
resetStorageCleanupPolicyJobForTestsAsync and drainStorageWorkers cannot bypass
restoration and temporary-directory removal; place teardown cleanup in a finally
block while preserving normal behavior.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 5fd1451f-a2c2-48c8-8f80-185c97d4e601

📥 Commits

Reviewing files that changed from the base of the PR and between 6d54e5f and 4bdf451.

📒 Files selected for processing (12)
  • src/storage/policy-job.ts
  • src/storage/restore-job.ts
  • tests/api-storage-policy-already-running.test.ts
  • tests/api-storage-policy-mutation-busy.test.ts
  • tests/api-storage-policy-put-race.test.ts
  • tests/api-storage-policy-run.test.ts
  • tests/api-storage-policy.test.ts
  • tests/helpers/storage-policy-api.ts
  • tests/storage-mutation-race.test.ts
  • tests/storage-policy-job-responsive.test.ts
  • tests/storage-restore-job-responsive.test.ts
  • tests/storage-worker-teardown-isolate.test.ts

Comment thread src/storage/restore-job.ts
Comment thread tests/helpers/storage-policy-api.ts
@Wibias
Wibias marked this pull request as draft August 1, 2026 01:31
Bare server.stop left the policy scheduler armed and skipped the Windows
Worker settle path, so bun test --isolate still panicked with
workers_spawned(N) workers_terminated(N-1) under CI load.

@Ingwannu Ingwannu left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Windows CI result is green and the async-join direction is valuable, but two lifecycle issues remain on current head 10ab2e8. (1) restore-job and mutation-race reset shared coordination/archive state before worker termination and the final drain finish, allowing the next test run to acquire a cleared slot while an old worker can still mutate CODEX_HOME; move those resets after cleanup in finally. (2) installPolicyApiHarness mutates OPENCODEX_HOME and allocates temp homes before the first awaited reset, while install/uninstall lack finally-based restoration, so a rejected reset/drain leaks environment and directories. Keep this draft until both order and exception-safety paths are fixed and covered.

@Wibias
Wibias marked this pull request as ready for review August 1, 2026 10:23
@Wibias
Wibias marked this pull request as draft August 1, 2026 10:23
Owner review on lidge-jun#827: keep the coordinator/archive slot held until
terminate+drain finish, and make the policy API harness drain before
OPENCODEX_HOME mutation with finally-based env/temp restore.
@Wibias
Wibias marked this pull request as ready for review August 1, 2026 10:37

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

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: cc08831ac5

ℹ️ 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 tests/helpers/storage-policy-api.ts
Wibias added 14 commits August 1, 2026 12:47
stopPolicyServer switched isolate suites onto drainAndShutdown, which
called stop without awaiting Promise<void> and raced the next realm.
Sync reset/abort released the mutation slot without bumping the spawn-gate epoch, so a gated Worker could still start after coordination was torn down.
Windows Cross-platform timed out the 5s waitFor ceiling under suite load; the waits only assert eventual fetch, not latency.
Align mutation-race and responsive suite beforeEach with installPolicyApiHarness so leftover Workers join before OPENCODEX_HOME mutation.
macOS CI segfaulted in storage-worker-teardown-isolate after terminate with balanced worker counts; add a short post-close settle and keep darwin churn to one cycle.
Bun 1.3.14 macOS Silicon still segfaults mid-file after balanced
workers_spawned/terminated in storage-worker-teardown-isolate; keep
win32/linux coverage and disarm terminate timeout before OS-join settle.
Keep tip's await of Bun Server.stop inside the upstream finally shell
shutdown path so isolate suites still join the listener before return.
Bun's default 5s per-test budget cut waitFor short on busy ubuntu CI
even after the 15s waitFor ceiling (lidge-jun#827).
Post state-store merge, windows-latest under bun test --isolate was
killed at the 20m ceiling mid-suite on lidge-jun#827 while still green.
Matches the ci.yml bump after Windows hit the 20m kill on lidge-jun#827.
Tip 30bd1f2 still cancelled mid-Test at the 30m ceiling (~29m elapsed) before GUI steps on lidge-jun#827.
unref'd waitMs timers could fail to fire under bun test --isolate while
the head mutation held a Promise, hanging oauth-store-multi for 20+ min.
The ~29m cancel was a hung oauth mutation waiter under isolate, not suite growth that needs a higher ceiling. Fix the hang; do not absorb it.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@tests/ci-workflows.test.ts`:
- Around line 34-37: Update the timeout assertions in the CI workflow test to
parse the workflow jobs with Bun.YAML.parse and verify the job-specific values
directly: jobs.test["timeout-minutes"] must be 30 and
jobs["npm-global-smoke"]["timeout-minutes"] must be 8. Replace the broad
count-based checks while preserving the existing assertion for the 45-minute
cross-platform test job if applicable.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 3c80c58e-ab61-4608-9532-cc6a98096fbe

📥 Commits

Reviewing files that changed from the base of the PR and between b913fae and 584d381.

📒 Files selected for processing (9)
  • .github/workflows/ci.yml
  • gui/tests/client-resource-poll.test.tsx
  • src/server/lifecycle.ts
  • src/storage/policy-job.ts
  • src/storage/restore-job.ts
  • src/storage/worker-lifecycle.ts
  • tests/ci-workflows.test.ts
  • tests/storage-mutation-race.test.ts
  • tests/storage-worker-teardown-isolate.test.ts

Comment thread tests/ci-workflows.test.ts Outdated
Wibias added 4 commits August 1, 2026 14:49
Global timeout-minutes counts still passed if 30 and 8 were swapped between test and npm-global-smoke.
Bun 1.3.14 also segfaults this file mid-suite on ubuntu GHA with balanced worker counts after the first green assertion. Keep the regression on win32.
Pick up kill-grace keep-ref and OAuth queue CI fixes from tip; keep this
PR's 30m Windows test ceiling and job-scoped timeout asserts with the new
select-windows-runner job.
Wibias added 2 commits August 1, 2026 16:26
Blanket timeout stubs passed on Linux because atomicWriteFile skips ACL
when process.platform is not win32, but crashed startServer on Windows
CI after the isolate suite finally reached these cases.
Keep 750ms Windows Worker OS-join settle and non-Windows hammer skips for
Bun 1.3.14 isolate segfaults; take tip's scoped management-auth icacls fakes.
@Wibias

Wibias commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

[shipping-github] Verdict: changes-requested

PR: #827 — fix(storage): await Worker join in test beforeEach under isolate
Head: 9931337b on dev (mergeStateStatus: UNSTABLE — required checks green; review state not clear)
Linked: follow-up to #813 / none auto-closing

Usefulness

Real Windows bun test --isolate bug: fire-and-forget Worker terminate in storage beforeEach left workers_spawned(N) workers_terminated(N-1) and panicked the suite. Async join + drain, mutation-slot ordering, and related isolate timer keep-refs are the right fix class. Valuable for every Windows Cross-platform run.

Bugs / correctness

  • Method: bug-review.md — Bugbot: ran (stacked-base enforce-pr-target hit discarded as wrong merge-base / out of PR diff); complementary lenses: done (silent_failures / resource_leaks / edge_cases / lifecycle / races / clocks)
  • Findings: none blocking on tip
  • Fixed this session (on tip ancestry):
    • 60be0c50 — OAuth short waitMs stay ref'd (Windows isolate hang ~20+ min)
    • merge of 1ed2d704 — background-shell kill-grace stay ref'd (shutdown-drain hang after oauth fix)
    • f1fa4643 / tip ACL stubs — management-auth icacls fakes no longer blanket-timeout startServersaveConfig on real win32
    • 9931337b — re-sync dev; keep 750ms Windows Worker OS-join settle + non-Windows Worker-hammer skips

Security

  • Decision: Pass (no confirmed HIGH)
  • Scope: oauth mutation timers (short-wait ref keep — tests), drainAndShutdown / storage worker lifecycle, CI timeout + runner-select comments (from base), management-auth test stubs only
  • Findings: none confirmed
  • Residual: production long OAuth waits remain unref'd by design; kill-grace / short waits stay ref'd so shutdown and tests cannot hang the event loop under isolate

Spec / standards

  • Spec source: PR body (isolate Worker join follow-up to #813)
  • Gaps: advisory only — no dedicated harness catch/finally failure test for installPolicyApiHarness rejection path (owner asked for coverage; behavior is implemented)
  • Standards: Bun-native tests, focused regression suites, no CI ceiling raise past 30m (user constraint respected)

Reviews

  • Owners/maintainers: @Ingwannu CHANGES_REQUESTED on 10ab2e8b — both lifecycle items addressed in cc08831a+ (mutation reset after drain; harness drain-before-OPENCODEX_HOME + finally restore). Needs owner re-review to clear reviewDecision.
  • Bots: CodeRabbit job-scoped timeout asserts addressed; Codex P2 await Server.stop fixed in lifecycle.ts (65043ef1) — reply posted on thread PRRT_kwDOS-0Gi86Vnwvi; thread still unresolved (resolve needs an explicit instruction)

Base / CI

  • Behind/conflicts: clean vs dev @ 63735af4 after 9931337b
  • Required checks: green on 9931337bubuntu / macos / windows (~14m32s) / npm-global matrix / enforce-target / react-doctor
  • Local tip: bun test focused suites (ci-workflows, server-management-auth, shutdown-drain, storage-worker-teardown-isolate) — 97 pass

Gate

hard blockers for merge-ready / approve-comment:

  1. Owner CHANGES_REQUESTED still active — please re-check @Ingwannu
  2. Unresolved Codex review thread (code fixed; say resolve if you want it closed)

Bottom line

Ship direction is sound and Windows isolate CI is green under the 30m ceiling, but GitHub review state is not merge-clean yet: need owner re-approval and the Codex thread resolved. No further product fixes pending for the stated isolate panic.

@Wibias

Wibias commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

[shipping-github] Merging (override)

Merging with explicit merge anyway despite stale owner CHANGES_REQUESTED on 10ab2e8b — both requested lifecycle fixes are on tip 9931337b, bot threads are clear, and required CI is green (Windows ~14m under the 30m ceiling).

Why it helps: Windows bun test --isolate no longer panics mid-suite when storage Workers are still joining after a sync beforeEach reset. Suites await terminate+drain, hold the mutation slot until join finishes, and keep short isolate wait timers ref'd so shutdown/oauth cannot hang the run.

@Wibias
Wibias merged commit a1ed691 into lidge-jun:dev Aug 1, 2026
11 checks passed
@Wibias
Wibias deleted the fix/storage-worker-isolate-beforeeach branch August 1, 2026 20:24
Wibias added a commit to Wibias/opencodex that referenced this pull request Aug 1, 2026
Resolve oauth wait-timer, oauth-store-multi deadline, and management-auth ACL stub conflicts on top of the landed storage-worker isolate beforeEach work.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants