bleep-bsp: tighten cancellation, signaling, and lifecycle#598
Merged
Conversation
Production-hardening pass over the BSP server's concurrency primitives. Cancellation hygiene - Outcome.fromCancellationToken now routes Deferred.complete through a process-wide Dispatcher instead of unsafeRunSync on the callback thread (legal regardless of whether the cancel originates on a CE compute fiber or a foreign JVM thread). - Outcome.bridgeKillSignal switches callback list to CopyOnWriteArrayList so a re-entrant onCancel can't deadlock the cancel path. - TaskDag.executor stops wrapping the test handler in IO.uncancelable — withRecovery already produces a structured Killed TaskResult on fiber cancel; the blanket uncancelable could pin server shutdown indefinitely. - MultiWorkspaceBspServer.withDeadClientDetection only uncancelables the killSignal completion, leaving processEvent cancelable so a wedged client can no longer pin the consumer fiber. DAG executor - Replace the rotating-Deferred wakeup pattern with Queue.bounded(1) + tryOffer: coalescing semantics, no Ref swap race, eliminates the spurious "deadlock" false-positive on very fast no-op task bursts. - ParallelProjectCompiler spawns compiles under a Supervisor so cancelling the surrounding fiber actually cancels in-flight compiles instead of orphaning them with Zinc still writing class files. ProjectLock - Move Files.createDirectories outside the per-project lock (idempotent syscall has no business serializing). - JVM monitor → fair ReentrantLock so an exclusive waiter can't be starved by a continuous stream of shared acquirers. - File-handle close moved outside the lock on release (closing a FileChannel under load can hit slow paths on Windows / NFS). Diagnostics + metrics - BspDiagnosticTracker scoped per-build-operation (handleCompile / handleTest each have their own). startCycle atomically rotates current vs previous via a single AtomicReference; no more snapshot-then-clear race against concurrent recordDiagnostic. - BspMetrics gains a dedicated writer thread + bounded queue: producer threads enqueue non-blocking, the writer drains in batches with a single flush per batch instead of fsync-per-event under the global write lock. Saturated-queue events surface as dropped_events in the summary. - ZincBridge tracks abandoned ECJ compile threads (named per-compile, daemon-marked) so jstack + abandonedEcjThreadsSnapshot give operator visibility into the known leak when CompilationProgress cancellation is unavailable. Same pattern in Outcome.runInFreshThread for native-compiler threads that ignore Thread.interrupt. Locking + sharing - SharedWorkspaceState.unregister stopped removing the empty inner map — the value-based remove(K, V) check raced with concurrent register and could drop a just-registered operation. - SourceGenRunner.scriptSemaphores keyed on (scriptProject, mainClass) so two unrelated script projects sharing a main-class name no longer serialize against each other. - cachedExternalTestRunnerJars keyed per-resolver instead of process-wide; multi-tenant servers with different resolver configs no longer share the wrong jars. Misc - TestRunner.captureThreadDump bounded by 5s so a wedged JVM can't pin the timeout-handling path. - JsonRpcTransport.close() synchronizes against concurrent reads/writes. - BspServerDaemon's server-wide compile Semaphore is now FIFO-fair. - InProcessBspServer.serverExited returns the real exit code via CompletableFuture instead of IO.never; daemon thread reports failures. - Deleted unused CompilationCoordinator (393 LOC). All 552 bleep-bsp tests still pass. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Production-hardening pass over
bleep-bspconcurrency. Focused on places where toolchain code, JVM threads, and cats-effect met awkwardly: callback-threadunsafeRunSync, races between non-atomic ops, fiber leaks on cancel, blanketIO.uncancelableblocking shutdown, contention bottlenecks.CancellationTokenstays as the toolchain ABI; the bridges to/from CE are now CE-safe (Dispatcher on the way in, COWAL +.backgroundon the way out). Everything CE-side speaksDeferred[IO, KillReason]+ fiber cancellation.Cancellation hygiene
Outcome.fromCancellationTokenroutes through a lazy process-wideDispatcher.parallel(nounsafeRunSyncfrom callback threads — was illegal when cancel originated on a CE compute fiber).Outcome.bridgeKillSignalcallback list →CopyOnWriteArrayList(no deadlock if a callback re-entersonCancel).TaskDag.executordrops theIO.uncancelablearound the test handler —withRecoveryalready produces a structuredKilledresult on fiber cancel; the blanket uncancelable could pin server shutdown indefinitely.withDeadClientDetectiononly uncancelables the kill-signal completion;processEventstays cancelable so a wedged client can't pin the consumer fiber.DAG executor
Deferredwakeup replaced withQueue.bounded(1)+tryOffer: coalescing wakeups, no Ref-swap race, eliminates the spurious "DAG deadlock" false-positive on very-fast no-op task bursts.ParallelProjectCompilerspawns compiles under aSupervisor— cancelling the surrounding fiber now actually cancels in-flight compiles instead of orphaning them with Zinc still writing class files.ProjectLock
Files.createDirectoriesmoved outside the per-project lock (idempotent syscall, no contention).ReentrantLockso an exclusive waiter can't be starved by a continuous stream of shared acquirers.Diagnostics + metrics
BspDiagnosticTrackeris per-build-operation (handleCompile/handleTesteach have their own).startCycleatomically rotates current vs previous via a singleAtomicReference— no more snapshot-then-clear race against concurrentrecordDiagnostic.BspMetricsgains a dedicated writer thread + bounded queue: producersoffernon-blocking, the writer drains in batches with a singleflushper batch. Saturated-queue events surface asdropped_eventsin the shutdown summary.ZincBridgetracks abandoned ECJ compile threads (named per-compile, daemon-marked) so jstack +abandonedEcjThreadsSnapshotgive operator visibility into the known leak whenCompilationProgresscancellation is unavailable. Same pattern for native-compiler threads inOutcome.runInFreshThread.Sharing + keying
SharedWorkspaceState.unregisterstopped removing the empty inner map — the value-basedremove(K, V)raced with concurrentregisterand could drop a just-registered operation.SourceGenRunner.scriptSemaphoreskeyed on(scriptProject, mainClass)so two unrelated script projects with the same main-class name don't serialize.cachedExternalTestRunnerJarskeyed per-resolver instead of process-wide; multi-tenant servers with different resolver configs no longer share the wrong jars.Misc
TestRunner.captureThreadDumpbounded by 5s race so a wedged JVM can't pin the timeout-handling path.JsonRpcTransport.close()synchronizes against concurrent reads/writes.BspServerDaemon's server-wide compileSemaphoreis FIFO-fair.InProcessBspServer.serverExitedreturns the real exit code viaCompletableFutureinstead ofIO.never; daemon thread reports failures.CompilationCoordinator(-393 LOC).Net: −163 lines.
Test plan
bleep compile bleep-bspcleanbleep test bleep-bsp-tests— 552 passed, 0 failed🤖 Generated with Claude Code