history

package
v0.23.0 Latest Latest
Warning

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

Go to latest
Published: Sep 24, 2026 License: MIT Imports: 15 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 history is the durable, append-only, per-conversation message log the daemon writes as it fans envelopes out, and the backward reader that serves a connecting client the messages that happened before it arrived.

It is the storage floor only: nothing here produces or consumes entries. #2114 and #2115 append, #2116 serves a page, #2113 declares the wire verb.

Why a log rather than claude's own transcripts

The daemon owns this log; nothing here reads a file claude wrote. Serving history from claude's transcripts was rejected because that format is not a contract this repo versions — old files are never rewritten, so a serving path over them means supporting every format that ever existed, permanently — because it binds history to one harness (internal/acp is a second front door that will never write those files), and because the daemon already produces the wire mapping every turn.

What one entry is

One entry is one wire envelope: the triple internal/eventring retains — the wire type, the already-marshalled payload bytes and the timestamp — plus a durable id this package mints. Payload bytes are stored and returned OPAQUELY: this package never decodes one and never imports the wire-payload types, which is what keeps it the leaf eventring already is.

Why segments

Retention is none, deliberately, and the access pattern is newest-first walking backwards on demand. Those two decisions are the storage design: the newest segment is small, older ones are opened only when the operator scrolls into them, segment boundaries ARE the index so no sidecar file exists, and a future retention policy becomes a file delete rather than a rewrite. Not because a plain append-only file cannot be opened at its end cheaply — it can, and that was never the reason.

Durability

Process-restart durability, not crash consistency: a store opened over a directory an earlier store wrote reads back everything it wrote, and entry ids continue past every id on disk. Surviving a machine crash is out of scope, which is why no append fsyncs.

A write that loses PARTWAY is not out of scope, and is not a crash: an ordinary ENOSPC or EIO leaves behind a headerless segment or a torn final line, because a failing write reports the bytes it already transferred. An append undoes what it can, and the reader is built to make progress past what it could not — see writeSegment, decodeSegment and load. The rule is that a failed append is a failed append: it never costs a conversation the entries that succeeded before it.

Concurrency

Internally synchronised by one leaf mutex, the posture eventring establishes: more than one goroutine appends to a conversation (the envelope chokepoint and the delivery path) while reads run on a per-connection worker, and no producer takes a lock of its own. No goroutine is spawned and no file handle is held between calls, so there is nothing to shut down and no Close.

Logging

Payload bytes are conversation content and this log is the one place they are written. The package takes no *slog.Logger and makes no log call — the structural form of that guarantee. No error it builds names a payload, a wire type or an entry's size; refusals name the conversation id, the segment file and the failing operation only.

Index

Constants

View Source
const MaxPageEntries int = 4096

MaxPageEntries is the ceiling a requested page size is CLAMPED to — not refused above, since a page is "up to limit entries" and a clamped answer still returns a cursor, so an over-large ask pages rather than fails.

It is what makes Page's work bounded by a constant in this package rather than by its caller's arithmetic. #2116 derives its page size from what fits in the 65519-byte v2 application envelope, so this ceiling is far above anything it can legitimately ask for; without it, a caller passing math.MaxInt would read and decode every segment of the log.

View Source
const MaxSegmentBytes int64 = 1 << 20

MaxSegmentBytes is the named bound a segment rolls at. It is checked BEFORE a write, so a segment may exceed it by at most the one entry that crosses it — which, with Append's refusal of an entry line longer than the bound, is what gives a well-formed segment the structural ceiling the reader caps its allocation at (segmentCeiling).

A tunable starting point, not load-tested, in the same spirit as eventring.MaxEventsPerConversation. Tests construct through newStore to vary it, which is how a segment-boundary crossing is provable with tens of entries instead of thousands.

Variables

View Source
var ErrCorruptSegment = errors.New("history: segment does not decode")

ErrCorruptSegment reports a segment that IS of a recognised version but does not decode: a complete line that is not an entry, or a file past the ceiling a well-formed segment can reach. Deliberately distinct from ErrUnknownVersion — one says "not mine to read", the other "mine, and damaged".

An UNTERMINATED final line is deliberately not in that list: it is the residue of a write that lost partway, it is dropped rather than refused, and decodeSegment carries the reasoning.

View Source
var ErrInvalidCursor = errors.New("history: cursor was not minted for this conversation's log")

ErrInvalidCursor reports a cursor that will not be followed: malformed, of an unknown version, minted for another conversation, naming a segment that is not in this conversation's log, or an offset that is not an entry boundary in it.

ONE sentinel covers all of those on attachments.ErrNotFound's reasoning. The distinctions are exactly what a probe would want — "does this segment exist", "is this a real boundary" — so a consumer that cannot branch on them cannot leak them, and the decision survives a careless dispatch site rather than depending on one.

View Source
var ErrInvalidID = errors.New("history: conversation id is not of canonical shape")

ErrInvalidID reports a conversation id that is not of canonical shape. It is raised before the filesystem is touched, so a refusal leaves nothing behind.

View Source
var ErrInvalidPageSize = errors.New("history: page size must be at least one entry")

ErrInvalidPageSize reports a page request for fewer than one entry. An over-large request is clamped rather than refused; only a non-positive one is an error, because there is no page it could describe.

View Source
var ErrInvalidPayload = errors.New("history: entry payload is not storable")

ErrInvalidPayload reports an entry this package will not store: bytes that are not valid JSON, or an entry whose encoded line exceeds the segment bound.

ONE sentinel covers both because neither is repairable by anyone who could see the difference — both producers hand over the output of a json.Marshal of a wire payload, so either refusal is a daemon bug rather than something a client can re-send its way out of.

View Source
var ErrNotContained = errors.New("history: conversation log directory resolves outside the destination it was built for")

ErrNotContained reports a conversation's log directory whose symlink-resolved path is not the one its id maps to beneath the resolved instance directory — whether it lands outside that directory entirely, or inside it under another conversation. It is deliberately distinguishable from ErrInvalidID: an id refusal means no path was ever built.

View Source
var ErrUnknownVersion = errors.New("history: segment carries a schema version this build does not recognise")

ErrUnknownVersion reports a segment whose first written bytes are not a header this build recognises. The reader returns it having decoded NO entry from that segment, rather than reading it as the version it does know.

Functions

This section is empty.

Types

type Entry

type Entry struct {
	ID      uint64          `json:"id"`
	Type    string          `json:"type"`
	Payload json.RawMessage `json:"payload"`
	TS      time.Time       `json:"ts"`
}

Entry is one retained wire envelope: the durable id this package mints plus the three fields eventring.Event retains. The per-connection envelope id is deliberately absent, exactly as it is there — it is meaningless across connections.

Payload is stored and returned opaquely; nothing in this package decodes it. It round-trips through encoding/json, so JSON-insignificant whitespace does not survive, and both producers hand over already-compact json.Marshal output so in practice the bytes are unchanged. HTML escaping is off, so '<', '>' and '&' survive as written.

type Page

type Page struct {
	Entries []Entry // newest-first
	Cursor  string  // opaque; hand back to Page for the next-older page
	AtStart bool    // the start of the log was reached while filling this page
}

Page is one answer from the backward walk.

AtStart is what distinguishes "the log begins here" from "a full page that may have more behind it". A page that fills EXACTLY at the log's first entry reports AtStart false and a usable Cursor; the call after it returns no entries with AtStart true. So a walk terminates on AtStart, never on an empty Entries — which is also why Cursor is empty whenever AtStart is set.

type Store

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

Store is the per-conversation log rooted at one instance directory. The zero value is not usable — construct with New. All methods are safe for concurrent use.

func New

func New(instanceDir string) *Store

New returns a Store writing beneath instanceDir, with segments bounded at MaxSegmentBytes.

instanceDir is an ARGUMENT and is never resolved from configuration inside this package, matching attachments.EnsureDir. The layout beneath it is conversations/<conversation-id>/history/, a sibling of the attachments directory under the same per-conversation root.

func (*Store) Append

func (s *Store) Append(convID conversations.ConversationID, typ string, payload json.RawMessage, ts time.Time) (uint64, error)

Append records one envelope in convID's log and returns the durable id it minted. Ids are per-conversation, start at 1, strictly increase in append order, and are recovered from disk on the first touch of a conversation, so they continue past every id already written rather than restarting.

That is the one thing eventring's ids cannot do: its counter is in memory and restarts at 1 on every daemon start, which is exactly why its event_id cannot be the durable identifier here. The counter is per-conversation rather than store-wide — the inverse of eventring's #2022 choice — because the defect that drove #2022 cannot arise: every cursor this package mints names its own conversation and is refused on any other, so there is no shared scalar for a watermark taken in one conversation to mute another with.

PRECONDITION, and it carries the whole authorisation property: convID MUST be the conversation the authenticated session is already on, never one a client asserted. conversations.ValidID is a SHAPE predicate, not an authorisation check — a client-supplied id of canonical shape genuinely resolves inside the conversation it names and defeats every check below. This is attachments.ResolvePath's precondition, for the same reason; Intake's resolver-callback shape (reach the conversation through the session, not off the wire) is what a consumer should copy.

payload must be valid JSON and its encoded line must fit the segment bound; both are ErrInvalidPayload. The JSON check and the payload's own length are tested before the filesystem is touched at all; the encoded line carries the id, which is only known once the conversation has been resolved, so that refusal lands after the log directory exists. Neither stores an entry or creates a segment file — an empty directory is the most a refusal leaves.

Not durable against a machine crash: the bytes reach the page cache, not the platter, because the ticket rules crash consistency out of scope rather than buying it with an fsync per append.

func (*Store) Page

func (s *Store) Page(convID conversations.ConversationID, cursor string, limit int) (Page, error)

Page returns up to limit of convID's entries, newest-first, ending at cursor's position when one is given.

Hand back the Cursor of the previous page to get the next older one; a walk terminates when a page reports AtStart. An empty cursor starts at the newest entry, and a conversation with no log on disk reads as empty-and-at-the-start rather than as an error.

PRECONDITION: convID MUST be the conversation the authenticated session is already on — see Append, which carries the full reasoning. This is the method a remote request reaches, so the precondition is load-bearing here first.

cursor arrives from an untrusted client: the wire declares it opaque and the handler above passes it through without parsing, so THIS is the only place a cursor is ever validated. A cursor this package did not mint is refused rather than followed, and a refusal reads nothing.

limit below 1 is ErrInvalidPageSize; above MaxPageEntries it is clamped. The result slice is never pre-allocated from it, so an over-large ask pins no memory of its own.

The work is bounded by the page, not by the log: the number of segments opened and the bytes read from them are a function of limit and the segment bound, never of how many entries the conversation holds. The one cost that does grow with the log is the single directory listing, which opens no segment and decodes no entry — the price of tolerating a future retention delete, see listSegments.

Jump to

Keyboard shortcuts

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