filekind

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2026 License: MIT Imports: 20 Imported by: ? 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.

README

filekind

filekind defines one self-describing single-file SQLite format: the identity header a file carries, the registry of kinds, and the canonical digest of a file's rows, with one helper in Go and one in Python. Both implement SPEC.md and pass the same golden vectors.

  • Identity. PRAGMA application_id is 0x4F5242xx, the bytes ORB and a kind byte from kinds.tsv; PRAGMA user_version is the kind's format generation. A reader refuses, each by name, an unstamped file, another application's file, an unknown kind, a different kind than expected, and a generation outside the range its code reads.
  • Writing. A stamp sets both fields, reads them back and checkpoints, since a value just set sits in the WAL until a checkpoint. A create runs a new file's schema and stamp once under an exclusive transaction, however many writers race to make it.
  • Digest. Rows of a base table, ordered by a unique key, encoded value by value with their storage classes, separated by kind and set, hashed with SHA-256 and BLAKE3. Never the file's bytes.
  • Values. A kind is sql, base3 (no INTEGER or REAL value outside a rowid alias) or radix. A canonical JSON form for TEXT columns that hold JSON.

Go

go get github.com/bbmumford/filekind

Package filekind imports only the standard library's database/sql and a BLAKE3 package, so it works over any database/sql SQLite driver: tursogo, go-libsql or modernc. It uses no cgo. Package github.com/bbmumford/filekind/sqliteverify opens a file for Verify through modernc SQLite, so only a program that imports it links an engine.

h, err := filekind.Check(ctx, db, filekind.Want{Kind: filekind.AuditSegment, Newest: 1})
if errors.Is(err, filekind.ErrNewerGeneration) {
	// written by a newer release: refuse it, never guess at it
}

err = filekind.Stamp(ctx, db, filekind.AuditSegment, 1)

d, err := filekind.DigestRows(ctx, db, filekind.RowSet{
	Kind: filekind.AuditSegment, Set: "auditLog", Table: "audit_log",
	Columns: []string{"seq", "at", "body"}, Key: []string{"seq"},
})
fmt.Println(d.SHA256Hex(), d.BLAKE3Hex(), d.Rows)

The digest holds the values of Columns only, so every Key column must also be one of the Columns: a row set whose key is outside them is refused with ErrKeyNotCovered, because a signed digest would not bind the rows' keys. A set ordered by a key whose values are not part of what it signs says so with UnsignedKey: true.

Verify checks a file from elsewhere (its connection's query_only and trusted_schema, then quick_check, then the header) once the caller has opened it read-only through standard SQLite. It refuses a connection that does not report both settings safe, so it refuses every connection made through the Turso engine, which cannot set query_only. A file that needs verifying, such as an audit segment or a sealed file, is opened for the check through package sqliteverify even when Turso writes it, once its writer has checkpointed and closed it; a pool the process opens through Turso for its own use is judged by Check alone.

// The file's size is checked against the bound before it is opened read-only
// through modernc SQLite with query_only on and trusted_schema off.
h, err := sqliteverify.File(ctx, path, filekind.Want{Kind: filekind.AuditSegment, Newest: 1}, 64<<20)

// Or keep the safe connection to digest the file after verifying it.
db, err := sqliteverify.Open(path, 64<<20)
defer db.Close()
h, err = filekind.Verify(ctx, db, filekind.Want{Kind: filekind.AuditSegment, Newest: 1})
d, err := filekind.DigestRows(ctx, db, rowSet)

sqliteverify refuses a path that is not a regular file (ErrNotRegularFile) and a file over its bound (ErrTooLarge) before opening it. Create makes a new file of a kind on a *sql.Conn; CheckValues enforces a base3 kind's value rule; CanonicalJSON rewrites a JSON document in the canonical form; ReadFileHeader reads the two fields from a plaintext file without an engine.

Python

pip install ./python              # standard library only
pip install './python[fast]'      # the blake3 package's hasher instead of the built-in one
import sqlite3, filekind

conn = sqlite3.connect(path, isolation_level=None)
filekind.check(conn, filekind.Want("runLedger", 2))
d = filekind.digest_rows(conn, filekind.RowSet(kind="runLedger", set="runs", table="runs",
                                               columns=("path", "outcome"), key=("path",)))
print(d.sha256_hex, d.blake3_hex, d.rows)

filekind.writer.Writer is the writer for a file several processes append to at once: WAL mode, a busy timeout, the create under an exclusive transaction, and every write a short BEGIN IMMEDIATE transaction.

filekind.base3 stores base-3 values by calling the ternary codec package orbitra (orbitra.ternary), imported only when one of its functions is called; import filekind never needs it. Install orbitra from its own checkout first; the base3 extra (pip install './python[base3]') then finds it.

Tests

go test ./...
cd python/tests && PYTHONPATH=.. python3 -m unittest

enginetest/ is a separate module that runs the Go helper against the golden vectors through the Turso engine (tursogo); cd enginetest && go test ./....

Releases

Releases are cut by release-please from conventional commit messages (fix:, feat:, and so on); see AGENTS.md.

Dependencies

  • No other package of this estate.
  • github.com/zeebo/blake3, for the BLAKE3 half of the digest.
  • modernc.org/sqlite, for package sqliteverify and the tests; enginetest requires turso.tech/database/tursogo and replaces github.com/bbmumford/filekind with ../.

Used by

github.com/bbmumford/policypool, whose identity option checks and stamps a pool's database file through it.

Platforms and build

Pure Go, no cgo and no build tags. The module's go directive is 1.25.0. The Python helper needs only the standard library and supports Python 3.9 and later; the release checks run it on 3.9, 3.12 and 3.13.

Licence

MIT. Copyright (c) 2026 Brandon Miller-Mumford. The full text is in LICENSE.

Contributing

AGENTS.md holds the repository's two rules, for people and coding agents alike: no temporary documents in the repository, and conventional commit messages that stand on their own. CLAUDE.md imports it for Claude Code.

Documentation

Index

Constants

View Source
const Prefix uint32 = 0x4F524200

Prefix is the three bytes 'O', 'R', 'B' every registered application_id starts with; the low byte is the kind.

Variables

View Source
var (
	// ErrUnstamped: the file's application_id is zero, so it names no kind.
	ErrUnstamped = errors.New("filekind: file carries no kind")
	// ErrForeignFile: the application_id is set but outside the 'ORB' prefix,
	// or a stamp would take over a user_version another scheme already set.
	ErrForeignFile = errors.New("filekind: file belongs to another application")
	// ErrUnknownKind: the 'ORB' prefix with a kind byte the registry does not hold.
	ErrUnknownKind = errors.New("filekind: kind is not registered")
	// ErrWrongKind: a registered kind other than the one the caller expects.
	ErrWrongKind = errors.New("filekind: file is a different kind")
	// ErrNoGeneration: the right kind with a user_version below 1.
	ErrNoGeneration = errors.New("filekind: file carries no format generation")
	// ErrNewerGeneration: a format generation newer than the caller reads.
	ErrNewerGeneration = errors.New("filekind: format generation is newer than this reader")
	// ErrOlderGeneration: a format generation older than the caller reads.
	ErrOlderGeneration = errors.New("filekind: format generation is older than this reader")
)

Header refusals. Check returns each wrapped in a *HeaderError carrying what the file holds and what the caller asked for; errors.Is matches the sentinel. The Python helper raises an exception of the same name for each (SPEC.md, "Refusals"), and the golden vectors name the outcome the same way.

View Source
var (
	// ErrGenerationBackwards: a stamp would lower a file's format generation.
	ErrGenerationBackwards = errors.New("filekind: stamp would lower the format generation")
	// ErrStampNotHeld: the engine accepted a stamp and then read back other values.
	ErrStampNotHeld = errors.New("filekind: engine did not hold the stamp")
	// ErrCheckpointBusy: the checkpoint could not move every WAL frame into the
	// file, so the header on disk may still be the old one.
	ErrCheckpointBusy = errors.New("filekind: checkpoint did not complete")
	// ErrUnreadableHeader: the engine answered a header pragma with something
	// other than one whole number.
	ErrUnreadableHeader = errors.New("filekind: header pragma did not return one integer")
	// ErrNotPlainFile: ReadFileHeader found neither an empty file nor the
	// plaintext SQLite magic, so its header can only be read through the engine.
	ErrNotPlainFile = errors.New("filekind: not a plaintext SQLite file")
)

Writer refusals.

View Source
var (
	// ErrInvalidArgument: a caller passed an unregistered kind, a generation
	// below 1, or an empty or malformed row set.
	ErrInvalidArgument = errors.New("filekind: invalid argument")
	// ErrNotBaseTable: a row set names a view, a virtual table or nothing.
	ErrNotBaseTable = errors.New("filekind: row set does not name a base table")
	// ErrKeyNotCovered: a row set's Key names a column outside Columns and the
	// set does not say so with UnsignedKey. The key's values decide the order
	// but are not in the stream, so a digest over such a set does not bind
	// them: rows whose keys are renumbered, order kept, digest the same.
	ErrKeyNotCovered = errors.New("filekind: row set key is outside its columns")
	// ErrKeyNotUnique: two rows of a row set share a key, so their order is
	// not fixed by the key.
	ErrKeyNotUnique = errors.New("filekind: row set key is not unique")
	// ErrValueType: a value's Go type disagrees with the storage class typeof
	// reported, or the storage class is not one of the five.
	ErrValueType = errors.New("filekind: value does not match its storage class")
	// ErrInvalidText: a TEXT value is not valid UTF-8.
	ErrInvalidText = errors.New("filekind: text value is not valid UTF-8")
	// ErrBinaryNumber: a base-3 kind holds an INTEGER or REAL value.
	ErrBinaryNumber = errors.New("filekind: base-3 kind holds a binary number")
)

Digest and value refusals.

View Source
var ErrInvalidJSON = errors.New("filekind: not a canonical JSON value")

ErrInvalidJSON: a document CanonicalJSON cannot hold: not one JSON value, not UTF-8, a repeated key, an unpaired surrogate escape, or a number no float64 holds.

View Source
var ErrNotIntact = errors.New("filekind: quick_check found the file damaged")

ErrNotIntact: PRAGMA quick_check did not answer the single row "ok".

View Source
var ErrUnsafeOpen = errors.New("filekind: the file is not opened query_only with trusted_schema off")

ErrUnsafeOpen: Verify found the connection it was handed able to write the file (query_only off), able to run code the file's own schema carries (trusted_schema on), or not reporting either setting. A file from elsewhere is read on those two settings; without them its triggers and the functions its views and indexes name run with the reader's rights. Standard SQLite reports both; the Turso engine reports query_only off and trusted_schema with no row, so a file it writes is verified through standard SQLite (package sqliteverify).

Functions

func CanonicalJSON

func CanonicalJSON(doc []byte) ([]byte, error)

CanonicalJSON rewrites one JSON document in the one form a TEXT column holds JSON in, so equal bodies are equal bytes and digest equal: object keys sorted by their UTF-8 bytes, no whitespace, strings in UTF-8 with only the escapes Python's json.dumps(ensure_ascii=False) writes, integers as their digits, and every other number as Python's repr of the float64 it parses to. The Python helper's canonical_json writes the same bytes for the same document; the golden vectors hold both to it.

func CheckValues

func CheckValues(ctx context.Context, q Querier, kind Kind) error

CheckValues refuses a file of a Base3 kind that holds an INTEGER or REAL value in any column of any of its tables, naming the first table and column it finds. A rowid alias (a rowid table's single INTEGER PRIMARY KEY column) is the engine's own row number and passes. Kinds whose values are not Base3 pass without a read.

func Checkpoint

func Checkpoint(ctx context.Context, q Querier) error

Checkpoint moves every WAL frame into the main file and truncates the WAL, so the header bytes on disk are the values just set. A database in a rollback-journal mode has no WAL and passes. It refuses when a reader or writer kept the checkpoint from finishing, and cannot run inside a transaction.

func EncodeRows

func EncodeRows(ctx context.Context, q Querier, set RowSet, w io.Writer) (uint64, error)

EncodeRows writes set's canonical stream to w and returns its row count. A refusal can come after part of the stream is written; the partial stream is not a digest of anything.

func SetHeader

func SetHeader(ctx context.Context, q Querier, kind Kind, generation int32) error

SetHeader writes kind's application_id and generation into the header and reads both back. It works inside a transaction, where the write commits or rolls back with the rest; the value then sits in the WAL until Checkpoint.

It refuses to take over a file: one stamped with another kind, one outside the 'ORB' prefix, and one whose user_version some other scheme set while the application_id stayed zero. It refuses to lower a generation. Stamping the generation a file already holds is a no-op that still reads back.

func Stamp

func Stamp(ctx context.Context, q Querier, kind Kind, generation int32) error

Stamp is the writer for a file that is not in a transaction: SetHeader, then Checkpoint, then a read-back of both values.

Types

type Digest

type Digest struct {
	SHA256 [32]byte
	BLAKE3 [32]byte
	Rows   uint64
}

Digest is a row set's SHA-256 and BLAKE3 over its canonical stream, and the number of rows the stream holds. Stored in a file, each hash is lowercase hex TEXT.

func DigestRows

func DigestRows(ctx context.Context, q Querier, set RowSet) (Digest, error)

DigestRows hashes the canonical stream of set's rows. It reads rows through q and never the file's bytes, so two files holding the same rows digest the same however their pages are laid out.

func (Digest) BLAKE3Hex

func (d Digest) BLAKE3Hex() string

BLAKE3Hex is the BLAKE3 as lowercase hex, the form a file stores it in.

func (Digest) SHA256Hex

func (d Digest) SHA256Hex() string

SHA256Hex is the SHA-256 as lowercase hex, the form a file stores it in.

type Entry

type Entry struct {
	Kind       Kind
	Name       string
	System     string
	Generation int32
	Encrypted  bool
	Values     Values
	Use        string
}

Entry is one row of kinds.tsv.

Generation is the format generation the registry publishes as current: a writer stamps new files with it, and a reader whose code knows no later generation passes it to Check as the newest it reads.

func ByName

func ByName(name string) (Entry, bool)

ByName returns the registry row named name.

func Lookup

func Lookup(k Kind) (Entry, bool)

Lookup returns the registry row for k.

func Registry

func Registry() []Entry

Registry returns every registered kind in ascending byte order. It panics if the embedded kinds.tsv does not parse, which TestRegistryParses rules out for every build of this package.

type Header struct {
	ApplicationID int32
	UserVersion   int32
}

Header is the two identity fields of a database header: application_id at byte offset 68 and user_version at offset 60, each a big-endian 32-bit integer that the engine reads as signed.

func Check

func Check(ctx context.Context, q Querier, want Want) (Header, error)

Check reads the header and refuses it unless it holds want's kind at a generation want reads. It returns the header it read either way, so a caller that accepts an older generation knows which one it holds.

func Create

func Create(ctx context.Context, conn *sql.Conn, kind Kind, generation int32, schema []string) (Header, error)

Create makes conn's file a new file of kind at generation, once, however many writers race to create it. Inside one BEGIN EXCLUSIVE transaction it reads the header and the schema: an unstamped file with no schema gets the schema statements and the stamp, and a file another writer already created is checked to be kind at exactly generation instead. It then checkpoints and returns the header the file holds.

An unstamped file that already has a schema is refused with ErrUnstamped: taking an existing file into a kind is its own step, never a side effect of opening it. conn must not be in a transaction.

func Read

func Read(ctx context.Context, q Querier) (Header, error)

Read returns the header through the engine, which reads the WAL as well as the main file, so a value set and not yet checkpointed is already the value read here. Both fields come from one statement, headerQuery.

func ReadFileHeader

func ReadFileHeader(path string) (Header, error)

ReadFileHeader reads the header from the file's first 100 bytes without an engine. An empty file is a database not yet written and reads as the zero Header. A file that does not start with the plaintext magic is refused with ErrNotPlainFile: an encrypted file's header is read through the engine.

It sees only what has been checkpointed into the main file; a WAL database whose header was set and not checkpointed still shows the old values here, which is why Stamp checkpoints.

func Verify

func Verify(ctx context.Context, q Querier, want Want) (Header, error)

Verify checks a file from elsewhere that the caller has already opened read-only through standard SQLite, its size bounded first and query_only on and trusted_schema off set (SPEC.md, "Verifying a file from elsewhere"; package sqliteverify makes that open). It reads both settings first and refuses with ErrUnsafeOpen, before any page of the file is read, a connection that reports query_only off or trusted_schema on, or that answers either setting with no row: an engine without the setting cannot be shown to hold it. Then PRAGMA quick_check must answer the one row "ok", and the header must satisfy want, as Check judges it. A damaged file is refused before its header is trusted. The error names how many rows quick_check returned, never their text, which can quote the file. An engine that refuses to read a damaged page returns its own error instead. The size bound stays the caller's: it holds before the open, and Verify is handed an open connection. A file the process opens through the Turso engine for its own use is judged by Check alone.

func (Header) Expect

func (h Header) Expect(want Want) error

Expect judges a header already read, by the same rules Check applies. The refusals are tried in a fixed order, so one header always earns one name: unstamped, foreign, unknown kind, wrong kind, no generation, newer, older.

func (Header) Kind

func (h Header) Kind() (Kind, bool)

Kind splits the application_id into its kind byte; ok is false outside the 'ORB' prefix.

type HeaderError

type HeaderError struct {
	Err   error
	Found Header
	Want  Want
}

HeaderError is a header refusal with the values that caused it. It carries no path or data-source name, only the two header numbers.

func (*HeaderError) Error

func (e *HeaderError) Error() string

func (*HeaderError) Unwrap

func (e *HeaderError) Unwrap() error

type Kind

type Kind uint8

Kind is the low byte of a file's application_id. The zero value is never registered, so an unset Kind is refused wherever one is expected.

const (
	OrbtrdSystemStore    Kind = 0x01
	AccountStore         Kind = 0x02
	Lad                  Kind = 0x03
	TursoraftLocal       Kind = 0x04
	ScopeReplica         Kind = 0x05
	DevicePolicyStore    Kind = 0x06
	AuditSegment         Kind = 0x10
	AuditExport          Kind = 0x11
	RunLedger            Kind = 0x20
	EncodedIds           Kind = 0x21
	RunEvents            Kind = 0x22
	RunRecords           Kind = 0x23
	Lineage              Kind = 0x24
	MemoryBank           Kind = 0x25
	ContinuityStore      Kind = 0x26
	ConversionArtifact   Kind = 0x27
	EfferentGateRecord   Kind = 0x28
	TeacherFieldRecord   Kind = 0x29
	RemovalLedger        Kind = 0x40
	DecisionIndex        Kind = 0x41
	GuardIndex           Kind = 0x42
	PluginContributions  Kind = 0x43
	DocsSearchIndex      Kind = 0x44
	ImplementationLedger Kind = 0x45
	BillingWitness       Kind = 0x50
	UploaderLedger       Kind = 0x51
	Fixture              Kind = 0xff
)

Kinds registered in kinds.tsv. TestConstantsMatchTheRegistry holds every constant to its row and every row to a constant, so the two cannot drift.

func KindOf

func KindOf(applicationID int32) (Kind, bool)

KindOf splits an application_id into its kind byte. ok is false for a value outside the 'ORB' prefix, which is a file another application stamped or one nothing stamped.

func (Kind) ApplicationID

func (k Kind) ApplicationID() int32

ApplicationID is the value PRAGMA application_id holds for a file of kind k. Every registered value is below 2^31, so it reads back as the same positive number from an engine that returns the header field as a signed integer.

func (Kind) String

func (k Kind) String() string

String names k by its registry row, or by its byte when no row holds it.

type Querier

type Querier interface {
	QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
}

Querier is what every function here reads and writes through: *sql.DB, *sql.Conn and *sql.Tx all satisfy it. Pragmas are sent as queries and their rows drained, because the Turso engine answers a pragma as a query that returns rows and refuses nothing sent that way.

type RowSet

type RowSet struct {
	Kind        Kind
	Set         string
	Schema      string
	Table       string
	Columns     []string
	Key         []string
	Where       string
	Args        []any
	UnsignedKey bool
}

RowSet names the rows a digest covers: Columns of the base table Table, in the order given, every row ordered by Key under BINARY collation. Kind and Set are the domain the digest is separated by, so the same rows digested for two kinds, or as two sets of one kind, never share a digest.

Key must be unique over the rows Where selects, because rows that tie on the key have no order an engine is bound to; a tie is refused with ErrKeyNotUnique rather than digested in whatever order the engine chose. Where is an optional SQL condition with Args as its parameters. Schema names an attached database; empty is the main one.

The stream holds the values of Columns only; Key's values decide the order and are not encoded unless they are among Columns. A digest that is signed or sealed binds a row's key only when the key is one of its columns, so every Key column must also be in Columns, or the set is refused with ErrKeyNotCovered. UnsignedKey is the caller's statement that the key's values are not part of what the digest binds (a key that is only a position, renumbered freely): with it set, a Key column outside Columns is digested as before.

type Values

type Values uint8

Values names how a kind stores its values. A Base3 kind holds every value as base-3 text or a base-3 blob, never as an INTEGER or REAL value outside a rowid alias; CheckValues enforces it. A Standard kind uses SQL integers as usual. A Radix kind's rows each name the radix their numbers are written in, so only the kind's own schema can say which values must be base 3, and CheckValues leaves it to that schema's tests.

const (
	Standard Values = iota + 1
	Base3
	Radix
)

func (Values) String

func (v Values) String() string

type Want

type Want struct {
	Kind   Kind
	Newest int32
	Oldest int32
}

Want is what a reader expects of a file: its kind and the generations its code reads. Oldest 0 reads every generation from 1 up to Newest.

Directories

Path Synopsis
Package sqliteverify opens a file from elsewhere through standard SQLite (modernc.org/sqlite) the way filekind.Verify requires, whichever engine wrote the file: read-only, with query_only on and trusted_schema off, after its size is checked against the caller's bound.
Package sqliteverify opens a file from elsewhere through standard SQLite (modernc.org/sqlite) the way filekind.Verify requires, whichever engine wrote the file: read-only, with query_only on and trusted_schema off, after its size is checked against the caller's bound.

Jump to

Keyboard shortcuts

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