Design Deterministic Tests for Concurrent Code Without sleep() or Retry-Until-Green
You are helping me write reliable tests for code that involves concurrency (threads, async tasks, goroutines, queues, locks, or callbacks). I want tests that fail deterministically when the bug exists and never rely on sleeping or hoping timing works out. Here is the code and a description of the behavior it must guarantee: [PASTE CODE] [PASTE THE INVARIANTS: e.g. "a job is processed at most once", "counter equals number of increments", "shutdown never drops queued items"] Please: 1. Restate each invariant as a testable property, and name the interleavings or orderings that could violate it (check-then-act gaps, lost updates, ordering assumptions, shutdown races, double delivery). 2. For each risky interleaving, propose a test technique that forces it rather than waiting for it: injected latches/barriers or controllable fakes for time and schedulers, a hook point that pauses one actor at an exact line, a deterministic scheduler or single-threaded executor, or a stress loop with many iterations plus a strong invariant check. Say which technique fits and why. 3. Identify what I would need to change in the code to make it testable (injecting a clock, executor, or channel) and keep those changes minimal. 4. Write the test cases in my language/framework, each with a one-line comment stating the interleaving it targets. 5. List any tests that can only be probabilistic (stress tests), and state how many iterations and what assertion makes a failure unambiguous. 6. Note what these tests cannot prove, and which tools (race detectors, sanitizers, model checkers) I should run alongside them. Do not use arbitrary sleeps to "give the other thread time". If a test needs to wait, wait on an explicit signal with a timeout that only exists to fail fast.
Sign in to upvote this prompt.