Python SDK
The SDK does what the client does, from Python. If you can type it in a terminal, you can call it from a program.
Installing
The SDK runs on the Python SDK Core, a proprietary compiled module licensed under the Client EULA. The Python SDK Core is not on PyPI. The client’s installer installs it with the client, so install the client first:
1 | curl https://testflows.com/machine/install -fsS | bash |
Then install the SDK from PyPI:
1 | pip3 install testflows.machine |
It needs Python 3.11 or later, on the systems the client runs on: Linux x86_64 and arm64, and Macs with Apple Silicon. If you need another platform, contact us.
Without the Python SDK Core, import testflows.machine.v1 raises ImportError with
the installer’s command. Running the installer again updates the client and
the Python SDK Core together.
Hello Machine
1 | import testflows.machine.v1 as machine |
This creates a session, boots a run from the disk hello and prints the last
twenty lines of its console. A run waits for commands, so it moves only when
you call run.run(...); pass daemon=False to have it run to the end by
itself.
Leaving a with block deletes what it created, whether the block ends normally
or with an error. That is how you make sure a session never outlives your
program.
The same names
Every client command has a matching SDK call, and the names follow a simple rule.
| In the client | In the SDK |
|---|---|
a top-level command, machine create --disk app |
a method on the client, client.create(disk="app") |
a group, machine sessions use ci-1 |
an attribute of the client, client.sessions.use("ci-1") |
a command that takes a run, machine fork app --at ^boot |
a method on the run, run.fork(at="^boot") |
a group that takes a run, machine tasks app hold 56 |
an attribute of the run, run.tasks.hold(56) |
| a positional argument | a positional argument |
a flag like --no-wait, -w or -f |
a keyword argument like wait=False, watch=True or follow=True |
So once you know the client, you know most of the SDK. Commands
lists them, and the client’s --help says what each call takes.
Signing in
The SDK signs in with an API key from TESTFLOWS_MACHINE_API_KEY if it is set.
If it isn’t, it uses the login that machine login stored, which it shares
with the client. Without a login, it uses the API key saved for the client with
machine account api-keys create --save, which a coding agent saves when it
signs the client in.
A program can also sign in by itself with a one-time code, which arrives by email:
1 | machine.login.start("me@example.com") |
machine.login.logout() signs out.
Sessions
A client has a current session, like the CLI does. You can set it when you create the client, or later.
1 | client = machine.Client(session="ci-1") # like -s ci-1 |
sessions.use only changes the session for this client. It never changes it for
the machine command. Without a session you can still read your account’s runs:
client.runs(), client.branches() and a run’s describe(), lineage()
and checkpoints() all work.
client.sessions does what machine sessions
does. A session is a context manager, so leaving the with block deletes it:
1 | with client.sessions.create("ci-1", cpus=4, mem=8192) as session: |
| Call | Does |
|---|---|
client.sessions.create(name, cpus=..., mem=..., storage=..., class_=...) |
creates a session and waits until it runs; mem is in MB and storage in GB |
client.sessions(), client.sessions.show(name) |
lists them, or reads one |
client.sessions.keep(name, minutes) |
keeps a session running idle for that long |
client.sessions.rename(name, new_name), client.sessions.delete(name) |
renames or deletes one |
Disks
client.disks builds and manages disks, as machine disks
does. A build takes the same sources: binary, from_, image or compose.
1 | disk = client.disks.build("hello-py", from_="python:3.12-slim", |
image and compose read your local Docker, as --image and --compose do.
Disks says what each source needs.
| Call | Does |
|---|---|
client.disks(), client.disks.show(name) |
lists your disks, or reads one: name, size_bytes, state, labels |
client.disks.rename(name, new_name) |
renames one |
client.disks.delete(name) |
deletes one |
client.preload.disk(name), client.offload.disk(name) |
copies a disk into the session ahead of time, or drops the session’s copy; preload_and_offload.py shows both |
Runs
Here is a typical run, from creating it to branching and replaying.
1 | run = client.create("app", disk="app", rng=True) |
These are the calls used most often:
| Call | Does |
|---|---|
client.create(name, disk=..., cpus=..., ...) |
creates a run and boots it; takes every option machine create does |
client.runs(), client.runs["app"] |
lists runs, or finds one by name |
run.run(until=..., iters=...), run.plan(file) |
drives it |
run.checkpoint(name), run.checkpoints() |
saves a checkpoint, lists them |
run.fork(...), run.go(point), run.switch(branch), run.detach(...) |
branches |
run.replay(), run.play(...), run.diff(...) |
replays and compares |
run.hash() |
the hashes of the machine as it stands, memory and the disk included, as machine hash |
run.dump(show="regs"), run.vcpu() |
the machine’s state, and where one vCPU stopped |
run.rng(), run.rng.seed(7), run.fork(at="^booted", rng_seed=7) |
the RNG device’s seed, seeding it again, and a branch whose machine draws other random numbers |
run.run(irq_delay="blk=1ms", timer_slack="0:20ms"), run.irq.pending() |
hold interrupts a drawn time, draw how late a timer may be, and list the interrupts owed and held |
run.describe(), run.state(), run.now(), run.entries(...) |
reads it |
run.output(...) |
reads what it printed |
run.output.search(pattern, from_=..., to=...), run.output.find(pattern), run.output.entry(offset) |
finds text in what it printed, between two points if you like; each match has the entry that printed it and a place to go to |
run.output.sources(), run.output(source="ttyS1"), run.output.lines(source="all") |
lists the sources that printed, reads one, and reads them all with the source of each line |
run.fs.ls(path, at=...), .cat(...), .cp(...) |
reads its disk at a checkpoint, which at names |
run.send(text, device=...) |
sends input to a device or to a file in the machine, as machine send does; returns a Sent with queued, and process for a file |
run.exec(command), run.exec(command, wait=False), run.process(id), run.processes() |
executes a command in the machine, a list for a program and a str for a shell line, and returns its Process: pid, exit_code, stdout, stderr, events, exits |
run.exec(command, container="db", user="root") |
executes it in a container, named by its Compose service or by its own name, as a user of it |
run.exec(command, net="db") |
runs a program of the machine on db’s network, such as tcpdump on its eth0 |
run.core(pid, dest, container=...) |
gets a core dump of a process into a file; the process dies of it |
run.profile("2s", container=..., pid=...) |
samples what runs for a time and returns a Profile: samples, functions, stacks, and folded text for flame graph tools |
run.profile(from_="^request", to="^reply") |
profiles a stretch the run already recorded, without changing the run |
run.profile("2s", in_guest=True) |
samples with a process in the run, for the functions of the kernel by name |
run.containers(), run.containers.kill("db", restart="5s"), run.containers.crash("db", restart="0") |
lists the containers, the Compose service of each, and its addresses and links; stop, kill, crash, start, pause, resume, throttle, memory, pids, ports and files put a fault on one, as machine containers does |
run.put(source, path, container=..., mode=..., owner=...) |
puts a file of any size into the machine or into a container of it; source is bytes or the path of a file |
run.get(path, dest, container=...) |
gets a file out, as it is now; returns a Got with size, mode, uid, gid, and data when no dest is given |
run.tasks(), run.focus.add(...), run.irq(...), run.vtime.rate(...) |
steers the machine |
run.inject.add("syscall", "read", "valid", in_="/usr/bin/app", pick=1, prob=0.1), run.inject.add("syscall", "read", delay="0:20ms", in_="/usr/bin/app"), run.inject.add("disk", in_="all", prob=0.01), run.inject.add("function", "malloc", ret=0, prob=0.01, in_="/usr/bin/app"), run.inject.add("disk-corrupt", in_="all", file="/var/lib/db/*/data.bin", op="write", bytes=8, times=1), run.inject(), run.inject.delete(2), run.inject.clear() |
injects faults as machine inject does: system calls fail with chosen errors or wait first, a program’s function returns ret without running, and the kernel’s disk, allocation, usercopy and futex-access sites fail, and the disk corrupts, tears or loses data; lists the faults with their counts, and deletes them; in_ takes the words --in takes, delay the span --delay takes, at the tid whose files hold the function, as --at takes it, and file, op, sectors and bytes the disk options |
run.tasks.exist("/usr/bin/app") |
returns the tasks running that program, comm, tid or tgid now, or raises NotFound; it changes nothing |
run.task(tid) |
a task of the machine to debug, by its tid: registers(), read(address, size), address("main+4"), symbol(address), symbols(regex="^wait"), backtrace(), libraries() |
task.set(rax=0, rip="main+4"), task.write(address, data) |
writes its registers and its tgid’s memory; a replay makes the writes again |
task.print("shape->at.x", frame=1), task.print("counter = 3"), task.locals(args=True) |
an expression in a frame, a write with TARGET = VALUE, the locals or the arguments of a frame |
task.step(), task.step(line=True, over=True), task.finish() |
steps an instruction or a line, over calls, or out of the function |
task.back(), task.back(line=True, over=True) |
goes back over the task’s code onto a branch, as reverse-stepi and reverse-next |
task.call("strlen", "buf"), task.return_(0) |
calls a function in the task, or returns from its innermost one |
task.breakpoint("main"), task.watch("counter", on="access") |
stops its tgid at a location, or at a write or an access of its bytes; run.run(...).hits names the one the run ended at |
run.breakpoints.catch("fork", in_="tgid=1"), run.breakpoints.catch("io", file="/db/*/data.bin", op="write") |
stops at an event of a task: exec, exit, fork, vfork, syscall, signal, load, unload, fault, io, throw, catch, rethrow; in_ takes the words --in takes, tid=N, tgid=N or comm=NAME; file and op are an io catchpoint’s, as --file and --op |
run.breakpoints.list(), .enable(2, False), .condition(2, "n > 3"), .ignore(2, 5), .delete(2), .hits() |
the run’s stops, changed one at a time, and the hits the run log keeps |
run.run(iters=0), run.run(until="tid=412:at=main"), run.back() |
runs to the next hit, or until a task reaches a location; goes back onto a branch at the newest hit |
run.tasks.signal(412, "SIGTERM") |
sends a task a signal; a replay sends it at the same instruction |
run.start(), run.stop(), run.pause(), run.kill(), run.delete() |
lifecycle |
run.start(at="^booted"), run.start(at="^booted", read_only=True), run.start(recover=False) |
replays from a checkpoint to the tip, opens a checkpoint to read, or refuses to replay the tail, as machine start does |
run.fork(from_="^booted", name="b"), run.rewind("^booted") |
a branch forked at the checkpoint before a point and replayed to it; the run put back at a checkpoint |
run.sync(), run.cancel(), run.cancel(soft=True) |
publishes the run to your storage; cancels the drive or checkpoint in progress, at once or, with soft=True, at the end of the dispatch in progress so the run stays repeatable |
client.create(disk="app", instr_margin=100000, dispatch_bound="2s"), run.replay(instr_margin=100000), run.describe().repeats_to |
sets where a recording stops, as Recording that repeats describes; replays with that margin; the first entry where recording the run again stops repeating, None when it repeats to its tip |
run.keep() |
keeps a run created in a with block when the block exits, such as one that just failed, with its tree |
run.marks.add("good"), run.marks.list(), run.marks.remove("good"), client.marks.list() |
names a branch, as Marks describes; the last lists every mark |
run.tasks.hold(56), .release(56), .yield_(56), .slice(56, "10us"), .pin(56, "2") |
steers one thread, as Holding threads describes |
run.syscalls.counts("/usr/bin/app"), run.ints.counts(...), run.vtime.add("5s") |
counts a task’s system calls or interrupts; pushes the clock forward |
run.debug.log(lines=-20), run.debug.err(), run.control.log() |
the run’s debug output, its error log, and the commands issued to it |
Every call returns a record with named fields, such as a RunInfo from
describe() or a list of TaskInfo from tasks(). Call as_json() on one to get
a plain dict.
run.run(...) and run.plan(...) drive the run, and return a RunResult
that says how far the drive went. An iteration has no fixed length, so
iterations alone does not say how far:
| Field | Is |
|---|---|
iterations |
the iterations that ran |
vtime_elapsed |
how far the machine’s clock moved, in nanoseconds |
reached |
whether until held; False when iters ran out first |
clauses |
each clause the drive drew from, with the iterations it applied to |
entry_id |
the entry the drive ended at |
entries |
where each vCPU stopped |
hits |
the breakpoints, watchpoints and catchpoints the drive ended at; empty when none ended it |
printed |
the lines printed by stops that print, in the order the stops hit |
1 | done = run.run(iters=300, when="/app:on", mode="step") |
until takes the conditions machine run --until does,
including a machine time: run.run(until="vtime=+10ms").
Bounding a drive
within bounds a drive by the machine’s clock, as --within does. When
until is given too, whichever comes first ends the drive, and reached says
which. The machine checks the bound itself, so a slow host never ends the
drive early:
1 | done = run.run(until=r"console~app \| ready", within="30s") |
timeout is different: it is how many seconds of real time the call waits,
and it raises Timeout when they run out. To wait for a run that something
else drives, such as another program or a run stopping in the background, use
run.wait:
1 | run.stop(wait=False) |
for_ takes the predicates machine wait does: ready, stopped,
halted, entry>=N, vtime>=T, console~REGEX, or a task event such as
/app:exit.
Scheduling from Python
Every option of machine run is a keyword. The draws that
Schedules describes look like this in
Python. The run’s program was focused with run.focus.add("/app") before the
checkpoint booted was taken, so every branch forked at booted has the
focus too:
1 | for seed in range(10): |
The explore_seeds.py example keeps the branches that fail and marks them.
Faults
run.inject adds the faults Fault injection
describes, with the same subsystems and options as keywords. Check the target
first with run.tasks.exist, which raises NotFound when nothing runs it:
1 | run.tasks.exist(f"tgid={pid}") |
A C library opens a file with open or openat, depending on the library,
so the fault names both. glibc’s open() makes no open system call, so
add issues a UserWarning that names openat, and adds the fault on open
all the same. In the listing, matched counts the calls the fault saw and
fired counts the ones it failed.
A disk fault takes the file and the operation. An ordinary buffered write
reaches the disk from the kernel’s flusher, not from the program, so the
example writes with conv=fsync and the request is dd’s own:
1 | run.inject.add("disk", in_="comm=dd", file="/var/data.bin", op="write") |
The fault_injection.py example runs both and prints what the program saw.
on and off make a fault cycle:
run.inject.add("disk", in_="all", on="2s", off="5s") fails every disk
request for 2 seconds in every 7 of machine time. Each Fault says where it
is in its cycle: active, and left_ns, the time left in that window.
Container faults
run.containers puts a fault on one service of a Compose project, as
Container faults describes, while the
others keep running. A crash loses what the service had not synced to the
volumes its project names under x-machine:
1 | run.exec("echo synced > /data/kept && sync", container="app") |
stop, kill, start, pause, resume, throttle, memory, pids,
ports and files work the same way. stop and kill take restart= as
crash does, and stop also takes grace=. fresh=True starts a new
container instead of the old one. pause and throttle take for_=, and
throttle takes cpus=.
memory("db", "64m", for_="30s") limits a container’s memory.
pids("db", 20), ports("api", 40000, 40009) and files("api", 64) run a
container out of processes, local ports or open files, and each takes for_=
too.
run.containers() lists the containers with the service, name, state and
limits of each. The container_crash.py example builds a project, crashes one
service and reads its volume after the restart.
Clock faults
run.clock changes the machine’s date or one container’s, as
Clock faults describes. Each method returns the date as it
is now, with the change pending until the run next executes:
1 | run.clock.jump("+59m50s") |
run.clock(container="db") reads one container. ClockInfo.containers lists
each container whose date differs from the machine’s, with its offset,
drift, slew and jitter. ClockInfo.jitter and ClockInfo.leap are the
machine’s own.
The machine’s kernel takes a change when the run executes, so read the clock after
the next run to see whether the change was refused. ClockInfo.refused names each change
of the last batch the kernel refused, with its errno and the reason:
1 | run.clock.set("2038-01-19T03:13:30Z") |
To find how much skew a system tolerates, fork one branch at a checkpoint for each skew:
1 | for skew_ms in (50, 100, 200, 400, 800): |
Network faults
run.net puts faults on the links between a run’s containers, as
Network faults describes. A fault acts on every packet a
container sends, or only on the packets a match selects. A match combines any
of these keywords: to, a peer;
proto, tcp, udp, icmp or arp; port, a source or destination
port; and syn=True, the TCP SYNs that open a connection:
1 | run.net.delay("db", "100ms", jitter="20ms", seed=7) |
delay, loss, duplicate, corrupt, reorder, rate and hold
return a LinkChange, the link before and after; partition returns one
for each link it cuts, and heal and release return the links as they
were before. duplicate, corrupt and reorder take a share as loss does,
and rate takes bits a second, such as "1mbit".
A Link gives its delay
and jitter in nanoseconds and its shares in parts per billion, and what the
fault did since it was set: sent, dropped, and queued, the packets it
holds now. A replay delays and drops the same packets.
log=True on a fault writes each of its decisions to the container’s file
under /output/drop/.machine/net, and log=False stops it, as --log and
--no-log do. A run does not store files under /output/drop unless it is
told to keep them, so this run was created with
client.create("app", disk="app", keep_output="/output/drop/.machine/net"):
1 | run.net.loss("db", "30%", to="nest", seed=7, log=True) |
hold keeps a link’s packets until release, or for the duration for_
gives, and the held packets then leave together. With no container name,
hold holds every link at the point where the machine stopped, until a
release with no name. reset aborts TCP connections and returns how many it
aborted:
1 | run.net.hold("node1", for_="10s") # node1's messages arrive late, in a burst |
run.net.arp shows and changes a container’s neighbour table, and returns
the table as Neighbor entries:
1 | run.net.loss("db", "100%", proto="arp", to="api") # db's ARP to api lost |
Stopping at an event
A catchpoint stops the run at an event of a task, as
machine catch does. The drive that reaches it
returns the hit in hits:
1 | stop = run.breakpoints.catch("syscall", "open", "openat", in_="comm=cat") |
The kinds are exec, exit, fork, vfork, syscall, signal, load,
unload, fault, io, throw, catch and rethrow. An io catchpoint
takes file= and op=, and stops at a file’s disk request before any disk
fault decides on it:
1 | run.breakpoints.catch("io", file="/var/lib/db/*/data.bin", op="write") |
Debugging a task
run.task(tid) returns the task with that tid, to debug while the machine is
stopped. Debugging describes the same debugger on the command
line:
1 | task = run.task(412) |
The debug_task.py example stops at a catchpoint, reads the registers of the
task that hit it, reads the path it was opening from its memory, and prints
its stack.
Points in a run’s history
Calls that take a point, such as fork(at=...), go, rewind,
replay(to=...) and profile(from_=..., to=...), take it as text, "^booted",
"#300", "1.194s" or "-10ms", or as one of three records:
| Record | Is | Works on |
|---|---|---|
Point |
a time: vtime, the machine’s clock in nanoseconds |
every run; each finds its own entry at that time |
Place |
one entry: the run_id that recorded it, entry_id, point and vtime_offset |
the run that recorded it, and branches forked after it |
Checkpoint |
a saved state: its name, and the place it was saved at |
wherever its place works |
start(at=...) and the fs readers take only a checkpoint, by its name or as
a Checkpoint: they open a saved state, and a time or an entry is not one.
A point moves by a duration: an int of nanoseconds, a string such as "10ms",
or a timedelta. Subtract one point from another for the nanoseconds between
them. run.now() returns a Place, and run.place(point) finds the entry a
point names.
1 | booted = run.checkpoint("booted") |
A place is one run’s entry, so once the parent and the branch have both run
past the fork, run.place(here) is refused: the parent’s entry with that id
is another state. Pass here.point to take the same time instead.
Watching and following
A listing takes watch=True and then gives you a new list every time
something changes. A log takes follow=True and gives you new lines as they
come, like tail -f.
1 | for runs in client.runs(states=["running"], watch=True, timeout=60): |
Choosing entries
Every call that reads entries accepts the same forms:
| You write | Means |
|---|---|
200 or (100, 200) |
that entry, or that range, both ends included |
"100:200", "100:", ":200" |
a range, from 100 on, or up to 200 |
"-20" or "-20:" |
the last 20 entries |
"-20:-2" |
the 20th entry from the end through the 2nd |
slice(100, 200) |
a Python slice, so 100 through 199 |
slice(-20, -1) |
a Python slice from the end, so the same as "-20:-2" |
Be careful with the slice rows. A pair and a string include both ends, the way
Machine’s own messages do. A slice is Python’s, so it stops before the end.
That makes (100, 200) one entry longer than slice(100, 200).
Both ends of a range count from the same end: "-20:5" and slice(-20, 5)
are refused.
lines= selects lines of output in the same grammar: 20 is line 20, -20
the last 20, "-10:-2" the tenth line from the end through the second, and
0 none, which starts a follow at the end.
Cleaning up
A session costs from the moment you create it, and a run keeps its log and checkpoints until you delete it. Both are context managers, as in the first example. Deleting a run also deletes its branches.
If you want to keep a run that found something, don’t wrap it in a with
block. Nothing is deleted until you call delete().
Errors
Every exception the SDK raises is a machine.Error, and each one says what
went wrong.
| Exception | Raised when |
|---|---|
NotSignedIn |
there are no credentials |
Unauthorized |
a key or a sign-in code was rejected |
Forbidden |
your account is not allowed to do that |
NotFound |
nothing matches the name or id |
AlreadyExists |
something with that name exists |
InvalidArgument |
an argument is wrong, or a name matches more than one thing |
NotRunning |
it exists, but it is not running |
Conflict |
the request does not fit the thing’s current state |
NoCapacity |
no host of the session’s class has room for it now; the same request can succeed later, or a smaller session or another class may fit |
ClassUnavailable |
no machine of the session’s class is in service; a create on it succeeds once one is, and another class may be available now |
Diverged |
play() could not follow the recording; replay() returns a divergence in its result instead |
Timeout |
a wait ran out of time; the work goes on in the service |
ServiceUnavailable |
the service could not be reached |
ApiError |
the service refused the request |
A replay that does not reproduce the recording is a result, not an exception, so check it:
1 | result = branch.replay() |
The exceptions you will usually handle are the ones with a way out. A full class can be retried or sized down, and a run that stopped can be started again:
1 | try: |
The error_handling.py example raises NotFound, Forbidden,
InvalidArgument, NotRunning, Conflict and Timeout, and recovers from
the last three.
Examples
Small example scripts are in
sdk/python/examples of the TestFlows
Machine repository. Each one creates its own session and
deletes it at the end. Most run as python <script> --disk <name>.
disks.py builds the disk first and takes --binary and --name.
container_crash.py builds its own disk too and takes --name, and deletes
the disk at the end.
| Script | Shows |
|---|---|
hello.py |
creates a run, boots it, reads its console |
disks.py |
builds a disk from a static executable, boots a run from it, renames the disk and deletes it |
checkpoint_and_fork.py |
a checkpoint after boot, and branches from it |
replay_verify.py |
replays a recording and names what diverged |
explore_seeds.py |
one branch per seed, with the failing ones marked and kept |
force_interleaving.py |
holds one thread while another runs past it |
plan_file.py |
drives a run with when and else clauses |
watch_and_follow.py |
watches a listing and follows a console |
syscall_profile.py |
counts a program’s system calls and interrupts |
read_fs.py |
reads and copies files from a checkpoint’s disk |
machine_time.py |
changes the machine’s clock (vtime) rate and pushes it forward |
inject_interrupt.py |
injects an interrupt and replays it |
stop_and_resume.py |
what stop, kill, start and sync keep |
resume_elsewhere.py |
stops a run in one session and starts it in another |
preload_and_offload.py |
preloads a disk onto the session, then drops the session’s copy |
ci_job.py |
a CI job with an API key, a session per job and an exit code |
error_handling.py |
the errors a program usually handles, and how to recover from them |
fault_injection.py |
fails a program’s opens with a syscall fault and its synced write with a disk fault, and prints what the program saw and the fault counts |
container_crash.py |
builds a Compose project with an x-machine volume, crashes one service, and reads what the volume kept; takes --name for the disk it builds |
debug_task.py |
stops at a catchpoint on open, reads the task’s registers, memory and stack |
License
The SDK is licensed under Apache 2.0, and its source is in
sdk/python of the TestFlows Machine repository.
The Python SDK Core it runs on is proprietary
and is not part of the SDK. It comes with the client, under the
Client EULA.