corestore

package
v2.8.2 Latest Latest
Warning

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

Go to latest
Published: Aug 7, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Overview

Package corestore owns the daemon's authoritative SQLite state in daemon.db.

The store exposes typed transactions for mutable state, append-only evidence, broker-scoped order safety, retained observations, and statement projections. Every durable mutation advances a monotonic authority head. Opening, inspection, backup, and upgrade paths validate schema, integrity, content hashes, and any caller-supplied rollback floor; they never repair or recreate an existing authority after a validation failure.

Store serializes mutations internally. Callers never receive the underlying SQL handle and must use the combined operations when state and evidence need to become visible atomically.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrRevisionConflict       = errors.New("corestore: revision conflict")
	ErrPreviewTokenConsumed   = errors.New("corestore: preview token already consumed")
	ErrBrokerScopeCollision   = errors.New("corestore: broker scope collision")
	ErrAuthorityMismatch      = errors.New("corestore: authority mismatch")
	ErrRollback               = errors.New("corestore: authority rollback detected")
	ErrBlocked                = errors.New("corestore: health is blocked")
	ErrOrderIDFloor           = errors.New("corestore: reserved order id does not advance global floor")
	ErrOrderNotModifiable     = errors.New("corestore: order durable frontier is not modifiable")
	ErrCheckpointBusy         = errors.New("corestore: WAL checkpoint is busy")
	ErrLegacyImportConflict   = errors.New("corestore: legacy authority was already imported from a different source")
	ErrFreshAuthorityConflict = errors.New("corestore: fresh trading authority requires empty order and purge state")
	ErrProjectionConflict     = errors.New("corestore: immutable projection conflict")
	ErrUpgradeRequired        = errors.New("corestore: schema upgrade required")
	ErrRecoveryNotEligible    = errors.New("corestore: transient recovery is not eligible")
)

Store errors classify authority, concurrency, and durability failures that callers may handle without parsing error text.

Functions

This section is empty.

Types

type ActionKind

type ActionKind string

ActionKind classifies the broker-side action represented by durable order evidence.

const (
	ActionPlace        ActionKind = "place"
	ActionModify       ActionKind = "modify"
	ActionCancel       ActionKind = "cancel"
	ActionPurge        ActionKind = "purge"
	ActionRestore      ActionKind = "restore"
	ActionExercise     ActionKind = "exercise"
	ActionSmokeCleanup ActionKind = "smoke_cleanup"
)

Supported broker action kinds.

type AuthorityHead

type AuthorityHead struct {
	AuthorityEpoch   string
	HeadGeneration   int64
	LastEventSeq     int64
	SignerGeneration int64
}

AuthorityHead is the rollback-detection identity and monotonic write head carried inside every database and backup.

type BackupInfo

type BackupInfo struct {
	Path          string
	SchemaVersion int
	Head          AuthorityHead
	Integrity     IntegrityReport
}

BackupInfo describes a validated standalone authority backup.

func PrepareUpgradeTargetBackup added in v2.6.0

func PrepareUpgradeTargetBackup(ctx context.Context, opts UpgradeTargetBackupOptions) (BackupInfo, error)

PrepareUpgradeTargetBackup creates or reuses an independently copied, verified backup of one exact published target. It is deliberately separate from PrepareUpgrade: calling it only after candidate publication prevents a large source backup, candidate, and target backup from consuming space at the same time while the bloated source file is still live.

func VerifyBackup

func VerifyBackup(ctx context.Context, path string, minimum AuthorityHead) (BackupInfo, error)

VerifyBackup performs read-only schema/checksum, integrity, foreign-key, and minimum-head checks. It never upgrades or repairs the candidate.

func VerifySealedBackup

func VerifySealedBackup(ctx context.Context, path string, minimum AuthorityHead) (BackupInfo, error)

VerifySealedBackup verifies a backup that was sealed at whatever schema version was current when it was written. A sealed artifact is frozen, so requiring it to match today's version makes every future migration fail startup once a sealed backup exists. Genuineness is proved instead by its migration ledger being a valid, checksum-matching prefix of the current plan, which validateSchemaLedgerWithPlan already checks.

type BrokerScope

type BrokerScope struct {
	ScopeKey string
	Endpoint string
	ClientID int
	Account  string
	Mode     string
}

BrokerScope binds an authority namespace to all broker identity pins. A ScopeKey can never be rebound, and one binding cannot be aliased by a second ScopeKey.

type CapitalEventProjection

type CapitalEventProjection struct{ Kind, AmountBaseText, EffectiveAt, ReportID string }

CapitalEventProjection is the typed searchable projection of a capital event.

type CheckpointResult

type CheckpointResult struct {
	Busy               int
	LogFrames          int
	CheckpointedFrames int
}

CheckpointResult reports SQLite WAL checkpoint progress. A nonzero Busy value means the authority was not fully quiesced.

type EventDiscardSelector added in v2.8.0

type EventDiscardSelector struct {
	ScopeKey  string
	EventType string
	Predicate string
}

EventDiscardSelector identifies the one reviewed class of event snapshots a migration may discard. Predicate is a frozen implementation identifier, not caller-supplied SQL and not a general event-retention surface.

type EventDiscardSummary added in v2.8.0

type EventDiscardSummary struct {
	MigrationVersion    int
	MigrationName       string
	Selector            EventDiscardSelector
	RemovedRows         int64
	PayloadBytes        int64
	OrderedDigestSHA256 string
}

EventDiscardSummary is deterministic evidence of the event rows one maintenance migration removed from its disposable working snapshot. OrderedDigestSHA256 uses the domain "canary.event-discard.v1\x00", then the selector strings as 8-byte big-endian lengths plus bytes, then each event sequence as 8-byte big-endian plus its stored 32-byte payload digest in ascending sequence order. Payload bytes are never copied into coordination state.

type EventInput

type EventInput struct {
	ScopeKey    string
	EventKey    string
	Type        string
	Action      string
	Origin      string
	OccurredAt  time.Time
	PayloadJSON []byte
	Projection  EventProjection
}

EventInput is one append-only event and an optional typed projection written in the same transaction. PayloadJSON is retained byte-for-byte.

type EventProjection

type EventProjection struct {
	RegimeDecision   *RegimeDecisionProjection
	RuleTransition   *RuleTransitionProjection
	StressTransition *StressTransitionProjection
	CapitalEvent     *CapitalEventProjection
	RiskPolicyEvent  *RiskPolicyEventProjection
	ProposalOutcome  *ProposalOutcomeProjection
}

EventProjection is a typed tagged union; zero values append only the canonical event_log row. At most one member may be non-nil.

type EventQuery

type EventQuery struct {
	ScopeKey      string
	Type          string
	FromAtMS      int64
	ToAtMS        int64
	AfterEventSeq int64
	Limit         int
}

EventQuery filters append-only events. Zero-valued filters are open and AfterEventSeq provides forward pagination.

type EventReceipt

type EventReceipt struct {
	EventSeq   int64
	RecordedAt time.Time
	Head       AuthorityHead
}

EventReceipt identifies a committed event and the single resulting authority head shared by its mutation batch.

type EventRecord

type EventRecord struct {
	EventSeq    int64
	ScopeKey    string
	EventKey    string
	Type        string
	Action      string
	Origin      string
	OccurredAt  time.Time
	RecordedAt  time.Time
	PayloadJSON []byte
}

EventRecord is one retained append-only event in event-sequence order.

type ForeignKeyViolation

type ForeignKeyViolation struct {
	Table       string
	RowID       *int64
	ParentTable string
	ForeignKey  int64
}

ForeignKeyViolation describes one row returned by SQLite foreign_key_check.

type Health

type Health struct {
	Ready            bool
	Code             string
	BlockedAt        time.Time
	RecoveryEligible bool
}

Health is fail-closed mutation health. Critical failures caused by a full, busy, readonly, corrupt, or I/O-failing SQLite store remain latched until an explicit reopen. RecoveryEligible is true only for the narrow case where a mutation committed but reading its post-commit head hit the bounded context deadline; the live store may clear that latch only after an integrity, identity, monotonic-head, and external-watermark proof succeeds.

type InspectOptions

type InspectOptions struct {
	Path          string
	MinimumHead   *AuthorityHead
	TargetVersion int
}

InspectOptions configures a non-mutating authority inspection. Path must already exist. MinimumHead, when non-nil, enforces the external monotonic watermark while the database is still opened read-only. TargetVersion selects one frozen migration-plan prefix; zero means the current version.

type Inspection

type Inspection struct {
	Path           string
	SchemaVersion  int
	TargetVersion  int
	Status         InspectionStatus
	Head           AuthorityHead
	Integrity      IntegrityReport
	HeadTransition UpgradeHeadTransition
}

Inspection is the validated identity, version, and write head of an authority database. TargetVersion is the selected frozen plan version.

func Inspect

func Inspect(ctx context.Context, opts InspectOptions) (Inspection, error)

Inspect validates an existing authority without migrating, repairing, or opening it for writes. A supported older version is reported as InspectionUpgradeRequired rather than treated as corruption.

func QuiesceForReplacement

func QuiesceForReplacement(ctx context.Context, opts QuiesceOptions) (Inspection, error)

QuiesceForReplacement checkpoints the exact validated old authority and removes only disposable SQLite sidecars. The caller must hold the daemon's state-root persistence lock and have closed every Store handle for this path for the full call through atomic replacement. It is intentionally separate from PrepareUpgrade because this is the one step that may change SourcePath's physical representation, and belongs immediately before atomic publication.

type InspectionStatus

type InspectionStatus string

InspectionStatus classifies whether a validated authority is directly serviceable by this build or requires an out-of-place upgrade.

const (
	InspectionCurrent         InspectionStatus = "current"
	InspectionUpgradeRequired InspectionStatus = "upgrade_required"
)

Inspection statuses returned by Inspect.

type IntegrityReport

type IntegrityReport struct {
	QuickCheckResults    []string
	ForeignKeyViolations []ForeignKeyViolation
}

IntegrityReport combines SQLite structural and foreign-key results. Content hash mismatches are returned as errors rather than represented in this value.

func (IntegrityReport) OK

func (r IntegrityReport) OK() bool

OK reports whether SQLite returned exactly one successful quick-check row and no foreign-key violations.

type LegacyConsumedToken

type LegacyConsumedToken struct {
	Scope          BrokerScope
	PreviewTokenID string
	ConsumedAt     time.Time
}

LegacyConsumedToken is a consumed canonical preview-token identifier and broker scope recovered during one-time legacy import.

type LegacyOrderFloor

type LegacyOrderFloor struct {
	Scope BrokerScope
	Floor int64
}

LegacyOrderFloor is a broker-scoped conservative order-ID floor recovered during one-time legacy import.

type LegacyOrderImport

type LegacyOrderImport struct {
	SourceFingerprint string
	GlobalFloor       int64
	ScopedFloors      []LegacyOrderFloor
	ConsumedTokens    []LegacyConsumedToken
	Events            []OrderEventRecord
}

LegacyOrderImport is the complete one-time order-authority cutover input. SourceFingerprint makes replay of the same source idempotent and rejects a different source after import.

type LegacyOrderImportResult

type LegacyOrderImportResult struct {
	Imported  bool
	EventSeqs []int64
	Head      AuthorityHead
}

LegacyOrderImportResult reports whether this call performed the import and the resulting event sequences and authority head.

type LifecycleCommit

type LifecycleCommit struct {
	Scope  BrokerScope
	Events []OrderEventRecord
	State  *StateDocumentCAS
}

LifecycleCommit couples order lifecycle events with an optional state CAS in one transaction.

type LifecycleResult

type LifecycleResult struct {
	EventSeqs []int64
	State     *StateDocument
	Head      AuthorityHead
}

LifecycleResult reports the committed event sequences, optional state revision, and resulting authority head.

type Observation

type Observation struct {
	ID            int64
	ScopeKey      string
	Source        string
	Kind          string
	ObservedAt    time.Time
	RecordedAt    time.Time
	ContentType   string
	Payload       []byte
	PayloadSHA256 [sha256.Size]byte
	MetadataJSON  []byte
	// DecisionEligible is a typed authority boundary. Imported legacy
	// observations are false and must never seed current runtime state.
	DecisionEligible bool
}

Observation is a retained source measurement. Payload is evidence, not trusted authority; only DecisionEligible rows may feed live decisions.

type ObservationDiscardSelector added in v2.6.0

type ObservationDiscardSelector struct {
	ScopeKey string
	Source   string
	Kind     string
}

ObservationDiscardSelector identifies one exact class of derived observations that a reviewed migration may discard. All three fields are required; this is not a general retention or expiry surface.

type ObservationDiscardSummary added in v2.6.0

type ObservationDiscardSummary struct {
	MigrationVersion    int
	MigrationName       string
	Selector            ObservationDiscardSelector
	RemovedRows         int64
	PayloadBytes        int64
	OrderedDigestSHA256 string
}

ObservationDiscardSummary is deterministic evidence of the rows one maintenance migration removed from its disposable working snapshot. OrderedDigestSHA256 uses the domain "canary.observation-discard.v1\x00", then each selector string as an 8-byte big-endian length plus bytes, then each observation ID as 8-byte big-endian plus its stored 32-byte payload digest in ascending ID order. Payload bytes are never copied into coordination state.

type ObservationInput

type ObservationInput struct {
	ScopeKey         string
	Source           string
	Kind             string
	ObservedAt       time.Time
	ContentType      string
	Payload          []byte
	MetadataJSON     []byte
	DecisionEligible bool
}

ObservationInput stores Payload byte-for-byte. ContentType and MetadataJSON describe it without interpreting untrusted source content as authority.

type ObservationQuery

type ObservationQuery struct {
	ScopeKey           string
	Source             string
	Kind               string
	FromObservedAtMS   int64
	ToObservedAtMS     int64
	AfterObservationID int64
	DecisionEligible   *bool
	Limit              int
}

ObservationQuery filters observations within one required scope. Time bounds are inclusive Unix milliseconds, AfterObservationID provides forward pagination, and a nil DecisionEligible includes both eligibility classes.

type ObservationReceipt

type ObservationReceipt struct {
	ID            int64
	PayloadSHA256 [sha256.Size]byte
	RecordedAt    time.Time
}

ObservationReceipt identifies one immutable observation and the exact payload digest recorded for it.

type OperationalPruneSelector added in v2.8.0

type OperationalPruneSelector struct {
	Predicate string
}

OperationalPruneSelector identifies the one reviewed beta-history reset. Predicate is a frozen implementation identifier; it is never caller input and does not establish a general retention or age-based deletion surface.

type OperationalPruneSummary added in v2.8.0

type OperationalPruneSummary struct {
	MigrationVersion int
	MigrationName    string
	Selector         OperationalPruneSelector

	RemovedObservationRows         int64
	RemovedObservationPayloadBytes int64
	ObservationDigestSHA256        string
	RemovedEventRows               int64
	RemovedEventPayloadBytes       int64
	EventDigestSHA256              string

	RemovedRegimeDecisionRows   int64
	RemovedRegimeIndicatorRows  int64
	RemovedRuleTransitionRows   int64
	RemovedStressTransitionRows int64
}

OperationalPruneSummary is the deterministic receipt for the v6 operational-only compaction. Observation and event digests bind the ordered row identities to their already-stored payload hashes. Projection rows are derived from those event payloads, so fixed per-table counts prove that the matching children were removed before their parent events without copying private payloads into coordination state.

type Options

type Options struct {
	Path        string
	BusyTimeout time.Duration
	// MinimumHead, when non-nil, prevents opening an older copy of the same
	// authority. It is intended for restore/backup selection boundaries.
	MinimumHead *AuthorityHead
	// CommitObserver runs synchronously after every successful durable
	// mutation while the store's write lock is still held. Production uses it
	// to persist an external monotonic head; an observer failure is returned
	// to the caller and latches the store unhealthy without rolling back the
	// already-committed SQLite transaction.
	CommitObserver func(AuthorityHead) error
}

Options configures the authoritative store. Path is required; the daemon integration decides where daemon.db lives.

type OrderEventRecord

type OrderEventRecord struct {
	EventSeq        int64
	Scope           BrokerScope
	EventKey        string
	AtMS            int64
	Type            string
	Action          ActionKind
	Origin          TransmitOrigin
	OrderRef        string
	PreviewTokenID  string
	ReservedOrderID int64
	PermID          int64
	Status          string
	RawJSON         []byte
}

OrderEventRecord is one append-only order lifecycle event bound to an exact broker scope. RawJSON is retained evidence and is not interpreted as authorization.

type OrderQuery

type OrderQuery struct {
	ScopeKey        string
	FromAtMS        int64
	ToAtMS          int64
	AfterEventSeq   int64
	OrderRef        string
	ReservedOrderID *int64
	PermID          *int64
	PreviewTokenID  string
	Limit           int
}

OrderQuery filters order events in ascending event-sequence order. AfterEventSeq provides forward pagination; nil order-ID pointers omit those filters, while zero-valued time bounds are open.

type PreTransmitRequest

type PreTransmitRequest struct {
	Scope                 BrokerScope
	TokenDigest           PreviewTokenDigest
	AuthorityEpoch        string
	SignerGeneration      int64
	RequestedOrderIDFloor int64
	ReservedOrderID       int64
	// ExpectedOrderEventSeq binds a modify to the exact durable per-order
	// frontier it validated. Nil leaves place/cancel/other actions unconditional.
	ExpectedOrderEventSeq *int64
	Action                ActionKind
	Origin                TransmitOrigin
	Events                []OrderEventRecord
}

PreTransmitRequest is committed before a caller may transmit. Success is evidence of durable staging, not broker-submit authority.

type PreTransmitResult

type PreTransmitResult struct {
	EffectiveOrderIDFloor int64
	EventSeqs             []int64
	Head                  AuthorityHead
}

PreTransmitResult is durable proof that the pre-transmit transaction succeeded. It does not itself authorize or confirm a broker transmission.

type PreviewTokenDigest

type PreviewTokenDigest [sha256.Size]byte

PreviewTokenDigest is the persisted SHA-256 identity of a canonical preview token identifier. Raw signed preview tokens do not belong in the store.

func HashPreviewTokenID

func HashPreviewTokenID(previewTokenID string) PreviewTokenDigest

HashPreviewTokenID hashes the canonical preview-token identifier. Callers must not pass the raw signed token; legacy state stores only this identifier.

type ProposalOutcomeProjection

type ProposalOutcomeProjection struct{ ProposalKey, Revision, Bucket, Symbol, SecType, Action, State string }

ProposalOutcomeProjection is the typed searchable projection of a proposal outcome event.

type QuiesceOptions

type QuiesceOptions struct {
	Path                  string
	ExpectedSchemaVersion int
	ExpectedHead          AuthorityHead
}

QuiesceOptions identifies the exact old authority that may be physically checkpointed immediately before an atomic candidate replacement. The caller must hold the state-root persistence lock and must have closed every Store handle; SQLite cannot prove that process-level ownership from a pathname.

type RecomputeUpgradeMaintenanceOptions added in v2.6.0

type RecomputeUpgradeMaintenanceOptions struct {
	SourcePath            string
	ExpectedSchemaVersion int
	TargetVersion         int
	ExpectedHead          AuthorityHead
}

RecomputeUpgradeMaintenanceOptions identifies an exact immutable source backup and frozen target plan. RecomputeUpgradeMaintenance derives the same discard evidence as candidate preparation without changing any file.

type RegimeDecisionProjection

type RegimeDecisionProjection struct {
	DecisionKey string
	Stage       string
	Severity    string
	Readiness   string
	Confidence  string
	Verdict     string
	Fingerprint string
	Indicators  []RegimeIndicatorProjection
}

RegimeDecisionProjection is the typed searchable projection of a regime decision event.

type RegimeIndicatorProjection

type RegimeIndicatorProjection struct {
	Indicator       string
	Status          string
	Band            string
	Value           *float64
	Depth           *float64
	StreakSessions  *int64
	Freshness       string
	Eligible        *bool
	Latched         bool
	ThresholdsLabel string
}

RegimeIndicatorProjection is one indicator row attached to a projected regime decision.

type RevisionConflictError

type RevisionConflictError struct {
	Expected int64
	Actual   int64
	Exists   bool
}

RevisionConflictError reports the actual state observed after a failed compare-and-swap.

func (*RevisionConflictError) Error

func (e *RevisionConflictError) Error() string

Error describes the expected revision and the state observed in the store.

func (*RevisionConflictError) Is

func (e *RevisionConflictError) Is(target error) bool

Is reports whether the error matches ErrRevisionConflict.

type RiskPolicyEventProjection

type RiskPolicyEventProjection struct {
	Kind, PolicyID, PolicyFingerprint string
	PolicyVersion                     *int64
}

RiskPolicyEventProjection is the typed searchable projection of a risk-policy governance event.

type RuleTransitionProjection

type RuleTransitionProjection struct {
	RuleID, Status, PreviousStatus, PolicyID, PolicyFingerprint string
	PolicyVersion                                               *int64
}

RuleTransitionProjection is the typed searchable projection of a rule transition event.

type StateDocument

type StateDocument struct {
	ScopeKey  string
	Kind      string
	Revision  int64
	JSON      []byte
	UpdatedAt time.Time
}

StateDocument is the current revision of one scope- and kind-addressed JSON document. JSON contains verified stored bytes and UpdatedAt is the commit timestamp.

type StateDocumentCAS

type StateDocumentCAS struct {
	ScopeKey         string
	Kind             string
	ExpectedRevision int64
	JSON             []byte
	// UpdatedAtNotBefore is an optional atomic commit-clock floor. The store
	// compares it with the exact timestamp it will persist inside the same
	// critical mutation, before touching the document or authority head. It is
	// zero for ordinary callers.
	UpdatedAtNotBefore time.Time
}

StateDocumentCAS requests a compare-and-swap update. ExpectedRevision zero creates a missing document at revision one; a positive value updates exactly that revision. UpdatedAtNotBefore can reject a commit whose clock would move behind a retained authority timestamp.

type StatementEquityDayRecord

type StatementEquityDayRecord struct {
	ID                  int64
	ScopeKey            string
	AccountKey          string
	Day                 string
	EquityBaseText      string
	StatementFileKey    string
	StatementFileSHA256 [sha256.Size]byte
	GeneratedAt         time.Time
	RawJSON             []byte
}

StatementEquityDayRecord is the current statement-derived winner for one account and day, linked to the exact retained statement digest.

type StatementFileRecord

type StatementFileRecord struct {
	ScopeKey             string
	FileKey              string
	SizeBytes            int64
	SHA256               [sha256.Size]byte
	Status               string
	StatementGeneratedAt *time.Time
	IngestedAt           *time.Time
	UpdatedAt            time.Time
}

StatementFileRecord is one file in the current retained-statement inventory. The digest, rather than the file name or size, identifies a restatement.

type Store

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

Store is the daemon-owned authoritative handle. Its database handle is intentionally private so all writes pass through typed transactions.

func Open

func Open(ctx context.Context, opts Options) (*Store, error)

Open validates or creates the authority at opts.Path and returns a single-connection store. Existing older schemas return UpgradeRequiredError; future, corrupt, rolled-back, or otherwise invalid authorities are never repaired or recreated.

func (*Store) AdvanceSignerGeneration

func (s *Store) AdvanceSignerGeneration(ctx context.Context, expected, next int64) (AuthorityHead, error)

AdvanceSignerGeneration atomically advances the preview-token signer generation from expected to a larger next value and advances the authority head. A concurrent or stale expected value returns ErrAuthorityMismatch.

func (*Store) AppendEvents

func (s *Store) AppendEvents(ctx context.Context, inputs []EventInput) ([]EventReceipt, error)

AppendEvents records a non-empty event batch, its typed projections, and one authority-head advance atomically.

func (*Store) AppendObservation

func (s *Store) AppendObservation(ctx context.Context, input ObservationInput) (ObservationReceipt, error)

AppendObservation stores one immutable observation and advances the authority head.

func (*Store) AppendObservations

func (s *Store) AppendObservations(ctx context.Context, inputs []ObservationInput) ([]ObservationReceipt, error)

AppendObservations stores one batch atomically, preserving each payload's exact bytes alongside a digest.

func (*Store) AppendOrderEvents

func (s *Store) AppendOrderEvents(ctx context.Context, events []OrderEventRecord) ([]int64, error)

AppendOrderEvents appends normal lifecycle events atomically and returns their stable event_seq values in input order.

func (*Store) AppendOrderEventsAtHead

func (s *Store) AppendOrderEventsAtHead(ctx context.Context, expectedLastEventSeq int64, events []OrderEventRecord) ([]int64, error)

AppendOrderEventsAtHead appends events only when the authoritative order event frontier still equals expectedLastEventSeq. It is the reconciliation CAS boundary: a journal write after the caller's reload makes absence evidence stale instead of allowing it to close a newer row.

func (*Store) AuthorityHead

func (s *Store) AuthorityHead(ctx context.Context) (AuthorityHead, error)

AuthorityHead reads the current rollback identity and monotonic write head.

func (*Store) Backup

func (s *Store) Backup(ctx context.Context, destination string) (BackupInfo, error)

Backup creates a verified, consistent backup without replacing an existing destination. The returned head is read from the backup snapshot itself.

func (*Store) CheckIntegrity

func (s *Store) CheckIntegrity(ctx context.Context) (IntegrityReport, error)

CheckIntegrity verifies SQLite structure, foreign keys, and application-level content hashes without modifying the store.

func (*Store) Checkpoint

func (s *Store) Checkpoint(ctx context.Context) (CheckpointResult, error)

Checkpoint quiesces in-process writers and fully checkpoints/truncates the WAL. A busy result is explicit; callers must not publish a cutover snapshot.

func (*Store) Close

func (s *Store) Close() error

Close releases the database handle and reapplies private modes to the authority and any SQLite sidecars. It is idempotent.

func (*Store) CommitLifecycle

func (s *Store) CommitLifecycle(ctx context.Context, commit LifecycleCommit) (LifecycleResult, error)

CommitLifecycle appends exact-route lifecycle events and optionally performs a versioned state mutation in the same transaction. The state scope may be global and need not equal the broker scope.

func (*Store) CompareAndSwapStateDocument

func (s *Store) CompareAndSwapStateDocument(ctx context.Context, update StateDocumentCAS) (StateDocument, error)

CompareAndSwapStateDocument commits one revision and advances the authority head atomically. A stale expected revision returns RevisionConflictError.

func (*Store) CompareAndSwapStateDocumentWithBoundObservations

func (s *Store) CompareAndSwapStateDocumentWithBoundObservations(
	ctx context.Context,
	update StateDocumentCAS,
	inputs []ObservationInput,
	build func(nextRevision int64, receipts []ObservationReceipt) ([]byte, error),
) (StateDocument, []ObservationReceipt, error)

CompareAndSwapStateDocumentWithBoundObservations appends immutable observations, gives their uncommitted receipts to build, and publishes the resulting state document under one transaction and one head advance. This is the narrow path for state JSON that must name the exact observations created by the same commit. A build error or stale state revision rolls every observation back.

build must be deterministic and must not call the Store. It receives the revision the document will have and a copy of the receipts in input order.

func (*Store) CompareAndSwapStateDocumentWithEvents

func (s *Store) CompareAndSwapStateDocumentWithEvents(ctx context.Context, update StateDocumentCAS, inputs []EventInput) (StateDocument, []EventReceipt, error)

CompareAndSwapStateDocumentWithEvents commits a state revision, a non-empty event batch, its projections, and one authority-head advance atomically.

func (*Store) CompareAndSwapStateDocumentWithObservations

func (s *Store) CompareAndSwapStateDocumentWithObservations(ctx context.Context, update StateDocumentCAS, inputs []ObservationInput) (StateDocument, []ObservationReceipt, error)

CompareAndSwapStateDocumentWithObservations changes current state and appends its immutable observations under one commit and one head advance.

func (*Store) ExactDecisionEligibleObservation

func (s *Store) ExactDecisionEligibleObservation(ctx context.Context, receiptID int64, scopeKey, source, kind string, observedAt time.Time) (Observation, bool, error)

ExactDecisionEligibleObservation returns one immutable observation only when its receipt ID, authority coordinates, exact observation time, and decision-eligibility all match. It is the narrow live-decision reader for a state document that already names its evidence receipt; it never searches for a newest or nearby substitute.

func (*Store) GetStateDocument

func (s *Store) GetStateDocument(ctx context.Context, scopeKey, kind string) (StateDocument, bool, error)

GetStateDocument returns the current verified document for scopeKey and kind. The boolean is false when no document exists; a digest mismatch is an error, never absence.

func (*Store) GlobalOrderIDFloor

func (s *Store) GlobalOrderIDFloor(ctx context.Context) (int64, error)

GlobalOrderIDFloor returns the greatest order ID reserved across all broker scopes, or zero when no floor exists.

func (*Store) Health

func (s *Store) Health() Health

Health returns mutation health. A false Ready value blocks critical mutations. Only the explicitly eligible post-commit head-read timeout can be proof-recovered in process; every other latch requires an explicit reopen.

func (*Store) ImportLegacyOrderAuthority

func (s *Store) ImportLegacyOrderAuthority(ctx context.Context, input LegacyOrderImport) (LegacyOrderImportResult, error)

ImportLegacyOrderAuthority performs the one-time cutover transaction. It imports token tombstones and conservative floors independently of the selected full-chain events, so omitted terminal chains never require fabricated user-visible events. SourceFingerprint makes retries idempotent.

func (*Store) InitializeFreshOrderAuthority

func (s *Store) InitializeFreshOrderAuthority(ctx context.Context, initialState StateDocumentCAS) (StateDocument, error)

InitializeFreshOrderAuthority atomically establishes the empty order-safety epoch and its companion mutable state document. It is only for a newly created authority: any existing order event, token tombstone, broker scope, order-ID floor, order import marker, or target state document is a conflict. Unrelated daemon state may already exist in the same database.

func (*Store) LatestDecisionEligibleObservation

func (s *Store) LatestDecisionEligibleObservation(ctx context.Context, scopeKey, source, kind string) (Observation, bool, error)

LatestDecisionEligibleObservation is the only observation read intended for a live decision path. Generic observation reads are research/inspection surfaces and may include quarantined legacy rows.

func (*Store) LatestObservation

func (s *Store) LatestObservation(ctx context.Context, scopeKey, source, kind string) (Observation, bool, error)

LatestObservation returns the newest retained observation regardless of its decision eligibility. The boolean is false when no row matches.

func (*Store) LatestOrderEventSeq

func (s *Store) LatestOrderEventSeq(ctx context.Context, scope BrokerScope, reservedOrderID int64) (int64, error)

LatestOrderEventSeq returns the exact durable frontier for one broker order. Zero means no event exists for the scope/order pair.

func (*Store) LatestQuarantinedObservationForRecovery

func (s *Store) LatestQuarantinedObservationForRecovery(ctx context.Context, scopeKey, source, kind string) (Observation, bool, error)

LatestQuarantinedObservationForRecovery returns the newest explicitly decision-ineligible observation for a narrow startup-repair path. Callers must validate the full payload and preserve quarantine provenance before publishing any state derived from it. It is not a decision-history reader and must never be used as a fallback for ordinary live evaluation.

func (*Store) ListObservations

func (s *Store) ListObservations(ctx context.Context, query ObservationQuery) ([]Observation, error)

ListObservations returns matching observations in ascending observed-time and observation-ID order. A zero limit defaults to 1,000 rows.

func (*Store) LoadEvents

func (s *Store) LoadEvents(ctx context.Context, query EventQuery) ([]EventRecord, error)

LoadEvents returns matching events in ascending event-sequence order. A zero limit defaults to 1,000 rows.

func (*Store) LoadOrderEvents

func (s *Store) LoadOrderEvents(ctx context.Context, query OrderQuery) ([]OrderEventRecord, error)

LoadOrderEvents returns matching order events in ascending event-sequence order. A zero limit defaults to 1,000 rows.

func (*Store) LoadStatementEquityDays

func (s *Store) LoadStatementEquityDays(ctx context.Context, scopeKey, fromDay, toDay string, limit int) ([]StatementEquityDayRecord, error)

LoadStatementEquityDays returns current statement-derived winners in ascending day and row-ID order. Day bounds are inclusive; a zero limit defaults to 1,000 rows.

func (*Store) LoadStatementFiles

func (s *Store) LoadStatementFiles(ctx context.Context, scopeKey string) ([]StatementFileRecord, error)

LoadStatementFiles returns the current complete statement inventory for one scope in file-key order.

func (*Store) RecoverTransientHeadWatermark added in v2.8.2

func (s *Store) RecoverTransientHeadWatermark(ctx context.Context) (bool, error)

RecoverTransientHeadWatermark attempts the only supported in-process authority recovery. The write lock keeps every mutation blocked throughout the proof. Success requires intact content, the exact authority epoch, a head no older than the last externally observed head, and a successful synchronous persistence of the current head through CommitObserver.

func (*Store) ReplaceStatementProjection

func (s *Store) ReplaceStatementProjection(ctx context.Context, scopeKey string, files []StatementFileRecord, days []StatementEquityDayRecord) error

ReplaceStatementProjection atomically replaces the complete current inventory/winner projection while retaining every distinct file-content and derived-day version as append-only evidence. A same-name restatement is a new version when its SHA-256 changes, regardless of file size.

func (*Store) ScopedOrderIDFloor

func (s *Store) ScopedOrderIDFloor(ctx context.Context, scopeKey string) (int64, error)

ScopedOrderIDFloor returns the greater of the global and named broker-scope floors, or zero when neither exists.

func (*Store) StagePreTransmit

func (s *Store) StagePreTransmit(ctx context.Context, request PreTransmitRequest) (PreTransmitResult, error)

StagePreTransmit atomically binds the broker scope, validates and consumes an optional preview-token digest, advances conservative order-ID floors, appends pre-transmit evidence, and advances the authority head. Success is durable staging evidence; the caller still owns the guarded broker transmission.

type StressTransitionProjection

type StressTransitionProjection struct {
	Action, Severity, Direction, MarketStage, InputHealth string
	PortfolioAlertRelevant                                *bool
}

StressTransitionProjection is the typed searchable projection of a portfolio-stress transition event.

type TransmitOrigin

type TransmitOrigin string

TransmitOrigin identifies the allowlisted path that initiated a broker-side action.

const (
	OriginAgentCLI TransmitOrigin = "agent_gated_cli"
	OriginHumanCLI TransmitOrigin = "human_cli"
	OriginDaemon   TransmitOrigin = "daemon_internal"
)

Supported broker-write origins.

type UpgradeHeadTransition added in v2.6.0

type UpgradeHeadTransition string

UpgradeHeadTransition is the only authority-head effect an out-of-place schema upgrade may report. Ordinary pending migrations advance exactly once. A batch preserves the head only when every pending migration is an explicitly reviewed maintenance operation that leaves store_meta and event_log alone.

const (
	UpgradeHeadTransitionAdvanceOnce UpgradeHeadTransition = "advance_once"
	UpgradeHeadTransitionPreserve    UpgradeHeadTransition = "preserve"
)

Supported upgrade head transitions.

func ExpectedUpgradeHeadTransition added in v2.6.0

func ExpectedUpgradeHeadTransition(sourceVersion, targetVersion int) (UpgradeHeadTransition, error)

ExpectedUpgradeHeadTransition returns the frozen head effect for one supported source-to-target plan prefix. Coordinators persist this typed value in upgrade intent rather than inferring it from version numbers or legacy defaults.

type UpgradeMaintenanceResult added in v2.6.0

type UpgradeMaintenanceResult struct {
	Discards                       []ObservationDiscardSummary
	EventDiscards                  []EventDiscardSummary
	OperationalPrunes              []OperationalPruneSummary
	Compacted                      bool
	SourceBackupRetirementRequired bool
}

UpgradeMaintenanceResult reports physical work required by pending migration metadata and the exact discard evidence produced while building the candidate. SourceBackupRetirementRequired is an instruction to the outer crash-recovery coordinator: the large old-head backup may be retired only after publication and independent target-head backup verification.

func RecomputeUpgradeMaintenance added in v2.6.0

func RecomputeUpgradeMaintenance(ctx context.Context, opts RecomputeUpgradeMaintenanceOptions) (result UpgradeMaintenanceResult, retErr error)

RecomputeUpgradeMaintenance validates one exact old-version authority and recomputes the deterministic maintenance evidence for a frozen target plan. It opens the source read-only, creates no backup or candidate, and changes no authority bytes. Coordinators use it against the retained exact source backup before retiring that backup.

type UpgradeOptions

type UpgradeOptions struct {
	SourcePath            string
	BackupPath            string
	CandidatePath         string
	MinimumHead           *AuthorityHead
	TargetVersion         int
	ReplaceCandidate      bool
	ResetUnboundArtifacts bool
}

UpgradeOptions describes an out-of-place schema upgrade. BackupPath is an immutable exact-old-head snapshot. CandidatePath is an unpublished, independent database for the caller to atomically publish after any outer coordination state is durable. The target-head backup is deliberately a post-publication operation so source backup plus candidate stays within the large-authority space bound. TargetVersion zero means current. ResetUnboundArtifacts is only for a preparing intent whose candidate has not been durably fingerprint-bound: with ReplaceCandidate it revalidates the exact source, durably removes all deterministic candidate and source-backup artifacts, and rebuilds from the source.

type UpgradeRequiredError

type UpgradeRequiredError struct {
	CurrentVersion int
	TargetVersion  int
}

UpgradeRequiredError reports a valid, supported authority that must be upgraded out of place before this build can open it for service.

func (*UpgradeRequiredError) Error

func (e *UpgradeRequiredError) Error() string

Error describes the current and target schema versions.

func (*UpgradeRequiredError) Is

func (e *UpgradeRequiredError) Is(target error) bool

Is reports whether the error matches ErrUpgradeRequired.

type UpgradeResult

type UpgradeResult struct {
	Source         Inspection
	Backup         BackupInfo
	Candidate      Inspection
	TargetBackup   *BackupInfo
	Maintenance    UpgradeMaintenanceResult
	HeadTransition UpgradeHeadTransition
}

UpgradeResult contains independently verified artifacts. Source and Backup remain at the old version and exact old head. HeadTransition says whether Candidate preserves that head or advances HeadGeneration exactly once. TargetBackup remains nil during preparation. A maintenance coordinator calls PrepareUpgradeTargetBackup only after publishing and verifying Candidate; this ordering keeps the promised two-source-footprint space bound honest.

func PrepareUpgrade

func PrepareUpgrade(ctx context.Context, opts UpgradeOptions) (UpgradeResult, error)

PrepareUpgrade creates an immutable exact-head backup and an independently validated target-version candidate. It never changes SourcePath and never publishes CandidatePath over an existing file unless ReplaceCandidate is explicitly set for crash recovery.

type UpgradeTargetBackupOptions added in v2.6.0

type UpgradeTargetBackupOptions struct {
	SourcePath            string
	BackupPath            string
	ExpectedSchemaVersion int
	ExpectedHead          AuthorityHead
}

UpgradeTargetBackupOptions binds the narrow post-publication recovery copy to one exact frozen target schema and authority head. The source is opened read-only and is never migrated, checkpointed, or otherwise modified.

Jump to

Keyboard shortcuts

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