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 ↗

Waiting for the manager

Dana's refund went through on its own, but most refunds at the desk don't. Before the shop pays back money, a manager has to say yes, and the manager reads the queue once a day, in the morning.

So a refund that comes in at six in the evening has to wait overnight, and the question is where. Written as ordinary code, the program that asked is still running, blocked on an answer, until tonight's deploy restarts the server and takes the process with it, along with the fact that anyone asked. The usual fix is a table: write the request down with a status column, exit, and have a job pick it up when the answer arrives. It works, and it is a second program whose only job is remembering where the first one stopped, with its own schema and its own bugs. Why Flow sketched one for desk.py.

A person is a Tool

In Flow the manager is a Tool, in a library like payments:

use "./tools"pub flow main(order: Text, dollars: Int) -> Text =    match tools.ask_manager("Refund ${dollars} dollars on ${order}?") {        Ok(Approve) => "Approved: refund ${dollars} dollars on ${order}",        Ok(Deny) => "Denied: no refund on ${order}",        Err(problem) => "No decision: ${problem}",    }
Ask the manager, then say what was decided.
// Generated by flow build from python module tools. Do not edit.// from tools.py: Answerpub type Answer { Approve, Deny }/// Put a question to the manager. A person answers it, later.// from tools.py: ask_managerpub flow ask_manager(question: Text) -> Answer
The manager's Tool as the program sees it.

Nothing in the contract says a person answers ask_manager. The program knows the question it sends and the answers it accepts, Approve or Deny, and whether a person, a rule or a model gives that answer is up to the library. Here it's a person, and a person doesn't answer while a function waits, so the function doesn't wait:

def 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 ask_manager(question: str) -> Answer:    """Put a question to the manager. A person answers it, later."""    return answered(Answer, question)
Show all 49 lines of tools/tools.py
# The manager's Tool. A person answers it, so the function can't answer while# the call waits: it writes the question with the call's key to questions.txt# and holds. The manager saves an answer with answer.py, and the Tool returns it# when the run asks again.import jsonfrom dataclasses import dataclassfrom pathlib import Pathfrom flow_toolkit import DecodeError, Hold, context, from_json, log, tool, variant@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 ask_manager(question: str) -> Answer:    """Put a question to the manager. A person answers it, later."""    return answered(Answer, question)
The manager's Tool posts the question with its call's key and holds the call until an answer is saved for that key.

raise Hold() is the library's promise to answer later. Flow writes the promise down and keeps the call open. Getting the question to the manager and the answer back is the library's own business, and the call's key, context().key, is what ties the two together: the run's id and the call's id, the same every time this call is asked. A real library would post the question to a chat channel or an approvals queue. This stand-in writes it to questions.txt, with the key in front, and you play the manager at the terminal.

The manager answers with the library's other half, a script that saves the answer under the question's key:

# 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 manager's side: save an answer for a key.

When the run asks the call again, answered finds the saved answer, reads it as an Answer and returns it. Until then, every time it's asked, it holds.

In the browser you can play the manager from the menu, including the evening when nobody has answered yet:

Ask the manager
main.flow
use "./tools"

pub flow main(order: Text, dollars: Int) -> Text =
    match tools.ask_manager("Refund ${dollars} dollars on ${order}?") {
        Ok(Approve) => "Approved: refund ${dollars} dollars on ${order}",
        Ok(Deny) => "Denied: no refund on ${order}",
        Err(problem) => "No decision: ${problem}",
    }
tools/contract/lib.flow
// Generated by flow build from python module tools. Do not edit.

// from tools.py: Answer
pub type Answer { Approve, Deny }

/// Put a question to the manager. A person answers it, later.
// from tools.py: ask_manager
pub flow ask_manager(question: Text) -> Answer
Expected "Approved: refund 40 dollars on A-1042"

The browser shows a waiting run, but it can't continue one. Continuing is the point of this chapter, so the rest happens on your computer.

In the evening

In 3-manager-answers-tomorrow from the support-desk project, start the refund:

flow run main.flow order=A-1042 dollars=40run fa7d0d4e4da6fa7d0d4e4da6 waiting: every open call waits for a replyopen root#1, held by its implementation  key: fa7d0d4e4da6fa7d0d4e4da6fa7d0d4e/root#1  tools.ask_manager    arguments: {"question":"Refund 40 dollars on A-1042?"}reply details: flow show fa7d0d4e4da6 'root#1'next: flow show fa7d0d4e4da6

The command has returned and its process has exited, with status 3: the run is open, waiting for an answer. open root#1 is the call that's waiting, the run's first, and the lines under it give its key and say what was asked. The library has posted the question:

cat tools/questions.txtfa7d0d4e4da6fa7d0d4e4da6fa7d0d4e/root#1 Refund 40 dollars on A-1042?

Nothing of the run is in memory anywhere. All of it is in one directory, under runs in FLOW_HOME:

ls -1 "${FLOW_HOME:-$HOME/.flow}"/runs/fa7d0d4e4da6*historylock
flow runsfa7d0d4e4da6	waiting	main.flow	…		1 call held

history is the record you read in What the run was told, with the program's source inside it. lock is held by whichever process is writing the run, and none is now. A desk with a hundred refunds waiting has a hundred of these directories and no processes.

The record ends at the question and the library's promise:

flow show fa7d0d4e4da6run fa7d0d4e4da6state: waitingopen root#1 tools.ask_manager, held by its implementation  question = "Refund 40 dollars on A-1042?"  returns tools.Answer  key: fa7d0d4e4da6fa7d0d4e4da6fa7d0d4e/root#13 of 3 facts · 0 hidden   1 Program    fa7d0d4e4da6 ./main.main       order = "A-1042"       dollars = 40   2 Call       root#1 tools.ask_manager       question = "Refund 40 dollars on A-1042?"   3 Hold       root#1 held: its implementation promised to answer laterhost activity (4 records; not semantic facts):…full host records: flow show fa7d0d4e4da6 --json

There's no answer and no end, and nothing in the record itself says "waiting": the state line is the command's reading of it. As far as the run is concerned it asked a question, was promised an answer, and hasn't heard back. A waiting run has no special state; its record simply stops at a call with no answer.

The next morning

The manager reads the question and answers. Whatever carries that answer, a form, a chat message, an email, it is written as JSON, as a value of the call's result type: "Approve". The manager's first answer is "Maybe", saved under the question's key:

python3 tools/answer.py 'fa7d0d4e4da6fa7d0d4e4da6fa7d0d4e/root#1' '"Maybe"'

Saving an answer runs nothing; continuing the run does. A library that holds a call says that asking it again under its key is safe, so flow resume asks each held call once more. Naming the call with --resend asks it the same way, under the same key, and the CLI says so:

Goes wrong
flow resume fa7d0d4e4da6 --resend 'root#1'› "Maybe" is not an answer: 'Maybe' is not a constructor of Approve | Denynote: Open calls were selected for resend. The original call ID does not guarantee external deduplication; an external effect may happen again.fa7d0d4e4da6 waiting: every open call waits for a replyopen root#1, held by its implementation  key: fa7d0d4e4da6fa7d0d4e4da6fa7d0d4e/root#1  tools.ask_manager    arguments: {"question":"Refund 40 dollars on A-1042?"}reply details: flow show fa7d0d4e4da6 'root#1'next: flow show fa7d0d4e4da6

"Maybe" is not an answer. The library reads the saved text as an Answer, finds no such case, logs why and holds again, so the call stays open and nothing is recorded. A library never makes up an answer in place of one it can't read, and Flow checks whatever it does return against the call's type before the program sees it. The note is --resend being careful: Flow can't know what asking again does at the other end. Here it posts nothing twice, because the library posts a key only once.

The manager approves:

python3 tools/answer.py 'fa7d0d4e4da6fa7d0d4e4da6fa7d0d4e/root#1' '"Approve"'
flow resume fa7d0d4e4da6 --resend 'root#1'Approved: refund 40 dollars on A-1042note: Open calls were selected for resend. The original call ID does not guarantee external deduplication; an external effect may happen again.fa7d0d4e4da6 completednext: flow replay fa7d0d4e4da6
flow replay fa7d0d4e4da6Replay fa7d0d4e4da6: matchedNo tools were called.

The morning's process read the record and ran main from the top, from the source stored in the record, so it doesn't matter whether main.flow changed overnight. When the program reached the manager's call, the record had the question and no answer, and you had named the call with --resend, so the process asked the library again, under the same key and with the same question. The library returned the saved answer, Flow checked it against Answer and recorded it, and the run went on live to its end. Its history now has five lines: the three from the evening, the manager's answer, and the end.

What waiting costs

Nothing in Flow decides when to resume. A waiting run waits until something runs flow resume: the manager's button, a deadline in a scheduler, never. It doesn't expire and doesn't wake up on its own. That decision belongs to your application, and Answering calls from your own service shows a service making it.

A run waits like this only on a call its library holds. Any other call is waited for inside the process, as in any program, so a slow Tool that doesn't hold keeps its process alive until it answers.

LangGraph's interrupt() does the same job for a graph: it stops at a node, a checkpointer saves the graph's state, and you resume it with the person's answer. Since version 1.2.12 it can check that answer against a response_schema. In Flow the check isn't optional: whatever a library returns is checked against the call's type before the program sees it, and this library's own reading of the answer turned "Maybe" away before that.

What resume does is run the program again from the top. This program asked nothing before the manager, so there was nothing to repeat. The next morning is about a program that did.

Exercises

  1. Start three refunds with different orders and amounts, all waiting on the manager, then run flow runs. How would you tell which run is waiting on which order?
  2. Answer one of them with '"Deny"'. What does the run return, and how many lines does its history have?
  3. Save '"Deny"' for the finished run's key and ask its call again with --resend. What does flow resume say, and what would you do instead if the manager changed their mind?