|
| 1 | +# Adopt Effect for structured concurrency (reduce Promise.race / AbortSignal / timer complexity) |
| 2 | + |
| 3 | +Status: proposal (incremental adoption; no API-breaking rewrite) |
| 4 | + |
| 5 | +## Problem |
| 6 | + |
| 7 | +Roboppi currently implements cancellation / timeouts / concurrency using a mix of: |
| 8 | + |
| 9 | +- `AbortController` / `AbortSignal` listeners |
| 10 | +- `setTimeout` / `clearTimeout` |
| 11 | +- `Promise.race` / ad-hoc backoff loops |
| 12 | +- manual cleanup in `finally` blocks |
| 13 | + |
| 14 | +This is workable but has predictable failure modes as complexity grows: |
| 15 | + |
| 16 | +1) duplicated patterns with subtle differences |
| 17 | +- `waitForAbort`, `sleep(ms, signal)`, `createScopedAbort`, and repeated `Promise.race([...])` exist in multiple places |
| 18 | + |
| 19 | +2) cleanup correctness is hard to audit |
| 20 | +- listeners and timers must be removed on *every* exit path |
| 21 | +- request maps / waiter maps can leak when new early-return paths are added |
| 22 | + |
| 23 | +3) error handling is fragmented |
| 24 | +- some paths intentionally suppress unhandled rejections (`p.catch(() => {})`) |
| 25 | +- some timeouts are modeled as exceptions, others as sentinel values (e.g. `null`) |
| 26 | + |
| 27 | +4) concurrency semantics are implicit |
| 28 | +- cancellation propagation (parent abort -> child operations) is often implemented manually |
| 29 | +- multi-step flows (submit_job -> permit -> execute -> cancel) interleave timeouts and cancellation in ways that are hard to reason about |
| 30 | + |
| 31 | +Representative hotspots: |
| 32 | + |
| 33 | +- `src/workflow/core-ipc-step-runner.ts` (multiple races + scoped abort + cancel best-effort) |
| 34 | +- `src/ipc/protocol.ts` (`pendingRequests` + timers + fast-fail on disconnect) |
| 35 | +- `src/worker/process-manager.ts` (graceful shutdown uses multiple races / timeouts) |
| 36 | +- `src/scheduler/supervisor.ts` (spawn + transport bridging has several `new Promise` blocks) |
| 37 | + |
| 38 | +## Goals |
| 39 | + |
| 40 | +1) make cancellation / timeout behavior explicit and composable |
| 41 | +2) centralize cleanup via structured resource management |
| 42 | +3) reduce `Promise.race` / timer / listener boilerplate and the chance of leaks |
| 43 | +4) keep external behavior stable (Promise-returning public APIs can remain) |
| 44 | +5) preserve Bun + ESM runtime compatibility |
| 45 | + |
| 46 | +## Proposed Approach (Effect-TS) |
| 47 | + |
| 48 | +Adopt `effect` (Effect-TS) for *internal* concurrency primitives: |
| 49 | + |
| 50 | +- interruption-aware async boundaries: `Effect.async((resume, signal) => ...)` |
| 51 | +- timeouts: `Effect.timeout` / `Effect.timeoutFail` |
| 52 | +- racing: `Effect.race` |
| 53 | +- structured finalization: `Effect.acquireRelease` (Scope) |
| 54 | +- retry/backoff: `Effect.retry` + `Schedule` (exponential + jitter) |
| 55 | +- structured concurrency: fibers (`Effect.fork`, `Fiber.interrupt`, `Effect.all/forEach` with concurrency) |
| 56 | + |
| 57 | +Key idea: do not rewrite the entire codebase to be Effect-first. Instead: |
| 58 | + |
| 59 | +- keep call sites `async/await`-friendly by bridging at module boundaries (`Effect.runPromise`) |
| 60 | +- move the most fragile Promise patterns behind small, well-tested Effect helpers |
| 61 | + |
| 62 | +## Migration Plan (Staged) |
| 63 | + |
| 64 | +### Phase 0: feasibility + footprint |
| 65 | + |
| 66 | +- Add dependency: `bun add effect` |
| 67 | +- Validate Bun+ESM integration in CI (`make typecheck`, `make test`) |
| 68 | +- Decide a minimal internal wrapper surface (avoid importing many submodules everywhere) |
| 69 | + |
| 70 | +Deliverable: |
| 71 | + |
| 72 | +- new internal module (name TBD) that provides a tiny bridge layer |
| 73 | + - `runPromise` wrapper |
| 74 | + - `sleep`, `waitForAbort`, `withTimeout`, `raceAbort`, etc. |
| 75 | + |
| 76 | +### Phase 1: IPC request/response waiter (highest leverage) |
| 77 | + |
| 78 | +Target: `src/ipc/protocol.ts` `waitForResponse()`. |
| 79 | + |
| 80 | +Replace the manual `{ timer, pendingRequests Map }` pattern with an Effect-based implementation: |
| 81 | + |
| 82 | +- register waiter in a single place |
| 83 | +- guarantee cleanup in a finalizer (remove from map + clear timer) |
| 84 | +- fail-fast on transport close without callers needing to add special logic |
| 85 | + |
| 86 | +Keep `waitForResponse()` returning `Promise<unknown>` for now: |
| 87 | + |
| 88 | +- internal: Effect |
| 89 | +- boundary: `Effect.runPromise` |
| 90 | + |
| 91 | +### Phase 2: Core IPC step flow (submit/permit/execute/cancel) |
| 92 | + |
| 93 | +Target: `src/workflow/core-ipc-step-runner.ts`. |
| 94 | + |
| 95 | +Goals: |
| 96 | + |
| 97 | +- remove ad-hoc races (`Promise.race([completionPromise, waitForAbort(...)])`) |
| 98 | +- model cancellation and timeouts as interruption and structured timeouts |
| 99 | +- guarantee listener cleanup in one place |
| 100 | + |
| 101 | +Nice-to-have: |
| 102 | + |
| 103 | +- express "best-effort cancel then wait up to 5s for completion" as a clear combinator |
| 104 | + |
| 105 | +### Phase 3: Process lifecycle (spawn + graceful shutdown) |
| 106 | + |
| 107 | +Target: `src/worker/process-manager.ts`. |
| 108 | + |
| 109 | +Replace multi-race shutdown logic with: |
| 110 | + |
| 111 | +- `acquireRelease` for registration and abort-listener lifecycle |
| 112 | +- `timeoutFail` for grace windows |
| 113 | +- clear modeling of escalation: SIGTERM -> SIGKILL -> "stuck" fallback |
| 114 | + |
| 115 | +### Phase 4: Supervisor spawn / transport bridging |
| 116 | + |
| 117 | +Target: `src/scheduler/supervisor.ts`. |
| 118 | + |
| 119 | +This file has several promise-wrapped callbacks and error/close paths. |
| 120 | + |
| 121 | +- wrap callback-style writes / server close into `Effect.async` |
| 122 | +- make cleanup uniform (close server, rm temp dirs) via finalizers |
| 123 | + |
| 124 | +### Phase 5 (Optional): Workflow-level structured concurrency |
| 125 | + |
| 126 | +Target: `src/workflow/executor.ts`. |
| 127 | + |
| 128 | +This is the biggest payoff but also the biggest rewrite. |
| 129 | + |
| 130 | +- model step execution with fibers and a concurrency limit using `Effect.forEach(..., { concurrency })` |
| 131 | +- ensure workflow abort interrupts all child fibers |
| 132 | +- keep existing `ExecEventSink` emission semantics |
| 133 | + |
| 134 | +## Acceptance Criteria |
| 135 | + |
| 136 | +1) `make typecheck` passes |
| 137 | +2) `make test` passes |
| 138 | +3) no regressions in cancellation semantics: |
| 139 | +- parent abort cancels in-flight waits without leaking listeners/timers |
| 140 | +- step deadlines still apply to worker budget the same way as today |
| 141 | +4) no unbounded growth in internal maps (`pendingRequests`, waiters) |
| 142 | +5) new helpers have unit tests for: |
| 143 | +- timeout |
| 144 | +- interrupt |
| 145 | +- finalizer cleanup on all exit paths |
| 146 | + |
| 147 | +## Non-goals |
| 148 | + |
| 149 | +- converting the entire codebase to functional style |
| 150 | +- introducing Effect contexts (Layers/Services) across the whole runtime immediately |
| 151 | +- replacing existing logging/telemetry wholesale |
| 152 | + |
| 153 | +## Risks & Mitigations |
| 154 | + |
| 155 | +1) learning curve / mixed paradigm |
| 156 | +- mitigate by keeping Effect usage behind a small internal helper layer at first |
| 157 | + |
| 158 | +2) new dependency footprint |
| 159 | +- mitigate by limiting surface imports and using staged adoption |
| 160 | + |
| 161 | +3) subtle semantic drift (e.g., timeouts vs cancellation) |
| 162 | +- mitigate via tests that assert current behavior at module boundaries |
| 163 | + |
| 164 | +4) stack traces / debugging ergonomics |
| 165 | +- mitigate by enabling Effect tracing only where needed and preserving existing error messages |
| 166 | + |
| 167 | +## Reference |
| 168 | + |
| 169 | +- Effect docs: https://github.com/Effect-TS/effect |
| 170 | +- Related: `docs/issues/0005-supervised-ipc-submit-job-timeout.md` (IPC timeouts / correlation) |
0 commit comments