Reliability, Cancellation and Recovery
Faults injected at every transition of a request's life in the Chapter 27 engine, what leaked, what hung and who was told what; an engine that rolls each one back; cancellation in every state; inputs that cannot be served; a worker that is killed, hung or hit by a device-side assert; and what retries do to a service past its capacity.
One allocation failure was injected into an admission step of the Concurrent Requests and Streaming engine while eight GPT-2 requests were being exercised on a GPU. Five streams had already arrived. The harness told those five that the engine had failed, but it did not cancel their underlying sequences. The engine then generated 39 more tokens for streams whose callers had been told to stop waiting. A reservation of two cache blocks remained accounted for, and one sequence remained in its state. The other three requests, submitted later, completed correctly. The engine could still serve another probe request. That is why this fault is dangerous: it can consume capacity and do wasted work without bringing the service down.
Under the same injected out-of-memory exception, the guarded engine rolled back the partial admission, put the request back in the waiting queue, and retried it once. All eight requests completed with the same greedy token sequences as the fault-free reference; no reservation or cache block remained at the end. This result is from a controlled single-fault experiment, not evidence that an allocator or CUDA context is generally safe to reuse after every possible failure.
This chapter studies the boundary between a correct inference loop and a recoverable service. Chapters 25–29 supplied request handling, scheduling, streaming, partitioning and process separation. Here the system must confront a failed allocation, an invalid token id, a disappearing client, an expired deadline and the loss of the process that owns the model. The engineering target is failure containment: return each request’s resources, preserve unaffected work where safe, and expose an unambiguous outcome. The experiments test parts of that target; they do not prove that every failure affects only one request. A lost worker, for example, still ends all of its in-flight requests.
The question
The chapter’s experimental gate is to inject faults at the transitions where a request acquires, modifies or releases state, and to inspect the result. The lab defines nine named injection sites and three fault classes. For each run it records terminal outcomes, leftover reservations or blocks, unexpected work after failure, and whether a subsequent probe succeeds. Nine sites are a deliberate test matrix, not an exhaustive proof over every possible instruction, interleaving or hardware fault. To interpret its outcome, we first need explicit invariants.
Five questions organise the investigation. When a Concurrent Requests and Streaming step raises after partially changing the cache, what state remains? Can the guarded engine repair that state and isolate a bad request without changing healthy requests’ observed tokens? Which cancellation points are exercised and what is the delay between signalling and release? Which malformed or impossible requests must be rejected before they reach a kernel? Finally, when a worker process is lost rather than a step failing, what does the supervisor detect, how long does replacement take, and what would a restart or continuation need to preserve? These questions separate in-process rollback, cooperative cancellation, and process-level recovery, which have different safety assumptions.
A sixth question connects reliability to Request Scheduling and Admission Control: what happens when timed-out clients retry while the engine remains busy with their earlier attempts? The chapter addresses this with a calibrated virtual-time simulation and a separately reported, hardware-confounded live series. The policy ranking comes from the simulation; it is not a measured controlled comparison of production retry systems.
Where this sits
PagedAttention introduced the paged cache and its allocator and sequence tables. From Inference Loop to API constrained HTTP requests, while Request Scheduling and Admission Control added admission and deadline policies: this chapter puts an additional validation boundary at the engine, including for callers that pass token ids directly. Concurrent Requests and Streaming implemented continuous batching, cancellation and a 300-stream disconnect stress test; that test did not inject an exception inside prefill or decode. Distributed Inference exposed collective and shared-memory costs, and Prefill/Decode Disaggregation built a multi-process harness whose blocked control and event pipes revealed a circular wait. The supervisor here uses an independent sender, reader and monitor to avoid the same class of deadlock. A passing result at one layer does not imply that another layer correctly propagates cancellation or failure.
Inference Protocols and Harmony returns to client-visible protocol semantics. This chapter records terminal events in the engine and supervisor, but does not put the Concurrent Requests and Streaming HTTP/SSE server in front of the supervisor during worker loss. Whether a real remote client receives an error event before a connection drops remains an untested integration question. A terminal event created inside the supervisor is not by itself proof of delivery over HTTP.
Where the starter was wrong
The starter demonstrated success, retry, cancellation and timeout with a set of request-id strings released in a finally block. Its release operation could not fail, its retry skipped the failing step rather than replaying it, and its timeout and cancellation were local control-flow exercises. Those tests are useful introductions to cleanup discipline, but they do not cover a paged allocator, incomplete GPU writes, concurrent requests or a lost process. The starter implementation remains unchanged; the results below come from the new fault-injection and supervisor labs.
The gRPC cancellation guide makes a narrower point than a general promise of cancellation: the transport library can signal cancellation, but application work must check and cooperate. The chapter tests that proposition using this engine’s step boundaries, then measures the time between the cancellation call and a finish event. No gRPC implementation is exercised.
What a request owns, and what must stay true
In the Concurrent Requests and Streaming engine a request can move through the following states. The table distinguishes logical reservation (need_blocks, an admission-accounting quantity) from physical cache blocks, which are allocated as the sequence grows.
| transition | state or resource acquired | cleanup responsibility |
|---|---|---|
| submitted | request in a thread-safe inbox; no physical KV blocks | step removes it, or processes its cancellation |
| waiting | request tracked and queued for capacity; no cache reservation yet | cancellation, timeout or eventual admission |
| admission | need_blocks added to the engine’s reservation counter; cache table created |
rollback on error or terminal cleanup |
| prefill | physical KV blocks and cached keys/values for the prompt | request cleanup; rollback must handle a partially built table |
| generation | active sequence, its last sampled token and advancing KV cache positions | normal finish, cancellation, timeout or contained error |
| terminal | a finish reason and release record; no further generation should occur | engine emits one terminal event and returns owned resources |
A reservation is not the same as allocated physical blocks. A failure can leave the two counts inconsistent even if the next request still runs.
The fault harness checks four invariants at step boundaries. They express the engine’s intended ownership model, rather than providing a general-purpose proof of transactional execution.
- Logical cache length matches the request. For a live decoding sequence, the cached prefix length is
len(prompt_ids) + len(generated) − 1: the newest generated token remains incuruntil the next decode. The count does not establish that the tensor contents of every cached position are correct. - Reservation matches holders. The engine’s
reservedequals the sum ofneed_blocksfor the sequences still marked as holding cache capacity. A stale reservation can deny admission long before the physical pool is full. - Physical blocks have valid owners. Allocated blocks and sequence tables must be consistent; no free-list entry may simultaneously be owned, and no orphaned table may retain blocks.
- Termination and release are idempotent. Each request should have one externally meaningful terminal outcome and physical cache resources should be returned once, without subsequent zombie decoding. The test’s one-finish and one-release assertions are necessary checks, not evidence that an external client received that outcome.
The original Concurrent Requests and Streaming _finish protects against double finalisation after a request has reached finished, but a Python exception can interrupt the step before _finish runs. Even a post-failure engine that later becomes idle may have generated unnecessary tokens or retained a logical reservation. The guarded engine explicitly handles selected exceptions; a sticky device-side error is handled instead by losing and restarting the worker.
Building an engine that survives its steps
examples/ch30/reliability_lab.py introduces GuardedEngine, a subclass of the Concurrent Requests and Streaming BatchEngine. It preserves the normal token path while adding engine-level validation, rollback on failed admission, bounded retry, failed-batch bisection, cache-length repair, an allocation audit and relative request deadlines. Its fault-free output agrees with the original engine in the recorded checks. This is a laboratory implementation with targeted exception handling, not a general transaction manager or a replacement for process isolation.
Refuse work that cannot run. validate_request checks the token-id sequence, vocabulary bounds, positive integer max_new, model positional limit, per-request cache-block requirement and optional EOS id before the request enters the engine. It explicitly rejects Python booleans as token ids or counts, even though bool is a subclass of int. The checks rely on known configuration and cache capacities; they do not assess global admission pressure, available GPU memory outside the cache, HTTP authentication or whether a deadline can realistically be met. A rejection raises RequestRejected with a machine-readable code before reserving blocks.
Roll back a failed admission. _admit_one increments the reservation and creates the sequence table before computing the prompt. An exception invokes _abort_admit, which tries to release any table, reverses the logical reservation and either requeues or fails that request. A fault classified as transient—torch.OutOfMemoryError, OutOfBlocks, or an explicitly transient injected fault—gets one extra attempt with the default max_attempts=2. A nontransient exception becomes a terminal error:<type> for that request. This is a deliberately bounded policy: a repeated failure does not receive unbounded retries, and an exception during rollback can itself require an audit. It does not certify that a real device-level failure left CUDA safe for reuse.
Isolate a failing decode batch. If the batched forward pass raises, _repair_lengths resets the recorded cache length from each sequence’s prompt length and generated-token count; _decode_batch then tries smaller halves until work succeeds or a single offending sequence fails. A transient single-sequence exception receives at most one additional attempt by default. Token selection (_pick) is protected separately so a sampling failure can end just one sequence. Bisection changes the batch composition and can require extra forward passes; it is a diagnostic recovery policy, not a latency-neutral operation. Most importantly, resetting a length counter does not roll back tensor bytes that a failed kernel may have written. The injected faults exercised here produced reference-matching completed tokens, but atomicity under arbitrary partial writes, asynchronous GPU errors or corrupted cache contents was not established.
Audit allocation consistency. _finish catches an exception raised by the cache free operation, records it, removes the logical reservation and requests an audit. audit inspects sequence tables, allocator ownership and the reservation tally and can repair the tested orphan or partial-release states. The audit does not compare every KV tensor against recomputed keys and values, cannot reconstruct lost application output, and is itself a possible failure point. Accordingly, clean allocator bookkeeping and correct model state must remain separate acceptance criteria.
Give requests deadlines, but distinguish them from interruption. submit(..., deadline_s=...) stores a wall-clock expiry relative to submission. At the start of a later step(), the guarded engine ends overdue waiting or active sequences with timeout. A deadline can therefore be exceeded during an already-running prefill or decode operation; it is not a preemptive kernel timeout or proof that the caller receives an answer within the requested duration. The HTTP, queue, engine and supervisor layers still need a shared cancellation contract.
The Injector replaces selected functions with wrappers that trigger a chosen exception at one of nine named lifecycle points. The matrix covers admission table creation, prefill reservation and computation, token selection, decode reservation and computation, post-advance failure, and release. There are three mechanisms: a one-shot RuntimeError, a persistent request-specific poison fault, and an allocator-raised torch.OutOfMemoryError induced by attempting an enormous 16 TiB allocation. That last mechanism tests exception handling, not exhaustion of a GPU by ordinary traffic. The comparison reuses equivalent fault sites for the original and guarded engines, but it does not span all instructions, combinations of faults, asynchronous GPU execution or failures in the recovery code.
What fails, in each engine
The fault workload consists of eight GPT-2 requests on one RTX 2060: five submitted initially and three after two steps, with 10 requested new tokens per request. The recorded prompt lengths are 9, 14 and 33 tokens; the batch limit is eight and the cache has 400 blocks. The harness injects one fault, drives the engine to quiescence or a 400-step cap, checks the ownership invariants and submits a reference-token probe. For the original engine it reproduces the hub-like behaviour under a step exception: notify the streams it considers open with engine_error, do not cancel their engine sequences, and keep stepping. The metrics therefore distinguish engine_error notifications, token generation after notification, incomplete state, and whether later work can still succeed.
The recorded matrix has 21 cases per engine: nine injection points with a one-off allocator exception and a one-off runtime error, plus three persistent poison requests. The table below shows only the allocator-exception cases. Counts of residual reservations and physical blocks refer to different accounting quantities, and a completed probe is not a proof that the cache is fully clean.
| point (what was in flight) | Concurrent Requests and Streaming engine | guarded engine |
|---|---|---|
admit.tables_add (a request popped from the queue, blocks reserved, no table yet) |
5 streams told they failed; 39 tokens decoded for them afterwards; 2 blocks of reservation and 1 sequence left | all 8 finish; the admission was retried; clean |
prefill.reserve (allocating the prompt’s blocks) |
39 tokens decoded for dead streams; reservation 2, 2 sequences left | all 8 finish; clean |
prefill.layer (part-way through the prompt, 9 layer writes in) |
40 tokens; 3 blocks not returned, reservation 3, 2 sequences left | all 8 finish; clean |
prefill.pick (prompt run, first token not chosen) |
39 tokens; 1 block, reservation 2, 2 sequences left | all 8 finish; clean |
decode.reserve (making room for the next token) |
all 8 told they failed; 67 tokens decoded for them | all 8 finish after one bisection |
decode.forward (the batched pass, before it begins) |
all 8 told; 62 tokens | all 8 finish after one bisection |
decode.post_advance (pass finished, lengths advanced, logits lost) |
all 8 told; 62 tokens | all 8 finish after one bisection |
decode.pick (choosing one request’s token) |
all 8 told; 64 tokens | 7 finish; the request whose token could not be chosen fails alone |
finish.free (a release that returns one block and raises) |
all 8 told; 12 tokens; 1 block, reservation 2, 1 sequence left | all 8 finish; the release was repaired by audit; clean |
Here, told is a harness-level engine_error terminal outcome, not an HTTP packet observed by a remote client. In several baseline decode cases the underlying engine eventually released the cache only because it continued computing tokens for streams already declared failed. Thus an apparently clean final allocator does not imply correct cancellation or useful work: the 62–67 additional tokens in these rows are counted as zombie work rather than successful responses.
One-shot runtime errors caused analogous baseline failures, but the guarded engine intentionally distinguishes exception classes. It retries a transient admission error once, whereas the four nontransient admission errors fail their affected request. The guarded decoder can recover from one-off forward-pass errors by bisection, and a decode.pick failure ends its particular request. The nine total guarded failures in the complete matrix should not be confused with nine failed experiments: all 21 cases completed and cleaned up, while nine individual requests ended unsuccessfully.
Persistent poison requests are a more demanding test than one-shot faults. In the original engine, a poisoned prefill left an incomplete sequence and stale capacity accounting; persistent decode faults repeatedly raised and prevented the workload from quiescing within the 400-step limit. The guarded engine used the same batch-halving path to separate healthy requests from the offending one. In the tested cases, the seven healthy requests retained their reference tokens and the engine ended cleanly. This isolation is a property of the tested synchronous exceptions; it is not guaranteed after a process crash, corrupted model state or an unrecoverable CUDA device error.
Summed over the 21 cases:
| Concurrent Requests and Streaming | guarded | |
|---|---|---|
| cases that left the engine not clean | 13 | 0 |
| cases where decoding went on for streams that had been told they were over | 19 | 0 |
| cases that never finished within 400 steps | 2 | 0 |
| requests that ended in failure | 141 of 168 | 9 of 168 |
| cases in which a request that completed had different tokens from the fault-free run | 0 | 0 |
| cases in which the probe request afterwards failed | 0 | 0 |
The guarded engine’s nine unsuccessful requests were attributable to the nontransient admission faults, decode.pick failures and three poison requests; the other requests in those experiments continued. The Concurrent Requests and Streaming engine nevertheless served the later probe in every case, including cases with leaked state. A successful health probe thus answers can this request run now?, not has every earlier request released its ownership?. Both checks belong in an operational readiness test.
The result has two explicit limits. First, failed-batch bisection can change floating-point reduction and kernel choices, so token equality under the tested float32 GPT-2 workload does not guarantee equality for other batches, dtypes or accelerators. Second, each scenario injected a single fault at a fixed hit count. Interleaved errors, an exception during rollback or audit, repeated allocator pressure and arbitrary GPU corruption were not evaluated. The reported clean state is an observed property of the instrumented allocator in these runs, not a formal proof of failure atomicity.
Cancellation in every state
Concurrent Requests and Streaming accepts cancellation requests through an inbox and applies them when a step next drains that inbox. This experiment covers eleven request situations in each engine, including cancellation that arrives while a prefill is already executing. The tests check final reason, terminal-event count, release bookkeeping, surviving requests’ token sequences and whether the engine becomes idle and clean. Cancellation is evaluated independently from the injected exception matrix.
The eleven situations are: still in the submission inbox; waiting for capacity; during a currently running prefill; after the first generated token; after five tokens; paused for backpressure; after the final token; after the finish event has already been observed; duplicate cancellation; cancellation of an unknown id; and cancellation of all active work. Some are tests of idempotency or no-op behaviour, not cancellations of an unfinished victim.
All eleven scenarios passed in each engine, giving 22 clean scenario runs. For an unfinished request, cancellation ordinarily became effective at the next available step boundary. A cancellation sent during an in-progress prefill was observed after that step finished, and its finish event occurred two step boundaries after the call. Requests already finished retained their length reason; an unknown-id cancel made no change. The result establishes the tested cooperative cancellation semantics, not a promise of immediate kernel interruption or bounded latency in every workload.
This is an important positive result for Concurrent Requests and Streaming: the ordinary cancellation path remains consistent across waiting, running and paused states in the tested workload, even though that engine’s failure path can leave zombie work. Cancellation correctness and exception recovery are distinct properties. A request may be cancellable at the next step boundary but remain vulnerable to a step that raises before that boundary is reached.
To quantify the cancellation delay, the test runs the engine’s step loop on a separate thread, cancels a victim after three generated tokens, and measures the interval from the API call to its finish event. Each condition has 25 observations on the same GPU. These are end-of-step acknowledgement times, not measurements of a network client receiving cancellation confirmation or of physical GPU memory becoming available at the instant of the call.
| condition | cancel to finish (p50 / p90 / max) | decode step (p50) |
|---|---|---|
| victim alone | 23.4 / 26.8 / 30.8 ms | 23.6 ms |
| 8 other streams running | 45.3 / 51.1 / 59.3 ms | 22.8 ms |
| 8 streams, and a 900-token prompt admitted in the same step | 116.9 / 123.9 / 147.6 ms | 22.8 ms |
Cancellation is cooperative. The receiving thread can enqueue a cancel while the engine is busy; the next step processes it, and the event becomes visible only after the step completes. A 900-token prefill in that same step therefore delays acknowledgement. The observed median grew from 23.4 ms for the lone victim to 45.3 ms with eight other streams and 116.9 ms when the long prompt joined. The gRPC guide likewise says that a library cannot interrupt an application handler by itself: the handler must check for cancellation and propagate it to dependent work. This is a useful analogy, not a measurement of gRPC or a guarantee that this engine checks often enough for strict service deadlines.
Inputs that cannot be served
The malformed-input experiment submits fifteen invalid, impossible-to-complete or contract-violating requests ahead of three valid requests. Some inputs fail immediately in Python, some block a first-come-first-served queue, and some are silently reinterpreted—for example, negative indices and boolean token ids. The matrix therefore measures more than exception safety: it tests semantic validation and the effect of an invalid request on unrelated work.
| input | Concurrent Requests and Streaming engine | guarded engine |
|---|---|---|
empty prompt; max_new of 0, −3 or a string |
refused by the engine’s own checks (ValueError, TypeError) |
refused, with a code |
| prompt is a string; a token that is a float; a token id equal to the vocabulary size; a token id of 2⁴⁰ | accepted; the step raised; the 3 healthy requests all lost; 1 block not returned | refused |
| a prompt longer than the model’s context | accepted; the step raised; 3 lost; 68 blocks not returned | refused |
max_new of 10⁹ |
accepted; never admitted and the 3 healthy requests behind it never ran | refused |
prompt and max_new together beyond the context |
accepted; reached position 1,024 three tokens in, then raised at every step (296 times) and never ended; the 3 healthy requests had finished before; 65 blocks held for ever | refused |
| a request that needs more cache blocks than the engine has | accepted; waits at the head of the queue for ever; the 3 healthy requests behind it never ran | refused |
a token that is True; an end-of-sequence id outside the vocabulary |
accepted; harmless (True is read as 1; the end id never matches) |
refused |
| a negative token id | accepted, with no error: the table is indexed with it, and −1 reads its last row | refused |
Of the fifteen test cases, the original engine accepted eleven. Seven accepted cases prevented the three healthy requests from completing, for 21 affected healthy-request outcomes across separate test runs. The guarded engine rejected all fifteen before reserving cache blocks and allowed the healthy requests to complete. The remaining accepted cases are still validation bugs even where no other request is lost: a negative id selects an unintended embedding row, and True is interpreted as token id 1.
Two failure modes need no exception. A request requiring more cache blocks than the pool contains sits at the head of the original queue indefinitely and can starve eligible requests behind it. Separately, a negative token id is legal Python tensor indexing in the tested CPU path, so the request can finish after reading a different embedding rather than fail visibly. A health check that only counts raised exceptions would miss both. Engine validation must happen before queue ownership and kernel execution.
The main malformed-input matrix ran on the CPU, where out-of-range embedding indices raised ordinary exceptions. A separate GPU worker experiment bypassed validation and submitted token id 60,000 to GPT-2, whose vocabulary has 50,257 entries, while ten healthy requests were active. The CUDA embedding access triggered a device-side assertion and the worker deliberately reported the failure and exited; the ten in-flight requests were then lost. The code does not test continuing safely after that assertion, and CUDA may report asynchronous errors at later operations. This experiment establishes the impact of one unvalidated token on this worker, not that every invalid input or GPU assertion always terminates a process.
From Inference Loop to API’s HTTP boundary accepts text and enforces request limits, but token-id APIs, internal agents, state import and direct engine calls can bypass a tokenizer. The engine must reject invalid token ids and requests exceeding its positional or cache capacity regardless of their origin. At the same time, these pure checks do not replace queue admission, tenant quotas, memory-pressure handling, schema validation of imported KV state or an external authentication boundary.
Losing the worker
In-process recovery stops being credible when the worker has exited, stopped making progress or encountered a device error after which continued execution is unsafe. The demonstrated response is process replacement: mark unresolved requests as lost, terminate the old worker and launch a fresh one. Recovery time, terminal notification and replay semantics are measured separately. No second hot replica or automatic failover route was deployed in these experiments.
examples/ch30/supervisor_lab.py places GuardedEngine in a spawned worker process under a Supervisor. One thread sends commands, a second reads events, and a monitor checks process liveness and a shared-memory timestamp updated as the worker loops. If the process disappears or the timestamp stops moving beyond the configured threshold, the monitor declares that generation lost, ends unresolved request handles with error:worker_lost, terminates the old process and starts a new one. This local terminal event can be generated even when the worker can no longer send it. The heartbeat indicates loop activity, not successful request progress; a legitimate long prefill, blocked operation or pause longer than the threshold could also be classified as a hang. The experiment does not calibrate that false-positive risk or transmit the event through an HTTP server.
The supervisor was exercised with ten in-flight requests (20–60 prompt tokens, 64 new tokens each), after a median of 13 output tokens per request had been delivered. Three single-fault scenarios were run: deliberate process exit, an induced infinite sleep, and a device-side assertion from an unvalidated token id. The hang detector used a two-second timeout. These are one run per fault, not latency distributions or a study of independent-node failures.
| fault | detected after | terminal events sent | new worker ready after | requests lost |
|---|---|---|---|---|
| process exits | 0.21 s | at once | 12.3 s | 10 of 10, with 130 tokens delivered |
| process hangs | 2.03 s | at once | 12.5 s | 10 of 10, with 130 tokens delivered |
| device-side assert | 0.52 s | at once | 12.6 s | 10 of 10, with 130 tokens delivered |
For a hung worker, detection at 2.03 s follows the configured two-second threshold; the timeout is a suspicion rule, not a mathematical test that the process cannot recover. Deliberate exit was detected after 0.21 s, and the device assertion after 0.52 s. Once the supervisor detected loss, it marked the ten request handles terminal almost immediately; the replacement then took another 12.3–12.6 s to become ready, largely from Python imports, checkpoint loading and warm-up. From the fault injection until a replacement was ready, the recorded range was approximately 12.5–14.6 s. The experiment did not measure externally delivered SSE notifications or queueing during replacement.
The pinned DeepInfer deployment note describes a different operational strategy: redundant prefill and decode capacity, rerouting and keeping KV state outside an individual compute process, because large-scale restarts may take minutes. That is an authors’ description, not a deployment reproduced here. This lab has one worker and restarts it; it therefore measures restart recovery, not failover availability. A spare replica would require additional work on routing, request ownership, KV compatibility and duplicate suppression.
The requests the supervisor could not finish were then handed to the new worker three ways:
- Fail explicitly. The supervisor marks the request
error:worker_lostand retains the tokens already observed. The client or a higher-level coordinator decides whether the request may be reissued; the lab does not automatically resend it. - Replay from the beginning. The same prompt is submitted to the replacement engine and its regenerated prefix is compared with the previously delivered prefix. In the tested float32 greedy workload, 10 of 10 requests reproduced uninterrupted output in each fault scenario; their median completion after resubmission was 0.94–1.01 s. Replaying can duplicate tool or business actions unless those actions are separately idempotent.
- Reconstruct and continue. The prompt plus previously delivered token ids becomes a new prefill, with only the remaining output length requested. All 10 of 10 continuations matched the uninterrupted greedy reference in each scenario; completion after resubmission had a median of 0.76–0.81 s. This recomputes state rather than transferring the lost worker’s KV cache, and only has the same semantics if the exact token prefix, model, tokenizer and decoding parameters are preserved.
Continuation was also tested independently of worker loss. Forty prompts each generated 64 greedy tokens; after retaining the first 1, 8 or 32 tokens, the engine prefilled the original prompt plus that output prefix and generated the remainder. All forty batched continuations matched for each split, and the first ten were checked in solo runs. A fresh prefill and incremental decoding need not use numerically identical kernels or reduction orders, so matching argmax tokens across these tests does not prove general bytewise cache equivalence. These results apply to GPT-2 float32 on the tested device and context lengths; the replayed text and token ids must not be conflated.
Sampling introduces an additional piece of request state. This lab’s seeded TorchSampler selects a draw using the seed and generation position. Replaying 40 sampled requests from the original prompt with the same seed reproduced all 40. Resuming after eight tokens without restoring the position reproduced only 1 of 40; after 32 tokens, 8 of 40. Setting sample_offset to the number of previously delivered tokens restored agreement for 40 of 40 at both checkpoints. The result depends on this position-indexed sampler and unchanged sampling configuration; a backend with one advancing RNG stream, different kernels or different logits would require a fuller state contract. Resumption cannot safely be inferred from the seed alone.
A partial stream is not a completed answer. The supervisor’s local handles receive error:worker_lost, while Concurrent Requests and Streaming’s SSE design defines done and error events. A client should mark a streamed response complete only after observing an application-level terminal success event; EOF, timeout or a socket close without one means the answer may be truncated. The end-to-end distinction matters because the transport cannot determine whether the application finished or whether externally visible side effects occurred. This chapter did not connect the supervisor to the HTTP streaming endpoint, so it has not verified whether an SSE client actually receives the loss event. An integration test must cover that path and the possibility that even an error event is lost with the connection.
Timeouts, and what retries do
Timeouts need an explicit owner and propagation path. A client has a total deadline; the admission queue should discard work that can no longer succeed; the guarded engine checks relative deadline_s at step boundaries; and the supervisor monitors worker liveness with a separate hang threshold. These are not interchangeable: an overloaded request is not a hung worker, and an application deadline does not preempt a GPU kernel. A heartbeat monitor can also make false suspicions under slow steps. Production recovery should carry request identity, generation epoch, deadlines and cancellation downstream, and should avoid classifying temporary slowness as permanent loss without a documented policy.
Retries are only safe when their application effects are safe to repeat. In the laboratory, greedy decoding on a fixed backend reproduced the tested outputs, and a sampled request needed its seed and position; neither property makes an external tool call, charge or message idempotent. A client timeout means the result was not observed in time, not that the first attempt stopped. Therefore a retry policy must combine bounded attempts, cancellation of abandoned work, server admission, and where effects matter, stable request ids or idempotency keys with result deduplication. The lab models some of these controls but does not implement a distributed exactly-once effect system.
The queueing model explains why retries can amplify overload. With a roughly stable service capacity c requests per second and q requests ahead, the crude FCFS waiting-time approximation is q/c; after including a request’s own service time s, a client with deadline T will miss when q/c + s > T. This is an illustration, not a precise bound for the batched, time-varying GPU server, and it ignores the spread in prompt lengths and queue discipline. If each attempt fails with conditional probability p, a capped policy with up to k retries has expected attempts approximately 1 + p + ... + p^k under a constant-probability assumption; in overload those failures are correlated, so p is not fixed. As it approaches one, two allowed retries can nearly triple attempts without adding any service capacity.
The calibrated virtual-time engine uses Prefill/Decode Disaggregation’s fitted prefill and context-dependent decode costs, iteration-level admission and a batch limit of 16. At permanent saturation it models 16.3 completed requests per second for 64-token prompts and 64 generated tokens. Closed-loop live probes on the shared GPU ranged from 8.2 to 16.0 requests per second, with the fastest probe near the model and slower probes substantially below it. The model’s light-load median latency around 0.84 s is also only approximately supported by live observations (roughly 0.78–1.0 s in the first series, with a later 6/s median reaching about 1.8 s). Calibration against a best-case probe is not validation of a stable production capacity or of tail latency under overload.
The simulator generates five seeded Poisson arrival traces per cell over 60 seconds. Each attempt has a three-second response timeout, a fixed 64-token prompt and 64-token completion target, and one of the following policies. The figures compare the policies under this virtual-time engine, not a randomised live A/B test.
- Abandon: stop waiting at the timeout, without cancelling the engine attempt.
- Cancel: stop waiting and enqueue cancellation of that attempt.
- Retry: after abandon or cancel, immediately start up to two more attempts; the original attempt may still be running under abandonment.
- Budgeted retry: cancel, then permit at most two delayed attempts with exponential backoff starting at 0.5 s and jitter, subject to a global retry allowance of about 10% of arrivals plus one.
- Shed: cancel on timeout and immediately refuse a new attempt when 16 requests are already waiting; an early refusal is counted separately from a late response.
These policies do not enforce distributed deduplication, per-tenant fairness or a production retry budget shared across independent clients.
Simulated goodput—successful original requests delivered before their timeout per second, averaged across five seeded 60-second traces. Offered load is expressed relative to the model’s 16.3-requests/s saturation estimate; the denominator counts original requests, not individual retry attempts.
| policy | 0.9× | 1.2× | 1.6× | 2.4× |
|---|---|---|---|---|
| abandon | 14.4 | 3.3 | 1.7 | 1.1 |
| cancel | 14.5 | 6.6 | 2.0 | 1.1 |
| abandon, then retry twice | 13.6 | 3.3 | 1.7 | 1.1 |
| cancel, then retry twice | 13.7 | 3.5 | 1.8 | 1.1 |
| cancel, budgeted retries | 13.9 | 4.7 | 1.8 | 1.2 |
| cancel, shed at 16 waiting | 14.4 | 16.0 | 16.1 | 16.3 |
At 0.6× modeled capacity, every policy succeeded for all requests on the tested traces. At 0.9×, short bursts already caused a few timeouts, and immediate retries reduced goodput slightly relative to no retry. At 1.2×, simulated abandonment delivered only 3.3 successful requests/s out of about 19.6 offered, with roughly 971 attempts per 60-second run executed to completion after their callers had left. Cancelling improved goodput to 6.6, although generation before cancellation was still wasted. Immediate retries raised attempts to about 2.65 per original request with little or no gain. Budgeted retries limited additional attempts to roughly 10% but delivered 4.7, less than cancellation alone. These are model outcomes under a fixed service-speed trace, not confidence-bounded estimates for a deployed API.
The load-shedding policy performed best in this simulated overload regime: around 16.0–16.3 timely responses/s at offered loads of 1.2×, 1.6× and 2.4×, while immediately rejecting an increasing fraction (approximately 18%, 38% and 58%). Its limit of 16 waiting attempts is a fixed laboratory threshold chosen below an approximate deadline-driven queue cliff; it was not optimised against alternative admission algorithms. Because rejected work is not counted as a successful response, this is a claim about timely service for accepted requests and useful completed work, not universal availability. The operational lesson is to protect scarce execution capacity with admission and cancellation before relying on client retries.
The live experiment was run too, but its cells cannot establish a policy ranking. Policies were evaluated sequentially at 6, 9, 12 and 16 requests/s on a GPU shared with other work. Closed-loop probes around the runs reported about 8.3–8.5 requests/s, yet execution speed varied markedly within and between cells; one policy at 16/s served all 592 offered requests while another served only 16. The controlled comparison is therefore the virtual-time simulation above. The live traces still illustrate failure modes within a run: at 12/s the abandonment arm delivered 38 of 437 responses before deadline but completed 369 attempts for absent callers and ended with 53 waiting and 16 active; the cancellation arm delivered 63 and cancelled 375. Those observations show zombie-work and cancellation mechanics, not a causal estimate of one policy’s advantage under equal hardware conditions.
What the numbers do not show
- Scoped engine and hardware. GPT-2 small, float32, one RTX 2060 and selected greedy or seeded top-k decoding. The shared desktop/GPU environment introduced real performance variability.
- One injected fault at a time. Nine named sites and fixed hit counts were examined; no proof covers arbitrary interleavings, two simultaneous faults, rollback that fails, or hidden corruption after partial GPU writes.
- Synthetic allocator exception. The 16 TiB allocation request exercised
OutOfMemoryErrorhandling without filling the GPU; actual sustained memory exhaustion and driver resets were not tested. - No general GPU recovery guarantee. A CUDA device-side assert was handled by replacing the process. The guarded in-process recovery path was not qualified for arbitrary sticky accelerator errors.
- Limited resume evidence. Float32 GPT-2 matched under the tested prompt lengths and sampling configuration; other dtypes, RNG schemes, model revisions and externally visible side effects could invalidate replay equivalence.
- One local worker. There was no second hot replica, distributed checkpoint service, cross-machine fencing, failover, or real network.
- Watchdog accuracy unmeasured. The fixed inactivity threshold might mistake a healthy but slow worker for a failed one; only injected exit, sleep and device assertion were exercised.
- Retry policy evidence is modelled. Five seeded traces per point use fitted Prefill/Decode Disaggregation costs; the live series is confounded by changing GPU speed and cannot validate the relative goodput claims.
- No HTTP end-to-end failure test. The supervisor produced local terminal outcomes, not observed SSE delivery through the Concurrent Requests and Streaming API. gRPC, Ray Serve and DeepInfer are documentary references, not systems run here.
Inference Lab increment
examples/ch30/reliability_lab.py adds:
validate_requestandRequestRejected: engine-side preflight checks for token ids, context, EOS and cache capacity.GuardedEngine: bounded admission retry, batched decode bisection, logical KV-length repair, release audit, relative deadlines and position-aware sampling.Fault,InjectorandPOINTS: synthetic failures at nine lifecycle sites; exception injection does not exhaust actual GPU capacity.run_case,reference_run,cancel_case,run_malformedandmeasure_cancel_latency: reproducible engine-level fault, cancellation and validation experiments.- Commands
faults,cancelandmalformed; the evidence is recorded inresearch/ch30/results.json.
examples/ch30/supervisor_lab.py adds worker_main, Supervisor, simulate_clients (virtual-time policy comparison), run_clients (the confounded live counterpart), and the commands worker_loss, resume, retries, retries_sim and capacity. The supervisor supplies process replacement and local request termination, but it is not wired into the Concurrent Requests and Streaming HTTP server and does not implement a durable replay log.
To run every injection point against both engines, and then the simulation of clients:
python examples/ch30/reliability_lab.py faults
python examples/ch30/supervisor_lab.py retries_sim
The engineering rule of this chapter is make ownership, failure and terminal status explicit at every boundary. Validate before acquiring capacity; repair or abandon partial state without leaving orphaned cache blocks; cancel work when its caller is gone; and refuse work that cannot meet its deadline instead of letting retries multiply it. Within one process, selective rollback and bisection preserved the tested outputs. At the process boundary, the supervisor recovered by restart and left replay to a caller. Neither local cleanup nor a local terminal event constitutes end-to-end delivery or exactly-once execution—those contracts must be established at the service and client layers.
What you should now be able to do
- Draw a request-state diagram showing logical reservations, physical KV blocks, owned token buffers and terminal events; identify which states are reconstructible from a prompt and which are not.
- Explain what the nine injected-fault points establish and which faults they leave untested, including partially corrupted KV contents and failed audit.
- State the conditions under which batch bisection isolates a poison request without changing other requests’ results, and why a CUDA device assert belongs at a different recovery boundary.
- Interpret cancellation latency as a step-boundary property, not an instantaneous interruption guarantee.
- Explain how rejected inputs can silently alter the prompt or indefinitely block head-of-line admission.
- Separate detection, local terminal notification, process restart and client-visible completion; specify the extra state needed for sampled continuation.
- Use the simulated load experiments to distinguish cancellation, retries and admission control; identify why the live results cannot rank those policies.
Key terms
- Lifecycle transition: a state change where a request acquires, mutates or relinquishes cache, queue or output ownership.
- Logical reservation versus physical allocation: admission’s promised cache capacity versus blocks currently held by a sequence.
- Rollback from request state: restoring tested bookkeeping invariants from prompt and generated-token counters; not necessarily restoring every mutated tensor value.
- Poison request: an input that triggers a repeatable exception when it participates in a batch.
- Batch bisection: retrying halves of a failed batch to isolate a request-specific failure, with extra work and potentially different numerical execution.
- Zombie work: token generation for an attempt that the caller has abandoned or been told has failed.
- Terminal event: application-level success or failure notification; it must reach the consumer to establish observed completion.
- Failure detector: a liveness policy that may suspect a healthy but slow worker as well as detect a dead one.
- Resume offset: the generation position needed by this chapter’s seeded per-position sampler to continue the same random choices.
- Retry budget: a bound on additional attempts, distinct from a bound on the original arrival rate.
- Load shedding: early refusal of new work to protect accepted requests’ latency and the engine’s useful throughput.
Reader exercises
- Inject two faults during a single request, including an exception from
audit; compare allocator invariants with the actual cached K/V contents and record whether either can be reconstructed. - Put Concurrent Requests and Streaming’s streaming HTTP server in front of the supervisor. Kill the worker before the first byte, mid-stream and after the engine finishes; record whether the remote client receives
done,erroror EOF without a terminal event. - Add a second warm worker and a monotonic worker-generation/lease token. Fail one worker, fence its late output and measure whether a healthy replica can continue serving without duplicates.
- Test a deliberately slow but healthy prefill that lasts beyond the two-second hang threshold. Estimate false positives and separate loop heartbeat, step duration and request progress.
- On an isolated test GPU, induce genuine memory pressure with explicit safety limits and record allocator, CUDA and recovery behaviour separately; do not run such a test on a shared desktop device.
- Compare predicted-deadline admission from Request Scheduling and Admission Control with the fixed 16-waiting shed rule under held-out arrival traces, recording fairness and completed responses per offered request.
- Resume greedy and sampled continuations under half precision, changed batch composition and a second model checkpoint; require exact token-prefix verification before accepting resumed output.
- Add stable request and idempotency keys, terminal-event persistence and an end-to-end replay test with a tool side effect; prove that duplicate client attempts cannot repeat the effect.
References
- gRPC: Cancellation — provider documentation: cancellation signals reach a call but application handlers must check and propagate them; not exercised in the lab.
- Ray Serve: Fault Tolerance — provider documentation: replica health checks, restarts and service continuity depend on deployment conditions; no in-flight request guarantee is inferred here.
- DeepInfer deployment Q&A, pinned commit 774ce244 — authors’ description of redundant serving capacity, KV-state handling and rerouting; not reproduced.
- Unreliable Failure Detectors for Reliable Distributed Systems — Chandra and Toueg, Journal of the ACM 43(2), 1996; supplies the conceptual distinction between detecting an actual crash and suspecting failure on a timeout. This chapter’s watchdog is far simpler than the paper’s formal models.
- The Tail at Scale — Dean and Barroso, Communications of the ACM 56, 2013; background on why latency tails, overload and outliers matter to a multi-component service. Its empirical results are not reproduced here.
- End-to-End Arguments in System Design — Saltzer, Reed and Clark, ACM Transactions on Computer Systems 2(4), 1984; background for why a local release record or transport completion does not establish application-level completion or duplicate suppression. No formal end-to-end reliability proof is attempted here.
Evidence in this chapter
| Claim | Category and qualification |
|---|---|
| The Concurrent Requests and Streaming engine was not clean in 13 of 21 injected-fault cases and generated zombie tokens in 19; two poison cases did not quiesce within 400 steps | Book result: one injected fault per run, GPT-2, GPU, fixed hit counts |
| The guarded engine ended clean in all 21 cases, with nine unsuccessful individual requests against 141 in the baseline; all completed requests matched the fault-free greedy reference | Book result: tested bookkeeping and tokens; not a proof of arbitrary recovery atomicity |
An injected allocator OutOfMemoryError lost no request in eight of nine guarded sites |
Book result: immediate failed 16 TiB allocation, not naturally exhausted GPU memory |
| Cancellation passed 11 scenario types in both engines; median time to finish was 23.4, 45.3 and 116.9 ms across three load conditions | Book result: 25 timings per condition, cooperative step-boundary cancellation |
| The baseline accepted eleven of fifteen invalid/impossible requests, leading to 21 lost healthy-request outcomes; negative token ids silently selected a different row | Book result: CPU malformed-input matrix |
| An unvalidated out-of-range token caused a CUDA device-side assertion, and the worker deliberately exited with ten in-flight requests lost | Book result: one GPU-worker scenario; post-assert safe continuation not attempted |
| Process exit, injected hang and device assert were detected in 0.21, 2.03 and 0.52 s; replacement worker ready around 12.5–14.6 s after injection | Book result: three single trials, one worker, includes restart delay |
| Replaying from start or recomputing the prompt plus delivered tokens reproduced ten greedy responses per worker-loss fault and forty continuations at three split points | Book result: fixed GPT-2 float32 configuration and finite prompts |
| Seeded sampled resume without the generation offset matched 1/40 and 8/40; with the offset, 40/40 at both splits | Book result: this position-indexed sampler, temperature 0.8 and top-k 40 |
| Simulated overload reduced goodput; a fixed queue shed rule preserved ~16 useful responses/s where immediate retries added load without improving useful work | Modelled: Prefill/Decode Disaggregation fitted costs, five virtual-time traces per cell, not a controlled live comparison |
| Modelled capacity was 16.3 requests/s; live closed-loop probes ranged 8.2–16.0 | Model plus measured probes on shared hardware |
| gRPC cancellation, Ray Serve recovery and DeepInfer deployment | Documentary descriptions only; not tested |
| Formal failure-detector results, end-to-end duplicate suppression and tail-at-scale conclusions | Published research context; not reproduced |
| Second replica, multi-node recovery, true allocator exhaustion, combined faults and client-visible HTTP/SSE worker-loss behaviour | NOT_RUN |
Implementation status
- Manuscript:
content/books/inference/30-chapter.md. - Runnable examples:
examples/ch30/reliability.py(original starter, unchanged),examples/ch30/reliability_lab.py(validation, fault injection, guarded engine, cancellation and malformed inputs), andexamples/ch30/supervisor_lab.py(worker monitoring, replacement, replay/continuation and retry-policy experiments). - Tests:
tests/test_ch30_reliability.pyandtests/test_ch30_reliability_lab.py; the latter’s 29 tests use a small CPU GPT-2 and, unlessCH30_SKIP_LIVE=1is set, include process-loss tests. The saved GPU matrix and simulations are additional evidence; they are not rerun just by reading this chapter. - Evidence:
research/ch30/results.json,research/ch30/sources.md,research/ch30/build_results.pyand the cross-bookresearch/evidence-register.md. - Verification command:
python -m unittest discover -s tests -vwith required model assets and dependencies present. Some live tests may be skipped when the environment cannot support them.
This chapter remains marked draft = false in its front matter, but that publishing flag should not be mistaken for complete operational qualification. The strongest verified outcome is contained recovery for the tested synchronous engine faults; the most consequential open work is transactional correctness under partial GPU mutation, watchdog false-positive testing, real service-to-client terminal delivery and replica-aware restart or replay. Inference Protocols and Harmony’s protocol discussion is where the last of those boundaries must become observable from outside the engine.