# Inspecting a finished run

> Seek to any point in a recorded sandbox run, read its files at that moment, and step through events.

This is the Markdown of https://docs.dvm.run/guides/inspect/. Every page of the dvm.run docs is served as Markdown at its address plus `.md`; the list of pages is https://docs.dvm.run/llms.txt.

Once a sandbox exits, you can replay its recording and seek (jump to a chosen moment in the execution) to any point in its run. At any point, you can read the sandbox’s files as they existed then and step forward to the next event you are watching for.

* Python

  `python/examples/inspect_run.py`

  ```python
  with Sandbox.create("alpine:3.20") as sandbox:
      sandbox.run("echo first > /tmp/state; echo second > /tmp/state")
      sandbox.end()
  ```

* TypeScript

  `js/examples/inspect-run.ts`

  ```ts
  await using sandbox = await Sandbox.create("alpine:3.20");
  await sandbox.run("echo first > /tmp/state; echo second > /tmp/state");
  await sandbox.end();
  ```

* Rust

  `rust/dvm-run/examples/inspect_run.rs`

  ```rust
  let sandbox = client.create_sandbox("alpine:3.20").await?;
  sandbox
      .scope(async |sandbox| {
          sandbox
              .run("echo first > /tmp/state; echo second > /tmp/state")
              .await?;
          Ok(())
      })
      .await?;
  ```

## Which runs can be inspected

Any sandbox that exited can be inspected, regardless of exit code, as can one that reached its time limit. Seeking fails with `409` and the matching reason if the sandbox is:

* still running: `sandbox N is still running`;
* stopped: `sandbox N was stopped before exit`;
* failed: `sandbox N failed before exit`;
* recorded on an older dvm version than the runner now runs: `... ran on an older dvm than its runner's now: run it again`.

A session (a sandbox that accepts commands) exits when you close its input with `end()`, or at the end of a `with` block, `await using`, or `scope`.

## Seek to a point

Call `seek` with no target to jump to the end of the run.

* Python

  `python/examples/inspect_run.py`

  ```python
  end = sandbox.seek()
  print(end.thread, end.event, end.ns, end.at.kind)
  print(end.read_file("/tmp/state"))
  ```

* TypeScript

  `js/examples/inspect-run.ts`

  ```ts
  const end = await sandbox.seek();
  console.log(end.thread, end.event, end.ns, end.at.kind);
  console.log(new TextDecoder().decode(await end.readFile("/tmp/state")));
  ```

* Rust

  `rust/dvm-run/examples/inspect_run.rs`

  ```rust
  let end = sandbox.seek_end().await?;
  println!(
      "{} {} {:?} {:?}",
      end.thread(),
      end.event(),
      end.ns(),
      end.at()
  );
  println!(
      "{:?}",
      String::from_utf8_lossy(&end.read_file("/tmp/state").await?)
  );
  ```

There are three seek targets:

| Target   | Python, TypeScript                                   | Rust                        | Lands                                                            |
| -------- | ---------------------------------------------------- | --------------------------- | ---------------------------------------------------------------- |
| the end  | `seek()`                                             | `seek_end()`                | where the run ended                                              |
| a time   | `seek(at_ns=…)`, `seek({ atNs })`                    | `seek_at_ns(ns)`            | near that time in the recording (progress is sampled 1 ms apart) |
| an event | `seek(thread=…, event=…)`, `seek({ thread, event })` | `seek_event(thread, event)` | exactly at that thread and event                                 |

A point describes where execution stopped:

* `thread`, `process`, and `event`: the thread where execution stopped, its process, and the thread’s event count. Together, a thread and an event identify a point uniquely; seek to them to return to it.
* `ns`: approximate timestamp in the recording, if known.
* `at`: what the thread was doing: a `syscall` (with its number, name, raw arguments, and values dvm decoded such as paths, strings, addresses, and bytes), a `page_fault` (with its address, whether it was a write, and whether the page was present), or an `arrival` (with the instruction address `rip`).
* `operations` and `stats`: counters dvm tracks for the run up to that point.

The first seek on a run starts its replay, which can take a while. Further points in the same run share that replay. Replaying a run is free ([Plans, limits and credit](/concepts/plans/)).

## Read files at a point

* Python

  `python/examples/inspect_run.py`

  ```python
  for entry in end.list_dir("/tmp"):
      print(entry.name, entry.type)
  status = end.stat("/tmp/state")
  print(status.type, status.size, oct(status.mode), status.mtime)
  ```

* TypeScript

  `js/examples/inspect-run.ts`

  ```ts
  for (const entry of await end.listDir("/tmp")) console.log(entry.name, entry.type);
  const status = await end.stat("/tmp/state");
  console.log(status.type, status.size, status.mode.toString(8), status.mtime);
  ```

* Rust

  `rust/dvm-run/examples/inspect_run.rs`

  ```rust
  for entry in end.list_dir("/tmp").await? {
      println!("{} {:?}", entry.name, entry.kind);
  }
  let status = end.stat("/tmp/state").await?;
  println!(
      "{:?} {} {:o} {:?}",
      status.kind, status.size, status.mode, status.mtime
  );
  ```

- `read_file(path)` returns a regular file’s bytes.
- `list_dir(path)` returns a directory’s entries, each with its name and type.
- `stat(path)` returns the type, mode, owner, size, link count, and modified and changed timestamps as seconds and nanoseconds. It follows symbolic links unless you opt out; a link’s own status includes its target.

Paths must be absolute. Missing paths return `404`. File bytes that dvm cannot serve from the recording return `422`. Mounts not yet supported return `501`.

## Step through events

Stepping moves forward from a point to the next matching event and returns that new point, or nothing once no more matching events remain.

* Python

  `python/examples/inspect_run.py`

  ```python
  point = sandbox.seek(at_ns=0, watch=["file-syscalls", "syscall:execve"])
  marks = []
  while point is not None and len(marks) < 20:
      print(point.thread, point.event, point.at.kind, point.at.name)
      marks.append((point.thread, point.event))
      point = point.step()
  ```

* TypeScript

  `js/examples/inspect-run.ts`

  ```ts
  let point: SandboxPoint | null = await sandbox.seek({ atNs: 0, watch: ["file-syscalls", "syscall:execve"] });
  const marks: [number, number][] = [];
  while (point !== null && marks.length < 20) {
    console.log(point.thread, point.event, point.at.kind, point.at.name);
    marks.push([point.thread, point.event]);
    point = await point.step();
  }
  ```

* Rust

  `rust/dvm-run/examples/inspect_run.rs`

  ```rust
  let execve = SyscallName::try_from("execve".to_owned()).expect("a syscall's name");
  let mut point = Some(
      sandbox
          .seek_at_ns(0)
          .watch(WatchPoint::FileSyscalls)
          .watch(WatchPoint::NamedSyscall { name: execve })
          .await?,
  );
  let mut marks = Vec::new();
  while let Some(here) = point.take() {
      println!("{} {} {:?}", here.thread(), here.event(), here.at());
      marks.push((here.thread(), here.event()));
      if marks.len() < 20 {
          point = here.step().await?;
      }
  }
  ```

On any seek or step, you can specify up to 32 watch points (the event categories you want stepping to stop on):

| Watch point          | Python, TypeScript  | Rust (`WatchPoint::`)   |
| -------------------- | ------------------- | ----------------------- |
| every syscall        | `"syscall"`         | `Syscall`               |
| one syscall, by name | `"syscall:execve"`  | `NamedSyscall { name }` |
| file syscalls        | `"file-syscalls"`   | `FileSyscalls`          |
| socket syscalls      | `"socket-syscalls"` | `SocketSyscalls`        |
| processes            | `"processes"`       | `Processes`             |
| page faults          | `"page-fault"`      | `PageFault`             |

Python and TypeScript also accept each watch point as the raw API object, such as `{"kind": "named_syscall", "name": "execve"}`. A syscall name must be 1 to 64 letters, digits, or `_`.

If a run’s first seek specifies no watch points, it defaults to file syscalls, processes, and socket syscalls. Later seeks or steps that omit watch points keep the current set; passing watch points replaces it.

## Return to a point

Save a point’s thread and event number, then seek to them later to return to that exact moment.

* Python

  `python/examples/inspect_run.py`

  ```python
  thread, event = marks[-1]
  again = sandbox.seek(thread=thread, event=event)
  print(again.at.name, [argument.value for argument in again.at.decoded])
  ```

* TypeScript

  `js/examples/inspect-run.ts`

  ```ts
  const [thread, event] = marks.at(-1)!;
  const again = await sandbox.seek({ thread, event });
  console.log(again.at.name, again.at.decoded?.map((argument) => argument.value));
  ```

* Rust

  `rust/dvm-run/examples/inspect_run.rs`

  ```rust
  let (thread, event) = *marks.last().expect("a stop");
  let again = sandbox.seek_event(thread, event).await?;
  println!("{:?}", again.at());
  ```

## Seek errors

* `409`: the run cannot be inspected (see above), or replay failed (with dvm’s reason).
* `409` with `too many timeline seeks in progress; try again in a moment`: you reached your plan’s limit on concurrent replays.
* `503` with `the sandbox is returning to that point`: the SDKs wait and retry automatically.

A replay may differ from its recording, and dvm reports when it does ([What replay promises](/concepts/replay/)).
