Skip to content
pi-c Artifact [be955dbe8f]
Login

Artifact [be955dbe8f]

Artifact be955dbe8f736c038994bfcd117c24521b1faa9bcae87ad8eec2ccac887acb3c:


# The inbox

How a message from another process reaches a running conversation, and how another process
follows it: grapevine stages 1 to 4 ([the design](../design/grapevine.md)). The user's view is in
[remote control](../manual/remote-control.md).

## The table

`pic_inbox` (schema 17), one row per message:

| Column | Meaning |
|---|---|
| `msg_key` | the sender's idempotency key, unique, never forgotten |
| `command_hash` | SHA3-256 of `session_id`, `sender` and `command`: the same key and hash is a retry; any other a conflict |
| `session_id` | the receiving conversation, resolved when sent |
| `sender` | `cli` (`pic send`), `attach` (`pic attach -i`), `remote:DEVICE`, `session:JOURNAL_ID/CONVERSATION` (`send_message`), or `wake:ID` (a loop's fire, key `wake:ID:N`; [loops](../design/wakes.md)) |
| `command` | one Pi RPC command line (`prompt`, `steer`, `follow_up`, `abort`); NULL once pruned |
| `hops` | 0 from a person or script; from a peer, its request's hops plus one |
| `target` | an abort's request: the conversation's admitted one when it was sent |
| `created_ms`, `expires_ms` | when it was accepted; after `expires_ms` it is expired, never run |
| `state` | `pending`, `delivered`, `refused` or `expired` |
| `response` | the response line `src/commands.c` gave, or the inbox's own for an abort or expiry |
| `submission_id`, `queued_id` | what delivery made: the `pic_queued` row of a steer or follow-up |
| `settled_ms` | when it left `pending`; retention counts from it |

## Accepting

The sender opens the journal with `pic_open_narrow` (`src/store.c`): the journal lock shared, no
recovery, no schema change, refused unless the schema is this build's and the file is the user's.
`pic_inbox_accept` (`src/inbox.c`) is one `IMMEDIATE` transaction: a known key returns its state
(or is refused as a conflict), the limits (100 pending rows, 64 MB pending per conversation, a
16 MB line) and the conversation are checked, and the row is inserted. An abort sent while nothing
runs, and a prompt with no `streamingBehavior` sent while a request runs, are inserted already
`refused`, with Pi's answer. A prompt expires as a follow-up does, or as a steer when its
`streamingBehavior` is `steer`. After the commit the sender rings the bell,
`journal.sqlite.pic-leases/ID.bell`: a 20-digit counter rewritten in place.

## Delivering

`pic_run` (`src/loop.c`) calls `pic_inbox_poll` at each step, once it holds the running request's
lease. The first poll starts a thread that waits on the bell through `pic_platform.watch` (kqueue's
`EVFILT_VNODE`, inotify), or stats it every 200 ms where there is none (`PIC_NO_WATCH=1` in tests),
and wakes every 30 s regardless; it writes a byte to a pipe whose read end is `pic_watch_fd`
(`src/net.h`), which every wait polls beside the side descriptor. The thread never touches SQLite.

Each pending row, oldest first, is settled in one transaction begun with `pic_begin_outer`, inside
which `pic_begin` is a savepoint: an expired row becomes `expired`; an abort is `delivered` when its
target is still the running request (the cancel follows at the loop's next step, as Ctrl-C's) and
`refused` otherwise; a steer or follow-up goes through `pic_commands_line` with a response sink
(`pic_commands_sink`), so the `pic_queued` row and the inbox row commit together. A prompt goes
through `pic_commands_enqueue`, answered as `prompt`: a steer when its `streamingBehavior` is
`steer`, else a follow-up, so one sent while nothing ran is the next request after the one that
delivers it. The events it
makes (`queue_update`) go to a memory stream while the transaction is open and out only after the
commit, so a slow reader never holds the write lock and a rolled-back delivery shows nothing; a
rollback also puts back `pic_store.running`, which a follow-up's admission may have moved. A steer or
follow-up with no admitted request (and no just-answered one of this process) stays pending, and so
do the rows behind it, keeping commit order.

A sender that finds the conversation running (a request admitted, or its lease held) starts no
run: the running one takes the message. One accepted after the run's last look and before it lets
go would then wait for good, so `pic_unlease` ends with `pic_inbox_released`: each delivery look
records the last row it saw (`pic_store.inbox_seen`, read in the look's own transaction), and when
a process that ran a request of the conversation lets go, a pending prompt after that row (not a
loop's fire, which has its own start) gets a `pic run --session` through the starter the
composition root registers (`pic_peer_wake`, off with `grapevine.wake`). Any sender after the
release sees nothing running and starts one itself; two starts find one lease, and the second run
finds nothing to do.

A crash before the delivery commits leaves the row pending for the conversation's next owner; after
it, the queued message recovers as any does. A delivered abort is itself the record of a cancel to
make: until the loop journals the cancel, the row (`state` delivered, `target` the admitted
request; only aborts have a target) stands for it, and if the owner dies first, recovery
(`settle_session` in `src/loop.c`, reached through `recover_abandoned` at any open or through the
next lease) cancels that request. Ctrl-C keeps its window: it is a signal, journaled only by the
cancel itself, and recording it earlier would mean a write from every wait that notices it; a pic
killed between Ctrl-C and its cancel leaves the request to run on.

## Retention

Hourly with image pruning in `pic_open`, and for its own row in `pic send --wait`: pending rows
past `expires_ms` become `expired`; rows
settled more than 7 days ago lose `command` and `response`, keeping key, hash and state.

## Invariants

`pic check` adds: every row has `expires_ms`; a settled row that is not pruned has its response, at
most one of `submission_id` and `queued_id`, and none for an abort; a pending row has its command
and no response or product; a `queued_id` names a `pic_queued` row of the same conversation.

## Fault points

`inbox_accept` and `inbox_deliver`, each reached twice per message: arrival 1 just before the
commit, arrival 2 just after. `before-cancel` (`src/loop.c`) is where the loop has seen an abort or
Ctrl-C and not yet journaled the cancel. `test/pic/grapevine.sh` crashes at all five. `live-first`
(`src/store.c`) is just before a reply's first text goes to the `.live` file; the same test delays it
with `PIC_RUN_AT` to show a follower's terminal draws the reply before its owner dies.

## pic attach

`src/attach.c` (bundled) collects each pass's output and writes it after the pass's read
transaction ends, so a reader that stops reading never pins the WAL. It reads with the narrow open and writes only through `pic_inbox_accept`;
with `-i` and nothing running it starts a request as a `pic ask --session` child in a session of
its own (`setsid`), which opens the journal fully and takes the lease, and follows it like any.
When that child exits, the steers this attach sent it and that are still pending are withdrawn
(`pic_inbox_withdraw`: refused by their sender, needing no lease): reported after a failure, sent
as the next request after an answer. Each
pass is one read transaction, run when `PRAGMA data_version` changes (polled every 100 ms), so a
request's `agent_end` is never seen before its last entry. Events: `agent_start` at a request's
first entry, `message_start` and `message_end` for user entries, `message_end` for replies,
`tool_execution_start` once a call leaves `intent`, `tool_execution_end` at its result entry,
`agent_end` once the request is not admitted. Entry events carry `seq`. Not rebuilt: turn events,
queue updates, usage, compactions, hook and instruction entries, images.

What a conversation reads (`PIC_PATH_SEQS_SQL`) is two sets of entries. The first is its fork
point and that entry's parents, walked back by `parent_seq`; the fork point is the parent of its
first own entry, or its head while it has none, and a conversation that is no fork has none. The
second is every entry of its own requests (`pic_submission.session_id`). The follow, its first mark,
earlier pages and `pic remote`'s `fetch`, `earlier` and images read those, so a fork follows from
what it shares. The walk stops at the first entry at or below the pass's start, so a pass reads only
what is new. A shared request is the fork's: its events name the fork as `conversation`, and it is
never shown running (a fork never shares a running one: `pic fork` and `fork_session` without an
entry start where the last ended request did, and refuse an entry of a running request).

`--from end` inside a request whose lease is held starts with that request's `agent_start` and a
`tool_execution_start` for each call out of `intent` with no result entry yet.

Following in JSON, each 100 ms tick reads the owner's `.live` file ([remote](remote.md)) while the
open request is admitted: a new inode, or a file shorter than what was read, is a new reply; one
whose head `seq` is below the last entry shown was committed already. What grew goes out as
`message_update` (`text_delta`, `contentIndex` 0) after one `message_start`, holding back a
character cut at the end. When the reply's entry is shown, what its text blocks hold beyond what
was sent goes out as a last delta before its `message_end`.

While the open request is admitted and its `agent_start` went out, the tick looks at its lease
twice a second (`pic_lease_holder`, shared, an instant). Once it has been seen held, a lease free
for 2 s reports the request `agent_end` with status `interrupted` (a request admitted and not yet
taken, as between `pic submit` and the `pic run` it spawns, is never reported); once the lease is held again, or an entry of it is shown, `agent_start` goes out
again. Nothing is recovered or written: the next pic to take the lease does that.

## Peers and waking

`send_message` (`src/peer.c`, bundled) runs as any tool, possibly in a parallel batch's child: it
opens its own journal narrowly to read its call (`pic_tool_hooks` carries the journal, effect and
input) and the receiver's to insert one row, key `fx:JOURNAL_ID:EFFECT`, so a replay after a crash
finds the row and sends nothing new (it is in the replay-safe list). `JOURNAL_ID` is
`pic_meta.journal_id`, random, written by the first full open. Another workspace's journal is the
one `picu_workspace` names for its real path.

A request's hops are not stored: `pic_inbox_hops` takes the most of the delivered rows that
started it (`submission_id`), joined it (a `pic_queued` row of it) or became it (`queued-ID`). A
message over the limit (`grapevine.maxHops`, the sender passes it) is refused at accept, writing
nothing.

The sender's result line is made by `pic_peer_standing`, called where the row is saved (`pic_peer_send`, `pic send`): a running request (an
`admitted` submission or a lease) is "delivered into"; otherwise, with the wake spawned, it polls the
row for up to 5 s, since the run settles it as it admits the prompt: `delivered` is "woke",
`refused` names the cap (the text of `pic_inbox_wake`'s refusal) or the hook. Without a wake, a
conversation that a follower holds `journal.sqlite.pic-leases/ID.watch` shared (`pic_watch_hold`:
`pic attach` with a lifeline on stdin, which the terminal runs while idle; `pic_watched` tries it
exclusive) is "open in a terminal". `pic send` calls the same `pic_peer_standing` for a prompt and says on stderr where the message
stands; stdout stays the state and key.

The wake component, after a row stays `pending` in a conversation with nothing admitted and no
lease, spawns `pic --db J --workspace W run --session ID` in a session of its own when
`grapevine.wake` is not false. `pic run --session` with nothing admitted calls `pic_inbox_wake`: the oldest
pending prompt is refused when `grapevine.maxWakes` (when above 0) requests keyed `inbox:` came after the last
request a person made there, or when a `UserPromptSubmit` hook blocks it (origin: its sender); a
loop's fire (sender `wake:ID`) is never refused for `grapevine.maxWakes`, nor counted by it;
otherwise it is admitted with `pic_submit_hooked` as `inbox:KEY` on the conversation's last model,
and then settled `delivered` with that `submission_id`. Fault point `inbox_wake` (arrival 1) is
between the two: the row stays pending and the request admitted, and the next delivery of that row
(`inbox_deliver_one`) finds `inbox:KEY` and settles it as that request instead of running it again.