store/file
import filestore "github.com/barevoidco/zelk/core/store/file"Package filestore is a durable store.LogStore on a local filesystem: one append-only log file per session, plus a directory of each session’s outputs and one of its checkpoint versions.
The record format, the write protocol and how crash damage is told apart from corruption are specified in docs/design/durability.md. In short: every append is one framed, checksummed record, acknowledged only after fsync; a crash can damage only the final, unacknowledged record, which is the only damage ever repaired; anything else is reported as corruption.
Inbox keeps observer occurrences outside the session log without requiring a lease. Pending durably seals payloads before returning them for admission; Trim follows log acknowledgment. Both bounds and immutability are enforced.
See docs/design/durability.md for the Windows NTFS process-crash contract.
Constants
Section titled “Constants”const DefaultLockWait = 10 * time.SecondDefaultLockWait is how long an append waits for another store’s append to release a session’s writer lock, unless WithLockWait says otherwise.
const DefaultOpenLogs = 64DefaultOpenLogs is how many session logs a Store keeps open by default.
Variables
Section titled “Variables”var ( // ErrBroken is returned for a session whose writer failed to write or // sync, or to repair a torn tail. The failed batch may or may not be on // disk, and until the machine restarts the page cache can show it // either way, so the session is neither written nor read again: not by // this store, and, through a marker file, not by other stores or // processes either (docs/design/durability.md). ErrBroken = errors.New("session log writer broken by a failed write or sync") // ErrCorrupt is returned for a log or blob whose contents are damaged // in a way a crash can't explain. Nothing is repaired. A whole log // another generation of zelk wrote isn't damaged: reading it reports // event.ErrFormatBreak or event.ErrUnsupportedVersion alone, and // nothing in it is repaired, a torn tail included. ErrCorrupt = store.ErrCorrupt // ErrLocked is returned by Append when another writer, in this process // or another, holds the session log's lock. ErrLocked = errors.New("session log is locked by another writer"))Option
Section titled “Option”type Option func(*Store)Option configures a Store.
WithLockWait
Section titled “WithLockWait”func WithLockWait(d time.Duration) OptionWithLockWait sets how long an append waits for another store’s append to release the session’s writer lock before failing with ErrLocked. Appends hold it only from write to sync; a writer that broke holds it until its process exits.
WithLogger
Section titled “WithLogger”func WithLogger(l *slog.Logger) OptionWithLogger sets the logger the store reports torn-tail repairs to. The default discards everything.
WithOpenLogs
Section titled “WithOpenLogs”func WithOpenLogs(n int) OptionWithOpenLogs bounds how many session logs the store keeps open between appends; the least recently written is closed first, and reopened when next written. The default is DefaultOpenLogs. A broken session’s log stays open regardless (see Close).
type Store struct { // contains filtered or unexported fields}Store is a store.LogStore that keeps each session’s log in its own file under a directory, and each session’s outputs and checkpoint versions in directories beside the logs. A Store is safe for concurrent use. Close it when done.
Example
dir, err := os.MkdirTemp("", "zelk-example-*")if err != nil { panic(err)}defer os.RemoveAll(dir)
ctx := context.Background()s, err := filestore.New(ctx, dir)if err != nil { panic(err)}defer s.Close()
tok := lease.Token{Session: "s1", Fence: 1}now := time.Date(2026, 10, 15, 9, 0, 0, 0, time.UTC)if err := s.Append(ctx, "s1", 0, tok, event.Event{Seq: 1, Time: now, Payload: event.Warning{Code: "hello"}}); err != nil { panic(err)}for ev, err := range s.Read(ctx, "s1", 0) { if err != nil { panic(err) } fmt.Println(ev.Seq, ev.Payload.(event.Warning).Code)}// Output:// 1 helloOutput:
1 hellofunc New(ctx context.Context, dir string, opts ...Option) (*Store, error)New opens the store in dir, which must be the absolute path of an existing directory. The host owns dir and its durability; the store creates its own subdirectories in it and makes them durable before returning. ctx is checked before each step; the file system calls themselves can’t be interrupted.
Store.Adopt
Section titled “Store.Adopt”func (s *Store) Adopt(ctx context.Context, session string, token lease.Token) (uint64, error)Adopt makes everything the session’s log holds durable, records token’s fence, and returns the sequence number of the log’s last event (docs/design/durability.md, L11). A new holder adopts a log before folding it, so it never decides anything from a batch another writer wrote but never synced. Adopting a session that was never written creates its empty log.
Store.Append
Section titled “Store.Append”func (s *Store) Append(ctx context.Context, session string, expectSeq uint64, token lease.Token, evs ...event.Event) errorAppend atomically adds evs to the session’s log as one record, and returns only once the record is synced. It takes the log’s writer lock for this append only (docs/design/durability.md, L9), waiting for another store’s append if one holds it, and refreshes what it knows of the log under the lock, since another store may have written while it was free. ctx is honoured until the write starts; once started, the write and sync run to completion, because abandoning them would break the session.
Store.Blobs
Section titled “Store.Blobs”func (s *Store) Blobs() store.BlobStoreBlobs returns the store of the sessions’ outputs, kept per session under outputs/ (docs/design/retention.md).
Store.Close
Section titled “Store.Close”func (s *Store) Close() errorClose closes the store’s open log files, releasing their locks. Appends after Close fail; reads and blob operations keep working, and a session that broke stays refused.
A broken session’s log is deliberately left open, holding its lock until the process exits: until then the page cache may show the uncertain batch, and the lock is the one guard that can’t fail, so no other writer can adopt the batch even if the broken-session marker couldn’t be written.
Store.DropHistory
Section titled “Store.DropHistory”func (s *Store) DropHistory(ctx context.Context, session string) errorDropHistory removes the session’s version directory and everything in it.
Store.Durable
Section titled “Store.Durable”func (*Store) Durable() boolDurable reports true: logs outlive the process, along with the fences that guard them, so the store needs a lease whose fences do too, such as lease/file.
Store.GetVersion
Section titled “Store.GetVersion”func (s *Store) GetVersion(ctx context.Context, session string, ref blob.Ref) ([]byte, error)GetVersion returns a version of the session’s history after checking it against its digest.
Store.Inbox
Section titled “Store.Inbox”func (s *Store) Inbox() store.InboxInbox returns the store’s durable observer inbox. Operations take the existing session writer lock but require no lease token, and never append to the log.
Example
dir, err := os.MkdirTemp("", "zelk-inbox-example-*")if err != nil { panic(err)}defer os.RemoveAll(dir)ctx := context.Background()s, err := filestore.New(ctx, dir)if err != nil { panic(err)}defer s.Close()if err = s.Inbox().Append(ctx, "session", "build", store.Occurrence{Payload: event.OccurrencePayload{Text: "Build failed"}}); err != nil { panic(err)}pending, err := s.Inbox().Pending(ctx, "session", "build", 0)if err != nil { panic(err)}fmt.Println(pending[0].Number, pending[0].Payload.Text)// Output: 1 Build failedOutput:
1 Build failedStore.Leftovers
Section titled “Store.Leftovers”func (s *Store) Leftovers(ctx context.Context) iter.Seq2[string, error]Leftovers yields the sessions the listing leaves out that still hold storage: logs that are empty or tombstoned, and outputs, file history or inboxes with no log.
Store.PruneVersions
Section titled “Store.PruneVersions”func (s *Store) PruneVersions(ctx context.Context, session string, keep func(digest string) bool) errorPruneVersions removes the session’s versions keep rejects, and any temporary file a crashed PutVersion left behind.
Store.PutVersion
Section titled “Store.PutVersion”func (s *Store) PutVersion(ctx context.Context, session string, data []byte) (blob.Ref, error)PutVersion stores data in the session’s history: written and synced under a temporary name, linked into place, and the directory synced, before it returns.
Store.Read
Section titled “Store.Read”func (s *Store) Read(ctx context.Context, session string, fromSeq uint64) iter.Seq2[event.Event, error]Read yields the session’s events from fromSeq on. A torn tail, the unacknowledged remains of a crash, ends the log silently; corruption is reported as ErrCorrupt, after the whole records before it. Once the store has read or written a session, it reads only from the record holding fromSeq; records before that were verified when they were indexed.
Store.RemoveSession
Section titled “Store.RemoveSession”func (s *Store) RemoveSession(ctx context.Context, session string, token lease.Token) errorRemoveSession removes the session’s outputs, inbox, file history and then its log, under the log’s writer lock (docs/design/retention.md). The log is not decoded or repaired, so unreadable logs can be removed. The fence file stays: a writer whose lease ended before the removal still holds the old log open, and the fence keeps refusing it. A broken log is refused with ErrBroken: it is evidence, and removing it is an operator’s decision.
Store.Sessions
Section titled “Store.Sessions”func (s *Store) Sessions(ctx context.Context) iter.Seq2[store.SessionInfo, error]Sessions yields the sessions whose logs hold an event, most recently updated first. The store remembers how far it has summarized each log, so listing again reads only what was appended since. An unreadable log is yielded with its ID, error and file modification time in Updated; if stat fails, Updated is zero and the error includes that failure.