Token LabSearch

Agent infrastructure for software engineers: build a recoverable SRE diagnostic assistant

At 02:14 an on-call engineer asks why checkout latency doubled after a release. Their browser disconnects, a worker restarts, and an incident lead takes over. The useful deliverable is one diagnostic draft, with citations that still resolve and a record of who authorized each action. Follow this incident through nine engineering disciplines, then use the acceptance lab at the end to judge an implementation.

Sources & version details
In this article

Agent infrastructure is the software that translates model proposals into bounded, authorized, observable work. OpenAI's public Codex Core Agents role names the execution loop, tool interfaces, reliability, latency, capacity and cost. Anthropic lists an Agent Runtime Platform team. These examples motivate the curriculum. The wider sample of nearly twenty employers is the contributor's observation; there is no independently verified frequency ranking here.

You will need HTTP request semantics, SQL transactions and basic Linux processes. HTTP matters because clients may retry after losing a response. A transaction defines which local writes survive together. A process can disappear with its heap while committed rows remain. These three facts explain why a reliable assistant needs an identity, durable state and an explicit boundary around external effects. The reference design uses synthetic logs and a deterministic model; production performance and provider behavior require separate measurement.

Reference architecture for an SRE diagnostic assistant
Reference architecture for an SRE diagnostic assistant · Open the full-size diagram

1. The execution loop and the tool contract

Give the assistant two read tools, one for deployment history and one for logs. A model might propose reading fifty checkout records covering the previous ten minutes. The runtime resolves the registered tool, validates types and ranges, resolves the requesting tenant, checks the resource permission, sets a deadline and records the call identifier. Only then does the adapter perform the read. The next model turn receives the result labeled with that identifier. The loop ends with a draft, an explicit missing-evidence result, cancellation or an exhausted budget.

An empty successful search establishes that no records matched a specified snapshot and filter. A timeout establishes that the query outcome is unknown. Return distinct result types or a plausible-sounding diagnosis may silently turn an outage in logging into evidence that checkout produced no errors. Preserve the snapshot and line range in every citation. A release at line 18 and connection-pool waits at lines 81–96 establish temporal association; pool saturation as the root cause still requires occupancy data or a comparable unaffected instance.

Bound steps, total tokens, output bytes, tool time and wall time independently. Charge failed attempts against the appropriate budgets. A schema bounds a single call's arguments; it cannot stop a model from requesting the same valid page forever. Persist the stop reason so another engineer can distinguish missing evidence from an exhausted budget.

2. An asynchronous Run API with resumable progress

A Run is the durable identity of one submitted investigation. In one transaction, create the Run, enqueue its first task and append the accepted event. Return HTTP 202 and the identifier after commit. Bind a submission key to tenant and request digest. A retry with matching content retrieves the same Run; conflicting content using that key yields a conflict. Otherwise a client that lost the first response can unknowingly launch a second investigation.

Keep the status snapshot and ordered events complementary. The snapshot answers what is true now. Events describe transitions for a viewer who was absent. If the last displayed event was 41, accept the SSE reconnect cursor, return later events in order and deduplicate by Run and sequence. Assign sequence numbers within the same serialization boundary as the transition. Close the gap between replay and live delivery with a durable tail or subscribe-and-catch-up strategy. Expired history requires a fresh authorized snapshot and its watermark.

Queued work can be cancelled immediately. A running worker observes a durable cancellation request at safe points. Serialize success and cancellation so the winning terminal transition is explainable. Cancelling future work does not erase a notification already delivered. Preserve its receipt separately.

3. Durable execution and side-effect identity

Suppose the worker commits its draft and crashes before acknowledging delivery. The queue reasonably delivers the task again. Give the logical draft a stable identity such as tenant, Run, step and draft version. A uniqueness constraint on those fields survives retries across workers. A random identifier generated on each attempt identifies attempts, not the effect being deduplicated.

Commit the draft, checkpoint and result event together. On redelivery read the recorded outcome before repeating work. A useful checkpoint includes the immutable input snapshot, evidence references, completed step, remaining budget and next action. A conversational summary can help the model resume reading, but cannot prove which business effect committed.

For an external incident tracker, record the outbound intent in the same transaction as the local transition. A separate dispatcher delivers it. If the remote service applied the write and its acknowledgement was lost, the dispatcher sees the same timeout as if delivery never happened. Reuse a stable provider-supported idempotency key within its documented scope and lifetime. When that guarantee is unavailable, reconcile against the provider's authoritative ledger or expose an unknown outcome for human resolution.

4. Dispatch, failover and bounded capacity

Claim a task and assign its owner, lease deadline and monotonically increasing ownership epoch in a short transaction. PostgreSQL queue consumers can use SKIP LOCKED to avoid waiting on rows being claimed by other consumers. Release the transaction before running inference. Heartbeats renew a valid lease; they cannot prove a paused former owner will never resume.

Suppose A holds epoch 7, stalls and resumes after B acquires epoch 8. The database must check the epoch on the write itself. Also compare the case revision read by the worker. Even the current owner can produce a stale draft if a different authorized update changes the case while inference runs. A conditional update affecting zero rows discards the draft. Insert the draft only inside the same successful transaction. This check protects participating storage; it cannot fence a remote tool that ignores the token.

Two workers with four slots each and twenty seconds of average slot occupancy offer an idealized 24 Runs per minute. A shared dependency allowing twelve calls per minute, with two calls per Run, caps throughput at six. State whether every limiter is per process, per tenant or global. Under overload retain bounded queues, give retries a budget and use backoff with jitter. Adding workers against a saturated global dependency can spend more without completing more work.

5. Tenant identity, permission and audit

Bind the authenticated principal and tenant at submission. Recheck access when reading status, replaying events, resolving evidence and invoking tools. Read permission for one checkout environment conveys no permission to inspect a different tenant's identically named service. Service-side resource lookup should derive the scope from authoritative identity records. Never treat model-supplied identity fields as grants.

A log line requesting that a report be forwarded elsewhere is evidence text. The gateway still checks the actual actor, operation, resource, parameters and current policy. Give a worker short-lived credentials scoped to the granted operation. Keep provider secrets outside model context and general-purpose diagnostic logs.

For a write, bind approval to an operation digest and revision, approver, resource and expiry. Approval to save draft v3 does not authorize broadcasting v4. Record both the decision and execution result under the Run. If approval can be revoked between scheduling and dispatch, specify where the last effective revocation check occurs and what happens after the external service accepts the action.

6. Sandbox lifecycle and isolation

For this assistant a trusted parser reads a fixed log snapshot and writes a small temporary summary. Give it a read-only input mount, bounded scratch space and no inherited application credentials. A filesystem namespace controls its view; a read-only mount controls modification. Resource limits on memory, CPU and process count contain resource consumption. A seccomp profile restricts allowed system calls. Network policy constrains destinations. These controls cover different failure modes and must be verified independently.

Tie the sandbox to one task attempt, apply the deadline outside the guest and cap output before returning it to the model. On timeout terminate descendants, reclaim mounts and scratch space, and record the cleanup result. Arrange periodic reclamation for a host-side supervisor crash. A container shares its host kernel; workloads containing less trusted code may justify a different runtime, at a cost in startup time, complexity and density. Document which workload your isolation argument covers.

7. Observability and operational diagnosis

A sixty-second wait could contain fifty seconds in the queue, multiple intervals backing off a model rate limit, or a stalled log read. Instrument submission, enqueue, claim, model turn, tool execution, retry delay and terminal commit separately. Carry the trace context through the queue message. Separate attempts retain their own identifiers and can use span links where appropriate. The Run identifier joins the investigation across attempts; a span records a bounded interval in one execution.

Keep high-cardinality Run IDs in logs and traces. Aggregate metrics by bounded dimensions such as stage and outcome. Report queue and execution p95 separately. Their sum does not generally equal end-to-end p95 because different Runs can occupy each tail. Publish the sample size, interval, error categories and definition of recovery time.

For a settled submission cohort, divide all attributable model, tool and compute spend, including unsuccessful attempts, by successful Runs. If ten investigations cost six dollars in total and eight succeed, the illustrative cost is 75 cents per success. If none succeeds, report zero successes and total spend; the ratio is undefined. A fake model can validate accounting, whereas a real invoice requires actual provider usage and rates.

8. Offline evaluation and regression

Separate runtime invariants from diagnostic quality. A JSON-valid answer can arrive on time and attribute the incident to the wrong release. Give each of twenty synthetic incidents an immutable log snapshot, an expected cause or indeterminate label, required evidence, permissible operations and forbidden effects. Include cases where the correct decision is to ask for another measurement.

Split incident families before tuning. Ten development incidents and ten frozen comparison cases form a deliberately small learning set. Changing a host name does not make a genuinely independent variant. Keep budgets, fixtures, tool behavior and scoring rules fixed across versions. Score evidence support independently of cause accuracy; a lucky correct guess has different operational value from a diagnosis another engineer can reproduce.

Use deterministic model transcripts for tool-error and recovery regression. Measure live-model variation in a distinct evaluation, recording configuration and repetitions. A change from seven to eight successes in ten examples merits inspection of changed cases. It cannot establish population-wide reliability. Predeclare release gates, especially unacceptable cross-tenant reads and unsupported production actions.

9. Delivery, upgrades and design communication

The control plane owns identity, API contracts, policy and Run status. The execution plane consumes durable work, invokes bounded tools and proposes conditional state transitions. Start a local API, two independently killable workers and shared PostgreSQL with one documented command. Define readiness against required migrations and storage access. Commit dependency versions, sample configuration and a seed dataset. An engineer beginning with an empty environment should be able to recover the same incident.

An image rollback cannot repair an incompatible checkpoint. Introduce readers compatible with both formats before enabling new writers, or route old Runs to workers that can drain their contract version. Apply the same reasoning to tool schemas and event consumers. Specify deadlines for draining, how to reclaim interrupted leases, and how an operator identifies stranded Runs. Capacity planning should identify whether backlog rises because of worker saturation, database contention or an external quota; the appropriate scaling action differs in each case.

Practice and verification

These are acceptance criteria for the reader's implementation. Record measurements from your environment; the worked capacity and cost figures above are synthetic.

Capability Action Required evidence
Loop Return invalid parameters, a timeout and repeated identical calls No invalid invocation, distinct timeout status, budget stop, exact evidence references
Run API Retry submission, disconnect after event 41 and request cancellation One Run, ordered continuation, duplicate suppression, explained terminal race
Persistence Stop a worker after draft commit and before acknowledgement One durable draft, named unique constraint, separate handling of unknown external delivery
Scheduling Pause A until B takes over, then resume A Stale write affects zero rows; waiting time, peak concurrency, retries, recovery interval and limiter scope
Identity Request tenant B's logs as A; approve and reject separate writes Denied read, scope-bound approved action, complete audit correlation
Sandbox Run the trusted parser, enforce a timeout and inspect cleanup Authorized read-only input, no injected credentials, denied test egress, bounded resources, reclaimed descendants
Operations Inject queue delay, tool timeout and simulated model throttling separately Stage attribution from one Run ID, queue/execution p95, completion rate, recovery time, cost per success
Evaluation Compare two revisions on ten frozen cases Paired cause, citations, abstention, latency, spend, regression cause and release decision
Delivery Start the local stack, upgrade with a Run in flight, then roll back Reproducible startup, compatible recovery, measured bottleneck, explicit expansion condition

Three original interview exercises follow. They are teaching questions, without employer attribution.

  1. A restarted worker writes a second draft. Where should the invariant live? First hint: compare the lifetime of a process-local set with that of a queue message. Second hint: define what one draft means across attempts. Answer: use a durable scoped unique key, atomically commit the draft and checkpoint, then acknowledge. Show the duplicate delivery and database row count. A local set alone disappears on restart.
  2. A lease expires while the remote incident tracker is processing a write. Can the next worker retry safely? First hint: who enforces the epoch? Second hint: distinguish receiving from acknowledging. Answer: the database can reject an old local writer. The external service must enforce its own operation identity or provide an authoritative reconciliation path. Otherwise preserve the unknown result and escalate according to business impact.
  3. Adding a worker doubled attempts but completed no extra Runs. What would you inspect? First hint: distinguish queue wait from active execution. Second hint: identify shared quotas and backoff. Answer: match trace intervals to dependency throttling, compare attempted calls per completion, and measure the global limit. Hold the cohort and workload fixed while changing only concurrency. Roll back if increased spend buys no additional successful throughput.

Score each response on five cumulative points: one for naming the failure, two for identifying the responsible component, three for explaining its mechanism, four for showing reproducible evidence and five for explaining a boundary or counterexample. A convincing portfolio demonstration pauses A, lets B complete, resumes A to show a rejected write, then opens the sole draft and follows its citation to the original lines.

Download the local reference project

Unzip the project and run the commands below in its directory. The standard-library test checks twenty synthetic cases with line-level evidence, split evenly between development and comparison. Compose adds an API, two workers and a PostgreSQL queue. The HTTP test targets that running stack. The worker uses a fixed diagnostic rule. Production identity, a separate per-run sandbox, approvals and telemetry export remain implementation exercises. The Compose stack was not executed during this publication.

Download the local reference project (.zip)

python3 -m unittest -v test_local
docker compose up --build -d
python3 test_live.py

A browser-local simulation with synthetic logs. Read the trace in order, then identify the write rejected after handoff.

Predict, test and keep evidence

Before revealing an answer, predict one result. After the exercise, record the discrepancy and a transfer test. Saved locally across language editions.

Open notebook / export / clear →

The mathematical review scope is recorded per lesson. It does not establish empirical paper reproduction; report suspected errors in your notes. Review scope

Primary sources and specifications