The runs library
On this page
This specification owns the runs library: the first-party library through
which a program reads other runs, checks and starts programs, and asks for the
same changes to a run that a person or an application can. It owns the
library's declarations, what each operation answers, how its typed reads and
starts compare types, which requests it refuses, and what its execution reads
answer.
It does not own what a change to a run does. Starting, stopping, replying,
resending, resuming and forking are
Running a program's, for every caller alike;
that a change is a request to the run's writer, and its receipt, are
Running a program's; a run's origin is the first
Program fact's (The history format). The types that name a place in a
run, the code model and code.Checked are std's
code module's. What a step is, is
Evaluation's. What a program may
see of its own run is
History's.
§1A first-party library
runs is a library of Tools under libraries/runs in Flow's own repository,
imported like any remote library:
use "github.com/buttercrab/flow@v1/libraries/runs"It is not part of std. Every std function is closed
(Standard library),
and every runs operation observes or changes something outside the run that
calls it. Its contract is generated from its Rust implementation like any
library's (The host boundary), and is versioned with the
library, not with the language.
Its implementation needs the host's own store of runs and the writers of the
runs it names, so a host that offers runs binds it by substitution
(The host boundary). A host that offers none binds it from its
flow.toml like any library, and there its implementation, which works only
inside a host, refuses to start, so a program that reaches its Tools is
refused before it starts.
§2Every operation is a Tool call
Each runs operation is one ordinary Tool call of the run that makes it,
recorded and replayed like any other. Replaying the caller serves the recorded
answers and never touches the run it named. A read is a recorded answer, so
another run's ids, positions and values reach a program as data, which the
one rule allows
(History).
A change a program asks for is the request any caller makes
(Running a program), sent to the target run's
writer like a person's. There is no second path and nothing privileged about
it. A code.RunId is an address, not a permission: who may read or change
which run is the host's decision, made outside Flow. The host of the asking
run may decline the call, which the program sees as NotStarted
(Tools). The writer of
the target run may refuse the request, which answers Declined.
Every operation answers Result<T, Error>, so a call has the two layers every
Tool call has: Err(problem) when no answer came back, and Ok(Err(error))
when runs answered with one of its own typed failures (Refusals).
§2.1The asking run itself
A program is never given its own run's id, task or call
(Code), but another run may
hand it its id as data. Every runs operation refuses the asking run itself
with OwnRun: wait on yourself never ends, stop and resume act on the
run that is asking, and a read describes a past the program could have kept
for itself. A change to, or a wait on, the run whose run call drives the
asking run is refused with DrivingRun.
These refusals are a convenience, not a guarantee. A loop through a third run stays possible, and stays deterministic, since every answer is recorded. Two runs that wait on each other wait forever, as any two held calls can; the remedy is a deadline in the program (Concurrency).
§3The contract
// github.com/buttercrab/flow@v1/libraries/runs/contract/lib.flow, generated by flow builduse "std@v1/code"use "std@v1/json"// Reading.pub flow status(run: code.RunId) -> Result<Status, Error>pub flow watch(run: code.RunId, after: Generation) -> Result<Status, Error>pub flow children(run: code.RunId) -> Result<List<Status>, Error>pub flow history(run: code.RunId, from: code.FactNumber, limit: Int) -> Result<Page, Error>pub flow program(run: code.RunId, segment: code.Segment) -> Result<code.Program, Error>pub flow calls<A, R>(run: code.RunId, tool: code.ToolRef<A, R>, which: Which = All) -> Result<List<Recorded<A, R>>, Error>// Checking and starting.pub flow check(bundle: code.Bundle) -> Result<code.Checked, Error>pub flow run<I, O>(program: code.Checked, entry: code.EntryRef<I, O>, input: I) -> Result<Ended<O>, Error>pub flow start<I, O>(program: code.Checked, entry: code.EntryRef<I, O>, input: I, name: Option<RunName> = None) -> Result<Child<O>, Error>pub flow run_untyped(program: code.Checked, input: json.Value) -> Result<Ended<code.Value>, Error>pub flow start_untyped(program: code.Checked, input: json.Value, name: Option<RunName> = None) -> Result<Child<code.Value>, Error>pub flow child<I, O>(run: code.RunId, entry: code.EntryRef<I, O>) -> Result<Child<O>, Error>pub flow child_untyped(run: code.RunId) -> Result<Child<code.Value>, Error>pub flow wait<O>(child: Child<O>) -> Result<Ended<O>, Error>// Changing, and trying a change first.pub flow fit(run: code.RunId, program: code.Checked) -> Result<Fit, Error>pub flow stop(run: code.RunId, out: CallsOut = Drain) -> Result<Status, Error>pub flow resume(run: code.RunId, program: Option<code.Checked> = None, drop: List<code.CallAt> = [], resend: Resend = Nothing) -> Result<Resumed, Error>pub flow fork(run: code.RunId, at: Cut, program: Option<code.Checked> = None, drop: List<code.CallAt> = [], name: Option<RunName> = None) -> Result<Forked, Error>pub flow reply<R>(call: CallId<R>, answer: Result<R, ToolProblem>) -> Result<Replied, Error>// Reading how a run executed.pub flow trace(run: code.RunId, from: code.Moment, limit: Int) -> Result<List<Step>, Error>pub flow frames(run: code.RunId, at: code.Moment) -> Result<List<Frame>, Error>pub flow local<T>(run: code.RunId, at: code.Moment, local: code.LocalRef<T>) -> Result<Option<Seen<T>>, Error>// A run and its state.pub type RunName(pub Text)pub type Generation(Int)pub type Status { pub run: code.RunId, pub name: Option<RunName>, pub state: State, pub open: List<code.CallAt>, pub facts: Int, pub origin: Origin, pub generation: Generation }pub type State { Running, Waiting, Stopping(StopReason), Stopped(StopReason), Completed }pub type StopReason { Asked { by: Option<code.RunId> }, Fault { fault: Fault, module: code.ModulePath, line: Int, column: Int }, ToolBug { call: code.CallAt, problem: ToolBug }, Working, Host { host: Text, words: Text }, Outer { run: code.RunId, call: Option<code.CallAt> },}pub type Fault { DivisionByZero, StoppedTask, FirstOfNone, CallDepth, ValueDepth, DecimalScale, IntSize, DecimalSize, TextSize }pub type ToolBug { NoAnswer(Text), NotAnAnswer(Text), ProcessEnded, Dropped }pub type Origin { Fresh, Called { run: code.RunId, call: code.CallAt }, Forked { from: code.RunId, at: code.FactNumber },}// What reads return.pub type Seen<T> { Present(T), Hole, Withheld, Omitted { bytes: Int } }pub type Answer<R> { Answered(Seen<Result<R, ToolProblem>>), Open { held: Bool }, Closed }pub type CallId<R> { run: code.RunId, at: code.CallAt }pub type Recorded<A, R> { pub id: CallId<R>, pub at: code.CallAt, pub latest: code.Segment, pub fact: code.FactNumber, pub site: code.Span, pub args: Seen<A>, pub answer: Answer<R> }pub type Which { All, Answers, OpenCalls, Problems }pub type Page { pub facts: List<Fact>, pub next: Option<code.FactNumber> }pub type Fact { pub number: code.FactNumber, pub segment: code.Segment, pub kind: FactKind }pub type FactKind { Program { entry: code.DeclId, input: Option<List<Seen<code.Value>>>, closed: List<code.CallAt> }, Call { at: code.CallAt, tool: code.DeclId, args: List<Seen<code.Value>> }, Reply { at: code.CallAt, outcome: Seen<Result<code.Value, ToolProblem>> }, Hold { at: code.CallAt }, Choice { task: code.TaskPath, first: code.TaskPath }, TaskStop { task: code.TaskPath, found: Found, closed: List<code.CallAt> }, End(Seen<code.Value>),}pub type Found { Running, Finished }// Starting and changing.pub type Child<O> { pub run: code.RunId, entry: Option<code.Signature> }pub type Ended<O> { pub run: code.RunId, pub segment: code.Segment, pub result: O }pub type CallsOut { Drain, Cancel }pub type Resend { Nothing, Calls(List<code.CallAt>), AllNotHeld }pub type Cut { Before(code.CallAt), After(code.CallAt), AtFact(code.FactNumber) }pub type Fit { pub reused: Int, pub dropped: List<Dropped>, pub live_at: Option<code.Moment> }pub type Dropped { pub at: code.CallAt, pub tool: code.DeclId, pub args: List<Seen<code.Value>>, pub state: CallState, pub replaced_by: Option<code.CallAt> }pub type CallState { Answered, Open, Held, Closed }pub type Resumed { pub fit: Fit, pub resent: List<Resent> }pub type Resent { pub at: code.CallAt, pub sent: Sent }pub type Sent { Sent, Unknown }pub type Forked { pub run: code.RunId, pub fit: Fit }pub type Replied { Admitted, AlreadyAnswered(Agreement) }pub type Agreement { Same, Different }// How a run executed.pub type Step { pub at: code.Moment, pub site: code.Span, pub event: Event }pub type Event { Enter { function: Callee, args: List<Seen<code.Value>> }, Bind { local: code.LocalId, value: Seen<code.Value> }, Branch(Taken), Call { tool: code.DeclId, at: code.CallAt, args: List<Seen<code.Value>>, answer: Answer<code.Value> }, Spawn { child: code.TaskPath }, Await { task: code.TaskPath }, First { winner: code.TaskPath }, Stop { task: code.TaskPath }, Return { function: Callee, value: Seen<code.Value> },}pub type Callee { Declared(code.DeclId), Local(code.LocalId), Anonymous(code.Span) }pub type Taken { Then, Else, Arm(Int) }pub type Frame { pub function: Callee, pub site: code.Span, pub locals: List<Local> }pub type Local { pub id: code.LocalId, pub name: code.Name, pub ty: code.Type, pub value: Seen<code.Value> }// Failures.pub type Error { NoSuchRun(code.RunId), NoSuchCall(code.CallAt), NoSuchMoment(code.Moment), Declined(Text), Unreachable(Text), DoesNotCheck(List<code.Diagnostic>), Refused(List<code.Diagnostic>), NameInUse(RunName), Mismatch(Mismatch), Incomplete { last: code.Moment }, NotStopped, AlreadyEnded, EntryChanged { was: code.Signature, now: code.Signature }, Diverged { fact: code.FactNumber, reason: Text }, Unconfirmed(List<code.CallAt>), OwnRun, DrivingRun,}pub type Mismatch { NoDeclaration(code.DeclId), Signature { wanted: code.Signature, found: code.Signature }, NoLocal { function: code.DeclId, name: code.Name }, LocalType { local: code.LocalId, mismatch: code.TypeMismatch }, Value(code.TypeMismatch),}Every id and position is code's: code.RunId, code.TaskPath,
code.CallPosition, code.CallAt, code.Segment, code.FactNumber and
code.Moment (Code). runs
declares none of its own. CallId<R> is not a new id: it is a call's key, a
run id and a call id, carrying the type R its answer must have.
CallId<R>, Child<O> and Generation have private fields or a private
constructor, so a program never builds one; it receives them from runs.
That proves nothing: private fields don't block decoding
(Tools), and runs checks every
one it is given again.
§4Reading
| Operation | Answers |
|---|---|
status(run) |
the run's Status |
watch(run, after) |
the run's Status, once its generation is above after; at once if it already is |
children(run) |
the Status of each run whose origin is Called by a call of run |
history(run, from, limit) |
at most limit facts from fact from on, and where the next page starts |
program(run, segment) |
that segment's program, as a code.Program |
calls(run, tool, which) |
the calls of one Tool, in fact order |
- A status gives the run's state, as the host shows it
(Running a program), with its stop reason when it
is stopping or stopped (Running a program); its open calls;
how many facts it has; its origin, from its first
Programfact (The history format); and its generation. - A generation is a number the host keeps for each run. It rises with
every commit to the run and every change of its state, and it never falls,
across a restart of the host included. A watcher compares generations, not
states, so a run that stopped, was resumed and stopped again still wakes it.
watchholds its call until then; a program that wants a limit wraps it intime.timeout(Concurrency). - A page of history has one
Factper fact, one variant per fact kind (History), with each value as acode.Value, so every value a history holds can be read. AProgramfact'sinputisSomeon the first fact, the entry's input, one value per parameter in declaration order, andNoneon later ones, which run the same input. Host notes are not facts and are never in it.nextisNoneon the last page. - A recorded call is a
Recorded<A, R>:id, to reply to it while it is open;at, its id;latest, the latest segment whose program made the call;fact, the fact that answered it, or that recorded it when it is open;site, the code that made it, in the program oflatest; its arguments; and its answer.whichkeepsAllthe calls, thoseAnswersadmitted, theOpenCalls, or theProblems: those answered with aToolProblem. Seen<T>isPresent(value), or why there is none: aHolethe host withheld (The history format),Withheldbecause it was computed from a withheld value, orOmittedbecause it is larger than the host will send, with its size. A value with any part missing is not present.Answer<R>isAnsweredwith the call's outcome,Openwith whether aHoldnames it (History), orClosedwhen it closed with no answer.
Typed reads are nominal. calls compares the signature tool names with
the one the target recorded, by declaration identity
(The host boundary), never by shape. A Tool the target
never declared answers Mismatch(NoDeclaration(..)), and one whose signature
differs answers Mismatch(Signature { .. }) with both signatures. Once the
signatures agree, every value decodes at A and R as
code.decode
does.
§5Checking and starting
| Operation | Does |
|---|---|
check(bundle) |
checks a bundle and answers its code.Checked, or DoesNotCheck with its diagnostics; starts nothing |
run(program, entry, input) |
starts a child the call drives, holds the call until the child ends, and answers its result |
start(program, entry, input, name) |
starts a child of its own and answers a Child<O> at once |
run_untyped, start_untyped |
the same, for a program whose types the caller does not know |
child(run, entry), child_untyped(run) |
a Child<O> for a run found another way, such as through children |
wait(child) |
holds the call until the child ends, and answers its result |
What starting does, the child's id, its origin, how it is bound and how it
stops are Running a program's. runs adds the types:
- Bundles are
code.Bundles.code.bundle(f)makes one from this program's own modules, and a program can build one from text, such as code a Tool wrote. A program read from another run turns back into a bundle with its modules' texts.runsnever reads a file. - A
code.Checkedis checked again whenever it is used (Code). A bundle that no longer checks answersDoesNotCheck. - Input and result are nominal.
code.EntryRef<I, O>carries the entry's signature (Code).run,startandchildcompare it with the entry of the program they start or find, by declaration identity, and any difference answersMismatch(Signature { .. }).Iholds every argument, defaults included. - Untyped starts take the input any caller gives.
run_untypedandstart_untypedtake the input as a JSON object keyed by parameter key, as a run's input from the command line is (Running a program), and start the bundle's entry. Their result is acode.Value, which a program decodes withcode.decodeor turns into JSON withcode.to_json. An input that does not decode answersRefusedwith its diagnostics. - A child's result is its entry's result,
Okeven when that result is anErr. AChild<O>remembers the signature it was made with, andwaitanswers at that type; a child made untyped answers acode.Value.
use "std@v1/code"use "github.com/buttercrab/flow@v1/libraries/runs"use "./harness"use "./shared"type Trouble { Unanswered(ToolProblem), Runs(runs.Error) }/// Start the harness on one task and wait for its typed answer./// `harness.main` is declared `pub flow main(input: shared.Input) -> shared.Answer`.flow attempt(task: shared.TaskId, seed: Int) -> Result<runs.Ended<shared.Answer>, Trouble> = { let program = runs.check(code.bundle(harness.main)).map_err(Unanswered)?.map_err(Runs)? let input = shared.Input { task, seed } let child = runs.start(program, code.entry(harness.main), input, name: Some(runs.RunName("attempt"))).map_err(Unanswered)?.map_err(Runs)? Ok(runs.wait(child).map_err(Unanswered)?.map_err(Runs)?)}.map_err(Unanswered)? handles the outer layer, a call that got no answer;
.map_err(Runs)? handles runs' own failure. Both keep their types inside the caller's
Trouble.
§6Changing, and trying a change first
| Operation | The request (Running a program) | Answers |
|---|---|---|
fit(run, program) |
none: a dry run of resuming onto program, which changes nothing (Running a program) |
the Fit that resume would make |
stop(run, out) |
stop the run; Cancel cancels the calls already out instead of letting them drain (Running a program) |
the run's Status once its flow.stopped note is committed |
resume(run, program, drop, resend) |
resume a stopped run, on program when given (Running a program) |
the Fit it acted on, and what it resent |
fork(run, at, program, drop, name) |
fork the run at a cut, on program when given (Running a program) |
the new run's id and its Fit |
reply(call, answer) |
reply to an open call (Running a program) | Admitted, or AlreadyAnswered, saying whether the recorded outcome is the same |
- A fit says how many recorded calls the program reuses, every call a
resume onto it would drop with whether it was answered or open and the
call, if any, the program makes in its place, and the moment the run would
go live, or
Nonewhen the program ends within the record. Where the program does not fit,fitanswers the error a resume would:EntryChanged, orDivergedwith the first recorded fact it does not reproduce and why. dropis the confirmation a resume onto edited code or a fork needs to drop calls (History, forks): the exact calls the request drops, compared as a set. Any other list is answeredUnconfirmedwith the calls it drops, and nothing changes.- With no program,
resumeandforkcontinue on the program the run's lastProgramfact records.runsnever looks for the file a run was started from. resendnames the open calls to send again:Nothing, the calls listed, orAllNotHeld, every open call that is not held. A stopped run never resends on its own. EachResentsays whether the call wasSent, orUnknownwhen a crash may have come between recording the resend and sending it (Running a program).- A cut is where a fork copies up to:
Before(c), every fact before theCallofc;After(c), every fact up to and including theReplythat answeredc, which must be answered; orAtFact(n), facts 1 ton. replyis typed by its id. ACallId<R>is answered with aResult<R, ToolProblem>, and the target checks it against the call's declared types again, answeringMismatch(Value(..))when it does not fit.
use "github.com/buttercrab/flow@v1/libraries/runs"use "./human"type Trouble { Unanswered(ToolProblem), Runs(runs.Error) }/// Answer one question a worker asked, as a person would.flow answer(q: runs.Recorded<human.Question, Result<human.Answer, human.AskError>>, given: human.Answer) -> Result<runs.Replied, Trouble> = Ok(runs.reply(q.id, Ok(Ok(given))).map_err(Unanswered)?.map_err(Runs)?)The reply sent, Ok(Ok(given)), is the Tool's own success. What remains after
the two ?s is reply's answer: Admitted, or AlreadyAnswered when
someone answered first.
Asking again is safe. Each change is committed with a receipt for the call that asked for it, so a caller that crashed and asks again, under the same key, gets the answer it was first given instead of acting twice (Running a program). A refusal leaves no receipt and is decided again.
§7Steps and moments
A program may read how another run executed, step by step. Nothing about steps is stored: the host rebuilds them by replaying the target's history, as Running a program says, so a read costs evaluation, not Tool calls, and the reader pays for it once, since its answer is recorded.
A step is one of the events
Evaluation defines, and a Step
is one step as data: its moment, its site, and its Event, one constructor
per kind of step, holding what that step concerns:
Event |
Holds |
|---|---|
Enter |
the function, and its arguments |
Bind |
the binding, and its value |
Branch |
the way taken: Then for an if or guard's first way, Else for its second, or Arm with the arm's index |
Call |
the Tool, the call's id, its arguments and its answer |
Spawn, Await, First, Stop |
the task it concerns, or the task first picked |
Return |
the function, and its value |
A step's site is the span of the source that made it, in the program of the
segment that is evaluating:
enter: the call that entered the function. A function std calls back is entered at the call into std that led to it, and a task's first function at the call that started the task, such astask.spawn,task.maportask.all. The root task's entry function, which no call in the program enters, is entered at its declaration.bind: the binder.branch: theiforguardexpression, or the body of thematcharm taken.call,spawn,await,firstandstop: the call that made it, or for a Tool call std makes, the call into std that led to it.return: thereturnor?that returned, or the function's body when it returned through its value.
A function is Declared when it is a top-level declaration, Local when it
is a local function, by its binding, and Anonymous by the span of the
flow(..) that wrote it.
A moment is a code.Moment
(Code): the segment whose
program is evaluating, the task's last call, and the steps since, counted as
semantics.md counts them, so root#0+0 is a task's start. A moment is the same
under replay, under resume on the same program, and in a fork up to its cut.
After a resume onto edited code, the new segment's steps are the new
program's, which is why a moment names the segment evaluating.
| Operation | Answers |
|---|---|
trace(run, from, limit) |
at most limit of the task's steps, from from on |
frames(run, at) |
the task's stack at at, innermost first: each frame's function, the span it is at, and its bound locals, each with its name, type and value; a std function's call, which takes no step, has no frame, and the frame around it is at the call into std |
local(run, at, local) |
the value of local in the innermost frame of its function at at, or None when there is no such frame or the local is not bound yet |
localis the checked read. A target program without the function or locallocalnames answersMismatch(NoLocal { .. }), and a local of another typeMismatch(LocalType { .. }).framesis the dynamic read, for code the program does not know. Each value is acode.Value; a function, a task or a host value appears with its type and nothing else, as its shape says (Code).- A moment the run never reached answers
NoSuchMoment. A moment past the step where replay needs a value that is a hole answersIncomplete, withlast, the last moment of the task that can be rebuilt.
A program reads another run's steps but never its own: a read of another run is a recorded answer, while a read of its own steps would be recomputed from its own program on every replay, and unlike a Tool call a step does not survive a change to code the program does not own, such as renaming a helper in a library it uses.
§8What reads copy
A read copies values from the target's history into the reader's, and runs
does not follow the copies. A host that withholds values of a run
(The history format) cannot reach the copies another run holds, so a
host that must be able to withhold a run's values declines the reads that
would copy them, answering Declined.
§9Refusals
| Error | When |
|---|---|
NoSuchRun |
no run has the id, or the host cannot find it |
NoSuchCall |
the run never made the call, or After names a call with no answer |
NoSuchMoment |
the task never reached the moment |
Declined |
the target run's host refused the request, with its words |
Unreachable |
the target run's writer could not be reached, with what failed |
DoesNotCheck |
the bundle does not check |
Refused |
the run could not start: an input that does not decode, a Tool nothing binds, a library that fails to start (Running a program) |
NameInUse |
another run holds the name |
Mismatch |
a type or a declaration differs from the one named |
Incomplete |
replay of the target cannot rebuild the moment: it needs a value that is a hole |
NotStopped |
resume of a run that is not stopped |
AlreadyEnded |
stop or resume of a run that recorded End |
EntryChanged |
the program's entry differs from the run's |
Diverged |
an edited program does not reproduce the run's record |
Unconfirmed |
a resume or fork drops calls drop does not name exactly |
OwnRun, DrivingRun |
the request names the asking run, or the run driving it (The asking run itself) |
A refusal changes nothing in the target and leaves no receipt.
§10Considered and set aside
An opaque run handle. It would act as a token whose possession grants access. Who may act on a run is the host's decision, so a run is named by its id, which is only an address.
Positions as text to parse. Every reader would parse them again, and a typo would be a wrong position instead of an error.
Matching a child's input or another run's types by shape.
billing.Receipt { cents } would pass as shipping.Weight { cents }.
A child sending values to the run that started it. That would be a second
way into a run. watch and wait are ordinary calls that wait.
Stored steps. Every step can be rebuilt by replay, so storing them would make every run pay for reads few runs make.
§11Related documents
- Running a program owns every request to a run and how a child runs.
- The history format owns how a run's origin is recorded, and Running a program receipts and the causes of a stop.
- Code owns the places in a run, the code model and checked references.
- History owns facts, keys, open calls, continuing on edited code and forks.
Serves foundations: Closed, deterministic evaluation; Replay and resume read one history; The application stays in charge.