Awesome Reviewers

Reviewer · Concurrency

Race-safe async state handling

When code spans an await or is driven by concurrent callbacks, never assume that context captured or state observed at one point in time is still valid later — other async work may run in between and change it. Instead:

Instruction

When code spans an await or is driven by concurrent callbacks, never assume that context captured or state observed at one point in time is still valid later — other async work may run in between and change it. Instead:

  1. Capture async context (e.g. AsyncLocalStorage-backed “current unit”/creator) at the moment an operation is initiated or its identity is reserved, not at the moment it settles/completes, since by then a different concurrent flow may be active. For example, a thenable’s “creator” must be recorded when its row ID is reserved, not read off whatever context happens to be running when it resolves.

  2. Prefer structural ordering guarantees over timing-based assumptions to resolve races. Design the pipeline so that a dependent write is always emitted before the data that depends on it (e.g. “every piece of data in the response has its related entries already in the response before it”), so correctness holds for any interruption point (partial flush, backpressure, early close) rather than depending on which callback happens to run first.

  3. Re-validate the runtime state of any object that can be mutated by concurrent/async operations before using it, even if the static type suggests only one state is possible at that point — other in-flight async work (errors, cyclic resolution, etc.) may have already transitioned it.

  4. When multiple async streams/resources must be finalized together (e.g. closing a debug channel vs. a main channel), make the resolution trigger explicit and tied to the correct completion signal rather than implicitly bundling it with an unrelated stream’s close().

  5. When a write must not be split across an interruption point (e.g. backpressure), push it as a single atomic unit so it is always flushed or deferred as a whole.

// Bad: creator captured at settlement time — may belong to whichever
// unit happens to be running when the thenable resolves.
thenable.then(() => {
  const creator = currentUnitForRequest(request); // wrong unit!
  createTaskWithID(..., creator);
});

// Good: creator captured when the row id is reserved.
const creator = currentUnitForRequest(request);
thenable.then(() => {
  createTaskWithID(..., creator);
});