The Flow Book
  1. Why Flow

One week at the support desk

  1. A payment that timed out
  2. What the run was told
  3. Writing the payments library
  4. Waiting for the manager
  5. The next morning
  6. When the process dies mid-call
  7. Fixing a bug in a half-finished run
  8. Three carriers at once
  9. Answering calls from your own service

Projects

  1. What people build
  2. A research agent you can check

The language tour

  1. Values, functions and blocks
  2. Records, choices and match
  3. Modules, libraries and Python functions
  4. Result, ToolProblem and ?

Appendix

  1. The flow command
Language reference ↗

Fixing a bug in a half-finished run

Dana's lamp was not the only broken one. The whole batch went out with the same fault, and complaints about it are still coming in. You wrote the program that works through them: a model reads the task, the program looks each order up and refunds it, and it goes on to the next order until the model says it is done.

This morning it gave up halfway. Two customers have their money back and two do not, and the bug is in your code. Fixing the file will take a minute. The run is the harder part: starting it again pays the first two customers a second time, and leaving it alone means the last two never hear from you.

The refund loop

Each turn, the program shows the model the task and the latest part of the conversation so far. It does the one thing the model asks for, adds the request and its answer to the conversation, and goes round again. It stops when the model says it has finished, or when it runs out of turns.

// Work through a batch of complaints with a model: show it the task and the// latest part of the conversation, do the one thing it asks, and go round again.use "./tools"pub type Ending { Done(Text), OutOfTurns }pub flow main(task: Text) -> Result<Ending, ToolProblem> = turn(task, [], 10)flow turn(task: Text, conversation: List<tools.Entry>, left: Int) -> Result<Ending, ToolProblem> =    if left == 0 {        Ok(OutOfTurns)    } else {        match tools.next_step(task, conversation.take(8))? {            Finish(summary) => Ok(Done(summary)),            Use(action) => turn(task, conversation + [Asked(action), Saw(perform(action)?)], left - 1),        }    }flow perform(action: tools.Action) -> Result<Text, ToolProblem> = match action {    Lookup(order) => tools.lookup(order),    Refund(order, dollars) => tools.refund(order, dollars),}
The loop as it ran this morning. turn calls itself with a longer conversation and one turn fewer.

The model, the order system and the payment provider are Tools in the tools library, written in Python like the ones in Why Flow. Each stand-in appends to tools/calls.log the call it answered and what it said, and a refund also adds a line to tools/ledger.txt. The model stand-in follows a fixed plan for the batch: it finds the last step in the conversation it is shown, and answers with the step after it.

Show tools/tools.py · 100 lines
# Stand-ins for a model and the shop's order system, as a Tool library.# Every call is appended to calls.log with its id and its answer,# and every refund is a line in ledger.txt.from dataclasses import dataclassfrom pathlib import Pathfrom flow_toolkit import context, tool, variant@variant(positional=True)@dataclass(frozen=True)class Lookup:    order: str@variant(positional=True)@dataclass(frozen=True)class Refund:    order: str    dollars: intAction = Lookup | Refund@variant(positional=True)@dataclass(frozen=True)class Asked:    action: Action@variant(positional=True)@dataclass(frozen=True)class Saw:    text: strEntry = Asked | Saw@variant(positional=True)@dataclass(frozen=True)class Use:    action: Action@variant(positional=True)@dataclass(frozen=True)class Finish:    summary: strStep = Use | FinishPRICES = {"A-1043": 40, "A-1044": 35, "A-1045": 40, "A-1046": 55}# What the model does with this batch: look each order up, then refund it.PLAN = [step for order, dollars in PRICES.items() for step in (Lookup(order), Refund(order, dollars))]def words(step):    match step:        case Use(Lookup(order)):            return f"Lookup {order}"        case Use(Refund(order, dollars)):            return f"Refund {order} {dollars}"        case Finish(summary):            return f"Finish: {summary}"def log(name, said, answer):    with Path("calls.log").open("a") as calls:        calls.write(f"{context().call:<10} {name:<9} {said:<17} -> {answer}\n")@tooldef next_step(task: str, conversation: list[Entry]) -> Step:    """Ask the model for the next step. The stand-in finds the last step in the    conversation it is shown and answers with the one after it."""    asked = [entry.action for entry in conversation if isinstance(entry, Asked)]    at = PLAN.index(asked[-1]) + 1 if asked else 0    step = Use(PLAN[at]) if at < len(PLAN) else Finish("Refunded A-1043, A-1044, A-1045 and A-1046: 170 dollars in all.")    log("next_step", f"shown {len(conversation)} entries", words(step))    return step@tooldef lookup(order: str) -> str:    """Look an order up in the shop's order system."""    said = f"desk lamp, {PRICES[order]} dollars, arrived broken"    log("lookup", order, said)    return said@tooldef refund(order: str, dollars: int) -> str:    """Refund an order. The money moves: one line in ledger.txt."""    with Path("ledger.txt").open("a") as ledger:        ledger.write(f"{order} {dollars}\n")    log("refund", f"{order} {dollars}", f"refunded {dollars} dollars")    return f"refunded {dollars} dollars"
The stand-ins. flow build turns the Python types at the top into the Action, Entry and Step the program matches on.

A few pieces of syntax are new. List<tools.Entry> is a list of entries, [] is the empty list, and conversation + [a, b] makes a new list with two more entries on the end. turn repeats by calling itself as its last act, since Flow has no loop statement.

This morning's run

A long conversation will not fit in what a model can read at once, so the loop shows it only the last eight entries. That was the intent of conversation.take(8). In lamp-batch, run the batch:

flow run main.flow task='Refund the broken lamps from batch 7: A-1043, A-1044, A-1045, A-1046'run 24f70991a405Ok(OutOfTurns)24f70991a405 completednext: flow replay 24f70991a405
cat tools/ledger.txtA-1043 40A-1044 35

Ten turns, two refunds. The model's side of the log shows where the turns went:

Goes wrong
grep next_step tools/calls.logroot#1     next_step shown 0 entries   -> Lookup A-1043root#3     next_step shown 2 entries   -> Refund A-1043 40root#5     next_step shown 4 entries   -> Lookup A-1044root#7     next_step shown 6 entries   -> Refund A-1044 35root#9     next_step shown 8 entries   -> Lookup A-1045root#11    next_step shown 8 entries   -> Lookup A-1045root#13    next_step shown 8 entries   -> Lookup A-1045root#15    next_step shown 8 entries   -> Lookup A-1045root#17    next_step shown 8 entries   -> Lookup A-1045root#19    next_step shown 8 entries   -> Lookup A-1045

take(8) keeps the first eight entries of a list, and the loop needed the last eight. Up to the fifth turn the whole conversation fitted, so nothing looked wrong. From the sixth turn on, the model was shown the same four steps every time, ending with the refund for A-1044, and it asked to look up A-1045 again and again until the turns ran out. Every call worked. The fault was in the program, and the turn limit is what stopped it.

The fix is one word: take becomes take_last. What to do about the run takes longer.

Starting again pays twice

Running the batch again on the fixed file would finish the job, and it would also refund A-1043 and A-1044 a second time. The program has no way to know they were paid: it starts with an empty conversation, and the model plans the batch from the top. You could add a check against the ledger to every refund, and for money you probably should. Even so, you would be re-asking a model and re-reading orders for work the run had already done correctly, and checking by hand which steps a rerun may repeat.

Carrying on is not an option either:

Goes wrong
flow resume 24f70991a405error[run-ended]: the run has ended --> run 24f70991a405  = why: The stored End fact already records the run's terminal outcome; it cannot be resumed.  = help: Start a new run, or fork the run from the facts before its End to continue it.

As far as Flow is concerned, the run finished: main returned OutOfTurns, a value your program chose to return, and a run that has ended has nothing left to do.

What you want is a run that begins where this one was still right, and continues on the fixed program.

Where a run can begin again

Each line in calls.log starts with the call's id, and every turn makes two calls: root#11, the run's eleventh, is the model's call in the sixth turn. It is also the first wrong answer in the log, and everything before it was right.

A run's record is a numbered list of facts. Fact 1 names the program and its input, and after it every call and every reply is a fact of its own. So the reply to root#10, the last call before the wrong one, is fact 21:

flow show 24f70991a405 --fact 21 | head -4run 24f70991a405state: completed1 of 42 facts · 41 hidden  21 Reply      root#10 Ok

A fork on the fixed program

Make the fix, then start a new run from there. A fork is a new run whose record begins as a copy of another run's facts 1 to N. flow resume with --from N makes one, and like any resume it continues on the file you name, or on the file the run was started from, which is now the fixed main.flow (forks in the Reference):

flow resume 24f70991a405 main.flow --from 21error[unconfirmed-drop]: this drops 10 calls of the run, and the request does not name exactly them: root#11 tools.next_step (answered); root#12 tools.lookup (answered); root#13 tools.next_step (answered); root#14 tools.lookup (answered); root#15 tools.next_step (answered); root#16 tools.lookup (answered); root#17 tools.next_step (answered); root#18 tools.lookup (answered); root#19 tools.next_step (answered); root#20 tools.lookup (answered) --> run 24f70991a405, fact 21  = why: A dropped call's answer is never used, and its effect may already have happened and may happen again under a key no implementation has seen.  = help: resume, dropping these calls  = try: flow resume 24f70991a405 main.flow --from 21 --drop 'root#11' 'root#12' 'root#13' 'root#14' 'root#15' 'root#16' 'root#17' 'root#18' 'root#19' 'root#20'

This morning's run made ten more calls after fact 21, root#11 to root#20. Any of them may already have had its effect, and the fork may make it again under a key of its own, so the fork lists them and starts only when you name exactly those calls with --drop. Here they are the model's and the order system's calls from the turns that went wrong, and none of them is a refund:

flow resume 24f70991a405 main.flow --from 21 --drop 'root#11' 'root#12' 'root#13' 'root#14' 'root#15' 'root#16' 'root#17' 'root#18' 'root#19' 'root#20'run c7850103802dOk(Done("Refunded A-1043, A-1044, A-1045 and A-1046: 170 dollars in all."))c7850103802d completednext: flow replay c7850103802d
cat tools/ledger.txtA-1043 40A-1044 35A-1045 40A-1046 55

Each customer was refunded once. The fixed main.flow is not the program that recorded those facts, so the fork does not take up where fact 21 left off. It runs the fixed program from the start of the run against the copy. The fixed program must make every call the copy records, to the same Tool with the same arguments, and each is answered from the copy instead of being made again. What the fixed program does from there is recorded in a segment of its own, after a fact that names the new program. For five turns the whole conversation fitted in eight entries, so take_last(8) showed the model just what take(8) had, and the two refunds are among the answers the copy gave: nothing in the fork repeated them. At the sixth turn the model was shown the last eight entries, which this morning's run never showed it, so that call was new. The model asked to refund A-1045, and the batch went on to the end. The fork's lines in tools/calls.log start at p1:root#11: a call made after a run moved onto edited code carries the segment it was made in.

The fork has its own id and its own record, which starts by naming where it came from:

flow show c7850103802d --fact 1 | head -4run c7850103802dstate: completed1 of 37 facts · 36 hidden   1 Program    c7850103802d ./main.main, forked from 24f70991a405 at fact 21

The rest of its record is the answers it reused, then its own calls, and it checks out against its program like any other run's:

flow replay c7850103802dReplay c7850103802d: matchedNo tools were called.

The morning's run is still there, unchanged, with its two refunds and its ten turns:

flow runsc7850103802d	completed	main.flow	…24f70991a405	completed	main.flow	…

What a fork costs

A fork makes again every call the facts it copies do not answer, because those calls belong to the fork, and the fork has not made them yet. That is why it lists them first. Fork at fact 13 instead of 21 and the list includes root#8, the refund of A-1044: drop it, and A-1044 is refunded a second time. Choosing the fact is your job, and the list, the log or flow show is how you choose it.

The new program has to fit the run. It starts at main, so it must still have a main in main.flow that takes and returns what this morning's did; change that, and Flow refuses the fork and says why. Everything else may change, but the new program must make every copied call the same way: change what the model is shown on the first turn, and the fork is refused at that call, before anything is sent.

This loop passes the whole conversation to turn every turn. A loop meant to run for hours should carry only what the next turn needs, and it needs more than the last eight entries: a real model shown only those no longer knows which orders were paid, so a real loop also carries a short summary of what is done. The stand-in needs no such summary.

Exercises

  1. Run the whole batch again from the start on the fixed main.flow, as a new run. How many lines does tools/ledger.txt have for A-1043 now?
  2. Undo the fix in main.flow and fork this morning's run at fact 21 again, naming no file. Which version of turn does the fork run, and what does the end of tools/calls.log show?
  3. Fork at fact 13 on the fixed program and read the ledger. Which customer was paid twice, and which call in tools/calls.log paid them?
  4. Rename turn to step everywhere in main.flow and fork at fact 21 again. Does the fork work, and which calls does tools/calls.log show it made?
  5. Fork this morning's run on the fixed program from its last fact before the End, so the fork copies every fact the run made. Does the ledger come out differently from the fork at fact 21, and why?