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 ↗

Three carriers at once

Dana is getting a new lamp, and the desk wants it on a truck today. Three carriers can pick it up. Asking them one after another wastes the afternoon, so the desk asks all three at once and gives the parcel to whichever answers first. The manager signs off on every pickup the desk books.

You wrote the script for it in Python, and after the email Dana nearly got in Why Flow, you made sure a rerun asks nobody twice: every quote goes into a file the moment it arrives.

A pickup nobody approved

import asyncio, json, sysfrom pathlib import Pathfrom carriers import ask_manager, book_pickup, quoteSAVED = Path("quotes.json")  # every quote, kept so a rerun asks no carrier twiceasync def main(order):    saved = json.loads(SAVED.read_text()) if SAVED.exists() else {}    arrived = []    async def ask(carrier):        if carrier not in saved:            saved[carrier] = await quote(carrier, order)            SAVED.write_text(json.dumps(saved))        arrived.append(saved[carrier])    await asyncio.gather(ask("Parcelly"), ask("ShipFast"), ask("PostNord"))    first = arrived[0]  # the quickest carrier gets the parcel    answer = ask_manager(f"Book {first['carrier']} at {first['dollars']} dollars for {order}?")    if answer is None:        print("waiting for the manager")    elif answer == "Approve":        book_pickup(first["carrier"], order)        print(f"booked {first['carrier']} for {order}")asyncio.run(main(sys.argv[1]))
Ask three carriers at once, take the quickest, and book it once the manager agrees.
Show python/carriers.py · 25 lines
# Stand-ins for three carriers, the manager and the carriers' booking service.# Nothing leaves this directory.import asynciofrom pathlib import Path# How long each carrier takes to answer, in seconds, and its price in dollars.CARRIERS = {"Parcelly": (0.6, 15), "ShipFast": (0.2, 12), "PostNord": (0.4, 9)}async def quote(carrier, order):    seconds, dollars = CARRIERS[carrier]    await asyncio.sleep(seconds)    return {"carrier": carrier, "dollars": dollars}def ask_manager(question):    """Leave the question in question.txt; the manager writes answer.txt later."""    Path("question.txt").write_text(question + "\n")    answer = Path("answer.txt")    return answer.read_text().strip() if answer.exists() else Nonedef book_pickup(carrier, order):    with Path("pickups.txt").open("a") as pickups:        pickups.write(f"{carrier} picks up {order}\n")
Stand-ins for the carriers, the manager and the booking service. ShipFast answers quickest, then PostNord, then Parcelly.

asyncio.gather starts the three requests together. Each ask appends its quote to arrived when it comes back, so arrived[0] is the quickest carrier's. As in Why Flow, the manager answers through a file, and until answer.txt exists the script stops and waits to be run again.

On Monday afternoon the three requests go out, all three carriers answer, and the question goes to the manager:

python3 ship.py A-1042waiting for the manager
cat question.txtBook ShipFast at 12 dollars for A-1042?

On Tuesday morning the manager writes Approve into answer.txt, and the script runs again:

Goes wrong
python3 ship.py A-1042booked Parcelly for A-1042
Goes wrong
cat pickups.txtParcelly picks up A-1042

The manager approved ShipFast at 12 dollars. Parcelly, at 15, is coming for the lamp.

The rerun asked nobody twice, just as you meant it to. All three quotes were on disk:

cat quotes.json{"ShipFast": {"carrier": "ShipFast", "dollars": 12}, "PostNord": {"carrier": "PostNord", "dollars": 9}, "Parcelly": {"carrier": "Parcelly", "dollars": 15}}

On Tuesday every ask found its quote already saved and returned at once, without waiting for anything. With nothing to wait for, the three finished in the order gather started them, and Parcelly was first in the list. The script kept every answer and still lost something Monday knew: the order the answers arrived in. Which quote came first is not in any of the quotes. It was a fact about Monday afternoon, and nothing wrote it down.

Fixing it in Python

The fix is small: save the winner next to the quotes, and on a rerun read it back instead of looking at arrived. It is the right fix, and it is the same lesson as the email's, one level down. Every point in a program where it waits for whichever thing happens first, a race, a timeout, a "first reply wins", needs its own saved entry, and the program has to read that entry back before it reaches the point again. A table of answers covers what the program was told. The order it was told things in needs a column of its own, and nothing reminds you to add it.

The same desk in Flow

use "std@v1/task"use "./tools"pub flow main(order: Text) -> Result<Text, ToolProblem> = {    let first = task.race([        flow() = tools.quote("Parcelly", order),        flow() = tools.quote("ShipFast", order),        flow() = tools.quote("PostNord", order),    ])?    match tools.ask_manager("Book ${first.carrier} at ${first.dollars} dollars for ${order}?")? {        Approve => tools.book_pickup(first.carrier, order),        Deny => Ok("not booked"),    }}
The desk again: ask three carriers at once, ask the manager about the first quote, book it.

use "std@v1/task" brings in the task module of the standard library. flow() = tools.quote("Parcelly", order) is a function with no parameters: the request, written down but not yet sent. task.race takes a list of them and starts each one as a task, a piece of the program that runs beside the others. It returns the result of the first task to finish, and before it returns it stops the others, so nothing it started is still running when the program moves on to the manager.

The carriers, the manager and the booking service are Tools in a Python library, as before. In this chapter you play the carriers and the manager yourself, so quote and ask_manager post their questions to questions.txt and hold their calls, as the manager's Tool did in Waiting for the manager, until an answer is saved for the call's key:

Show tools/tools.py · 70 lines
# The carriers, the manager and the booking service, as a Tool library.# Carriers and the manager answer by hand in this chapter: quote and ask_manager# write their questions to questions.txt and hold their calls until answer.py# saves an answer and the run asks again. Booking a pickup adds a line to# pickups.txt.import jsonfrom dataclasses import dataclassfrom pathlib import Pathfrom flow_toolkit import DecodeError, Hold, context, from_json, log, tool, variant@dataclass(frozen=True)class Quote:    carrier: str    dollars: int@variant@dataclass(frozen=True)class Approve:    pass@variant@dataclass(frozen=True)class Deny:    passAnswer = Approve | Denydef answered(kind, question):    """The answer answers.json holds for this call's key, read as kind. Until it    holds one, write the question with the key to questions.txt and hold."""    key = str(context().key)    questions = Path("questions.txt")    if key not in (questions.read_text() if questions.exists() else ""):        with questions.open("a") as file:            file.write(f"{key} {question}\n")    answers = Path("answers.json")    saved = json.loads(answers.read_text()) if answers.exists() else {}    if key not in saved:        raise Hold()    try:        return from_json(kind, saved[key])    except DecodeError as error:        log(f"{saved[key]} is not an answer: {error}")        raise Hold()@tooldef quote(carrier: str, order: str) -> Quote:    """Ask a carrier for a pickup price. The carrier answers later."""    return answered(Quote, f"{carrier}: a pickup price for {order}?")@tooldef ask_manager(question: str) -> Answer:    """Put a question to the manager. A person answers it, later."""    return answered(Answer, question)@tooldef book_pickup(carrier: str, order: str) -> str:    """Book a carrier to pick up an order."""    with Path("pickups.txt").open("a") as pickups:        pickups.write(f"{carrier} picks up {order}\n")    return f"booked {carrier} for {order}"
The library. quote and ask_manager post their questions and hold their calls for an answer by hand; book_pickup adds a line to pickups.txt.
Show tools/answer.py · 11 lines
# The person's side of questions.txt: python3 tools/answer.py KEY ANSWER saves# ANSWER, written as JSON, for the question KEY names. The Tool reads it when# the run asks that call again, with flow resume RUN --resend CALL.import jsonimport sysfrom pathlib import Pathkey, answer = sys.argv[1], sys.argv[2]answers = Path(__file__).with_name("answers.json")saved = json.loads(answers.read_text()) if answers.exists() else {}answers.write_text(json.dumps({**saved, key: answer}, indent=2) + "\n")
The carriers' and the manager's side: save an answer for a question's key.

Monday

Start the run:

flow run ship.flow order=A-1042run 5c29fadac2695c29fadac269 waiting: every open call waits for a replyopen root/1#1, held by its implementation  key: 5c29fadac2695c29fadac2695c29fada/root/1#1open root/2#1, held by its implementation  key: 5c29fadac2695c29fadac2695c29fada/root/2#1open root/3#1, held by its implementation  key: 5c29fadac2695c29fadac2695c29fada/root/3#1  tools.quote    arguments: {"carrier":"Parcelly","order":"A-1042"}  tools.quote    arguments: {"carrier":"ShipFast","order":"A-1042"}  tools.quote    arguments: {"carrier":"PostNord","order":"A-1042"}next: flow show 5c29fadac269

All three requests went out before any answer came back. Each open call is named for where it sits in the program: root/2#1 is the first call of the second task that the run's root started, which is ShipFast's. Timing plays no part in the names, so they are the same in every run, and each call's key is the run's id followed by that name. The library has posted all three questions:

cat tools/questions.txt5c29fadac2695c29fadac2695c29fada/root/1#1 Parcelly: a pickup price for A-1042?5c29fadac2695c29fadac2695c29fada/root/2#1 ShipFast: a pickup price for A-1042?5c29fadac2695c29fadac2695c29fada/root/3#1 PostNord: a pickup price for A-1042?

ShipFast answers first, with 12 dollars:

python3 tools/answer.py '5c29fadac2695c29fadac2695c29fada/root/2#1' '{"carrier": "ShipFast", "dollars": 12}'

Continue the run and ask ShipFast's call again, so the library can return the quote it now has:

flow resume 5c29fadac269 --resend 'root/2#1'note: Open calls were selected for resend. The original call ID does not guarantee external deduplication; an external effect may happen again.5c29fadac269 waiting: every open call waits for a replyopen root#1, held by its implementation  key: 5c29fadac2695c29fadac2695c29fada/root#1  tools.ask_manager    arguments: {"question":"Book ShipFast at 12 dollars for A-1042?"}reply details: flow show 5c29fadac269 'root#1'next: flow show 5c29fadac269

The run is waiting for the manager, with the same question the Python script asked. Here is its record so far:

flow show 5c29fadac269 | head -31run 5c29fadac269state: waitingopen root#1 tools.ask_manager, held by its implementation  question = "Book ShipFast at 12 dollars for A-1042?"  returns tools.Answer  key: 5c29fadac2695c29fadac2695c29fada/root#113 of 13 facts · 0 hidden   1 Program    5c29fadac269 ./ship.main       order = "A-1042"   2 Call       root/1#1 tools.quote       carrier = "Parcelly"       order = "A-1042"   3 Call       root/2#1 tools.quote       carrier = "ShipFast"       order = "A-1042"   4 Call       root/3#1 tools.quote       carrier = "PostNord"       order = "A-1042"   5 Hold       root/1#1 held: its implementation promised to answer later   6 Hold       root/2#1 held: its implementation promised to answer later   7 Hold       root/3#1 held: its implementation promised to answer later   8 Reply      root/2#1 Ok       value = {"carrier":"ShipFast","dollars":12}   9 Choice     root picked root/2  10 TaskStop   root/1 found running, closing root/1#1  11 TaskStop   root/3 found running, closing root/3#1  12 Call       root#1 tools.ask_manager       question = "Book ShipFast at 12 dollars for A-1042?"  13 Hold       root#1 held: its implementation promised to answer laterhost activity (12 records; not semantic facts):…

Each numbered entry is one fact in the record. Facts 5 to 7 are the library's promises to answer the three quotes later, in the order its three calls happened to get to them, which can differ from run to run and changes nothing. Fact 9 is the one quotes.json was missing. It is a Choice: the race picked the second task, ShipFast's, because that task finished first, its answer recorded as fact 8. No line of the program says which task wins, and no answer does either. What the runtime chooses lists every pick that is recorded this way.

Facts 10 and 11 stop the two losers. Neither had answered, so both open calls were closed, and nothing can answer them now. When PostNord's quote of 9 dollars comes in a moment later, the race has already been decided, and the run never asks for it.

Tuesday

The manager approves:

python3 tools/answer.py '5c29fadac2695c29fadac2695c29fada/root#1' '"Approve"'
flow resume 5c29fadac269 --resend 'root#1'Ok("booked ShipFast for A-1042")note: Open calls were selected for resend. The original call ID does not guarantee external deduplication; an external effect may happen again.5c29fadac269 completednext: flow replay 5c29fadac269
cat tools/pickups.txtShipFast picks up A-1042

Tuesday's process ran main from the top, as the Python script did, and reached the race with ShipFast's quote already in the record. Nothing was left to arrive in any order, which is exactly where ship.py went wrong. Instead of looking at what finished first, the race read fact 9 and took ShipFast's quote, then stopped the other two tasks as facts 10 and 11 say. The manager's answer fitted the question, because it was the same question.

A replay, which has every answer in hand at once, makes the same pick:

flow replay 5c29fadac269Replay 5c29fadac269: matchedNo tools were called.

Why Flow said that the record would hold one more kind of thing for programs that do several things at once. The Choice is that thing: whatever the program could not have computed is written down, and which of several things finished first is one of them.

A deadline is a race against the clock

The manager took a night to answer Monday's question. The desk's rule is that the manager gets 48 hours, and after that the team lead decides. The program can say so:

use "std@v1/time"use "std@v1/duration"use "./tools"// The manager has 48 hours to answer. After that, the team lead decides.pub flow main(question: Text) -> Text =    match time.timeout(duration.seconds(48 * 3600), flow() = tools.ask_manager(question)) {        Done(Ok(Approve)) => "approved",        Done(Ok(Deny)) => "denied",        Done(Err(problem)) => "no decision: ${problem}",        TimedOut => "no answer in 48 hours: sent to the team lead",        ClockFailed(problem) => "no decision, the clock failed: ${problem}",    }
The manager's question with a deadline. time.timeout races the call against a timer.

time.timeout runs the manager's call against time.sleep for 48 hours, as two tasks, and stops whichever loses. It returns Done with the call's result, TimedOut, or ClockFailed if the clock itself went wrong. The clock in the standard library is a set of Tools that your application answers, like any other Tool, so the program still reads no clock of its own, and a replay knows which side won from a Choice, as before.

Nobody wants to wait two days to see the team lead get the question. A test can check it instead:

use "std@v1/time"use "std@v1/duration"use "./tools"use "./deadline"/// A manager who answers after three days.@fake(tools.ask_manager) flow slow_manager(_: Text) -> Result<tools.Answer, ToolProblem> = {    let _ = time.sleep(duration.seconds(72 * 3600))    Ok(Approve)}@test flow goes_to_the_team_lead_after_48_hours() -> Result<Unit, Text> =    match deadline.main("Book ShipFast at 12 dollars for A-1042?") {        "no answer in 48 hours: sent to the team lead" => Ok(()),        other => Err(other),    }
A manager who takes three days, and a test that expects the team lead.

A function marked @test is a test, and it passes when it returns Ok(()). A function marked @fake(tools.ask_manager) is written in Flow and answers that Tool's calls while the tests run. This manager sleeps for three days before approving. Tests run on a virtual clock (testing in the Reference), so the three days take no time at all:

flow test test.flowok   test.flow goes_to_the_team_lead_after_48_hours1 passed, 0 failed

What a race decides

A race picks whoever finished first, and that is all it picks. On Monday PostNord's 9 dollars lost to ShipFast's 12 by arriving later, because the desk valued a pickup today over three dollars. A desk that wanted the cheapest carrier would wait for all three with task.map_all, which returns every result in the order you listed the carriers and records no Choice, because it picks nothing.

Stopping a task means the program takes no further steps in it. A call that is still open, like Parcelly's, is closed, and the host calls its library once more with the call marked cancelled, so a library that posted a request somewhere can withdraw it. This stand-in posted nothing. Whether the carrier's system ever hears about it is up to the library, and the TaskStop fact records only that the run stopped waiting.

Exercises

  1. Start a new run, save PostNord's quote and ask only its call again. Which question does the manager get, and what does the Choice fact say?
  2. Save all three quotes, then resume with --resend naming all three calls. Run flow show and find the Choice and the TaskStop facts. Which carrier won, and would it win again in another run?
  3. In test.flow, change 72 * 3600 to 24 * 3600 and run flow test test.flow again. What does the test report, and why did the manager win this time?
  4. Change ship.flow to ask the carriers with task.map_all and give the parcel to the cheapest quote. Run it and look for a Choice in its record.
  5. Fix ship.py so Tuesday books the carrier the manager approved. Then make the script also give up on a carrier that takes longer than half a second, and decide what your fix must save for that.