msgqueue

package
v0.34.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 5, 2026 License: MIT Imports: 8 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package msgqueue is the in-memory, daemon-resident inbound backlog for phone-originated send_message turns. It is the inbound counterpart of internal/eventring (the outbound per-conversation event store): where eventring buffers what the daemon pushes OUT to phones, msgqueue buffers what phones send IN while claude is busy.

Today send_message delivers synchronously — the handler blocks the per-conn goroutine inside WriteUserTurn's idle gate while claude is mid-turn, and the turn fails if claude stays busy past a 30s cap (#594). A phone that types while claude is working therefore either blocks or loses the message, and concurrent messages race across handler goroutines with no defined order.

Queue fixes that. Enqueue appends a message to its conversation's FIFO and returns immediately (non-blocking), and a single drain goroutine per conversation delivers the backlog one at a time, in enqueue order, through an injected reliable-delivery seam (DeliverFunc, the shape of Supervisor.WriteUserTurn — the #594 ready-gate → commit-confirm → recovery path). The drain is paced entirely by that seam: DeliverFunc blocks while claude is busy and returns only on a confirmed commit, so a message enqueued mid-turn is held until the turn ends, one enqueued while claude is idle drains promptly, and there is never more than one in-flight delivery per conversation. No separate turn-state detector is needed.

The backlog lives above the claude child's lifecycle: an undelivered message is retried at the FIFO head until it is confirmed delivered, so it survives a claude *child* respawn and drains into the new child. It deliberately does NOT survive a full daemon-process restart — the queue is purely in-memory, the same loss boundary as eventring; reconnect/resync covers it. There is no on-disk persistence in this slice.

The package is wired into the daemon: cmd/pyry constructs the queue via msgqueue.New (cmd/pyry/main.go), drives delivery through the DeliverFunc seam (newInboundDeliver), reports backlog changes through the queue-state emitter (newQueueStateEmitterV2), and the send_message handler (internal/relay/handlers/send_message.go) is the enqueue caller (*msgqueue.Queue satisfies its Enqueuer interface). Enqueue is the single insertion point for the per-conversation backlog bound (#869): an Enqueue past the cap is rejected (returns 0) — never dropped, never evicting the oldest.

SECURITY: the queued text is untrusted, phone-originated content bound for claude's stdin verbatim. It is treated as opaque transit bytes — stored, never inspected or used in a control decision, and converted to []byte only at the DeliverFunc call. Since #2038 a message may carry a separate DELIVERY payload alongside it (EnqueueDelivery), composed by the send_message handler and possibly naming an on-host path; it gets the same treatment and is the one value that must never reach a client, which QueuedMessage's shape enforces rather than a rule. Since #2092 a message also carries the CLIENT'S OWN message_id, which is untrusted in exactly the same way but travels the opposite direction — it is echoed back to every paired device on purpose, as the key a client merges its optimistic echo on. NONE OF THE THREE IS EVER LOGGED BY THIS PACKAGE at any level; the drain's warn-on-error logs only conversation_id, the queued message id, and the enqueue timestamp. For text and delivery that mirrors internal/relay/handlers/send_message.go, which logs neither. It does NOT for message_id: that handler logs the value at three sites, deliberately, and those stay the only place it appears in any log. convID is used solely as a map key; validating/resolving it to a real session is the caller's job (upstream of Enqueue), so a hostile convID can at worst create an isolated FIFO that never drains — never reach another conversation's session.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ChangeFunc

type ChangeFunc func(convID string)

ChangeFunc is the injected change-notification seam — it mirrors the DeliverFunc seam style. It is invoked, NEVER while holding q.mu, with the id of the conversation whose backlog changed (on enqueue, on delivery-advance, and on a successful Remove). It carries only convID; the consumer re-reads the current backlog via Snapshot (the seam is edge-triggered — coalescing is the consumer's choice). nil disables notification.

It MUST NOT block (a blocking ChangeFunc on the drain path stalls that conversation's drain) and MUST be safe for concurrent invocation: it fires from the Enqueue caller's goroutine, from each drain goroutine, and from the Remove caller's goroutine. The consumer owns its own synchronization.

type Config

type Config struct {
	// Deliver is the reliable-delivery seam; required. New errors if it is nil.
	Deliver DeliverFunc
	// RetryInterval is the poll cadence while delivery keeps failing.
	// <= 0 ⇒ defaultRetryInterval.
	RetryInterval time.Duration
	// MaxQueuedPerConversation caps each conversation's not-yet-delivered
	// backlog; an Enqueue past it is rejected (reject, never drop).
	// <= 0 ⇒ defaultMaxQueuedPerConversation. A per-conversation bound,
	// independent across conversations.
	MaxQueuedPerConversation int
	// OnChange is the optional change-notification seam; nil ⇒ disabled.
	OnChange ChangeFunc
	// GiveUpAfter bounds how long the drain retries a persistently-failing head
	// before abandoning it. <= 0 ⇒ defaultGiveUpAfter. Measured as elapsed
	// wall-clock since the head's FIRST consecutive delivery failure; a
	// successful delivery resets the clock for the next head, and so does a head
	// removed between attempts (per-head, not per-session).
	GiveUpAfter time.Duration
	// OnGiveUp is the optional give-up-notification seam; nil ⇒ disabled.
	OnGiveUp GiveUpFunc
	// OnDelivered is the optional delivered-notification seam; nil ⇒ disabled.
	// It fires once per CONFIRMED delivery, carrying the item just delivered.
	OnDelivered DeliveredFunc
	// Pending classifies a delivery error as a legitimate hold rather than a
	// failure. While it returns true the drain retries the head WITHOUT counting
	// the elapsed window toward GiveUpAfter and RESETS the give-up streak, so a
	// slow-but-valid remote decision (e.g. a folder-trust accept) never races a
	// premature give-up, and a transient real failure preceding the hold cannot
	// leak into the held window. nil ⇒ every non-nil delivery error counts
	// (pre-#1014 behaviour). #1014 AC-1.
	Pending PendingFunc
	// SendNow is the optional send-now seam; nil ⇒ SendNow is inert (#2729).
	SendNow SendNowFunc
	// Logger; nil ⇒ slog.Default().
	Logger *slog.Logger
}

Config configures a Queue.

type DeliverFunc

type DeliverFunc func(ctx context.Context, convID string, payload []byte) error

DeliverFunc is the injected reliable-delivery seam — the shape of supervisor.WriteUserTurn. It MUST block while claude is busy (the WaitReady idle gate) and return nil ONLY on a confirmed commit; that blocking IS the drain's turn-end pacing. A non-nil return means the turn was not delivered and the drain retries the same message at the FIFO head.

type DeliveredFunc added in v0.16.0

type DeliveredFunc func(convID string, msg QueuedMessage)

DeliveredFunc is the injected delivered-notification seam (#2115). It mirrors ChangeFunc and GiveUpFunc: invoked NEVER while holding q.mu, from the drain goroutine, once per head whose delivery the seam CONFIRMED. It MUST NOT block indefinitely (it runs on the drain path, so it delays that conversation's next delivery) and MUST be safe for concurrent invocation across conversations. nil disables notification.

Unlike ChangeFunc it is NOT edge-triggered: the delivered message is gone from the backlog moments later, so a consumer that re-read Snapshot would find nothing. It therefore carries the item itself, and the parameter type is the reason this seam exists rather than a wider DeliverFunc.

SECURITY. The parameter is QueuedMessage — the SAME projection Snapshot and SnapshotAll return, which declares no delivery field. So this seam is structurally incapable of handing a consumer the composed payload that may name an on-host path (#2038, and docs/protocol-mobile.md § Error codes forbids putting one on the wire); a consumer cannot leak it by forgetting a filter, and a future one that wants it must widen the exported type to get it. That is deliberately the same barrier EnqueueDelivery's doc block describes, inherited rather than restated. The delivery seam cannot serve this purpose at all: it receives only the payload bytes, which ARE the composed value.

TS is the ENQUEUE timestamp, not the confirmation time. A consumer that stamps a durable record must mint its own: a message can sit in the backlog for a long time, and stamping at enqueue orders it behind entries carrying later times.

type GiveUpFunc added in v0.16.0

type GiveUpFunc func(convID, reason string)

GiveUpFunc is the injected give-up-notification seam. It mirrors ChangeFunc: invoked NEVER while holding q.mu, with the conversation whose head the drain abandoned after persistent delivery failure, plus a daemon-generated human-readable reason (the elapsed retry window and the last delivery error) that NEVER contains the queued message text. It MUST NOT block and MUST be safe for concurrent invocation. nil disables notification.

A later ticket routes this seam to a typed, client-visible error frame over the v2 wire exactly as OnChange routes to the queue_state producer; until then it ships disabled (nil), so the bound + head-drop + clean exit are the only production-visible effect — the give-up is real even when unobserved.

type PendingFunc added in v0.16.0

type PendingFunc func(error) bool

PendingFunc classifies a delivery error as a legitimate hold — the head is being deliberately withheld awaiting an external decision (a person is being asked to approve a tool call, so DeliverFunc declined having written nothing) — rather than a delivery failure. It is an injected predicate because msgqueue is a leaf that must not import the delivery seam's package; the composition root wires it as a predicate over a cmd/pyry-local sentinel marking a delivery held behind an approval parked on a person (#1911). The conversation-scoped question gating that mark is answered at the delivery seam, before the error reaches here — this predicate sees the error and nothing else. It MUST be a pure, non-blocking function (it is called on the drain path). nil ⇒ every non-nil delivery error counts toward the give-up bound (pre-#1014 behaviour). #1014 AC-1.

type Queue

type Queue struct {
	// contains filtered or unexported fields
}

Queue is a per-conversation, in-memory inbound message backlog with one serial drain goroutine per active conversation. The zero value is not usable — construct with New. Enqueue is safe for concurrent use; Run is called once.

func New

func New(cfg Config) (*Queue, error)

New constructs a Queue. It returns an error if cfg.Deliver is nil — the seam is caller-supplied, so a missing one is a wiring error to surface, not a programmer-constant to panic on (contrast eventring.New's bound). RetryInterval and Logger fall back to their defaults.

func (*Queue) Enqueue

func (q *Queue) Enqueue(convID, text string) uint64

Enqueue appends text to convID's FIFO and returns the stable id assigned to it (>= 1, monotonic per conversation, constant until the message is delivered). It never blocks on delivery: if the lifecycle is running and no drain is already servicing the conversation, it spawns one and returns. Conversations' queues are independent — appending to one never blocks or reorders another.

If the conversation's backlog already holds the per-conversation cap (Config.MaxQueuedPerConversation, default defaultMaxQueuedPerConversation), Enqueue REJECTS the message: it returns 0 (never a valid id) without appending, consumes no id, and leaves the existing backlog — including the in-flight head — untouched (reject, never drop). The one caller (the send_message handler) maps a 0 return to a retryable "backlog full" reply so the phone re-issues later.

It is EnqueueDelivery with the two halves equal and no client message id: what a client reads back is byte-for-byte what claude receives. Every caller but the attachment-composing one wants that, which is why this signature is the one that did not change.

The empty message id is not a sentinel and nothing branches on it. It is the true value — a message enqueued through this path was not minted by a client, so it carries no client id — and it is the same value a client that sent "message_id": "" gets. The two being indistinguishable is correct precisely because nothing reads the field.

func (*Queue) EnqueueAttached added in v0.26.0

func (q *Queue) EnqueueAttached(convID, messageID, text, delivery string, attachmentIDs []string) uint64

EnqueueAttached is EnqueueDelivery for a message that named attachments: the ids the send_message handler resolved (#2596) are stored on the record and projected onto the QueuedMessage OnDelivered receives, so the history producer can keep them on the operator's turn. EnqueueDelivery is this with no ids, and this is EnqueueSent with no sender (#2704).

func (*Queue) EnqueueDelivery added in v0.16.0

func (q *Queue) EnqueueDelivery(convID, messageID, text, delivery string) uint64

EnqueueDelivery appends a message whose queued TEXT and delivered PAYLOAD differ, and is Enqueue in every other respect — same id contract, same non-blocking append, same per-conversation cap and same 0-on-reject sentinel.

text is what a client reads back through Snapshot/SnapshotAll (and so through queue_state, on both the enqueue push and the connect-time reconcile); delivery is what the drain hands to DeliverFunc, and therefore what reaches claude's stdin. The one caller passing two different strings is the send_message handler composing a prompt that names an attachment's on-host path (#2038).

messageID is the client's own id for this message, stored on the record and projected beside text (#2092). It is the correlation key a client needs to merge the queued row with the optimistic echo it already drew. It is relayed verbatim — never trimmed, normalised, defaulted or minted — and reaches neither claude (drain delivers delivery, never this) nor any log line.

PARAMETER ORDER: the two identifiers lead, then the content pair. All four are strings, so a transposition compiles; grouping them this way keeps the text/delivery adjacency — the pair whose difference carries the security meaning below — unbroken rather than threading an unrelated id through it.

SECURITY, and it is the reason this method exists rather than a wider Enqueue. The delivery payload may carry a HOST PATH, which docs/protocol-mobile.md § Error codes forbids putting on the wire from the other side (neither attachment.storage_failed nor attachment.not_found may disclose the daemon's layout). QueuedMessage carries no delivery field, so Snapshot and SnapshotAll are structurally incapable of projecting one and no consumer can leak it by omission — a future consumer that wants the path on the wire has to widen the exported type to get it. All three strings stay opaque transit and none is ever logged, delivery least of all.

#2092 widened QueuedMessage for messageID, which is the deliberate act that note describes — and the distinction that keeps the property intact is PROVENANCE, not shape: delivery is daemon-composed and may name an on-host path, while messageID is client-authored and is being returned to the trust domain that authored it. Widening for the second is not licence to widen for the first.

func (*Queue) EnqueueSent added in v0.30.0

func (q *Queue) EnqueueSent(convID, messageID, text, delivery string, attachmentIDs []string, deviceName, clientVersion string, clientSentAt time.Time) uint64

EnqueueSent is EnqueueAttached that also records who sent the message and when the client says it was tapped (#2704): the pairing record's device name, the app version the connection's hello reported, and the client's tap time, zero when it sent none. They are stored on the record and projected onto the QueuedMessage OnDelivered receives, for the history producer. It is the method the send_message handler calls. Nothing here reads, orders by or logs them.

attachmentIDs is COPIED here, at the point it enters the queue, so the record never aliases the caller's slice. An empty list is stored as nil. The ids are never logged, like every other string on the record.

func (*Queue) Remove

func (q *Queue) Remove(convID string, id uint64) bool

Remove drops a queued, not-yet-committing message by id from convID's FIFO, preserving the surviving order, and returns true iff it removed one. An unknown conversation, an unknown or already-delivered id, or the head while it is committing (the write to claude has begun) is a safe no-op that returns false — no panic, no reorder. This is the engine op behind dequeue_message.

The head is removable while it is only WAITING for claude to go idle (draining && !committing): that is the message a user queued behind a running turn precisely so they could still cancel it (#487). Removing the waiting head also cancels its in-flight delivery so the seam's idle-gate wait unblocks at once and the drain advances without writing it. Only once the seam claims the head via commitGate (committing) does the drop no-op, so dequeue_message can never cancel a write already in progress. The committing flag is set/cleared under q.mu, the same lock this method takes, so the claim-versus-drop decision is atomic: either the claim wins and the drop no-ops, or the drop wins and the claim reports the head dropped.

Dropping the waiting head is safe against the drain's own advance because the drain advances by id: advanceLocked drops the front only when it still carries the id the drain attempted, under this same lock (#1484). Nothing here has to keep the head un-droppable for that to hold.

func (*Queue) Run

func (q *Queue) Run(ctx context.Context) error

Run binds the lifecycle ctx, starts a drain for any conversation that already holds a backlog (covering Enqueue-before-Run, with no lost wakeup), then blocks until ctx is done and joins every drain goroutine before returning ctx.Err(). It is called once; the daemon adds it to its errgroup in the wiring slice.

func (*Queue) SendNow added in v0.31.0

func (q *Queue) SendNow(convID string, id uint64) bool

SendNow writes the queued message id into convID's running turn through the SendNow seam instead of waiting for the drain, and returns true iff it was delivered (#2729). On success the message has left the backlog, OnChange fires for the queue_state without it, and OnDelivered fires once with SentNow set.

It is a no-op returning false, with the backlog unchanged, for a nil seam, an unknown conversation, an unknown or already-delivered id, and the head while its idle delivery is committing — the same refusal Remove makes, decided under the same lock, so a committed idle delivery always wins. A seam error (the turn is idle, the session cannot take input mid-turn, no live child) also returns false and puts the message back at its original position, where the drain delivers it at idle as if nothing had happened.

THE MESSAGE IS TAKEN OUT OF THE FIFO FOR THE DURATION OF THE WRITE. That is what settles every race against it with code that already exists: a concurrent Remove cannot find it, and a waiting head taken this way is no longer at the front, so commitGate refuses its in-flight attempt and the drain treats it as dropped — exactly the dequeue path. Taking the waiting head cancels that attempt, as Remove does, so the drain moves on to the next head and waits for idle with it. The take also sets headTaken, so a failed write that puts the head back before the drain re-locks still reads as that clean drop, never as a delivery failure that would start the head's give-up clock.

The write runs with q.mu released, on the caller's goroutine. Nothing here logs the text, the delivery payload or the client's message id.

func (*Queue) Snapshot

func (q *Queue) Snapshot(convID string) []QueuedMessage

Snapshot returns convID's not-yet-confirmed-delivered backlog as an ordered copy (the data queue_state reports). An unknown conversation yields an empty snapshot, not an error. The returned slice is freshly allocated and the elements are value copies, so a caller cannot mutate engine state through it.

The snapshot includes the head even while it is mid-delivery: an item is in the backlog until advanceLocked drops it on a confirmed commit, so "current items" is exactly "not-yet-delivered". The snapshot does not flag which entry is in-flight — Remove returning false is how a consumer learns the head is non-removable.

func (*Queue) SnapshotAll added in v0.16.0

func (q *Queue) SnapshotAll() map[string][]QueuedMessage

SnapshotAll returns every conversation's not-yet-confirmed-delivered backlog keyed by conversation id, omitting any conversation whose backlog is empty. Each value is a freshly allocated slice of value copies (identical semantics to Snapshot, including the in-flight head), so a caller cannot mutate engine state through it. A pure read: it mints no id and dequeues nothing. The empty (non-nil) map means no conversation holds a backlog. It is the connect-time queue reconcile's enumeration seam (#878) — Snapshot reads one named conversation, but convs is private, so enumerating the non-empty ones needs this read.

The whole read runs under q.mu, so the returned set is a single consistent instant with no window between enumerating the conversations and reading each one. A drained-but-retained convQueue (advanceLocked/shrinkLocked leaves the entry with items == nil) is skipped, so an empty conversation contributes no map entry and therefore no queue_state re-send.

type QueuedMessage

type QueuedMessage struct {
	ID            uint64
	MessageID     string
	Text          string
	TS            time.Time
	AttachmentIDs []string
	DeviceName    string
	ClientVersion string
	ClientSentAt  time.Time
	SentNow       bool
}

QueuedMessage is the engine-side projection of ADR 025's {queued_msg_id, text, ts} record (the producer maps ID -> queued_msg_id). It is the ordered element Snapshot returns.

TWO fields are untrusted, phone-originated content, not one: Text and MessageID. The consumer must never log either and must only surface them to the authorized conversation they belong to. ID is the daemon's own per-conversation counter and is the odd one out — do not read MessageID as its sibling because both are ids. MessageID is the client's own id for the message, carried since #2092 so a client can recognise a queued item as one of its own sent messages and draw it once instead of twice; it is relayed verbatim, is "" when the client sent none, and the daemon never mints one. Nothing reads it — it addresses, authorizes, matches and dedupes nothing.

AttachmentIDs (#2596) are the attachment ids the client's send_message named, as the handler resolved them, so the history producer can store them on the operator's turn. They are client-authored and untrusted like MessageID, and the same provenance argument applies: they return to the trust domain that authored them, which is not licence to project the delivery payload. Only the DELIVERED projection (OnDelivered) sets the field; Snapshot and SnapshotAll leave it nil, since queue_state does not carry it.

DeviceName, ClientVersion and ClientSentAt (#2704) say who sent the message and when the client says it was tapped, captured by the handler at enqueue so the history producer can store them on the operator's turn. ClientSentAt is a time the handler already parsed and normalised to UTC, never the client's raw bytes, and zero when the client sent none. Like AttachmentIDs, only the delivered projection sets them, and nothing here reads or logs them.

SentNow (#2729) is true only on the delivered projection of a message SendNow wrote into a running turn rather than the drain at idle. It is what lets an OnDelivered consumer that pairs with the drain's own delivery seam — the channel carry's clear — tell a delivery it did not compose apart from one it did.

func DeliveryMessage added in v0.34.0

func DeliveryMessage(ctx context.Context) (QueuedMessage, bool)

DeliveryMessage returns the safe queued projection for this write attempt. Delivery bytes are deliberately absent. Existing DeliverFunc decorators only need to forward their context; callers outside Queue have no metadata.

type SendNowFunc added in v0.31.0

type SendNowFunc func(ctx context.Context, convID string, id uint64, payload []byte) error

SendNowFunc is the injected send-now seam (#2729): it writes a queued message's delivery payload into the conversation's RUNNING turn, without waiting for idle. It must write nothing and return an error when the write does not belong there (the turn is idle, the session cannot take input mid-turn, no live child), and return nil only once the write has succeeded — the same point at which an idle delivery is confirmed. It is called with q.mu released.

id is the queued message's id, the one OnDelivered's QueuedMessage then carries (#2730), so a consumer can pair the write with its delivered notification without the payload ever reaching OnDelivered.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL