# Captured tmux state

Source: https://libtmux.org/en/elixir/pr-173/concepts/observations/

> Capture an immutable snapshot of an existing server and read it without further commands.

- [`LibTmux.Server.new/1`](<https://libtmux.org/en/elixir/pr-173/reference/libtmux-server-new-1/>) builds a descriptor with an explicit executable and a
  socket choice. The choice is a path, a name, one of `LIBTMUX_SOCKET_PATH` and
  `LIBTMUX_SOCKET`, or none, which leaves it to tmux. It does no I/O.
- [`LibTmux.Server.snapshot/2`](<https://libtmux.org/en/elixir/pr-173/reference/libtmux-server-snapshot-2/>) observes that existing server and returns an
  immutable [`LibTmux.Snapshot`](<https://libtmux.org/en/elixir/pr-173/reference/libtmux-snapshot/>).
- Neither call attaches a control client or starts a missing server.
- Configured tmux hooks remain environmental effects of commands, including
  list commands.

## Read one captured graph

- [`Snapshot.items/2`](<https://libtmux.org/en/elixir/pr-173/reference/libtmux-snapshot-items-2/>) returns a plain list for an entity atom or module.
- [`Snapshot.fetch/3`](<https://libtmux.org/en/elixir/pr-173/reference/libtmux-snapshot-fetch-3/>) looks up an exact ID.
- [`Snapshot.related/4`](<https://libtmux.org/en/elixir/pr-173/reference/libtmux-snapshot-related-4/>) follows captured indexes, and raises a structured
  coverage error when a relation is incomplete.
- [`Snapshot.sessions/1`](<https://libtmux.org/en/elixir/pr-173/reference/libtmux-snapshot-sessions/>), `windows/1`, `panes/1`, `window_links/1` and
  `clients/1` return materialized selections.
- None of these does I/O. See [filtering](https://libtmux.org/en/elixir/pr-173/guides/filtering/) for local predicates
  and portable criteria.

For common relationships, pass the snapshot and a session or window
observation to [`Session.windows/2`](<https://libtmux.org/en/elixir/pr-173/reference/libtmux-session-windows-2/>), [`Session.panes/2`](<https://libtmux.org/en/elixir/pr-173/reference/libtmux-session-panes-2/>), [`Session.active_window/2`](<https://libtmux.org/en/elixir/pr-173/reference/libtmux-session-active_window-2/>)
or [`Window.panes/2`](<https://libtmux.org/en/elixir/pr-173/reference/libtmux-window-panes-2/>):

- The plural helpers return selections for filtering and checked cardinality
  with [`LibTmux.Selection`](<https://libtmux.org/en/elixir/pr-173/reference/libtmux-selection/>). `active_window/2` returns a window or [`nil`](<https://elixir.hexdocs.pm/typespecs.html#literals>).
- They validate the observation's kind, ID and server incarnation, then use
  the supplied graph's fields and coverage. An older observation from the same
  incarnation is valid, and its other fields are ignored.
- Each selection keeps the supplied graph. `Enum.to_list/1` gives a plain list
  without it.
- Direct traversal validates only the requested source. One session's active
  window does not fail because another session has ambiguous active links.
- Relationship filters validate their whole captured source domain before
  iteration, even when the selection is empty.

Sessions, physical windows, panes and clients have separate maps:

- A pane belongs to one physical window.
- [`WindowLink`](<https://libtmux.org/en/elixir/pr-173/reference/libtmux-windowlink/>) records session membership, window index and active state. Its
  key is session ID, index and window ID, which does not prove a unique
  lifetime after unlink and relink.
- A window can appear at several indexes in one session, and in other
  sessions. Server-wide physical maps deduplicate identical rows and reject
  conflicting rows.
- Session pane traversal returns each physical pane once. Window-link
  traversal keeps memberships.
- Sessions, windows and panes sort by numeric native ID. A session's windows
  follow their first link's index; its panes sort by numeric pane ID. Links
  sort by numeric session ID and index. Clients sort bytewise by observed
  name.

Field notes:

- [`Session.attached_count`](<https://libtmux.org/en/elixir/pr-173/reference/libtmux-session-attached_count/>) keeps tmux's raw client count, and [`attached`](<https://libtmux.org/en/elixir/pr-173/reference/libtmux-session-attached/>) is
  derived from it. Control clients stay counted even with `no-output` and
  `ignore-size`.
- A control client's height is known [`nil`](<https://elixir.hexdocs.pm/typespecs.html#literals>) when tmux reports no started tty.
  It is not an unavailable field.
- [`Pane.pid`](<https://libtmux.org/en/elixir/pr-173/reference/libtmux-pane-pid/>) is known [`nil`](<https://elixir.hexdocs.pm/typespecs.html#literals>) when tmux reports no PID, including empty and
  retained dead panes on tmux 3.8. Other values stay as reported: older tmux
  can report zero for an empty pane, or a historical PID for a dead one.
  Neither a PID nor its absence proves a process is alive or cleaned up.

## Compare two snapshots

This example links one physical window into a second session at indexes 7
and 8. It captures the graph, unlinks index 7, then captures again.

Compare [`WindowLink.id`](<https://libtmux.org/en/elixir/pr-173/reference/libtmux-windowlink-id/>) values to find added and removed memberships. Each key
contains the session ID, index and physical window ID, so replacing the
window at an index gives a removal and an addition. Require complete window
link coverage in both captures and check that they came from the same
server incarnation before comparing their IDs.

<!-- example: examples/snapshot_changes.exs#memberships -->

```elixir
unless before.server_instance == later.server_instance do
  raise "the captures describe different tmux servers"
end

link_ids = fn snapshot ->
  :ok = Snapshot.require_complete!(snapshot, :window_link)
  Enum.map(Snapshot.window_links(snapshot), & &1.id)
end

before_ids = link_ids.(before)
later_ids = link_ids.(later)
removed = before_ids -- later_ids
added = later_ids -- before_ids
```

<!-- /example -->

From this checkout, with tmux on `PATH`:

```console
$ mix run examples/snapshot_changes.exs
```

It prints:

```text
{"removed":[["$1",7,"@0"]],"added":[],"window":"@0","panes":["%0","%2"],"destination_indexes":[8],"held_destination_indexes":[7,8],"same_panes":true}
```

Only the membership at index 7 disappeared. Index 8 still points to the
same window with both original panes. The held snapshot still has both
memberships. The comparison reports differences between captured keys.
Changes to fields such as the active flag, and an unlink and relink of the
same key between captures, are outside that comparison.

## Coverage and construction

- [`Snapshot.new/2`](<https://libtmux.org/en/elixir/pr-173/reference/libtmux-snapshot-new-2/>) validates fixture or adapter observations without I/O.
- [`fields`](<https://libtmux.org/en/elixir/pr-173/reference/libtmux-schema-fields-1/>) declares loaded fields over the supplied entity IDs. `complete`
  declares complete server entity sets; omissions stay partial. `unavailable`
  declares absent capabilities separately.
- Declared names and values validate before indexes or relations become
  observable.
- Known empty strings, known nullable values, `:unloaded` and `:unavailable`
  stay distinct. Required coverage checks run even for empty entity sets.
- Derived attachment coverage follows its source count.
- A relation to many objects needs a complete join domain, so missing
  children never become an empty relation. Complete target sets reject
  dangling references. A partial target set can keep unresolved foreign IDs,
  but traversal fails explicitly.

The [generated schema](https://libtmux.org/en/elixir/pr-173/topics/schema/) owns field types, wire names, tmux variables
and relation cardinalities. Physical windows carry no single session, session
index or active membership flag.

## Capture consistency and bounds

- Capture reads topology, then named fields, then topology again. It checks
  the tmux PID against Linux boot identity and process start ticks before and
  after those reads.
- Two empty session listings from the same server incarnation yield a complete
  graph with all entity sets empty. These reads use the same capture budgets.
- A replaced server or changing references trigger finite read retries, as
  does a disappearing read target. Invalid encoding and other decoding errors
  stay visible.
- Two attempts are the default; request one to three. All attempts share one
  deadline and the original budgets.
- Defaults: 1024 contextual topology rows, 512 commands, 8 MiB total response
  bytes, 64 KiB per response and 5000 ms.
- Stdout and stderr both consume the byte budget, including failed-command
  output. Overload returns an error, not a truncated success.
- Topology checks and retries also consume work. An overflowing pane listing
  can fall back to smaller listings or individual reads. That work stays
  charged to the original budgets. See [capture rows](https://libtmux.org/en/elixir/pr-173/topics/encoding/#capture-rows).
- One-shot retirement has a separate allowance; see [ownership](https://libtmux.org/en/elixir/pr-173/topics/ownership/).

Encoding:

- Free-form fields use the qualified versioned encoder. Numeric and ID
  topology columns validate their whole representation.
- Client rows combine one encoded identity with restricted scalar columns, so
  tabs and newlines cannot escape the identity.
- This is a fixed capture schema, not a general raw-format row parser.

A capture records an observation, not a transaction:

- Attributes can change within the interval. Matching topology before and
  after does not prove nothing changed in between.
- Holding a snapshot reserves no objects.
- Its server instance differs from a future connection epoch, and one-shot
  checks keep a check/use race.
- Sending a snapshot between BEAM processes can copy terms, and keeping one
  keeps its graph.

## Diagnose capture work

[`LibTmux.Server.snapshot_with_diagnostics/2`](<https://libtmux.org/en/elixir/pr-173/reference/libtmux-server-snapshot_with_diagnostics-2/>) puts a work report in the third
tuple element on success or error. Compare two response ceilings against the
same graph:

<!-- example: examples/capture_diagnostics.exs#ceilings -->

```elixir
{:ok, narrow, narrow_report} =
  Server.snapshot_with_diagnostics(server, max_response_bytes: 2500)

{:ok, wide, wide_report} =
  Server.snapshot_with_diagnostics(server, max_response_bytes: 8192)

```

<!-- /example -->

The runnable example creates a private server with four panes and checks
that both captures return the same long titles.

```console
$ mix run examples/capture_diagnostics.exs
```

| Capture | Commands | Pane batch reads | Individual reads |
| --- | ---: | ---: | ---: |
| 2500 bytes per response | 15 | 2 | 0 |
| 8192 bytes per response | 13 | 0 | 0 |

At 2500 bytes the full pane listing overflows. The fallback record names
`:pane` and counts two batch reads, one per ID range. The byte count
includes the retained prefix of the overflowing response. The last call
sets a command limit to stop before either batch and returns a capture
error with the report.

Use `max_response_bytes` to fit a known large row or listing. `max_bytes`
and [`timeout`](<https://elixir.hexdocs.pm/typespecs.html#built-in-types>) still bound the entire capture, including every fallback. Log
the report alone to leave out captured output that may be present in the error.
