Token LabSearch

Anthropic · Agent architecture

Building always-on agents: who keeps the promise after the model stops?

How an event-driven agent survives between model calls. Follow one delayed parcel through context assembly, lease handoff, guarded commits and uncertain delivery. Reproduce the failure windows locally.

Sources & version details
In this article

What keeps a promise after inference ends?

At 09:00 a carrier reports a delay on parcel P42. A support representative asks the assistant to check again in fifteen minutes and prepare a refund proposal if there is still no delivery estimate. Generating the sentence “I’ll check again” takes one model call. At 09:15 the process that produced the sentence might be gone. To keep the promise, another process must discover the deadline, identify the parcel, find out whether the promise still applies, and know which actions the representative authorized.

Start inside a single call. Given an input sequence and the tokens generated so far, a language model computes a distribution over the next token. Repeating that computation may produce a structured request to look up P42. Emitting a tool request changes no order record. Application code parses it, validates its arguments and scope, calls the carrier, and places the result in a subsequent model input. That is the inner loop. A call can finish after a useful draft, a request for clarification or a step limit. Its token history contains neither a running clock nor an enforceable obligation to wake up later.

The outer loop persists obligations, chooses when to start a run and commits its result. An event is a recorded input. A run is one bounded attempt at processing work. A session is the conversation and tool history from which some of a future input can be reconstructed. The case is the business record that owns the open obligation. It survives even if a session is compacted or the service switches models. On restart the runtime assembles a new input from current instructions, case state, relevant dialogue and observations. A stochastic proposal can differ on a retry. The application must still enforce the same rules for what may be committed.

Candidate design Where it works What happens to P42?
Scheduled rule Every qualifying event has a predetermined consequence A database job can recheck the parcel; no model is needed to compare a status code
One long-running chat with a sleep call A disposable demonstration with one user and a short lifetime A process restart discards an in-memory timer; retaining the transcript alone does not arrange another invocation
Durable workflow with bounded model runs Timing and authorization are explicit, but interpreting an exception requires judgment Software wakes the case; the model interprets conflicting carrier notes; a guarded commit accepts or rejects its proposal

William Hu’s Anthropic guide identifies five primitives. The implementation below is Token Lab’s own reference design. Two prerequisites carry most of the reasoning. A local database transaction can commit related local writes as a unit. A network timeout reports the caller’s observation and leaves open what happened remotely. With those two ideas, you can determine what evidence survives every handoff.

Read the two loops from left to right. Context x contains the current event, selected history and tools; y is the proposed token sequence. The application obtains a proposal a. The guard g checks the current state S, proposed action and trusted evidence e against policy. Only then does the application apply the transition δ. A failed check leaves the case unchanged.

P42 crosses two boundaries. The worker can commit case state and a delivery intent together. Receipt depends on a separate system. The timer feeds a future event back into the inbox.
P42 crosses two boundaries. The worker can commit case state and a delivery intent together. Receipt depends on a separate system. The timer feeds a future event back into the inbox. Open full-size diagram

One run, seen from both sides of the tool interface

The following abbreviated records are a teaching protocol. Follow the change of owner at each step. The first two rows belong to one model/tool round trip. The last two explain why a different process can take the next turn.

Owner Record What it establishes
Model → application lookup(P42) · C1 A request to look up P42. No lookup has occurred yet.
Carrier adapter → application C1 · delayed · 09:00 A fresh observation associated with request C1. The carrier may still revise it.
Case service → local transaction P42 · follow_up · 09:15 The case service validates and commits a follow-up. Only after commit can this worker finish the run.
Scheduler → inbox P42/0915 · ready One identified occurrence is ready. The next run must recheck the order before acting.

Intake and concurrency: which worker may advance the case?

A webhook conveys an observation; its delivery may be repeated. The handler verifies the source and tenant, validates the envelope and inserts an inbox row with a unique key over tenant, source and upstream event ID. Only after commit does it acknowledge receipt. If that acknowledgment is lost, the carrier retries and finds the original row. If the process had replied before the write, a crash in between would leave both parties with no outstanding work. Case ID routes the event. Using P42 itself as the deduplication key would also drop a later, distinct delivery scan. Record occurrence time and receipt time separately to preserve evidence of late arrivals.

At 09:15 worker A claims a follow-up for P42 with ownership epoch 7 and reads case revision r. An epoch identifies the holder of the claim. A revision identifies the version of the business facts. A runs inference outside the database transaction. Its lease expires while it is paused. Worker B takes over and obtains epoch 8. A lease permits recovery; the epoch prevents a recovered service and a late former owner from both writing. A system that merely declares A’s lease expired cannot stop A from waking up.

Suppose A returns before B has changed the case. The revision might still be r. An update guarded only by that revision would accept the wrong writer. Conversely, if a valid new order update changes the relevant revision while a worker retains ownership, checking only the epoch would accept an obsolete draft. At commit, the storage layer conditionally updates the case using its scoped identity, expected revision and current epoch. The same transaction marks the input consumed and stores any new obligation or delivery intent. Zero affected rows means discard the stale proposal and reload. Reading these fields, releasing the lock and writing unconditionally later reintroduces the race.

This guard protects the local commit. A worker that calls a payment provider before attempting the commit has already crossed a different boundary. Put externally visible operations behind an authorized, durably recorded intent. Group compatible inputs on the same case only while their individual identities, cancellation rules and precedence survive the grouping.

Time runs downward. A holds epoch 7 and reads revision r, then pauses. After the lease expires B takes over at epoch 8, still on r. A’s write affects zero rows. B checks both values inside a local transaction that updates state and inserts a delivery intent. The external send happens later.
Time runs downward. A holds epoch 7 and reads revision r, then pauses. After the lease expires B takes over at epoch 8, still on r. A’s write affects zero rows. B checks both values inside a local transaction that updates state and inserts a delivery intent. The external send happens later. Open full-size diagram

Timers: how a deadline becomes work exactly where it belongs

The initial run records a one-shot follow-up and the reason it exists, preferably in the same transaction that advances P42 into its waiting stage. Once that commit succeeds, release its compute slot. The timer stores a due time, case reference, purpose and timer generation. The generation distinguishes a rescheduled promise from a stale earlier one. A worker can be upgraded or terminated during the next fifteen minutes without changing when the promise becomes due.

When the deadline arrives, a scheduler scans ready timers. Give this occurrence a stable key. In one local transaction, insert an inbox event using that key and mark the occurrence fired, or advance a recurring schedule. If the transaction rolls back, the timer remains discoverable. If it commits but the scheduler fails before waking the worker, periodic inbox scanning recovers the event. A wake-up signal is a latency optimization. Dependence on the signal alone would recreate the lost-work problem. If the timer store and inbox use different services, this one-database transaction is unavailable. Record a durable intent and reconcile missing occurrences, or use a workflow service with documented delivery guarantees.

Consider a delivery scan recorded at 09:14 but delivered to the assistant at 09:16. The due event says a review is owed. It cannot establish that the parcel remains delayed. Reread current carrier state and verify the timer generation and case stage before taking action. Closing P42 can invalidate an already queued check. If the scheduler was down until 09:28, record that lateness and check the current state then. For recurring work, use the scheduled occurrence, timezone policy and schedule identity to distinguish missed runs; some digests can be coalesced, while individual customer promises may each require a decision.

Memory: reconstruct the next input without turning prose into authority

Imagine receiving the same follow-up twice, first while the carrier is offline and again after a delivery scan. Supplying yesterday’s transcript alone could elicit the same explanation twice. Supplying a versioned progress record plus a fresh observation gives the second run a reason to change its conclusion. Choose the owner of a fact before deciding how to present it to a model.

Needed fact Authoritative evidence Runtime treatment
What was promised? Representative instruction, deadline and provenance Load for P42 until fulfilled or cancelled
Where is the parcel now? Carrier/order lookup key and its latest available observation Refresh when the decision depends on freshness; preserve uncertainty after a lookup failure
What did a person approve? Immutable proposal, actor, revision and expiration Select by proposal identity; compare with the requested action
What has reached the customer? Delivery intent, provider receipt, recipient confirmation when available Report only the level supported by the channel

The prompt is a derived view of those records. Begin with a short task index and current constraints, retrieve the evidence needed for this decision, then include just enough dialogue to interpret a reply. A reply to a proposal should name the proposal. A new order from the same person can start another session. A summary can preserve tone and still lose a currency, an expiry or the distinction between “drafted” and “accepted.” Keep those distinctions in typed fields. Prompt-prefix caching may reduce the cost of repeated input, but cache eviction must have no effect on an open promise.

Save a correction with its origin, scope and time. A customer's general preference for email can inform channel choice. It cannot waive an order-specific approval. When compacting or deleting memories, track derived summaries and indexes so that obsolete information does not persist in a different form.

Permissions: define the action precisely enough to approve it

Assume the check at 09:15 still finds no estimate. The model reads policy and proposes refunding USD 12.00 in shipping fees. The proposal is a candidate action with evidence. The authenticated operator sees the parcel, recipient, amount, currency, applicable terms and expiry. Persist this exact operation under a proposal ID. End the run while waiting. Later, a reply referencing that ID is an input to a new run. Authentication establishes who replied; policy determines whether that actor may approve that exact operation for this tenant.

Now the fee is corrected to USD 15.00. Reconstructing a call from the latest order while reusing the old “yes” silently combines two incompatible versions. Bind approval to the action the person saw. At execution check subject, tenant, operation, destination, integer minor-unit amount, currency, revision, expiry and current permissions. If a critical term changed, supersede the old proposal and show the difference before seeking approval again. Credential injection belongs in a scoped tool gateway. A model-generated tool name and arguments may request an operation; only the policy-enforcing service can admit it. In the teaching replay approval creates a draft notification and moves no money.

Closing a case before external dispatch may cancel a pending intent if policy allows. Closing it after a provider has accepted a payment cannot undo the payment in a local rollback. Record the external result and initiate a separately authorized compensating action if business rules require one. Keeping those paths separate prevents an operator from interpreting a changed case label as proof of a financial reversal.

Outbox: the three meanings of “sent”

When a decision requires contacting the customer, write both the new case state and a pending message in the same local transaction. These writes must agree. If saving the message fails, roll back the case transition so that the obligation is still outstanding. If commit succeeds, a separate dispatcher can deliver the message after the worker exits. An outbox costs storage and operational attention; direct sending remains a reasonable trade for a disposable hint whose loss or duplication is tolerable.

Now split delivery into three facts: we intend to send, the provider accepted the message, the recipient received or read it. The associated evidence is respectively an outbox row, a provider receipt, and a channel-specific confirmation if available. At 09:16 the provider may accept P42’s notice and the dispatcher may exit before recording that receipt. A pending local row is consistent both with “never sent” and with “already accepted.” More model reasoning cannot distinguish those histories from identical local input.

Keep one stable operation key and identical payload across retries while the provider’s deduplication window is valid. A recipient that durably commits its key and visible effect together can tolerate redelivery. If lookup is available, reconcile first. If neither mechanism exists and duplicates matter, keep the outcome unknown, bound retries and route the case to a human. A receipt for one provider attempt still cannot establish that a person read the message. Ask for the strongest evidence the business requires and the channel actually supplies.

Capacity, operating cost and attention

One worker receives 12 compatible events per minute. At three events per run and eight seconds of occupied worker time per run, the workload uses 32 of the 60 available worker-seconds per minute. In the equation, λ is events per second, s is occupied seconds per run, b is compatible events per run and c is independently available workers. The ratio is dimensionless.

The resulting 53.3% is a synthetic offered-load estimate. With a batch size of one, the same input demands 96 worker-seconds per minute. A single worker can provide only 60. A ratio of 1.6 measures excess demand; no worker can actually be occupied 160% of the time. Batching can save repeated prompt setup but adds a wait to collect related inputs. Adding a second worker improves capacity for independent cases. It does little for one hot case whose writes must serialize. Holding a worker for the fifteen-minute business wait would invalidate the eight-second assumption entirely.

Report timer lateness, age of the oldest ready event, model/tool service time, approval wait and delivery uncertainty separately. An inference speedup can leave the customer's wait unchanged if approval dominates. Compare total compute and operations cost per resolved case at a fixed quality target. Count significant changes that went unreported as well as routine alerts the customer did not need. Alerts queued during an outage, sustained traffic from one tenant and recipients unable to acknowledge messages all require explicit service policy.

Practice and verification

16 checks, 14 trace steps, one visible notice, zero refunds. Modern browser or Node.js 22, no dependencies or random input. The in-memory fixture simulates a lost acknowledgement; it does not persist across process restarts.

View the reference implementation

always-on-parcel.js

node always-on-parcel.js
// Deterministic, single-process teaching model. Maps stand in for durable tables.
// No external I/O, model calls or financial operations. Amounts are USD cents.
(function () {
  "use strict";

  function run() {
    const trace = [];
    let checks = 0;
    function record(event, result) {
      trace.push({ step: trace.length + 1, event, result });
      return result;
    }
    function check(condition, description) {
      if (!condition) throw new Error(description);
      checks += 1;
    }

    const parcel = { id: "P42", state: "delayed", revision: 1, cents: 1200 };
    const seen = new Set();
    const outbox = new Map();
    const recipient = new Set();

    // One synchronous consumer represents one worker. A real inbox needs
    // an atomic claim and processing checkpoint; Set alone cannot survive a crash.
    function accept(source, id) {
      const key = JSON.stringify([source, id]);
      if (seen.has(key)) return record(id, "duplicate");
      seen.add(key);
      return record(id, "accepted");
    }

    function fire(timer) {
      if (timer.cancelled || parcel.state !== "delayed" ||
          timer.revision !== parcel.revision) {
        return record(timer.id, "stale_timer");
      }
      return record(timer.id, "follow_up_due");
    }

    function proposal() {
      return Object.freeze({
        parcel: parcel.id, operation: "propose_refund", currency: "USD",
        cents: parcel.cents, revision: parcel.revision
      });
    }

    // 'approval' represents an already authenticated user's exact request.
    // Validating it here only records an approved draft, never a money transfer.
    function approve(approval) {
      const current = proposal();
      const valid = parcel.state === "delayed" && Object.keys(current)
        .every(key => approval[key] === current[key]);
      if (!valid) return record("approval", "needs_new_approval");
      const id = "approved-draft/" + parcel.id + "/" + parcel.revision;
      if (!outbox.has(id)) outbox.set(id, { acknowledged: false });
      return record("approval", "draft_approved");
    }

    function deliver(id, loseAcknowledgment) {
      const row = outbox.get(id);
      if (row.acknowledged) return record(id, "already_acknowledged");
      // The fake recipient persists the key with the visible notification.
      const duplicate = recipient.has(id);
      recipient.add(id);
      if (loseAcknowledgment) return record(id, "accepted_ack_lost");
      row.acknowledged = true;
      return record(id, duplicate ? "duplicate_acknowledged" : "delivered");
    }

    check(accept("carrier", "event-0900") === "accepted", "first receipt");
    check(accept("carrier", "event-0900") === "duplicate", "replayed webhook");
    const timer = { id: "timer-0915", revision: parcel.revision, cancelled: false };
    check(fire(timer) === "follow_up_due", "due follow-up");
    const original = proposal();
    parcel.revision += 1;
    check(approve(original) === "needs_new_approval", "same amount, stale revision");
    const approvedBeforeChange = proposal();
    parcel.cents = 1500;
    parcel.revision += 1;
    check(approve({ ...approvedBeforeChange, revision: parcel.revision }) ===
      "needs_new_approval", "stale amount even with current revision");
    check(outbox.size === 0, "rejected approvals create no notice");
    const fresh = proposal();
    check(approve(fresh) === "draft_approved", "exact approval");
    approve(fresh);
    check(outbox.size === 1, "replayed approval creates one intent");
    const [id] = outbox.keys();
    check(deliver(id, true) === "accepted_ack_lost", "crash after recipient acceptance");
    check(deliver(id, false) === "duplicate_acknowledged", "recover lost acknowledgment");
    check(recipient.size === 1 && outbox.get(id).acknowledged, "one visible notice");
    check(deliver(id, false) === "already_acknowledged", "no further delivery");
    check(fire(timer) === "stale_timer", "timer refers to old revision");
    const nextTimer = { id: "timer-next", revision: parcel.revision, cancelled: true };
    check(fire(nextTimer) === "stale_timer", "cancelled follow-up");
    parcel.state = "resolved";
    check(fire({ ...nextTimer, cancelled: false }) === "stale_timer", "resolved shipment");
    check(approve(fresh) === "needs_new_approval", "closed case cannot approve");
    return { checks, summary: 'visible_notices=' + recipient.size + ' real_refunds=0 model_calls=0', trace };
  }

  if (typeof module === "object" && module.exports) {
    module.exports = { run };
    if (require.main === module) {
      const { checks, summary, trace } = run();
      console.table(trace);
      console.log(checks + " checks passed; " + summary);
    }
  } else {
    globalThis.ParcelLab = Object.freeze({ run });
  }
})();

Open the SQLite recovery lab

Download and run with Python 3.10+ and its standard sqlite3 module. Two temporary databases represent the case service and the recipient. The fixture deliberately interrupts local writes, closes and reopens a connection, and drops an acknowledgement after the recipient commits. The clock and lease takeover are supplied inputs. No random seed, account or network is needed.

always-on-handoff.py

python3 always-on-handoff.py

Expected output

timer=1 stale_writer=rejected rollback=clean keyed_effects=1 unkeyed=unknown->reconciled
View the reference implementation
"""P42 recovery lab. Python 3.10+ and SQLite, standard library only.

Reopening a connection models a replacement worker. Explicit exceptions mark
failure windows; the experiment does not kill a process or move real money.
Run with: python3 always-on-handoff.py
"""

import sqlite3
from contextlib import ExitStack, closing
from pathlib import Path
from tempfile import TemporaryDirectory


class Interrupted(Exception):
    """Stop at a specified point in the protocol."""


def fire_due_timer(db, now, interrupt=False):
    # UPDATE takes the SQLite write lock. Only the first caller can fire P42's
    # one-shot occurrence. A failed transaction leaves the timer ready again.
    with db:
        changed = db.execute(
            "UPDATE timer SET fired = 1 WHERE id = ? AND due <= ? AND fired = 0",
            ("P42/0915", now),
        ).rowcount
        if changed:
            if interrupt:
                raise Interrupted()
            db.execute("INSERT INTO inbox VALUES ('shop', 'timer', 'P42/0915', 0)")
        return changed


def finish_run(db, epoch, revision, interrupt=False):
    # The lease service has already issued the epoch. A local UPDATE guarded
    # by epoch and revision is the last point at which stale work can be rejected.
    with db:
        changed = db.execute(
            """UPDATE cases SET state = 'notice_due', revision = revision + 1
               WHERE id = 'P42' AND epoch = ? AND revision = ?
               AND state = 'waiting'""",
            (epoch, revision),
        ).rowcount
        if not changed:
            return False
        if interrupt:
            raise Interrupted()
        db.execute("INSERT INTO outbox VALUES ('P42/notice/2', 'pending')")
        db.execute("UPDATE inbox SET done = 1 WHERE source = 'timer' AND event = 'P42/0915'")
        return True


def keyed_delivery(local, remote, lose_ack=False):
    key = "P42/notice/2"
    # One remote insert represents both the visible effect and its dedupe key.
    # Splitting those two writes would introduce another failure window.
    with remote:
        remote.execute("INSERT INTO received VALUES (?) ON CONFLICT(id) DO NOTHING", (key,))
    if lose_ack:
        raise Interrupted()  # Remote committed. Local record still says pending.
    with local:
        local.execute("UPDATE outbox SET state = 'confirmed' WHERE id = ?", (key,))


def run(directory):
    with ExitStack() as resources:
        def connect(name):
            return resources.enter_context(closing(sqlite3.connect(directory / name)))

        first = connect("service.sqlite")
        first.executescript("""
            CREATE TABLE cases (id TEXT PRIMARY KEY, epoch INTEGER, revision INTEGER, state TEXT);
            CREATE TABLE timer (id TEXT PRIMARY KEY, due INTEGER, fired INTEGER);
            CREATE TABLE inbox (tenant TEXT, source TEXT, event TEXT, done INTEGER,
                                PRIMARY KEY (tenant, source, event));
            CREATE TABLE outbox (id TEXT PRIMARY KEY, state TEXT);
            INSERT INTO cases VALUES ('P42', 7, 1, 'waiting');
            INSERT INTO timer VALUES ('P42/0915', 15, 0);
        """)
        with first:
            for _ in range(2):
                first.execute("""INSERT INTO inbox VALUES ('shop', 'carrier', 'delay/42', 0)
                                 ON CONFLICT(tenant, source, event) DO NOTHING""")
        assert first.execute("SELECT count(*) FROM inbox").fetchone() == (1,)
        assert fire_due_timer(first, 14) == 0
        try:
            fire_due_timer(first, 15, interrupt=True)
        except Interrupted:
            pass
        assert first.execute("SELECT fired FROM timer").fetchone() == (0,)
        assert first.execute("SELECT count(*) FROM inbox WHERE source = 'timer'").fetchone() == (0,)

        replacement = connect("service.sqlite")
        assert fire_due_timer(replacement, 15) == 1
        assert fire_due_timer(first, 15) == 0
        with replacement:  # Model successful ownership transfer after lease expiry.
            replacement.execute("UPDATE cases SET epoch = 8 WHERE id = 'P42' AND epoch = 7")
        assert not finish_run(first, epoch=7, revision=1)
        assert not finish_run(replacement, epoch=8, revision=0)
        try:
            finish_run(replacement, epoch=8, revision=1, interrupt=True)
        except Interrupted:
            pass
        assert replacement.execute("SELECT state, revision FROM cases").fetchone() == ("waiting", 1)
        assert replacement.execute("SELECT count(*) FROM outbox").fetchone() == (0,)
        assert replacement.execute("SELECT done FROM inbox WHERE source = 'timer'").fetchone() == (0,)
        assert finish_run(replacement, epoch=8, revision=1)
        assert not finish_run(replacement, epoch=8, revision=1)

        provider = connect("recipient.sqlite")
        provider.executescript("""
            CREATE TABLE received (id TEXT PRIMARY KEY);
            CREATE TABLE ordinary_receipts (case_ref TEXT, receipt TEXT PRIMARY KEY);
        """)
        try:
            keyed_delivery(replacement, provider, lose_ack=True)
        except Interrupted:
            pass
        replacement.close()
        resumed = connect("service.sqlite")
        assert resumed.execute("SELECT state FROM outbox").fetchone() == ("pending",)
        assert provider.execute("SELECT count(*) FROM received").fetchone() == (1,)
        keyed_delivery(resumed, provider)
        assert resumed.execute("SELECT state FROM outbox").fetchone() == ("confirmed",)
        assert provider.execute("SELECT count(*) FROM received").fetchone() == (1,)

        # Alternative channel: an operation reference is searchable but the
        # recipient does not enforce uniqueness on it. A retry could duplicate.
        with resumed:
            resumed.execute("INSERT INTO outbox VALUES ('P42/manual', 'sending')")
        with provider:
            provider.execute("INSERT INTO ordinary_receipts VALUES ('P42/manual', 'receipt-19')")
        # Time out after the provider commits. Stop; no automatic second send.
        with resumed:
            resumed.execute("UPDATE outbox SET state = 'unknown' WHERE id = 'P42/manual'")
        assert resumed.execute("SELECT state FROM outbox WHERE id = 'P42/manual'").fetchone() == ("unknown",)
        # The operator has an authoritative, complete receipt ledger for this
        # fixture. An empty, stale or ambiguous lookup would leave state unknown.
        matches = provider.execute(
            "SELECT receipt FROM ordinary_receipts WHERE case_ref = 'P42/manual'"
        ).fetchall()
        if len(matches) == 1:
            with resumed:
                resumed.execute("UPDATE outbox SET state = 'reconciled' WHERE id = 'P42/manual'")
        assert resumed.execute("SELECT state FROM outbox WHERE id = 'P42/manual'").fetchone() == ("reconciled",)
        print("timer=1 stale_writer=rejected rollback=clean keyed_effects=1 unkeyed=unknown->reconciled")


if __name__ == "__main__":
    with TemporaryDirectory() as temp:
        run(Path(temp))

Compare runs using the same ordered inputs, source revisions, deadlines, permissions and channel semantics. Vary batching alone to study cost and time to the first useful notice. Vary receiver deduplication alone to study the uncertainty after acknowledgment loss. Preserve the source records for cases left unresolved; dropping them can make a design look artificially fast.

Original interview exercise 1. A worker pauses, loses its lease and returns with a polished draft. Should the database accept it?

Hint 1

locate the current owner.

Hint 2

consider the moment between reading the owner and writing the draft.

Answer

require the current generation and expected case revision in the atomic commit condition. Reject a stale write and reconsider the case using current evidence. A timestamp check performed before writing leaves a race.

Original interview exercise 2. The representative approved one refund amount. A policy update increases the suggested amount. Can the system reuse the approval?

Hint 1

identify exactly what the representative saw.

Hint 2

track what can change after that screen closes.

Answer

invalidate the pending operation on the relevant revision or amount change. Present the new terms, obtain fresh approval and recheck them at dispatch. A general preference for refunds supplies no authorization for this transaction.

Original interview exercise 3. An outbound send timed out. The dashboard reports one pending message. How many messages did the customer receive?

Hint 1

identify whose state the dashboard shows.

Hint 2

distinguish provider acceptance from recipient acknowledgment.

Answer

local pending state alone cannot tell. Reconcile by operation key and provider receipt where possible, preserving an unknown state otherwise. Verify recipient acknowledgment separately if the workflow needs it.

Score each answer from 1 to 5. One point identifies the visible symptom. Two name the durable record that matters. Three describe the ordinary transition and its owner. Four account for stale, duplicate or ambiguous outcomes. Five specify the enforceable recovery condition and the evidence an operator can inspect.

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 further reading

  1. William Hu · Building always-on agents · 2026-11-13https://claude.com/resources/articles/building-always-on-agents
  2. AWS Prescriptive Guidance · Transactional outboxhttps://docs.aws.amazon.com/prescriptive-guidance/latest/cloud-design-patterns/transactional-outbox.html
  3. Stripe API · Idempotent requestshttps://docs.stripe.com/api/idempotent_requests
  4. SQLite · Transactionhttps://www.sqlite.org/lang_transaction.html
  5. Claude Platform · Tool use with Claudehttps://platform.claude.com/docs/en/agents-and-tools/tool-use/overview
  6. Martin Kleppmann · How to do distributed locking · 2016-02-08https://martin.kleppmann.com/2016/02/08/how-to-do-distributed-locking.html

Continue with agent action recovery