16-03

Chapter 16 · Specifying agentic systems

At-most-once side effects

  • 45 min core
  • Core track
  • Lab: State Graph Explorer
  • Skills: hostile-env, intent, evidence

00Recall

One card from 16-02 on models too small for their bug, one from 08-02 on what a lossy network allows, and one from 14-04 on what traces cannot see. Today the network is honest, nothing is lost, and the agent still charges a card twice.

16-02-a from AgentToolLoop

A teammate's agent passes its approval invariant with Budget = 1. Why might that pass mean nothing?

Show answer

With one model call, a session holds at most one risky request, so a design that approves once per session cannot differ from one that approves every request. The model is too small for the bug to exist.

08-02-a from Loss and duplication for free

In a spec whose network is a set, how do you allow duplicate delivery?

Show answer

Leave the message in the set when it is received. Nothing then forbids receiving it again.

14-04-a from What traces cannot see

A TraceSpec's MatchGet does not compare the value the code returned. What happens to a log in which the code read a lost value?

Show answer

It is accepted. A field the TraceSpec ignores is as good as unlogged; the replay can only catch what a matcher compares.

Skip recall Recall is never required.

01Commit

The chapter's opening question, in the owner's words: no payment tool runs twice for one user intent. specs/ToolEffects.tla is one intent carried out by an agent through a payment service. The agent sends a charge request with an idempotency key, a value the service uses to recognise a repeat. The service ignores a key it has already processed. A call can time out while its request is still on the wire, and then the agent may retry, up to MaxAttempts = 2 sends in all. The requirement is AtMostOnce == charges <= 1.

Four constants say what the harness does and what the world does: where the agent keeps its key (KeyStore), whether the agent can crash (AgentCrashes), whether the service deduplicates (ServiceDedupes), and MaxAttempts.

The naive loop, ToolEffects.naive.cfg, makes a new key for every send. The service deduplicates, and the agent cannot crash.

Commit a

The naive loop retries after a timeout with a new key. Can TLC find a run that charges twice?

  1. Yes: the first request can still be charged after the agent has given up on it.
  2. No: a timeout means the first request failed, so only the retry charges.
  3. No: the agent waits for the first reply before it sends again.

Answer Yes: the first request can still be charged after the agent has given up on it.

An AI teammate proposes a fix (you will review it in ai/1-dedupe-in-memory): keep the key in the agent's memory and reuse it on every retry. ToolEffects.memory.cfg checks it with no crash, and passes. ToolEffects.memorycrash.cfg lets the agent crash and restart; memory is lost in a crash, and the task record that counts attempts is not.

Commit b

The key lives in memory, the service deduplicates, and now the agent can crash. What does TLC report?

  1. No violation: the agent reuses its key, so the service drops the repeat.
  2. No violation: two attempts are too few for a crash to matter.
  3. A violation of AtMostOnce, with one crash between the two sends.

Answer A violation of AtMostOnce, with one crash between the two sends.

02Lab

Lab · State Graph ExplorerWhat you’re looking at: every reachable state of ToolEffects. Switch variants to change the key store, crashes, retries and deduplication; states with a second charge are the bug.

TLC found no violation

123456789101112131415161718192021222324252627282930313233343536

This is a teaching view. Real checking happens with TLC on your machine.

Text view: every state and step
States and their successors
StateseenrepliesagentcrashedattemptsmemKeyrequestslogKeychargesSteps (action → state)
initial 1{}{}"ready"FALSE00{}00Send → 2; Crash → 3
2{}{}"waiting"FALSE10{1}10Timeout → 4; Serve(1) → 5; Crash → 6
3{}{}"ready"TRUE00{}00Send → 7; Crash → self
4{}{}"ready"FALSE10{1}10Send → 8; Serve(1) → 9; Crash → 6
5{1}{1}"waiting"FALSE10{}11Timeout → 9; Receive(1) → 10; Crash → 11
6{}{}"ready"TRUE10{1}10Send → 12; Serve(1) → 11; Crash → self
7{}{}"waiting"TRUE10{1}10Timeout → 6; Serve(1) → 13; Crash → 6
8{}{}"waiting"FALSE20{1}10Timeout → 14; Serve(1) → 15; Crash → 16
9{1}{1}"ready"FALSE10{}11Send → 17; Crash → 11
10{1}{}"done"FALSE10{}11Halt → self
11{1}{1}"ready"TRUE10{}11Send → 18; Crash → self
12{}{}"waiting"TRUE20{1}10Timeout → 16; Serve(1) → 19; Crash → 16
13{1}{1}"waiting"TRUE10{}11Timeout → 11; Receive(1) → 20; Crash → 11
14{}{}"ready"FALSE20{1}10Serve(1) → 21; Crash → 16; GiveUp → 22
15{1}{1}"waiting"FALSE20{}11Timeout → 21; Receive(1) → 23; Crash → 24
16{}{}"ready"TRUE20{1}10Serve(1) → 24; Crash → self; GiveUp → 25
17{1}{1}"waiting"FALSE20{1}11Timeout → 26; Serve(1) → 15; Receive(1) → 27; Crash → 28
18{1}{1}"waiting"TRUE20{1}11Timeout → 28; Serve(1) → 19; Receive(1) → 29; Crash → 28
19{1}{1}"waiting"TRUE20{}11Timeout → 24; Receive(1) → 30; Crash → 24
20{1}{}"done"TRUE10{}11Halt → self
21{1}{1}"ready"FALSE20{}11Crash → 24; GiveUp → 31
22{}{}"gaveup"FALSE20{1}10Serve(1) → 31; Halt → self
23{1}{}"done"FALSE20{}11Halt → self
24{1}{1}"ready"TRUE20{}11Crash → self; GiveUp → 32
25{}{}"gaveup"TRUE20{1}10Serve(1) → 32; Halt → self
26{1}{1}"ready"FALSE20{1}11Serve(1) → 21; Crash → 28; GiveUp → 33
27{1}{}"done"FALSE20{1}11Serve(1) → 34; Halt → self
28{1}{1}"ready"TRUE20{1}11Serve(1) → 24; Crash → self; GiveUp → 35
29{1}{}"done"TRUE20{1}11Serve(1) → 36; Halt → self
30{1}{}"done"TRUE20{}11Halt → self
31{1}{1}"gaveup"FALSE20{}11Halt → self
32{1}{1}"gaveup"TRUE20{}11Halt → self
33{1}{1}"gaveup"FALSE20{1}11Serve(1) → 31; Halt → self
34{1}{1}"done"FALSE20{}11Halt → self
35{1}{1}"gaveup"TRUE20{1}11Serve(1) → 32; Halt → self
36{1}{1}"done"TRUE20{}11Halt → self

The variants are cfgs of the same module. base is the fixed design: the key is written to a durable log before the first send, the agent can crash, the service deduplicates, and the agent may send twice. naive-crash and memory-crash change only where the key lives, no-dedupe only the service, and no-retry only the number of sends (MaxAttempts = 1). naive and memory are the commits' worlds, which also turn crashes off. Before you switch, predict whether a state with charges = 2 will appear.

Or in the terminal. ./tla check 16-03 runs the exercises, then each ToolEffects cfg whose result this page quotes; these two are the commits' worlds:

shell
./tla check chapters/16-specifying-agentic-systems/specs/ToolEffects.naive.cfg
./tla check chapters/16-specifying-agentic-systems/specs/ToolEffects.memorycrash.cfg
Expected output 16-specifying-agentic-systems/specs/ToolEffects.memorycrash
16-specifying-agentic-systems/specs/ToolEffects.memorycrash  ToolEffects.memorycrash.cfg  (MaxAttempts=2, KeyStore="memory", AgentCrashes=TRUE, ServiceDedupes=TRUE)
parse ok
model check: invariant AtMostOnce violated; trace has 6 states (5 steps); 35 distinct states
expected outcome met: violation AtMostOnce
trace (changed variables only; ./tla trace --full shows all):
  1  Init   agent = "ready", memKey = 0, logKey = 0, attempts = 0, requests = {}, replies = {}, seen = {}, charges = 0, crashed = FALSE
  2  Send   agent: "ready" -> "waiting", memKey: 0 -> 1, attempts: 0 -> 1, requests: {} -> {1}
  3  Serve  requests: {1} -> {}, replies: {} -> {1}, seen: {} -> {1}, charges: 0 -> 1
  4  Crash  agent: "waiting" -> "ready", memKey: 1 -> 0, crashed: FALSE -> TRUE
  5  Send   agent: "ready" -> "waiting", memKey: 0 -> 2, attempts: 1 -> 2, requests: {} -> {2}
  6  Serve  requests: {2} -> {}, replies: {1} -> {1, 2}, seen: {1} -> {1, 2}, charges: 1 -> 2

Reveal for commit a

Yes. AtMostOnce is violated with a trace of 6 states: the agent sends, times out, sends again with a new key, and the service charges for both keys.

Reveal for commit b

A violation, again with a trace of 6 states. The crash wipes memKey, and the next send mints a key the service has never seen. Without crashes, the same design passed in 18 distinct states.

03Reason

If you picked "a timeout means it failed", look at what the agent knows when its timer fires. Its request may have been lost (this model has no loss; see below). It may have been processed, with the reply still travelling back. It may still be in a queue somewhere, not yet processed. The agent cannot tell these apart, and two of the three end in a charge. A retry after a timeout is a second request, and only something the service can recognise makes it the same request.

That something is the idempotency key. It turns "charge this card" into "charge this card for intent 7". The service keeps a table of keys it has processed, and a request with a known key changes nothing. Now the property depends on two parties keeping a contract: the agent sends the same key for the same intent, every time; the service honours it.

Write something before openingthe memory fix keeps its half of the contract until what happens?

Until the agent stops being the same process. A crash and restart produces an agent that has the task but not the key, so it mints a new one, and the contract is broken by the side that promised to keep it. The key has to live wherever the intent lives. Here the task record survives a crash, so the key must survive too.

ToolEffects.cfg puts the key in a durable log, and passes with crashes on:

TLA+
KeyForSend is defined as
    CASE KeyStore = "log" and logKey not equal to 0    to logKey
      always KeyStore = "memory" and memKey not equal to 0 to memKey
      always OTHER                             to attempts + 1

and Send writes the key to the log in the same step that sends it. That atomic step is itself a claim about the code: the log write must be durable before the request leaves. Code that sends first and logs afterwards has a crash window the spec does not show.

Write something before openingwhy is MaxAttempts = 2 big enough, and is anything smaller?

One send cannot charge twice: there is only one request. Two sends can, and every failure in this lesson needs exactly two: a retry after a timeout, or a send after a crash. So two is the smallest model in which the bug can exist. A third attempt would add states; whether it adds a new way to fail is a question for TLC, one constant away.

Write something before openingthe agent could ask the service whether its first request went through before it retries. Does that remove the need for deduplication?

Not on its own. Between the answer "not yet" and the retry, the first request can still arrive and be charged: a check followed by an act, with the world free to move in between. A status query helps the agent decide whether a retry is needed. Only help from the side that performs the effect, such as deduplication by key, makes a retry harmless.

ServiceDedupes is not the agent's decision; it belongs to whoever runs the payment service. Writing it as a constant forces the question into the open, and ToolEffects.nodedupe.cfg gives the answer: with the fixed design and a service that does not deduplicate, AtMostOnce is violated in a trace of 6 states. The key is sent faithfully, and nobody reads it.

04In your editor

ToolEffects and its cfgs are in chapters/16-specifying-agentic-systems/specs/. Check this lesson's specs and exercises with:

shell
./tla check 16-03

The fixed design, with crashes on, the service deduplicating, every action firing and both witnesses reached:

Output 16-specifying-agentic-systems/specs/ToolEffects
16-specifying-agentic-systems/specs/ToolEffects  ToolEffects.cfg  (MaxAttempts=2, KeyStore="log", AgentCrashes=TRUE, ServiceDedupes=TRUE)
parse ok
model check: no violation found in 36 distinct states (83 generated, depth 7)
expected outcome met: pass
coverage: all 7 actions fired
witness ChargedAfterRetry reached (trace of 6 states)
witness ChargedAfterCrash reached (trace of 5 states)

For your own agent, list every tool with a side effect outside your system: payments, emails, tickets, deployments, and answer the four questions of the optional Practice item below for each. A tool whose other side promises nothing about a repeated key can be at-least-once (retry until a reply) or at-most-once (never retry), and you should choose which on purpose. Do this in my-system/ (a private repository; see 00-04 before you share any of it).

05Practice

Warm-up. A refund agent mints a new key on every send. Make it reuse a key that survives a crash.

Core. A payments model whose service ignores its own environment constant. Write the service, and a cfg for each world.

Mixed. A lookup tool behind a network that loses messages, and an agent that waits for a reply that never comes.

Your own agent (optional, self-graded). For each tool with a side effect in an agent you run or are building, write four lines in NOTES.md: where its key lives, what survives a crash of your process, what the other party promises to do with a repeated key, and who could still be acting on a stale approval when the effect lands. Compare with "16-03 your own agent" in HINTS.md.

16-03-ex1Warm-up5 min

16-03-ex1 · Write the key down first

Tier: warm-up. Time: about 5 minutes.

A support agent issues one refund through a payments service that ignores a key it has seen. The agent keeps the key in memory and in a durable log, but chooses a fresh key for every send.

  1. Run ./tla check 16-03-ex1 and read the trace. Which two keys did the service see?
  2. Fill gap g1 in RefundAgent.tla: the key for the next send. Reuse a key that survives a crash if there is one; otherwise mint a fresh one.
  3. Run the check again. It must pass, with a refund after a retry and a refund after a crash both reached.
  4. The check also runs RefundAgent.grader.cfg, the course's check: the same agent on a later day, when the service has already processed keys 1..KeyBase for earlier refunds. A key that is not new to the service gets this refund ignored. Leave that file as it is.

Try the memory version first if you like: TLC will show you why it is not enough.

Hints: HINTS.md, under "16-03-ex1 hint 1" to "hint 3". The solution is in solutions/chapters/16-specifying-agentic-systems/exercises/03-ex1-write-the-key-down-first/; open it after you have a passing answer of your own.

If TLC finds no violation but an action never fires or a witness is not reached, ./tla prints "goal not met" and exits with code 1.

Both cfgs must meet the goal "goal met: pass".

Done when: ./tla check 16-03-ex1 prints "goal met: pass".

./tla check 16-03-ex1

Repo chapters/16-specifying-agentic-systems/exercises/03-ex1-write-the-key-down-first/

Hints

Hint 1

The trace shows two different keys reaching the service. Where does each come from? Read KeyForSend and the guard of Crash.

Hint 2

The agent keeps the key in two places. One of them is wiped by Crash; the other is not.

Hint 3 (nearly the answer)

One IF on logKey, and no memKey. A fresh key is KeyBase + attempts + 1, one the service has never seen, and Send already writes the key it sends to the log.

16-03-ex2Core8 min

16-03-ex2 · Name the environment

Tier: core. Time: about 8 minutes.

Payments.tla has an agent that already does its part: one key per intent, reused on every retry. Whether the payments service honours the key is the constant ServiceDedupes, and the starter's service ignores it.

  1. Run ./tla check 16-03-ex2. Both cfgs stop before any state: the constants have no values.
  2. Fill gap g1 in Payments.tla: the service takes a request off the wire and replies; it charges the card, unless it deduplicates and has seen the key before.
  3. Fill gap g1 in each cfg. Payments.cfg is the world where the service deduplicates; Payments.nodedupe.cfg is the world where it does not. Each checks the spec, both constants (with room for one retry), TypeOK and AtMostOnce.
  4. Before you run it, predict both verdicts.

Hints: HINTS.md, under "16-03-ex2 hint 1" to "hint 3". The solution is in solutions/chapters/16-specifying-agentic-systems/exercises/03-ex2-name-the-environment/; open it after you have a passing answer of your own.

Both cfgs must meet their goals: "goal met: pass" for Payments.cfg, and "goal met: violation AtMostOnce" for Payments.nodedupe.cfg.

Done when: ./tla check 16-03-ex2 prints "goal met: pass".

./tla check 16-03-ex2

Repo chapters/16-specifying-agentic-systems/exercises/03-ex2-name-the-environment/

Hints

Hint 1

TLC stops on the first constant that has no value. Each cfg is one world: what must it say about the service?

Hint 2

The service charges when it has not seen the key, or when it does not deduplicate at all. Only the line for charges' needs to change.

Hint 3 (nearly the answer)

charges' is an IF whose condition has two conjuncts: one about the service's constant, one about seen. Each cfg names Spec, both constants with MaxAttempts = 2, and the two invariants; only ServiceDedupes differs.

16-mxMixed20 min · mastery path

16-mx · The reply that never comes

Tier: mixed. Time: about 20 minutes.

An agent calls a remote lookup tool over a network that can lose the request or the reply. Asking twice is harmless: the tool has no side effects. The requirement is EventuallyAnswered: the agent eventually has its reply. The constant ToolUp says whether the tool's server is running.

  1. Run ./tla check 16-mx and read the trace. What can the agent do after a loss?
  2. Fill gap g1 in ToolChannel.tla: with nothing on the wire and no answer yet, the agent sends the request again.
  3. Run it. Read the lasso before you change anything else.
  4. Fill gap g2: the behavior spec, with fairness on the actions that must keep happening for the agent to get its answer despite loss. Use as little as you can defend, and say for each fairness condition what real mechanism it stands for.
  5. The check also runs two course cfgs. Leave both as they are. ToolChannel.down.cfg checks your fairness in a world where the tool's server is down (ToolUp = FALSE): no fairness about the network or the agent can produce a reply there, so EventuallyAnswered must still be violated. A Spec that demands the answer outright, such as one ending in /\ <>answered, leaves that world with no behaviors and passes, so it misses the goal. MCToolChannel.cfg checks that your Spec still allows a fair behavior that loses a message and is answered; a Spec that assumes the network eventually stops losing misses that goal.

Hints: HINTS.md, under "16-mx hint 1" to "hint 3". The solution is in solutions/chapters/16-specifying-agentic-systems/exercises/mx-the-reply-that-never-comes/; open it after you have a passing answer of your own.

If TLC finds no violation but an action never fires or a witness is not reached, ./tla prints "goal not met" and exits with code 1.

All three cfgs must meet their goals: "goal met: pass" for ToolChannel.cfg, "goal met: property EventuallyAnswered" for ToolChannel.down.cfg, and "goal met: property NoFairAnswerAfterLoss" for MCToolChannel.cfg.

Done when: ./tla check 16-mx prints "goal met: pass".

./tla check 16-mx

Repo chapters/16-specifying-agentic-systems/exercises/mx-the-reply-that-never-comes/

Hints

Hint 1

After a loss, nothing is on the wire and the agent has no answer. In the starter no action is enabled, so TLC reports a deadlock.

Hint 2

With Resend in place, the lasso loses the request every time it is sent. Which actions are enabled infinitely often in it, but never continuously?

Hint 3 (nearly the answer)

Three conditions. Once something is lost, Resend stays enabled until it fires, so the weaker kind is enough there. Loss keeps disabling Deliver and Receive: which kind survives that? Write down what each condition says about the world.

06Explain it

Open NOTES.md and answer the three prompts under 16-03, about the Core exercise.

output
What I built, and why it is correct:
Which assumption, if false, breaks it:
What TLC did not check here:

Compare your answers with "16-03 check your explanation" in HINTS.md.

After you writeCheck your explanation

A good answer: "My Serve charges unless the service deduplicates and has seen the key, so each cfg fixes one world. With deduplication the agent's retries are harmless; without it, a retry after a timeout charges twice. At-most-once is therefore a property of agent and service together, and the agent alone cannot provide it while retrying. TLC did not check how long a real provider keeps keys, crashes on either side, or the gap between writing the log and sending."

A weak answer: "The no-dedupe cfg fails and the other passes." It reports the verdicts without saying what they mean for whoever owns the service.

Done?