Capture and replay
Shadow records what every part of the Reaktor stack does, and it can run any recorded operation again against a chosen build with every dependency answered from the recording. This page is the build design for that layer. It covers phones, web and desktop clients, Cloudflare Workers and Durable Objects, queues and crons, JVM services on Kubernetes, the Kubernetes node itself, and the data stores. We write all of it ourselves. It is built on reaktor-service, reaktor-graph and OpenTelemetry, and it uses what Cloudflare and Kubernetes already provide: Tail Workers, automatic tracing, version metadata, Durable Object storage, eBPF on the node, pod identity and API audit.
Everything new on this page is a design; What exists today lists the code it builds on. Shadow describes the bases, workspaces and checks that the records feed.
How the layer works#
The layer has two halves. Capture writes an operation record every time a Reaktor operation runs. Replay takes records and runs them again.
An operation record describes one execution of one operation. It holds the request, the response or error, every outgoing call with the answer that came back, every clock and random value the code read, and the order in which all of this happened. When an outgoing call goes to another Reaktor operation, the record points at that operation's own record. A user action that crosses a phone, two Workers, a Durable Object and the JVM server therefore becomes a tree of records, joined by the trace and span ids that the stack already propagates.
Evidence is collected at three depths:
- Every runtime records at its Service boundary and at the clients it uses to reach dependencies. These records hold typed values, and replay runs from them.
- Platform and runtime evidence is collected next to the records: Cloudflare trace events, JVM flight recordings, crash and hang reports from devices, and Kubernetes pod identity. It explains results, and replay never uses it as an answer.
- On the Kubernetes node, an eBPF agent watches sockets, processes and kernel activity for every pod. It checks that each network call a process made appears in some record, and it captures what the in-process recorders cannot see.
Replay loads the exact build under test, feeds it the recorded input and answers each outgoing call from the record. A call is identified by the operation that made it and its position among that operation's calls. If the build makes a call the record does not contain, or skips one it does contain, the replay stops and reports the first point where the two executions differ. A replay has no route to a real dependency.
Principles#
These rules apply to every collector and every replay harness. They refine Shadow's execution cut for a layer we own end to end.
- Record at the Service boundary first. Every Reaktor runtime already sends typed requests and responses through the same interceptor chain, so one recorder design works on phones, in Workers and on the JVM.
- Record each dependency at the client that reaches it: the Ktor engines, the SQL and Cypher wrappers, the Cloudflare binding wrappers and the Durable Object storage wrapper. The eBPF agent then audits for calls that went around them.
- Identify each outgoing call by the operation that made it and its sequence number within that operation. Matching never looks at timestamps.
- During capture, any number of collectors may observe a call. During replay, exactly one adapter answers it.
- A replay that reaches an unrecorded call fails. It never falls back to a live dependency.
- Production keeps serving when capture fails. The record says what it lost, and an incomplete record cannot pass a verification.
- Redaction happens while the record is built, using the field classification carried by the serializers. A field without a classification is dropped.
- Record the values that the code read from clocks and random sources. Secret values, such as the bytes of a new token, are never recorded. Replay generates fresh ones, and the comparison treats them as opaque.
- The graph decides what to record, names where each record came from, swaps in recorded providers during replay and shows coverage in Hangar.
What exists today#
The design reuses these pieces. None of them records payloads in production today.
| Piece | Where it lives | What it already gives | What it lacks |
|---|---|---|---|
| Service interceptor chain | reaktor-service ServiceInterceptor | Typed request and response with their serializers on every tier. An interceptor can answer without calling proceed(). | Nothing records values |
| Operation identity | reaktor-service ServiceContract, OperationDescriptor, SchemaRef | Stable contract and operation ids with schema fingerprints that match between the JVM and JS builds | Nothing |
| Trace propagation | reaktor-service TracePropagation and HttpTracing; ClickHouse service_spans | traceparent from phone to Worker to JVM, and metadata spans from all three tiers | Spans hold no values. The span buffer drops when full, and spans expire after 14 days. |
| HTTP and socket observers | reaktor-io HttpObservation and SocketObservation | Bodies up to 64 KiB, socket frames up to 16 KiB and an intercept chain on every Ktor client | Only dev builds register an observer, and DevTools discards the bodies |
| Port instrumentation | reaktor-telemetry PortInstrumentation; reaktor-graph-port PortInterceptor | A graph visitor that installs and removes port hooks and reports the ports it skipped | Port hooks see no arguments and cannot substitute a result. The inline port() form skips the chain. |
| Worker entry and bindings | reaktor-cloudflare Hono.mount, CloudflareContext, WorkerFetchEngine, PostgresDatabase | One typed entry, and typed choke points for bindings, Worker-to-Worker calls and SQL | No hooks. A few call sites still read env directly. |
| Durable Object base | reaktor-cloudflare PartyServerDelegate and DurableObjectStorage | Connect, message, close and alarm callbacks, and a key-value storage wrapper | No event log. Object code calls SQLite through raw storage.sql. |
| Platform tracing | Workers observability, exporting logs and traces to Grafana; the OpenTelemetry Java agent on the JVM server | Automatic spans for most binding calls and for JVM libraries | Metadata only. Cloudflare's trace ids are separate from ours. |
| Dev tooling | reaktor-devtools GraphTap, FactStream and FaultInjection; Hangar sessions; MockWorld; Hangar flows | A bounded fact stream with drop counts, fault injection, a deterministic fake backend and headless flows | Sessions can be viewed but not run again |
| Journals and receipts | reaktor-work WorkJournal; kernel request ids and receipts | An ordered durable journal with cursors and acknowledgements, and idempotent operation receipts | Nothing |
| Backups | Nightly Postgres snapshot to R2; ClickHouse backup to R2; Memgraph snapshots | Restore points for later state work | No masking and no change stream |
The operation record#
One record type serves every runtime. It lives in reaktor-service common code, so phones, Workers and the JVM build it the same way.
@Serializable
data class OperationRecord(
val schema: String,
val captureId: String,
val operation: OperationKey,
val causal: CausalKey,
val origin: Origin,
val principal: String?,
val request: Payload,
val outcome: Outcome,
val calls: List<CallRecord>,
val reads: List<SourceRead>,
val coverage: Coverage,
)
@Serializable
data class OperationKey(
val contract: String,
val contractVersion: Int,
val operation: String,
val request: SchemaRef,
val response: SchemaRef,
)
@Serializable
data class CausalKey(
val traceId: String,
val spanId: String,
val parentSpanId: String?,
val callIndex: Int?,
val attempt: Int,
)
@Serializable
data class Origin(
val island: String,
val runtime: String,
val build: String,
val instance: String,
val instanceOrdinal: Long,
val startedAtMillis: Long,
val durationMicros: Long,
)
@Serializable
sealed interface Outcome {
@Serializable
data class Returned(val response: Payload) : Outcome
@Serializable
data class Failed(val errorClass: String, val status: Int?, val detail: Payload?) : Outcome
}
@Serializable
data class CallRecord(
val index: Int,
val kind: CallKind,
val target: String,
val effect: Effect,
val request: Payload,
val answer: Payload?,
val failure: String?,
val childSpanId: String?,
val issuedAt: Int,
val answeredAt: Int?,
val durationMicros: Long,
)
@Serializable
data class SourceRead(val position: Int, val source: ReadSource, val value: Payload?)
@Serializable
data class Payload(
val codec: String,
val schema: SchemaRef?,
val inline: ByteArray?,
val blob: String?,
val policy: String,
val truncatedAt: Long?,
)
@Serializable
data class Coverage(
val collectors: List<String>,
val dropped: Int,
val truncated: Int,
val rawEscapes: Int,
val complete: Boolean,
)
enum class CallKind { Service, Sql, Cypher, Http, Binding, ObjectStorage, Queue, Ai, Push, SocketFrame }
enum class Effect { Read, Write, External }
enum class ReadSource { WallClock, MonotonicClock, Random, Uuid, SecretEntropy, WarmState }
The fields mean the following:
operationcomes from the handler'sOperationDescriptor. The schema fingerprints let a record be decoded after the operation changes, and they let a replay report a schema change before it compares anything.causalholds the trace and span ids from the propagated trace context.parentSpanIdandcallIndexsay which call of which parent operation started this one, and they are empty for a root input.attemptcounts retries of the same logical call.origin.buildnames the exact artifact that ran: the Cloudflare version id for a Worker, the image digest for a JVM pod, or the app build for a client.instanceis the isolate, pod or device session.instanceOrdinalcounts the operations that instance served before this one, which matters because an isolate keeps module state between requests.principalis a keyed hash of the subject. Records can be found and deleted per person without storing who the person is.callslists every outgoing call in the order it was issued. Each operation keeps a counter that advances on every issue and every answer, andissuedAtandansweredAtare positions on it. Replay uses them to deliver answers in the recorded order.childSpanIdlinks a Service call to the callee's own record.effectseparates reads, writes to our own stores, and external effects such as a push notification or a third-party API call.readslists, in order, the clock, random and warm-state values the code consumed. ASecretEntropyentry records that a secret was drawn and never its value.Payloadbytes are encoded with the operation's own serializer as FlexBuffers through reaktor-flexbuffer. Small payloads sit inline. Larger ones are stored as separate objects named by checksum and referenced byblob.policynames the redaction policy version that produced the bytes.truncatedAtis set when a cap cut the payload, and the record is then incomplete.coveragelists the collectors that were active and counts what was dropped, truncated or missed.
The capture index keeps the shape of every serial descriptor by fingerprint, so a record written against an older schema still decodes.
A trace is a tree of records. An illustrative trace, with operation names simplified:
trace 4bf92f35… phone · send a chat message
└─ messaging.send Worker Sql read · Queue write · Service → moderation.check
├─ moderation.check Worker Ai external
└─ persistence batch Worker (queue) Sql write · Durable Object → chat room
└─ chat room: message Durable Object ObjectStorage write · SocketFrame ×3 · Push external
A capsule is a selected set of records, the references needed to rebuild their starting state, the assertion version and a retention class. Shadow's capsule rules apply unchanged.
Capture at the Service boundary#
The Service recorder is a ServiceInterceptor. Installed at the SERVER_APPLICATION stage, it records the operation a runtime is serving. Installed at CLIENT_APPLICATION, it records each outgoing Service call as a CallRecord, and it passes the callee its parent span and call index through the propagated headers.
class ServiceRecorder(
private val plan: CapturePlan,
private val sink: RecordSink,
) : ServiceInterceptor {
override val stages = setOf(InterceptorStage.SERVER_APPLICATION)
override suspend fun <In : Request, Out : Response> intercept(chain: ServiceChain<In, Out>): Out {
val policy = plan.policyFor(chain.handler) ?: return chain.proceed()
val capture = Capture.open(chain.context, policy)
val result = runCatching { withContext(capture) { chain.proceed() } }
sink.offer(capture.close(result))
return result.getOrThrow()
}
}
Capture is a coroutine context element that holds the record under construction. Every wrapper further down finds the current capture through the coroutine context. Code that runs outside coroutines needs a second carrier. On JS, the Worker entry also binds the capture into AsyncLocalStorage, so JavaScript libraries and callbacks find it. On the JVM, a ThreadContextElement places it in a thread-local while a coroutine runs, so Java libraries and the JVM agent find it.
The recorder encodes values with the request and response serializers that RequestHandler already carries. The capture plan decides whether an operation is recorded at all, at which depth and under which redaction policy; Graph and Hangar describes how a plan is built.
Ports need two changes before calls inside one process can be recorded with their values. PortInterceptor has to receive the invocation's arguments and result, and it has to be able to return a substitute result. The inline port() call form also has to go through the chain, because today it skips the interceptors. Service records already cover every call between processes without these changes. Port records add the calls between graph nodes inside one process, which matters most on clients.
Capture in Cloudflare Workers#
A Worker runs in a V8 isolate, and nothing outside the isolate can see inside it. All capture therefore happens in the Worker's own code, at choke points we already own.
Entry. One wrapper surrounds every handler a Worker exports: fetch, scheduled, queue and the Durable Object callbacks. It binds a capture into AsyncLocalStorage, which the nodejs_als or nodejs_compat compatibility flag provides. It wraps env in a recording Proxy and runs the handler inside withEnv, so code that imports env from cloudflare:workers sees the same Proxy. Cloudflare does not document whether withEnv holds across await, so phase 1 tests it. The wrapper also notes the cf-ray id and the version id from the version metadata binding, and it hands over to Hono.mount, where the Service recorder takes over for typed operations.
Outgoing calls.
| Path | Choke point | What is recorded |
|---|---|---|
| Worker to Worker, and Worker to Durable Object | WorkerFetchEngine (BindingEngine and DurableObjectEngine) through HttpObservation | Method, route, allowed headers, body, status and answer body |
| HTTPS to the internet | The Ktor JS engine through HttpObservation | The same as above |
| Postgres through Hyperdrive | PostgresDatabase | Statement text with placeholders, bound values, returned rows and row count |
| ClickHouse and the graph gateway over VPC services | reaktor-cloudflare ClickHouse.kt and Graph.kt | Query, parameters and answer |
| Workers AI, Queues, R2, KV and D1 | Typed bindings in CloudflareContext | Operation, arguments, answer and metadata such as etags |
Anything reached through raw env | The recording Proxy over env | Property path, arguments and answer, counted as a raw path to fix |
Anything that calls fetch directly | A global fetch shim installed once per isolate | The full call, counted as a raw escape |
A sketch of the entry, as the TypeScript wrapper that the generated entry modules call:
import { withEnv } from "cloudflare:workers";
import { AsyncLocalStorage } from "node:async_hooks";
const scope = new AsyncLocalStorage<Capture>();
function within<T>(capture: Capture, env: Env, ctx: ExecutionContext, run: (env: Env) => Promise<T>): Promise<T> {
const recorded = recordingEnv(env, capture);
return scope
.run(capture, () => withEnv(recorded, () => run(recorded)))
.finally(() => ctx.waitUntil(capture.flush()));
}
export function recordedWorker(worker: ExportedHandler<Env>, plan: CapturePlan): ExportedHandler<Env> {
return {
fetch: (request, env, ctx) =>
within(plan.openFetch(request, ctx), env, ctx, async (recorded) => worker.fetch!(request, recorded, ctx)),
scheduled: (controller, env, ctx) =>
within(plan.openScheduled(controller, ctx), env, ctx, async (recorded) => worker.scheduled!(controller, recorded, ctx)),
queue: (batch, env, ctx) =>
within(plan.openBatch(batch, ctx), env, ctx, async (recorded) => worker.queue!(batch, recorded, ctx)),
};
}
function recordingEnv<T extends object>(target: T, capture: Capture, path = "env"): T {
return new Proxy(target, {
get(object, key) {
const value = Reflect.get(object, key);
if (typeof key !== "string") return value;
if (typeof value === "function") return capture.wrapCall(`${path}.${key}`, value.bind(object));
if (value !== null && typeof value === "object") return recordingEnv(value, capture, `${path}.${key}`);
capture.noteConfig(`${path}.${key}`);
return value;
},
});
}
Properties are read from the real binding object, and binding methods are bound to it before they are wrapped, because host objects check their own receiver and reject a Proxy as this. Results that are themselves bindings, such as a Durable Object stub, are wrapped in the same way. Configuration reads are recorded by name. A secret binding records that it was read and never its value. Reading a Hyperdrive configuration shows that the Worker reached for Postgres, and PostgresDatabase records the SQL itself. Hyperdrive keeps no query log, and automatic tracing gives Hyperdrive calls no span, so this wrapper is the only record of the SQL a Worker runs.
Clocks and randomness. One set of shims is installed at module load. Outside a capture scope they do nothing. Inside a scope they record the values returned by Date.now(), new Date() without arguments, performance.now(), Math.random(), crypto.getRandomValues() and crypto.randomUUID(). Kotlin's Random.Default needs separate handling. On Kotlin/JS it is a generator that seeds itself once from Math.random() and never calls Math.random() again, and its state carries over from one request to the next in the same isolate. Worker code therefore draws randomness through the entropy capability described in Clocks, randomness and ordering, and a lint rule rejects Random.Default in Worker modules.
State that outlives a request. An isolate serves many requests, and module-level values, such as a cached JWKS key set, survive between them. The record notes instanceOrdinal. Caches that can change a result are declared through a warm-state capability, so the values in force are recorded as WarmState reads and replay seeds them from the record.
Platform evidence. A Tail Worker receives every invocation's outcome, logs, exceptions, and CPU and wall time after the invocation ends, without adding to its latency. Code inside the isolate cannot measure its own CPU use, so the Tail event is where a record gets its CPU time. Tail events carry no bodies. The recorder publishes the capture id on a diagnostics_channel, and the Tail event delivers it in diagnosticsChannelEvents, which joins each event to its record exactly.
Cloudflare's automatic tracing is already enabled and exported to Grafana. It adds spans for subrequests, service binding and Durable Object calls, KV, R2, D1, Durable Object storage and queue sends. Hyperdrive and Workers AI calls get no span. Cloudflare starts its own trace at each incoming request and carries it across service binding and Durable Object calls. It does not yet continue an incoming traceparent, and Worker code cannot read Cloudflare's trace ids. The recorder therefore opens a custom span at each entry with the capture id and our trace id as attributes, which ties Cloudflare's trace to our records.
The ingest Worker also consumes the Tail stream, so it can raise capture to full depth for a route that starts failing. For a forensic investigation, Cloudflare can take CPU and heap profiles of a deployed Worker or Durable Object for up to 50 seconds.
Writing the record. The record is built in memory and flushed in ctx.waitUntil after the response is sent, so the flush adds no latency. Its CPU time still counts toward the invocation's CPU time. The flush sends the record to a capture queue. Payloads larger than a queue message, which holds at most 128 KB, go straight to R2 and travel in the record as references. Every cap that is hit increments the record's loss counters.
Capture in Durable Objects#
A Durable Object keeps state across events, so one event's record is not enough to replay it. The Durable Object recorder captures three things: the ordered events the object received, every storage operation it performed, and periodic snapshots of its storage.
Events. PartyServerDelegate already receives the connect, message, close and alarm callbacks, and the object's fetch and RPC entry receives the rest. Each event becomes an operation record with an object-local sequence number:
- A connect records the allowed headers, the connection id, its tags and its hibernation attachment.
- A message records its bytes and its connection.
- A close records its code and reason.
- An alarm records its scheduled time and its retry count.
- A wake from hibernation runs the constructor again, and the constructor's storage reads are recorded as an event of their own.
Interleaving. An object runs one event at a time until the event's code awaits something other than storage. At that point the input gate opens and another event can start. The recorder notes, for each event, the positions at which other events began. Replay holds each event back until its recorded position, which reproduces the same interleaving.
Storage. Every read and write goes through a recording wrapper: the existing DurableObjectStorage for key-value calls, and a new typed wrapper for storage.sql, which object code currently calls directly. Each call becomes a CallRecord of kind ObjectStorage with the statement, the bound values, the returned rows and the rows written. A Proxy over ctx.storage catches any remaining raw use. The write half of this log is a complete change history of the object, written by the object itself.
Snapshots. Each Durable Object class gets an export call that writes its SQLite tables and key-value pairs to R2, tagged with the current event sequence, and a matching import for replay. The recorder takes a snapshot the first time it records an object, when a capsule is pinned, and on a schedule while capture is on. The state before event N is the newest snapshot taken before N, with the logged writes after it applied. Cloudflare offers no storage export. Point-in-time recovery rolls an object back in place to a moment in the last 30 days, and it does not run in local development. The export call is therefore the only way to give a replay its starting state. Applying the logged events to a snapshot must reproduce the logged writes, which also checks the recorder.
Frames and other effects. The frames an object sends to each connection are recorded as effects, because they are what the clients saw. Calls to other Workers, to FCM and to anything else are recorded as they are in a Worker.
Capture for queues, crons and workflows#
- A queue send is a
Writecall in the producer's record. The recorder adds the producer's trace context and capture id to the message envelope, so the consumer's record links back to the send. - A consumer batch is the input of one record: message ids, timestamps, attempt counts and bodies. Each message's processing is a child record, and the outcome includes the ack or retry decision for each message.
- A cron run records its scheduled time and cron expression as its input.
- A workflow records each step's input and output. Cloudflare already stores step results so that a failed workflow resumes after the last finished step, and replay serves the recorded results in the same way.
- Replay either runs the producer or delivers its recorded message. Doing both would process the message twice.
Capture in JVM services#
JVM services on Kubernetes record at three levels: the Service boundary, typed wrappers around their dependency clients, and a JVM agent for everything the wrappers do not reach.
Inbound. Services served through SpringRouter get the Service recorder. Routes written directly as WebFlux router functions get a WebFilter that copies request and response bodies, up to a cap, into a record of the same shape.
Typed wrappers. These come first because they see values with their types:
- SQL through Exposed and the Hikari pool: Exposed's statement interceptor records the statement text and its arguments, and a thin wrapper around the pool's
DataSourcerecords returned rows and update counts. - Cypher: reaktor-db's
GraphDbrecords the query or named query, its parameters and the returned records. - Google, Apple and Pub/Sub calls: the users of the JDK
HttpClientin reaktor-google and reaktor-secrets, the JWKS retriever in reaktor-auth and the Google connector's transport each get a recording wrapper.
JVM agent. A Java agent covers the libraries we do not wrap and the reads that code makes outside the capability. It ships as an extension of the OpenTelemetry Java agent that is already attached. The extension is one JAR, loaded through OTEL_JAVAAGENT_EXTENSIONS. There is then one agent on the command line, one context-propagation mechanism and a single owner of JAVA_TOOL_OPTIONS. The agent loads at startup, so the JDK's warnings and planned limits for agents attached to a running JVM do not affect it.
The extension's instrumentation modules use the agent's ByteBuddy advice, which can read a method's arguments, return value and exception. They record payloads on JDBC statements and result sets, the neo4j driver, java.net.http.HttpClient and HttpURLConnection whenever a call did not already pass through a wrapper. The OpenTelemetry agent has no instrumentation for the neo4j driver, so today Bolt calls produce no spans at all. The modules also record calls to Instant.now() and UUID.randomUUID() that bypassed the capability and count each one as an escape. System.currentTimeMillis() and System.nanoTime() are native methods that advice cannot reach, so a lint rule covers them. The extension never records the output of SecureRandom. For every call it notes the local and remote address of the connection used, which the eBPF audit needs.
Runtime evidence. The server image runs JDK 25, which adds method timing and tracing to JDK Flight Recorder (JEP 520), experimental CPU-time sampling on Linux (JEP 509) and cooperative sampling (JEP 518). Shadow uses them in bounded windows: method tracing for the operations a capture plan selects, CPU-time samples while deep capture is on, and the usual GC, allocation and lock events. Method tracing records timing and stack traces. It does not record arguments or return values; only the agent's advice can capture those. Its overhead has no stated bound, which is another reason to keep the windows short. Recordings are stored as referenced artifacts together with their settings, so an absent event can be interpreted. In forensic mode, DebugProbes from kotlinx-coroutines-debug dumps every coroutine when an anomaly fires. It slows all coroutine code while installed, so it is installed only for the forensic window, with creation stack traces off.
Trust tiers. A process that holds production credentials never runs a replay or a Live Shadow workload. Replays run in separate processes or pods that hold dev credentials only.
Capture on the Kubernetes node with eBPF#
The node agent is a DaemonSet that loads eBPF programs into the host kernel. Its jobs, in order of value:
- Coverage audit. Every connection a pod opens and every byte it sends is attributed to the pod through its cgroup. The JVM agent notes which connection each recorded call used. The node agent explains a send when a recorded call used the same connection at that moment, and anything left over is a raw escape, reported with its process, stack and peer.
- Process and kernel evidence. Process start and exit, OOM kills, TCP retransmits and resets, DNS lookups, run-queue delay and CPU profiles. Code inside a process sees none of this.
- Plaintext protocols outside our code. Bolt to Memgraph, the ClickHouse HTTP interface, OTLP to the collector and the cloud metadata server are all plaintext inside the node. The agent can record these exchanges for processes we do not instrument, such as Memgraph and ClickHouse themselves, for diagnosis.
Replay never uses eBPF records as answers. In-process records are typed and complete for each operation, and socket bytes are neither. TLS also hides the payload of every external call the JVM makes, because the JVM encrypts in Java code and shares nothing with OpenSSL that a probe could read. The JVM agent records those calls. OpenTelemetry's eBPF instrumentation reaches Java TLS the same way, by loading a Java agent of its own into the process.
Programs.
| Hook | Purpose |
|---|---|
sched_process_exec and sched_process_exit tracepoints | Process lifetime per cgroup |
cgroup_mkdir and cgroup_release tracepoints | New and removed containers, for the map from cgroup to pod |
tcp_connect, inet_csk_accept and tcp_close through fentry and fexit | Connection lifetime and peers |
tcp_sendmsg and tcp_cleanup_rbuf through fentry | Bytes sent and received per connection |
Syscall tracepoints for write, writev, sendto, sendmsg, read, readv, recvfrom and recvmsg | Payload chunks for selected plaintext ports, including DNS on port 53 |
tcp_retransmit_skb and tcp_send_reset tracepoints | Network trouble |
oom/mark_victim tracepoint | Memory kills |
sched_wakeup and sched_switch tracepoints, sampled | Run-queue delay |
| Perf events on the CPU clock, through the OpenTelemetry eBPF profiler | CPU profiles with kernel, native and JVM stacks |
Uprobes on SSL_read, SSL_write and their _ex forms (optional) | Plaintext for processes that use OpenSSL |
The programs are compiled once with CO-RE against the kernel's BTF type information, so the same object file loads on later kernels without a rebuild. Ubuntu builds its kernels with BTF, and phase 5 starts by confirming that /sys/kernel/btf/vmlinux exists on the node. The node runs kernel 6.8, which supports every hook in the table. CPU profiles come from the OpenTelemetry eBPF profiler, which unwinds HotSpot JVM frames without frame pointers. It is still in Alpha, so it runs as its own process that can be switched off.
Payloads. A program copies at most a fixed chunk per call, 16 KiB to start, into a BPF ring buffer and marks longer payloads as truncated. A ring-buffer reservation never blocks. When one fails, the program adds one to its own loss counter and moves on, because the ring buffer keeps no count of failed reservations. The agent filters by cgroup inside the kernel, so only pods covered by a capture plan produce events.
Identity. Each event carries its cgroup id, which is the inode number of the container's cgroup directory. The agent walks /sys/fs/cgroup once at start and then follows the cgroup tracepoints. It maps each id to a container and pod through the path that k3s and containerd create for each container, and the cluster watcher supplies the pod's deployment revision and image digest.
Languages. The eBPF programs are written in C and loaded through libbpf. The userspace agent can be written in Kotlin/Native for linuxX64, with a cinterop binding to libbpf, so it shares the record model and the FlexBuffer encoding with the rest of Reaktor. If that binding proves awkward, Go with cilium/ebpf and Rust with Aya are the alternatives. All three libraries are maintained: libbpf 1.8.0 was released on 5 October 2026, cilium/ebpf 0.22.0 on 29 June 2026 and Aya 0.14.0 on 24 June 2026. Decisions to make lists this choice.
Existing agents. OpenTelemetry's eBPF instrumentation, known as OBI, turns kernel events into spans for HTTP, gRPC, Postgres and several other protocols. It records metadata and a few extracted fields, it has no Bolt support, and by default it skips processes that already run an OpenTelemetry SDK, which includes the JVM server. We write our own agent because its first job, the coverage audit, needs the connection data in our records. OBI's source remains a useful reference for chunked payload reads and TLS hooks.
Privileges and budget. The DaemonSet shares the host's process namespace and holds the CAP_BPF, CAP_PERFMON and CAP_SYS_PTRACE capabilities. Uprobes may also need CAP_SYS_ADMIN on this kernel, which phase 5 checks. The node is small and already busy. The agent gets a fixed CPU and memory limit, drops events before it would exceed them, and reports the drops. Payload copying is enabled only for selected ports and selected pods.
Capture from the Kubernetes control plane#
A small cluster watcher records the environment that each operation ran in:
- For pods, ReplicaSets and Deployments: image digest, restart count, last termination reason such as
OOMKilled, probe failures, resource requests and limits, and the names and versions of mounted ConfigMaps and Secrets. Their contents are never recorded. - Kubernetes events and node conditions.
- API audit at the metadata level for writes. k3s enables it through
kube-apiserver-argentries in its configuration file, which name an audit policy and a log path. Without a policy file the API server writes no audit events. The node agent ships the log.
The watcher writes these as their own records, keyed by pod UID and container id. The node agent maps cgroups to containers, and the JVM agent writes its process id and pod name into each record's origin.instance. An operation therefore joins to its pod, its image and any restart or kill around it.
Kubernetes also gives replay its sandbox. Each replay run gets its own namespace, a default-deny egress NetworkPolicy that allows only cluster DNS and the replay runner, no production Secrets and a resource quota. k3s enforces NetworkPolicy with the kube-router policy controller it embeds.
Forensic tools. Two Kubernetes features help a single investigation. An ephemeral debug container that shares the pod's process namespace can run jcmd against the JVM to start a flight recording or take a heap dump without restarting the pod. The kubelet can also checkpoint a running container through CRIU and leave it running. The feature is in beta and enabled by default, and k3s ships a containerd that implements it, though k3s does not document it and CRIU has to be installed on the node first. A checkpoint holds the process's entire memory, including every secret it has loaded, so it gets the strictest access class. Restoring a JVM that held open sockets is unreliable, so a checkpoint is something to inspect, and replays always come from records.
Capture on phones, web and desktop#
Clients write the same operation records in the client phase, plus the things only a client knows.
- Service calls. The Service recorder at
CLIENT_APPLICATIONrecords every call to a backend operation with the answer the client received. The server's record of the same call carries the same span id, so both sides of each call can be compared. - HTTP and sockets.
HttpObservationandSocketObservationget a production mode that keeps bodies and frames within the capture plan's limits. Frames the server pushes are inputs to the client and are recorded in order for each socket session. - User input. Surface components are kernels with a pure
reduce(properties, state, input)step. Recording each kernel instance's inputs in order, with the reductions they produced, gives a complete record of the interaction. Replay feeds the same inputs to the same kernels and compares the reductions. This reproduces behavior at the level of interactions; screenshots remain the check for pixels. - Local state. A snapshot of the local database when a recorded session starts, a log of local database writes through reaktor-db, and the pending entries of
WorkJournal. - Lifecycle. Foreground and background changes, connectivity changes, push receipt and permission changes.
- Platform evidence. Crashlytics on Android and iOS, Android's process exit reasons from
ApplicationExitInfo, iOS MetricKit diagnostics and browser performance entries. Each links to the recorded session id. - Native calls. Deep mode would record calls at the admitted Service endpoint or shared exchange engine described in the unified FFI/RPC design. That integration is proposed work; the current
InteropRuntimesupplies synchronous JSON interop and does not establish universal capture coverage.
Clients keep records in a bounded on-device journal, built like FactStream with drop counts, and upload them while the app is in the foreground on an unmetered network. Tester and dev builds record by default. Recording real users needs the consent and scope decision listed in Decisions to make.
Capture for data stores#
Recorded replay needs no database state, because every answer comes from the record. State matters in two other cases: checking a candidate's writes against real data, and the Live Shadow profile, which runs against isolated copies of real stores.
| Store | What the layer adds |
|---|---|
| Postgres | Each write transaction calls pg_logical_emit_message with its capture id. Logical decoding delivers that message in commit order next to the transaction's changes, so the change history between restore points names the record behind each change. Decoding needs a direct connection, because poolers do not carry replication, and max_slot_wal_keep_size caps the WAL its slot can hold back. |
| Memgraph | Memgraph has no change stream, so the write queries that GraphDb records are the change history. The existing snapshots and write-ahead log give restore points. |
| ClickHouse | The existing backup to R2 gives restore points, and inserts are recorded as writes. |
| Durable Objects | Snapshots and the storage log described above. |
| R2 | The etag of every object read is recorded, so a replay can tell whether an object has changed since. |
| D1 and KV | D1 Time Travel gives restore points, and KV reads and writes are recorded as calls. |
Copies built for Live Shadow use the same field classification as capture, so a copy never holds what a record may not. Shadow's isolation rules apply.
Joining the evidence#
One user action produces records on several runtimes and evidence from several collectors. These keys join them:
| Key | Produced by | What it joins |
|---|---|---|
| Trace id and span id | TracePropagation on every tier | Records with each other, with service_spans and with OpenTelemetry spans |
| Parent span and call index | The Service recorder | A callee's record with the exact call in its caller's record |
| Capture id on a custom span and a diagnostics channel | The Worker recorder | Worker records with Cloudflare's traces and Tail events |
cf-ray | Cloudflare | Worker records with edge request logs |
| Version id, image digest and app build | The version metadata binding, the cluster watcher, the build | Records with the artifact that ran |
| Object id and event sequence | The Durable Object recorder | One object's events, storage log and snapshots |
| Message id | Queues | A producer's send with the consumer's processing |
| Pod UID, container id, cgroup id and process id | The cluster watcher, the node agent and the JVM agent | JVM records with kernel and pod evidence |
| Session id | The client recorder | Device records with crash reports |
OpenTelemetry is the correlation layer. It carries traceparent, tracestate and baggage between runtimes. Reaktor propagates traceparent itself on every tier, so records join across runtimes even where a platform keeps its own trace ids. Spans carry reaktor.capture.id and the keep decision as attributes, so a trace viewer can open the matching record. Attribute names inside records follow OpenTelemetry semantic conventions where one exists. Values are kept in records. Spans are a poor home for them, because spans are sampled, limited in size and dropped under pressure, while a replay needs every value. Observability owns the rules for attribution.
Clocks, randomness and ordering#
One capability. Reaktor gains a clock and entropy capability in core, provided through the graph like any other capability. It supplies wall-clock time, monotonic time, random numbers, UUIDs and secret bytes. During capture it records each value it hands out, except secret bytes. During replay it returns the recorded values in order. Reaktor and BestBuds read Clock.System directly in about 170 places, and BestBuds draws random values or UUIDs in about 50 more, so moving to the capability is real work. The runtime shims stay as a safety net, and any read that bypasses the capability and reaches a shim counts as an escape.
Secrets. Token bytes, keys and nonces come from the secret source. The record notes that one was drawn and where. Replay draws a fresh value, and the comparison treats it, and anything derived from it such as a signed token, as opaque.
Ordering. Each operation's counter advances when a call is issued and when an answer arrives. Replay delivers each answer at its recorded position. On JS this means resolving the substituted promises in the recorded order. On the JVM the replay runs the operation on a coroutine dispatcher that resumes continuations in the recorded order. Durable Objects also replay the interleaving of their events, as described above.
What each runtime gives for free. In a Worker, Date.now() only moves forward when I/O happens, and one isolate runs one piece of code at a time, so the boundary between computation and I/O is clean. A Durable Object runs one event at a time until it awaits non-storage I/O. Surface kernels are pure functions of their inputs. The JVM gives nothing for free: threads, pools and timers all run concurrently, so determinism there comes only from the capability and the dispatcher.
What stays out of reach. Some differences remain: Cloudflare's own scheduling across isolates, interleaving between threads inside Java libraries that run outside coroutines, behavior changes in third-party services, and timing. Every replay reports how faithful it was, as matching and ordering describes, and claims no more determinism than its controls provide.
Pipeline, storage and retention#
recorder ── bounded buffer ──▶ capture queue or HTTPS ──▶ ingest Worker
├─▶ R2: one object per batch, grouped by hour
├─▶ ClickHouse: capture_records index
└─▶ keeper: keep, extend or let expire
Ingest. One ingest Worker receives every record. Workers send through a Queue. The JVM, the node agent and clients send over HTTPS with service credentials. The ingest Worker checks the record schema and the policy version, removes any field the policy forbids, assigns a retention class and writes the record.
Layout. The ingest Worker writes records in batches, and each batch becomes one R2 object under its hour, which keeps the number of write operations low. R2 cannot append to an object and accepts about one write per second to the same key, so a batch object is never rewritten. Large payloads are separate objects named by checksum. The ClickHouse index holds one row per record: trace and span ids, parent, operation, island, build, outcome, duration, sizes, coverage counters, principal hash, retention class, and the batch object and byte range that hold the record. ClickHouse already holds service_spans, so a query can move from a span to its record.
Retention. Batch objects land under a hot prefix that an R2 lifecycle rule expires after a few days. The keeper waits until a trace has had no new records for a set time. It then keeps the whole trace when any record in it failed, ran slow, came from a flagged session or falls in the sampled share, and it copies that trace's records into one object under the kept prefix. Pinned capsules stay until they are retired under the textbook's rules. Forensic artifacts, such as JFR recordings and profiles, have their own limits.
Deletion. Account deletion also deletes records by principal hash. A suppression list stops a deleted person's data from returning through an old capsule or snapshot.
Cost. Storage grows with records per second, average record size and retention. R2 write charges grow with the number of batch objects. Phase 1 measures both and sets the budgets.
Replay#
The replay contract#
A replay request names four things:
- the selection: a record, a trace, a capsule or a query over the index;
- the build: an exact artifact, such as a Worker bundle by version id, an image by digest or a client build;
- the profile, from the table below;
- the comparator and normalization version.
The result is one of passed, diverged, missed (the build made an unrecorded call), assertion failed, capture incomplete or harness failed. It comes with a structured diff and with the coverage of the records used. The same request runs from the command line, from Hangar and from agents through the reaktor kernel.
Matching and ordering#
The tape indexes recorded calls by parent span and call index. When the build makes a call, the replay adapter finds the operation being replayed, takes the call at the next index, checks its kind and target, compares the request with the recorded request under the declared normalization, and returns the recorded answer at its recorded position.
class Tape(private val records: Map<String, OperationRecord>) {
fun next(replay: ReplayCapture, kind: CallKind, target: String, request: Payload): CallRecord {
val recorded = records[replay.recordedSpanId]?.calls?.getOrNull(replay.nextCallIndex())
?: throw ReplayMiss(replay.recordedSpanId, kind, target)
if (recorded.kind != kind || recorded.target != target) throw ReplayDivergence(recorded, kind, target)
replay.compare(recorded.request, request)
return recorded
}
}
A replayed operation gets new span ids, so the replay capture carries the span id of the record it is replaying. A Service call made during replay finds the callee's record through childSpanId.
A divergence report names the operation, the call index, what the build asked for, what the record holds, and the coverage of the record. Replay stops the operation at the first difference, because every later call depends on it.
Harnesses#
- Workers and Durable Objects. The replay runner loads the exact bundle into local workerd through
@cloudflare/vitest-pluginand switches the recorder's wrappers into answer mode. Miniflare'soutboundServicepoints at the tape, so anyfetch()orconnect()that goes around the wrappers gets a recorded answer or fails. The runner drives the recorded entry with the plugin's helpers: a request throughfetch, a queue batch throughcreateMessageBatch, a cron tick throughcreateScheduledController, and a Durable Object event sequence throughrunInDurableObjectafter importing the object's snapshot and applying its logged writes. Durable Object events are delivered by calling the object's handlers with stand-in WebSockets, which also avoids the plugin's limits on WebSockets under isolated storage. Breakpoints, CPU profiles and heap snapshots work in this local runtime through the V8 inspector. - JVM services. The runner starts the image by digest in a replay namespace, with egress denied and dev credentials only, and with the JVM agent and the Service recorder in answer mode. It then sends the recorded requests. For a single operation, a test can instead build the Spring context in-process with the same adapters.
- Clients. A recorded backend sits next to
MockWorldand answers Service calls and socket frames from the record. Surface input streams are replayed into kernels directly. For full journeys, Hangar flows and Maestro drive the app against the recorded backend. - Whole traces. The runner starts every island a trace touched, with several Workers in one workerd process plus the JVM service, and answers only the calls that leave the system, such as Postgres, Memgraph, FCM, Workers AI and Google. Calls between islands run for real, and each island's records are compared at every hop.
Profiles#
| Profile | What runs for real | Use |
|---|---|---|
| Recorded | Only the build under test | Fast regression checks on every change |
| Whole trace | Every island in the trace | Changes that cross services, such as a contract change |
| Differential | A baseline build and a candidate build on the same records | Showing exactly what a change alters |
| Live Shadow | The build plus isolated copies of real stores | Production-shaped runs |
| Forensic | One record under a debugger or profiler | Investigating one failure in depth |
Comparing results#
Each operation declares its comparator and normalization in the capture plan: exact, the same shape with stable fields, the same effects, or statistical for timings. Normalization may remove only the fields that are declared nondeterministic. It never hides ordering, authorization or duplicate effects. Re-recording an operation is a separate, reviewed action with its own receipt, so a candidate can never rewrite the record it is judged against.
Running candidates inside Cloudflare#
Two Cloudflare features could let some checks run where production runs.
The Cloudflare-Workers-Version-Overrides header sends a request to a chosen version, which allows a read-only operation to be compared across two versions with real data. The header only works for a version that is part of the current deployment, which holds at most two versions during a gradual rollout. When the named version is not part of that deployment, the request silently follows the normal traffic split. The header also does not apply to RPC calls over service bindings. Each record holds the version id that actually served it, so a comparison checks that id before it trusts the result.
Dynamic Workers, in open beta since March 2026, let a Worker load code at runtime through a worker_loaders binding. The loading Worker chooses the loaded code's env, which can hold stub bindings that answer from a tape. It also chooses globalOutbound, which can be null so that every fetch() and connect() fails. A production Worker could therefore run a candidate build against recorded answers without deploying it. Hyperdrive, Workers AI, Durable Object and Queue bindings would each need a stub, and Durable Object facets would give a candidate object its own SQLite storage.
Both features apply only to read-only operations with every write denied, and both need qualification before Shadow relies on them.
Privacy, security and authority#
Shadow's privacy rules apply. This layer adds the following.
- Classification. Fields of
@Serializabletypes carry classification annotations, such as personal, secret and user content. The annotations appear in the serial descriptor, so the recorder redacts per field: it drops the value, replaces it with a keyed hash that keeps equality, or keeps it. In production, a string field without a classification is dropped. - Headers and tokens. Only allowed headers are kept. Authorization headers, cookies, refresh tokens, push tokens and device keys are never stored, and stable placeholders take their place.
- Secrets. Secret entropy is never recorded, and secret configuration is recorded by name only.
- Platform traces. Cloudflare's automatic tracing puts SQL text, Durable Object bind values, KV and R2 keys and full URLs into span attributes, and those spans reach Grafana. The trace export therefore falls under the same classification rules as records, and its destinations and retention need the same review.
- At rest. Records are encrypted at rest. The most sensitive classes are also encrypted with a key that only the replay runner's authority can use.
- Access. Reading a record, pinning a capsule and running a replay are kernel operations with seats, approvals and receipts, like every other Hangar operation.
- Retention and deletion. As described in Pipeline, storage and retention.
- Untrusted content. Recorded content is data. It is shown to people and agents as data, and it can never grant authority or change an acceptance rule.
Overhead and loss#
The capture plan chooses one of four depths per operation:
| Depth | Content | When |
|---|---|---|
| Metadata | Spans, Tail events, pod and kernel events | Always |
| Sampled | Full records | A sampled share of traces |
| Escalated | Full records with larger payload limits | Errors, slow operations, flagged sessions and routes the Tail stream marks as failing |
| Forensic | Escalated content plus JFR, profiles, coroutine dumps and socket payloads | One investigation at a time |
The decision to record a trace is computed from its trace id, so every runtime records the same traces. An escalation flag travels in tracestate, so downstream hops follow an upstream decision.
Budgets are set by measurement in phase 1 and enforced by each recorder: Worker CPU time per request, JVM latency at the 95th percentile, node agent CPU and memory, and device battery and data use. A recorder that would exceed its budget drops content and counts what it dropped.
Every record and every session reports what was captured and what was lost. A replay built from an incomplete record can still help an investigation, but it cannot pass a verification.
Graph and Hangar#
- Selecting. A capture plan comes from a graph visitor, in the same way as today's port instrumentation plan. It selects operations, depth, sampling, redaction policy and comparator per Service or port. It installs through graph attachments and can be removed with a receipt.
- Attributing. Each record names its island and, through its operation descriptor, its Service node, so Hangar can place it on the graph. The island shape's version says which graph the record belongs to.
- Substituting. Reaktor already lets the graph choose a mock or a remote implementation for each Service. Replay adds a third choice, the recorded implementation, which answers from a tape.
- Showing. Hangar's Graph pane overlays coverage: which operations have recent records, which calls escaped capture and which replays failed. A trace view opens the records of one user action, and a replay view runs a selection and shows the diff. All of these are kernel operations, so agents can run them through the MCP door.
Build plan#
The phases are ordered by value, and each ends with a demonstrated result.
1. Record format and one Worker route
- Already done: the Service interceptor chain, operation descriptors, trace propagation,
service_spans, and the HTTP and socket observers. - To build:
OperationRecordand theCapturecontext element in reaktor-service; field classification and redaction; the Service recorder; outgoing wrappers inWorkerFetchEngineandPostgresDatabase; the ingest Worker writing to a dev R2 bucket and to ClickHouse; the workerd replay runner with outbound calls blocked. - Done means: one route recorded from dev traffic replays green on its own build, a planted regression fails with a readable diff, and a missing record fails the replay without reaching a dependency.
2. Every Worker entry, Durable Objects, queues and crons
- To build: the entry wrapper for every handler type, the
envProxy and thefetchshim, the clock and entropy shims and capability, warm-state capture, the Durable Object event log, storage wrapper and export and import calls, queue envelopes and batch records, and the Tail Worker join. - Done means: a chat message sent from one client replays through the Worker, the queue consumer and the chat room object, including the frames the other clients received.
3. JVM services
- To build: the WebFlux filter, the SQL and Cypher wrappers, the HTTP client wrappers, the agent as an OpenTelemetry extension, JFR windows, and the JVM replay runner in a replay namespace.
- Done means: an auth flow and a graph-gateway query replay against the image digest that served them, with egress denied.
4. Clients
- To build: production modes for the HTTP and socket observers in tester builds, the Surface input journal, the local-state snapshot, the recorded backend next to
MockWorld, and upload and consent controls. - Done means: a tester's recorded session reproduces in Hangar flows.
5. Node agent and cluster watcher
- To build: the eBPF programs, the userspace agent, the mapping from cgroup to pod, the coverage audit, the CPU profiler, the cluster watcher and API audit.
- Done means: a deliberately unwrapped HTTP call from the JVM appears as a raw escape attributed to its pod and process.
6. Whole traces, differential replay, retention and Hangar
- To build: replay across several islands, baseline-against-candidate runs, the keeper, deletion by principal, and the Hangar coverage, trace and replay views.
- Done means: a contract change between two Workers shows its effect at every hop of a recorded trace.
7. State for Live Shadow
- To build: masked copies of the stores, Postgres change history, scheduled Durable Object snapshots and the workspace lifecycle.
- Done means: the send, retry, reconnect case runs live against masked copies and its capsule reproduces.
Clean-up during phase 1
- Remove the Keploy scripts, their package scripts and their entries in the operational catalog.
Decisions to make#
- The language of the node agent's userspace half: Kotlin/Native with libbpf, Go with cilium/ebpf, or Rust with Aya.
- Whether and how real users' sessions are recorded: consent, scope and retention.
- The long-term structured store: ClickHouse alone, or Cloudflare's Basin Pipelines writing history tables into R2.
- How to move clock and entropy reads to the capability: all at once, or module by module behind the shims.
- The Durable Object snapshot schedule, weighed against its storage cost.
- Whether candidate builds may run inside Cloudflare against recorded answers.
- Whether to install CRIU on the node so that containers can be checkpointed for forensics.