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 ¶
- Variables
- type ActionKind
- type AuthorityHead
- type BackupInfo
- type BrokerScope
- type CapitalEventProjection
- type CheckpointResult
- type EventInput
- type EventProjection
- type EventQuery
- type EventReceipt
- type EventRecord
- type ForeignKeyViolation
- type Health
- type InspectOptions
- type Inspection
- type InspectionStatus
- type IntegrityReport
- type LegacyConsumedToken
- type LegacyOrderFloor
- type LegacyOrderImport
- type LegacyOrderImportResult
- type LifecycleCommit
- type LifecycleResult
- type Observation
- type ObservationInput
- type ObservationQuery
- type ObservationReceipt
- type Options
- type OrderEventRecord
- type OrderQuery
- type PreTransmitRequest
- type PreTransmitResult
- type PreviewTokenDigest
- type ProposalOutcomeProjection
- type QuiesceOptions
- type RegimeDecisionProjection
- type RegimeIndicatorProjection
- type RevisionConflictError
- type RiskPolicyEventProjection
- type RuleTransitionProjection
- type StateDocument
- type StateDocumentCAS
- type StatementEquityDayRecord
- type StatementFileRecord
- type Store
- func (s *Store) AdvanceSignerGeneration(ctx context.Context, expected, next int64) (AuthorityHead, error)
- func (s *Store) AppendEvents(ctx context.Context, inputs []EventInput) ([]EventReceipt, error)
- func (s *Store) AppendObservation(ctx context.Context, input ObservationInput) (ObservationReceipt, error)
- func (s *Store) AppendObservations(ctx context.Context, inputs []ObservationInput) ([]ObservationReceipt, error)
- func (s *Store) AppendOrderEvents(ctx context.Context, events []OrderEventRecord) ([]int64, error)
- func (s *Store) AppendOrderEventsAtHead(ctx context.Context, expectedLastEventSeq int64, events []OrderEventRecord) ([]int64, error)
- func (s *Store) AuthorityHead(ctx context.Context) (AuthorityHead, error)
- func (s *Store) Backup(ctx context.Context, destination string) (BackupInfo, error)
- func (s *Store) CheckIntegrity(ctx context.Context) (IntegrityReport, error)
- func (s *Store) Checkpoint(ctx context.Context) (CheckpointResult, error)
- func (s *Store) Close() error
- func (s *Store) CommitLifecycle(ctx context.Context, commit LifecycleCommit) (LifecycleResult, error)
- func (s *Store) CompareAndSwapStateDocument(ctx context.Context, update StateDocumentCAS) (StateDocument, error)
- func (s *Store) CompareAndSwapStateDocumentWithBoundObservations(ctx context.Context, update StateDocumentCAS, inputs []ObservationInput, ...) (StateDocument, []ObservationReceipt, error)
- func (s *Store) CompareAndSwapStateDocumentWithEvents(ctx context.Context, update StateDocumentCAS, inputs []EventInput) (StateDocument, []EventReceipt, error)
- func (s *Store) CompareAndSwapStateDocumentWithObservations(ctx context.Context, update StateDocumentCAS, inputs []ObservationInput) (StateDocument, []ObservationReceipt, error)
- func (s *Store) ExactDecisionEligibleObservation(ctx context.Context, receiptID int64, scopeKey, source, kind string, ...) (Observation, bool, error)
- func (s *Store) GetStateDocument(ctx context.Context, scopeKey, kind string) (StateDocument, bool, error)
- func (s *Store) GlobalOrderIDFloor(ctx context.Context) (int64, error)
- func (s *Store) Health() Health
- func (s *Store) ImportLegacyOrderAuthority(ctx context.Context, input LegacyOrderImport) (LegacyOrderImportResult, error)
- func (s *Store) InitializeFreshOrderAuthority(ctx context.Context, initialState StateDocumentCAS) (StateDocument, error)
- func (s *Store) LatestDecisionEligibleObservation(ctx context.Context, scopeKey, source, kind string) (Observation, bool, error)
- func (s *Store) LatestObservation(ctx context.Context, scopeKey, source, kind string) (Observation, bool, error)
- func (s *Store) LatestOrderEventSeq(ctx context.Context, scope BrokerScope, reservedOrderID int64) (int64, error)
- func (s *Store) LatestQuarantinedObservationForRecovery(ctx context.Context, scopeKey, source, kind string) (Observation, bool, error)
- func (s *Store) ListObservations(ctx context.Context, query ObservationQuery) ([]Observation, error)
- func (s *Store) LoadEvents(ctx context.Context, query EventQuery) ([]EventRecord, error)
- func (s *Store) LoadOrderEvents(ctx context.Context, query OrderQuery) ([]OrderEventRecord, error)
- func (s *Store) LoadStatementEquityDays(ctx context.Context, scopeKey, fromDay, toDay string, limit int) ([]StatementEquityDayRecord, error)
- func (s *Store) LoadStatementFiles(ctx context.Context, scopeKey string) ([]StatementFileRecord, error)
- func (s *Store) ReplaceStatementProjection(ctx context.Context, scopeKey string, files []StatementFileRecord, ...) error
- func (s *Store) ScopedOrderIDFloor(ctx context.Context, scopeKey string) (int64, error)
- func (s *Store) StagePreTransmit(ctx context.Context, request PreTransmitRequest) (PreTransmitResult, error)
- type StressTransitionProjection
- type TransmitOrigin
- type UpgradeOptions
- type UpgradeRequiredError
- type UpgradeResult
Constants ¶
This section is empty.
Variables ¶
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") )
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 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 ¶
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 ¶
CheckpointResult reports SQLite WAL checkpoint progress. A nonzero Busy value means the authority was not fully quiesced.
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 ¶
ForeignKeyViolation describes one row returned by SQLite foreign_key_check.
type Health ¶
Health is a process-lifetime latch. Critical mutation failures caused by a full, busy, corrupt, or I/O-failing SQLite store transition Ready to false; only closing and explicitly reopening the store can reset it.
type InspectOptions ¶
type InspectOptions struct {
Path string
MinimumHead *AuthorityHead
}
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.
type Inspection ¶
type Inspection struct {
Path string
SchemaVersion int
TargetVersion int
Status InspectionStatus
Head AuthorityHead
Integrity IntegrityReport
}
Inspection is the validated identity, version, and write head of an authority database. TargetVersion is the version supported by this build.
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 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 ¶
ObservationReceipt identifies one immutable observation and the exact payload digest recorded for it.
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 ¶
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 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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
GlobalOrderIDFloor returns the greatest order ID reserved across all broker scopes, or zero when no floor exists.
func (*Store) Health ¶
Health returns the process-lifetime mutation-health latch. A false Ready value blocks later critical mutations until the store is closed and reopened.
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) 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 ¶
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 UpgradeOptions ¶
type UpgradeOptions struct {
SourcePath string
BackupPath string
CandidatePath string
MinimumHead *AuthorityHead
ReplaceCandidate bool
}
UpgradeOptions describes an out-of-place schema upgrade. BackupPath is an immutable exact-head snapshot. CandidatePath is an unpublished, independent database for the caller to atomically publish after any outer coordination state is durable.
type UpgradeRequiredError ¶
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
}
UpgradeResult contains independently verified artifacts. Source and Backup remain at the old version and exact old head; Candidate is at TargetVersion with HeadGeneration advanced exactly once.
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.