Documentation
¶
Overview ¶
Package indexsubstrate contains the experimental durable index substrate.
The package is internal while the journal, segment, and manifest formats are still evolving. The package owns append-only observation journals, compaction-derived rows, the streaming spill/merge current-state row source drained by the production publish path, immutable segment manifests, and fail-closed boundary render contracts for the durable snapshot format. Segment reachability is modeled from retained manifests, parent chains, and latest pointers; refcounts are derived audit data for future compact/GC planning, not mutable truth.
Index ¶
- Constants
- Variables
- func CheckWriteLeaseAvailable(segmentSetRoot string) error
- func CheckWriteLeaseAvailableForMaintenance(segmentSetRoot string) error
- func CoverageSHA256(coverage []CoverageAttestation) (string, error)
- func HasContinuousLineage(manifest InternalManifest) bool
- func IsLineageCode(err error, code string) bool
- func LineageCodeOf(err error) string
- func ManifestSHA256Of(data []byte) string
- func ParseCanonicalUTCTime(raw string) (time.Time, error)
- func ReadLatestPublishedRows(latestPath string) (InternalManifest, []CurrentObjectRow, error)
- func RenderBoundaryManifestFile(config BoundaryRenderConfig) error
- func SetAuthorityRootForSegmentSet(segmentSetRoot string) (string, error)
- func TruncateToLastFullLine(path string) (int64, error)
- func ValidateAuthoritativeRunStartedAt(t time.Time) error
- func ValidateExactSnapshotCompletion(semantics string, runStartedAt, snapshotCompletedAt, hubCommittedAt time.Time) error
- func ValidateManifestLineageStructure(manifest InternalManifest) error
- func WalkManifestRows(segmentDir string, manifest InternalManifest, ...) error
- func WalkSegmentFile(path string, visit func(CurrentObjectRow) error) error
- func WalkSegmentFileHandleVerified(file *os.File, descriptor SegmentDescriptor, ...) error
- func WalkSegmentFileVerified(dir string, descriptor SegmentDescriptor, visit func(CurrentObjectRow) error) error
- func WriteInternalManifestFile(path string, manifest InternalManifest) error
- type AncestryBudget
- type AncestryMode
- type AncestryNode
- type AncestryResolveConfig
- type AncestryResult
- type BoundaryManifest
- type BoundaryPolicies
- type BoundaryRenderConfig
- type BoundarySegmentDescriptor
- type CompactionInput
- type CompactionResult
- type CoverageAttestation
- type CoverageBasis
- type CurrentObjectRow
- func ReadManifestRows(segmentDir string, manifest InternalManifest) ([]CurrentObjectRow, error)
- func ReadManifestRowsBounded(segmentDir string, manifest InternalManifest, maxRows int) ([]CurrentObjectRow, error)
- func ReadSegmentFile(path string) ([]CurrentObjectRow, error)
- func ReadSegmentFileVerified(dir string, descriptor SegmentDescriptor) ([]CurrentObjectRow, error)
- type CurrentStateSource
- type DerivedRefcount
- type ExpectedParentToken
- type InternalManifest
- func ReadInternalManifestFile(path string) (InternalManifest, error)
- func ReadInternalManifestFileBounded(path string, maxBytes int64) (InternalManifest, error)
- func WalkLatestPublishedRows(latestPath string, visit func(CurrentObjectRow) error) (InternalManifest, error)
- func WriteSegmentSet(config SegmentWriterConfig, rows []CurrentObjectRow) (InternalManifest, error)
- func WriteStreamingSegmentSet(ctx context.Context, config SegmentWriterConfig, src OrderedRowSource) (InternalManifest, error)
- type Journal
- type JournalFooter
- type JournalHeader
- type JournalSummary
- type JournalWriter
- type LatestPointerReference
- type LeaseVerdict
- type LineageError
- type LineageRecord
- type ManifestCounts
- type ManifestReachability
- type ManifestReference
- type ObjectRecord
- type ObjectRecordOp
- type OnSegmentProgressFunc
- type OrderedRowSource
- type ParentReaderCategory
- type ParentReaderError
- type ParentRowSource
- type PublicationMode
- type PublishConfig
- type PublishResult
- type PublishStep
- type PublishedParentRowSource
- type PublishedRunLookup
- type PublishedSnapshot
- func OpenLatestPublishedSnapshot(latestPath string) (PublishedSnapshot, error)
- func OpenLatestPublishedSnapshotBounded(latestPath string, maxMarkerBytes, maxManifestBytes int64) (PublishedSnapshot, error)
- func OpenPublishedRunSnapshot(completePath, expectedIndexSetID, expectedRunID string) (PublishedSnapshot, error)
- func OpenPublishedRunSnapshotBounded(completePath, expectedIndexSetID, expectedRunID string, ...) (PublishedSnapshot, error)
- func OpenPublishedRunSnapshotMaterial(completePath, manifestPath, segmentDir string, ...) (PublishedSnapshot, error)
- type ReachabilityInput
- type ReachabilityPlan
- type ReachableSegment
- type ReclaimResult
- type Scope
- type SegmentDescriptor
- type SegmentDigest
- type SegmentProgress
- type SegmentSizing
- type SegmentWriterConfig
- type SetAuthority
- type SetAuthorityLease
- type SliceOrderedRows
- type SliceParentRows
- type SpillMergeBudget
- type SpillMergeCategory
- type SpillMergeConfig
- type SpillMergeError
- type SpillMergeStats
- type StateParent
- type StreamSegmentCategory
- type StreamSegmentError
- type Tombstone
- type Window
- type WriteLease
- func (l *WriteLease) AssertHeld() error
- func (l *WriteLease) AssertHeldFor(indexSetID, latestPath string) error
- func (l *WriteLease) Holder() string
- func (l *WriteLease) IndexSetID() string
- func (l *WriteLease) Release() error
- func (l *WriteLease) Renew(_ time.Duration) error
- func (l *WriteLease) SegmentSetRoot() string
- func (l *WriteLease) Token() string
Constants ¶
const ( // BoundaryManifestType identifies the future boundary-safe manifest schema. BoundaryManifestType = "gonimbus.index.boundary_manifest.v1" ManifestRenderTypeBoundary = "boundary" // BoundaryTrustModel states the security boundary the future render does // and does not provide. BoundaryTrustModel = "boundary render does not de-identify row-level keys; key-unauthorized recipients require a different representation" )
const ( JournalHeaderType = "gonimbus.index.journal_header.v1" ObjectRecordType = "gonimbus.index.object_record.v1" ObjectRecordOpObserve ObjectRecordOp = "observe" ObjectRecordOpEnrich ObjectRecordOp = "enrich" // CrawlPlanModeLaneLocal marks a journal whose CrawlPrefixes records only the // subset of the run plan this journal attests, rather than the whole-run plan. // See JournalHeader.CrawlPlanMode. CrawlPlanModeLaneLocal = "lane-local" IndexSchemaVersion = 8 )
const ( // LineageVersionV1 is the only supported lineage.version. LineageVersionV1 = 1 // LineageBaselineGeneration is the generation of the first continuous // lineage baseline publication (baseline:true). Later continuous children // must use parent.generation + 1. LineageBaselineGeneration = 1 // Default ancestry resource budgets (graph-wide, not only per file). DefaultAncestryMaxDepth = 64 DefaultAncestryMaxNodes = 64 DefaultAncestryMaxAggregateBytes = 256 << 20 )
const ( LineageCodeLegacy = "lineage_legacy" LineageCodeUnknownVersion = "lineage_unknown_version" LineageCodePartial = "lineage_partial" LineageCodeInvalidTime = "lineage_invalid_time" LineageCodeInvalidDigest = "lineage_invalid_digest" LineageCodeCrossSet = "lineage_cross_set" LineageCodeMissingParent = "lineage_missing_parent" LineageCodeDigestMismatch = "lineage_digest_mismatch" LineageCodeSetRunMismatch = "lineage_set_run_mismatch" LineageCodeCycle = "lineage_cycle" LineageCodeGeneration = "lineage_generation" LineageCodeBaselineConflict = "lineage_baseline_conflict" LineageCodeBudgetDepth = "lineage_budget_depth" LineageCodeBudgetNodes = "lineage_budget_nodes" LineageCodeBudgetBytes = "lineage_budget_bytes" LineageCodeMalformed = "lineage_malformed" LineageCodeLookupRequired = "lineage_lookup_required" LineageCodeRequireContinuous = "lineage_require_continuous" LineageCodeBaselineNotAncestor = "baseline_not_ancestor" )
Stable lineage reason codes (operator/product APIs; sanitized messages).
const ( ManifestType = "gonimbus.index.manifest.v1" SegmentFormatParquet = "parquet" ManifestRenderType = "internal" DefaultTargetRowsPerSegment = 500_000 SegmentSizingRationale = "real-corpus rebaseline for hub export and hydrate artifact counts" ManifestReachabilityModel = "retained_manifests_parent_chain_latest_pointers" RefcountModeDerivedAudit = "derived_audit_plan_only" CompactOwnerIndexCompact = "index compact" )
const ( // CompleteMarkerTypeV1 is the legacy local durable commit marker. CompleteMarkerTypeV1 = "gonimbus.index.complete.v1" // CompleteMarkerTypeV2 is the local durable commit marker whose snapshot // completion time is sampled at the marker commit boundary. CompleteMarkerTypeV2 = "gonimbus.index.complete.v2" // SnapshotCompletionSemanticsCompleteMarkerCommit is the sole exact-time // admission discriminator. Producer version and timestamp inequality are // deliberately not substitutes for this value. SnapshotCompletionSemanticsCompleteMarkerCommit = "complete_marker_commit" )
const DefaultMaxPublishedManifestBytes = 64 << 20
DefaultMaxPublishedManifestBytes is the default bound for internal manifests.
const DefaultMaxPublishedMarkerBytes = 1 << 20
DefaultMaxPublishedMarkerBytes is the default bound for latest/complete JSON.
const MaxSetAuthorityDocBytes = 1 << 16
MaxSetAuthorityDocBytes bounds a well-formed authority doc, which is tiny. A file beyond this size is treated as invalid rather than parsed from a truncated prefix. It is exported so a fixture can plant a provably-oversized artifact against the real bound instead of a drifting copy of it.
const MaxSpillRecordBytes = int64(math.MaxInt - 2)
MaxSpillRecordBytes is the largest accepted MaxRecordBytes: the payload ceiling must stay representable as a platform int after the two-byte scanner framing allowance, so an accepted finite budget can never overflow into a runtime panic. Operator/library surfaces refuse larger values with typed SpillMergeInvalidConfig — an explicit value is never silently clamped.
const RelativeRootScopePrefix = "."
RelativeRootScopePrefix is an explicit rel_key-space sentinel for complete coverage of the whole index-relative root. It is distinct from blank or "/", which remain invalid publish scopes.
const ( // SetAuthorityDirectoryName is the package-owned stable authority directory // beside set-specific segment roots. GC must never treat it as a set target. SetAuthorityDirectoryName = ".gonimbus-set-authority" )
const WriteLeaseFileName = ".durable-write.lock"
WriteLeaseFileName is the package-owned durable writer lock artifact under a segment-set root. Metadata in the file is diagnostic only.
Variables ¶
var ( ErrIncompleteJournal = errors.New("incomplete journal") ErrInvalidJournal = errors.New("invalid journal") )
var ( ErrInvalidCoverage = errors.New("invalid coverage evidence") ErrSnapshotNotPublished = errors.New("snapshot not published") ErrSnapshotTimeIneligible = errors.New("snapshot completion time is not exact-time eligible") // ErrStaleParent is returned when ExpectedParent no longer matches the // authoritative latest pointer at advance time (lost CAS race). ErrStaleParent = errors.New("stale parent: latest advanced since capture") )
var ( ErrSetAuthorityHeld = errors.New("index set authority held") ErrSetAuthorityLost = errors.New("index set authority not held") ErrSetAuthorityScope = errors.New("index set authority does not authorize target") )
var ErrBoundaryRenderNotImplemented = errors.New("boundary render not implemented")
ErrBoundaryRenderNotImplemented is returned for all boundary render attempts until boundary segment variants are implemented.
var ErrWriteLeaseHeld = errors.New("durable write lease held")
ErrWriteLeaseHeld is returned when another durable writer holds the set lock.
var ErrWriteLeaseLost = errors.New("durable write lease not held")
ErrWriteLeaseLost is returned when a held guard is no longer valid at the commit boundary (released or never acquired).
var ErrWriteLeaseScope = errors.New("durable write lease does not authorize target")
ErrWriteLeaseScope is returned when a held lease does not authorize the publish target (index set ID or segment-set root mismatch).
Functions ¶
func CheckWriteLeaseAvailable ¶
CheckWriteLeaseAvailable probes an existing durable writer lock without creating or rewriting operator state. It is suitable for read-only planning; callers that mutate must still acquire and hold a WriteLease.
func CheckWriteLeaseAvailableForMaintenance ¶
CheckWriteLeaseAvailableForMaintenance is the read-only planning probe for destructive maintenance. Unlike the general writer probe, it requires the package-owned lock artifact to exist so execution can later take the same lock without changing the immutable target tree.
func CoverageSHA256 ¶
func CoverageSHA256(coverage []CoverageAttestation) (string, error)
CoverageSHA256 digests coverage attestations with stable JSON encoding.
func HasContinuousLineage ¶
func HasContinuousLineage(manifest InternalManifest) bool
HasContinuousLineage reports whether the manifest claims a continuous lineage record (not whether the graph has been digest-verified).
func IsLineageCode ¶
IsLineageCode reports whether err is a LineageError with the given code.
func LineageCodeOf ¶
LineageCodeOf returns the stable code when err is a LineageError.
func ManifestSHA256Of ¶
ManifestSHA256Of returns the SHA-256 hex digest of raw manifest bytes.
func ParseCanonicalUTCTime ¶
ParseCanonicalUTCTime parses the exact RFC3339Nano UTC representation used by durable authority artifacts.
func ReadLatestPublishedRows ¶
func ReadLatestPublishedRows(latestPath string) (InternalManifest, []CurrentObjectRow, error)
func RenderBoundaryManifestFile ¶
func RenderBoundaryManifestFile(config BoundaryRenderConfig) error
RenderBoundaryManifestFile fails closed until boundary rendering is implemented. It creates no files or directories.
func SetAuthorityRootForSegmentSet ¶
SetAuthorityRootForSegmentSet returns the stable authority root shared by every set beneath the same segment-cache parent.
func TruncateToLastFullLine ¶
func ValidateAuthoritativeRunStartedAt ¶
ValidateAuthoritativeRunStartedAt validates a run-start timestamp against the authoritative lineage wire rule (non-zero, UTC — non-zero offset refused). It is exposed so library build/publish entry points can refuse a non-UTC caller value or clock on the *raw* input, before any UTC normalization or side effect, and surface the same stable LineageCodeInvalidTime classification.
func ValidateExactSnapshotCompletion ¶
func ValidateExactSnapshotCompletion( semantics string, runStartedAt, snapshotCompletedAt, hubCommittedAt time.Time, ) error
ValidateExactSnapshotCompletion is the shared exact-time admission gate for local publication, hub export/acquisition, verified metadata, and machine receipts. A zero hubCommittedAt validates a local completion fact; a non-zero value additionally binds the remote commit ordering.
func ValidateManifestLineageStructure ¶
func ValidateManifestLineageStructure(manifest InternalManifest) error
ValidateManifestLineageStructure checks optional lineage fields when present. All-absent is legal (pre-continuity). Does not walk parents or verify digests.
When lineage is present, an authoritative non-zero UTC run_started_at is required so continuous nodes can serve as trustworthy delta boundaries later. Generation-1 baseline may optionally bind one exact state_parent as a verified pre-continuity state source (not a delta boundary).
func WalkManifestRows ¶
func WalkManifestRows(segmentDir string, manifest InternalManifest, visit func(CurrentObjectRow) error) error
func WalkSegmentFile ¶
func WalkSegmentFile(path string, visit func(CurrentObjectRow) error) error
func WalkSegmentFileHandleVerified ¶
func WalkSegmentFileHandleVerified(file *os.File, descriptor SegmentDescriptor, visit func(CurrentObjectRow) error) error
WalkSegmentFileHandleVerified verifies and walks a segment through the exact already-bound file handle supplied by a retained filesystem capability.
func WalkSegmentFileVerified ¶
func WalkSegmentFileVerified(dir string, descriptor SegmentDescriptor, visit func(CurrentObjectRow) error) error
func WriteInternalManifestFile ¶
func WriteInternalManifestFile(path string, manifest InternalManifest) error
Types ¶
type AncestryBudget ¶
type AncestryBudget struct {
MaxDepth int
MaxNodes int
MaxMarkerBytes int64
MaxManifestBytes int64
MaxAggregateBytes int64
}
AncestryBudget bounds graph walk resource use.
func DefaultAncestryBudget ¶
func DefaultAncestryBudget() AncestryBudget
DefaultAncestryBudget returns production defaults.
type AncestryMode ¶
type AncestryMode string
AncestryMode classifies continuous vs pre-continuity ancestry.
const ( // AncestryModeLegacy means no lineage object: verified current-state only; // not a trustworthy delta / --since-run boundary. AncestryModeLegacy AncestryMode = "legacy" // AncestryModeContinuous means lineage is present and the graph verified. AncestryModeContinuous AncestryMode = "continuous" )
type AncestryNode ¶
type AncestryNode struct {
IndexSetID string
RunID string
ManifestSHA256 string
Generation int
Baseline bool
RunStartedAt time.Time
// DeltaBoundary is true when this node is the earliest trustworthy
// continuous boundary (baseline:true). History without lineage behind it
// is not a delta boundary even if a prior-state source exists.
DeltaBoundary bool
}
AncestryNode is one verified hop in a continuous ancestry chain.
type AncestryResolveConfig ¶
type AncestryResolveConfig struct {
// Lookup is required when the root claims a non-baseline continuous parent.
Lookup PublishedRunLookup
Budget AncestryBudget
// RequireContinuous fails closed on legacy (no lineage) instead of
// returning AncestryModeLegacy.
RequireContinuous bool
// ThroughRunID stops the walk after verifying the named root/ancestor.
// Reaching the lineage baseline first returns baseline_not_ancestor.
ThroughRunID string
}
AncestryResolveConfig configures ResolveAncestry.
type AncestryResult ¶
type AncestryResult struct {
Mode AncestryMode
// Chain is root-first toward the baseline (root, parent, ..., baseline).
Chain []AncestryNode
// DeltaBoundary is set when the walk reaches the continuity baseline. An
// earlier ThroughRunID stop leaves it nil.
DeltaBoundary *AncestryNode
// RequestedBoundary is set when ThroughRunID names a verified node. Unlike
// DeltaBoundary, it may be any continuous ancestor, including the root.
RequestedBoundary *AncestryNode
// AccountedBytes is the total marker+manifest bytes charged across the graph.
AccountedBytes int64
}
AncestryResult is the outcome of ResolveAncestry.
func ResolveAncestry ¶
func ResolveAncestry(root PublishedSnapshot, cfg AncestryResolveConfig) (AncestryResult, error)
ResolveAncestry walks digest-bound same-set state parents from a verified snapshot. It does not materialize segment rows and does not mutate the FS.
Legacy roots (no lineage) return Mode=legacy without error unless RequireContinuous is set. Continuous roots fail closed on cycle, cross-set, digest mismatch, generation discontinuity, missing parent, or budget exhaustion.
Continuous roots require CompletePath and are always re-opened under the aggregate remaining-byte budget (self-asserted Accounted*Bytes alone are not provenance). Node budget is checked before parent lookup/open. Aggregate remaining is carried into the open seam so marker/manifest reads are capped.
baseline:true may optionally verify one pre-continuity state_parent (legacy parent need not carry lineage); trusted delta ancestry still stops at baseline.
type BoundaryManifest ¶
type BoundaryManifest struct {
Type string `json:"type"`
Render string `json:"render"`
IndexSetID string `json:"index_set_id"`
RunID string `json:"run_id"`
IndexSchemaVersion int `json:"index_schema_version"`
TokenNamespace string `json:"token_namespace"`
Policies BoundaryPolicies `json:"policies"`
Segments []BoundarySegmentDescriptor `json:"segments"`
}
BoundaryManifest is the schema shape reserved for boundary publication.
type BoundaryPolicies ¶
type BoundaryPolicies struct {
TrustModel string `json:"trust_model"`
IdentifierPolicy string `json:"identifier_policy"`
SegmentShapeMetadata string `json:"segment_shape_metadata"`
RestrictedColumnMetadata string `json:"restricted_column_metadata"`
}
BoundaryPolicies describes hardening rules carried by a boundary manifest.
func DefaultBoundaryPolicies ¶
func DefaultBoundaryPolicies() BoundaryPolicies
DefaultBoundaryPolicies returns the Phase 1 boundary render policy text.
type BoundaryRenderConfig ¶
type BoundaryRenderConfig struct {
OutputPath string
Source InternalManifest
TokenNamespace string
RestrictedColumns []string
}
BoundaryRenderConfig configures a future boundary manifest render.
type BoundarySegmentDescriptor ¶
type BoundarySegmentDescriptor struct {
Token string `json:"token"`
Format string `json:"format"`
Compression string `json:"compression"`
Digest SegmentDigest `json:"digest"`
}
BoundarySegmentDescriptor omits internal segment identifiers, paths, key ranges, tombstone counts, and restricted-axis distribution fields.
type CompactionInput ¶
type CompactionInput struct {
IndexSetID string
RunID string
RunStartedAt time.Time
PriorRows []CurrentObjectRow
Journals []Journal
Coverage []CoverageAttestation
// Mode selects tombstone and journal-shape policy. Prefer typed modes over
// ad-hoc booleans so observe journals cannot accidentally suppress deletes.
Mode PublicationMode
}
type CompactionResult ¶
type CompactionResult struct {
Rows []CurrentObjectRow
Tombstones []Tombstone
ObservedRecords int
EnrichmentRecords int
// PeakWorkspaceBytes is the high-water live on-disk spill workspace observed
// during a streaming merge (0 on the non-streaming path or when nothing
// spilled). Observational capacity evidence, not an artifact field.
PeakWorkspaceBytes int64
}
func Compact ¶
func Compact(input CompactionInput) (CompactionResult, error)
func CompactJournalFiles ¶
func CompactJournalFiles(input CompactionInput, journalPaths []string) (CompactionResult, error)
type CoverageAttestation ¶
type CoverageAttestation struct {
Scope *Scope `json:"scope,omitempty"`
Basis CoverageBasis `json:"basis"`
Complete bool `json:"complete"`
Gaps []Scope `json:"gaps,omitempty"`
}
type CoverageBasis ¶
type CoverageBasis string
const ( CoverageBasisConfirmed CoverageBasis = "confirmed" CoverageBasisInferred CoverageBasis = "inferred" )
type CurrentObjectRow ¶
type CurrentObjectRow struct {
IndexSetID string
RelKey string
SizeBytes int64
LastModified *time.Time
ETag string
StorageClass *string
ArchiveStatus *string
RestoreState *string
RestoreExpiry *time.Time
ContentType *string
HeadEnrichedAt *time.Time
FirstSeenRunID string
FirstSeenAt time.Time
LastChangedRunID string
LastChangedAt time.Time
LastSeenRunID string
LastSeenAt time.Time
DeletedAt *time.Time
}
func ReadManifestRows ¶
func ReadManifestRows(segmentDir string, manifest InternalManifest) ([]CurrentObjectRow, error)
func ReadManifestRowsBounded ¶
func ReadManifestRowsBounded(segmentDir string, manifest InternalManifest, maxRows int) ([]CurrentObjectRow, error)
ReadManifestRowsBounded materializes rows with an optional hard cap. maxRows < 0 means unlimited (after count-budget validation). When maxRows >= 0, manifest counts are pre-validated against the cap and materialization stops if actual rows would exceed maxRows (never allocates past cap+0).
func ReadSegmentFile ¶
func ReadSegmentFile(path string) ([]CurrentObjectRow, error)
func ReadSegmentFileVerified ¶
func ReadSegmentFileVerified(dir string, descriptor SegmentDescriptor) ([]CurrentObjectRow, error)
type CurrentStateSource ¶
type CurrentStateSource struct {
// contains filtered or unexported fields
}
CurrentStateSource is a pull row source that exposes no rows until READY.
func PrepareCurrentStateSource ¶
func PrepareCurrentStateSource(ctx context.Context, cfg SpillMergeConfig) (*CurrentStateSource, error)
PrepareCurrentStateSource validates inputs, stages sealed spill runs, and returns a READY source. No row is exposed until preparation succeeds.
func (*CurrentStateSource) AttemptID ¶
func (s *CurrentStateSource) AttemptID() string
AttemptID returns the opaque workspace attempt identifier.
func (*CurrentStateSource) Close ¶
func (s *CurrentStateSource) Close() error
Close releases drain handles and removes the owned attempt workspace. Idempotent on full success. Partial close/cleanup failures are sticky: subsequent Close retries failed components and returns the same class of error until success. Complete is set only when drain reached EOF with no terminal error and Close finishes without error.
func (*CurrentStateSource) Next ¶
func (s *CurrentStateSource) Next(ctx context.Context) (CurrentObjectRow, error)
Next returns the next sorted current-state row. Ownership of pointer fields is transferred to the caller (no buffer reuse across calls).
func (*CurrentStateSource) Stats ¶
func (s *CurrentStateSource) Stats() SpillMergeStats
Stats returns a copy of high-water counters. Complete is true only after full EOF plus successful final integrity/close.
func (*CurrentStateSource) WorkspaceDir ¶
func (s *CurrentStateSource) WorkspaceDir() string
WorkspaceDir returns the attempt directory (for tests / orphan checks).
type DerivedRefcount ¶
type DerivedRefcount struct {
SegmentID string `json:"segment_id"`
Path string `json:"path"`
Digest SegmentDigest `json:"digest"`
Count int `json:"count"`
}
type ExpectedParentToken ¶
type ExpectedParentToken struct {
IndexSetID string
RunID string
ManifestSHA256 string
// CoverageSHA256 is the digest of the parent's coverage attestation bytes
// (canonical JSON). Required for enrich-only; child coverage must match.
CoverageSHA256 string
}
ExpectedParentToken is the CAS token for latest advance. When set, Publish re-reads the authoritative latest immediately before advance and refuses if run_id or manifest digest disagree with this capture.
type InternalManifest ¶
type InternalManifest struct {
Type string `json:"type"`
Render string `json:"render"`
IndexSetID string `json:"index_set_id"`
RunID string `json:"run_id"`
IndexSchemaVersion int `json:"index_schema_version"`
CreatedAt time.Time `json:"created_at"`
// RunStartedAt is the optional authoritative run start.
// Not an alias of CreatedAt, journal start, or complete-marker time.
// Omitted on pre-continuity / legacy manifests; never invent from other
// timestamps. Pointer so JSON omitempty works (time.Time zero is not omitted).
// When Lineage is present, a non-zero UTC value is required.
RunStartedAt *time.Time `json:"run_started_at,omitempty"`
// StateParent is the optional exact single continuous-state parent binding
// (set/run/digest). Distinct from ParentManifests (reachability/enrich
// heritage; digest optional there). Requires Lineage when present.
StateParent *StateParent `json:"state_parent,omitempty"`
// Lineage is the optional all-or-nothing continuous-lineage record.
// Absence means pre-continuity (verified state source only — not a delta boundary).
Lineage *LineageRecord `json:"lineage,omitempty"`
// ParentManifests remain segment-reachability / enrich heritage references.
// Digests stay optional. Do not auto-translate into StateParent.
ParentManifests []ManifestReference `json:"parent_manifests"`
Reachability ManifestReachability `json:"reachability"`
SegmentSizing SegmentSizing `json:"segment_sizing"`
Coverage []CoverageAttestation `json:"coverage"`
Counts ManifestCounts `json:"counts"`
Segments []SegmentDescriptor `json:"segments"`
}
func ReadInternalManifestFile ¶
func ReadInternalManifestFile(path string) (InternalManifest, error)
func ReadInternalManifestFileBounded ¶
func ReadInternalManifestFileBounded(path string, maxBytes int64) (InternalManifest, error)
ReadInternalManifestFileBounded loads a manifest with an explicit size bound.
func WalkLatestPublishedRows ¶
func WalkLatestPublishedRows(latestPath string, visit func(CurrentObjectRow) error) (InternalManifest, error)
WalkLatestPublishedRows walks the latest published snapshot with streaming verify-before-emit semantics (per-segment digest check before that segment's rows are visited). Rows are not materialised as a slice.
func WriteSegmentSet ¶
func WriteSegmentSet(config SegmentWriterConfig, rows []CurrentObjectRow) (InternalManifest, error)
func WriteStreamingSegmentSet ¶
func WriteStreamingSegmentSet(ctx context.Context, config SegmentWriterConfig, src OrderedRowSource) (InternalManifest, error)
WriteStreamingSegmentSet drains an ordered row source into immutable parquet segments under config.Dir and returns the same in-memory InternalManifest contract as WriteSegmentSet.
This writer is the production publish sink (drained by PublishSnapshot); it does not itself write manifest.json, complete, or latest — PublishSnapshot owns those. Continuous-parent rows arrive through src and lineage metadata through the publish configuration; the writer derives neither itself.
Contract (folded seat freezes):
- Writer owns one terminal src.Close on every exit path.
- Success requires full EOF and successful Close.
- Does not re-sort; refuses duplicate/out-of-order RelKey.
- Converts each row to segmentParquetRow at ingress (one open-segment buffer).
- On failure, removes only segments this call newly linked (created=true).
- Progress callbacks always report Total=0.
- Single-writer mutation authority over config.Dir is assumed for one call (activation supplies write-lease exclusivity); concurrent writers are unsupported.
type Journal ¶
type Journal struct {
Header JournalHeader
Records []ObjectRecord
}
func ReadJournal ¶
type JournalFooter ¶
type JournalFooter struct {
// ContentSHA256 is the writer-generated lowercase-hex SHA-256 over the exact
// header line and every ordered record line (the footer line itself
// excluded). Any post-seal mutation of the header — including its
// crawl_prefixes provenance — or of any record, or truncation, changes the
// recomputed digest and fails validation. Absent on legacy journals sealed
// before content integrity; those are not tamper-evident and must not be
// trusted as observation provenance.
}
type JournalHeader ¶
type JournalHeader struct {
Type string `json:"type"`
JournalID string `json:"journal_id"`
IndexSetID string `json:"index_set_id"`
RunID string `json:"run_id"`
Shard string `json:"shard"`
Scope *Scope `json:"scope,omitempty"`
// CrawlPrefixes records the canonical provider-key prefix plan whose complete
// observation this journal attests. On a recovery re-publish, coverage
// authorizes tombstones over verified-parent rows, so public Retry validates
// its caller-supplied coverage against this recorded plan and re-publishes
// only within the observed plan. Absent on legacy journals; recovery over
// such a journal fails closed rather than trusting caller coverage.
CrawlPrefixes []string `json:"crawl_prefixes,omitempty"`
// CrawlPlanMode declares how CrawlPrefixes must be read across the sealed
// journal set of one run, and is the discriminator recovery uses to decide
// whether the journals it was handed are a complete observation set.
//
// Absent — the only form a single-lane run writes — is the legacy contract:
// CrawlPrefixes is the whole-run plan and every journal of the run must
// record it identically. CrawlPlanModeLaneLocal means CrawlPrefixes is only
// the subset this journal attests, so recovery authority is the union of the
// supplied lane plans; omitting a lane narrows that union instead of letting
// one lane attest whole-run coverage it never listed.
//
// The field is additive and deliberately does not move IndexSchemaVersion. It
// changes recovery interpretation of the multi-lane form only — object-record,
// segment, manifest, and boundary-row schemas are untouched — and bumping the
// shared epoch would either break the byte-identical single-lane journal or
// force journal/manifest/hub version work. The accepted cost is a reader older
// than lane support: handed the complete lane set it ignores this field,
// applies its identical-plan rule to disjoint lane plans, and refuses with a
// plan-disagreement message. That refusal is fail-closed but an imprecise
// diagnosis, so recovery diagnostics are not forward-compatible and a pre-lane
// reader must not be used for forward recovery. Authority still holds in such
// a reader: handed one lane it derives only that lane-local plan, so an
// omitted lane cannot widen coverage.
CrawlPlanMode string `json:"crawl_plan_mode,omitempty"`
IndexSchemaVersion int `json:"index_schema_version"`
StartedAt time.Time `json:"started_at"`
}
type JournalSummary ¶
type JournalSummary struct {
Header JournalHeader
Records uint64
ContentSHA256 string
}
func ValidateJournal ¶
func ValidateJournal(path string) (JournalSummary, error)
func ValidateJournalBounded ¶
func ValidateJournalBounded(path string, maxRecordBytes int64) (JournalSummary, error)
ValidateJournalBounded is the capacity-aware journal validation primitive for authority-sensitive paths (publish, Build, public Retry). Each line read is bounded by maxRecordBytes — encoded record payload bytes excluding the line terminator, matching the streaming scan and spill-run writer semantics — and an over-budget record refuses with the same typed SpillMergeBudgetExhausted as the streaming scan, before the journal is declared valid. maxRecordBytes <= 0 is unbounded; capacity paths must pass a resolved (defaulted, validated) budget, never a raw caller value.
type JournalWriter ¶
type JournalWriter struct {
// contains filtered or unexported fields
}
func CreateJournal ¶
func CreateJournal(path string, header JournalHeader) (*JournalWriter, error)
func (*JournalWriter) Append ¶
func (w *JournalWriter) Append(record ObjectRecord) (ObjectRecord, error)
func (*JournalWriter) Close ¶
func (w *JournalWriter) Close() error
func (*JournalWriter) Path ¶
func (w *JournalWriter) Path() string
type LatestPointerReference ¶
type LeaseVerdict ¶
type LeaseVerdict string
LeaseVerdict is the non-mutating lock-state verdict for a set-authority lock file. It is decided solely by a non-blocking lock probe on the existing file (never by a job record, PID, or holder string).
const ( // LeaseHeld means a live process holds the OS file lock right now: a // non-blocking exclusive lock attempt would block. Never reclaim a held lease. LeaseHeld LeaseVerdict = "held" // LeaseUnheld means the lock file exists with a well-formed authority doc but // no process holds the OS file lock: dead-holder residue, safe to reclaim. LeaseUnheld LeaseVerdict = "unheld" // LeaseMissing means no lock file exists for the index set. LeaseMissing LeaseVerdict = "missing" // LeaseInvalid is the indeterminate bucket: the artifact is not a regular file, // its binding changed under the probe, or its authority doc failed to parse. // Recovery treats it as needing operator attention, not blind removal. LeaseInvalid LeaseVerdict = "invalid" )
type LineageError ¶
type LineageError struct {
Code string
Message string
// Cause is optional low-level detail (not for operator presentation).
Cause error
}
LineageError is a fail-closed ancestry/structure error with a stable code.
func (*LineageError) Error ¶
func (e *LineageError) Error() string
func (*LineageError) Unwrap ¶
func (e *LineageError) Unwrap() error
type LineageRecord ¶
type LineageRecord struct {
Version int `json:"version"`
Generation int `json:"generation"`
Baseline bool `json:"baseline"`
}
LineageRecord is the all-or-nothing versioned lineage contract. Absence of the whole object means pre-continuity / no continuous ancestry — never "generation 0" inferred from timestamps or directory order.
func NormalizeLineage ¶
func NormalizeLineage(lin *LineageRecord) *LineageRecord
NormalizeLineage returns a copy of the lineage record or nil.
type ManifestCounts ¶
type ManifestReachability ¶
type ManifestReachability struct {
Model string `json:"model"`
SegmentNamespace string `json:"segment_namespace"`
RefcountMode string `json:"refcount_mode"`
CompactOwner string `json:"compact_owner"`
}
func DefaultManifestReachability ¶
func DefaultManifestReachability() ManifestReachability
type ManifestReference ¶
type ObjectRecord ¶
type ObjectRecord struct {
Type string `json:"type"`
JournalID string `json:"journal_id"`
Sequence uint64 `json:"sequence"`
Op ObjectRecordOp `json:"op"`
RelKey string `json:"rel_key"`
ObservedAt time.Time `json:"observed_at"`
SizeBytes *int64 `json:"size_bytes,omitempty"`
ETag string `json:"etag,omitempty"`
LastModified *time.Time `json:"last_modified,omitempty"`
StorageClass *string `json:"storage_class,omitempty"`
ContentType *string `json:"content_type,omitempty"`
ArchiveStatus *string `json:"archive_status,omitempty"`
RestoreState *string `json:"restore_state,omitempty"`
RestoreExpiry *time.Time `json:"restore_expiry,omitempty"`
HeadEnrichedAt *time.Time `json:"head_enriched_at,omitempty"`
}
type ObjectRecordOp ¶
type ObjectRecordOp string
type OnSegmentProgressFunc ¶
type OnSegmentProgressFunc func(progress SegmentProgress)
OnSegmentProgressFunc is optional and observational. Callers treat it as best-effort and never use its outcome as a publish failure vector.
type OrderedRowSource ¶
type OrderedRowSource interface {
Next(ctx context.Context) (CurrentObjectRow, error)
Close() error
}
OrderedRowSource is a pull stream of current-state rows already ordered by strict bytewise-increasing unique RelKey. Streaming segment write does not re-sort. Implementations include test adapters and CurrentStateSource.
Ownership: WriteStreamingSegmentSet takes exclusive ownership of one terminal Close call on every exit path. Callers must not Close the same source after handing it to the writer.
type ParentReaderCategory ¶
type ParentReaderCategory string
ParentReaderCategory classifies a PublishedParentRowSource failure. Rendered errors carry only category/phase/message — never a segment path, directory, or object key.
const ( ParentReaderInvalidConfig ParentReaderCategory = "invalid_config" ParentReaderOpen ParentReaderCategory = "open" ParentReaderDigest ParentReaderCategory = "digest" ParentReaderParse ParentReaderCategory = "parse" ParentReaderOrder ParentReaderCategory = "order" ParentReaderCount ParentReaderCategory = "count" ParentReaderIO ParentReaderCategory = "io" ParentReaderCanceled ParentReaderCategory = "canceled" ParentReaderClosed ParentReaderCategory = "closed" )
type ParentReaderError ¶
type ParentReaderError struct {
Category ParentReaderCategory
Phase string
Message string
// contains filtered or unexported fields
}
ParentReaderError is the sanitized failure surface of a parent row source. It never renders path or key material; Unwrap preserves cancellation classification for errors.Is.
func (*ParentReaderError) Error ¶
func (e *ParentReaderError) Error() string
func (*ParentReaderError) Unwrap ¶
func (e *ParentReaderError) Unwrap() error
Unwrap exposes only classification-bearing causes (e.g. context.Canceled). A raw filesystem cause that could render a path is intentionally not chained.
type ParentRowSource ¶
type ParentRowSource interface {
Next(ctx context.Context) (CurrentObjectRow, error)
Close() error
}
ParentRowSource supplies already-authorized, strictly sorted unique parent rows. Parent selection and digest binding remain for continuity activation.
type PublicationMode ¶
type PublicationMode string
PublicationMode selects compaction/publication policy for a snapshot write.
const ( // PublicationModeDefault is crawl/observe publication: coverage may // tombstone unobserved keys under confirmed complete scopes. PublicationModeDefault PublicationMode = "" // PublicationModeEnrichOnly is HEAD-enrichment republication: journals must // contain only enrich ops, coverage is inherited and never re-attested as // observation evidence, and coverage-driven tombstones are disabled. PublicationModeEnrichOnly PublicationMode = "enrich-only" )
type PublishConfig ¶
type PublishConfig struct {
IndexSetID string
RunID string
RunStartedAt time.Time
ManifestCreatedAt time.Time
// SnapshotCompletionClock is sampled immediately before the immutable
// complete marker commit, after the manifest and referenced segments have
// been written and verified. Nil uses the UTC wall clock.
SnapshotCompletionClock func() time.Time
ParentManifests []ManifestReference
// PriorRows seeds prior current-state when no ParentSource is supplied (the
// slice adapter path, used by enrich and tests). When ParentSource is set it
// takes precedence and PriorRows is ignored.
PriorRows []CurrentObjectRow
// ParentSource, when non-nil, streams the verified parent's current-state rows
// into the compaction merge without materializing them. Continuity activation
// passes a bounded reader over the verified parent snapshot here.
ParentSource ParentRowSource
// StateParent and Lineage are the digest-bound continuity metadata written
// into the published manifest. Nil on a legacy/baseline-free publication.
StateParent *StateParent
Lineage *LineageRecord
JournalPaths []string
Coverage []CoverageAttestation
SegmentDir string
ManifestPath string
CompletePath string
LatestPath string
TargetRowsPerSegment int
// SpillRoot is the operator-controlled directory under which the streaming
// current-state merge stages its owner-only, symlink-safe workspace. When
// empty it defaults to a "spillmerge" directory beside the sealed journals
// (which are already resolved through operator app-data path classes).
SpillRoot string
// SpillBudget bounds the streaming merge's memory, workspace disk, and merge
// topology. Zero fields fall back to DefaultSpillMergeBudget.
SpillBudget SpillMergeBudget
// Mode selects compaction/publication policy (default crawl vs enrich-only).
Mode PublicationMode
// ExpectedParent, when non-nil, enforces latest-pointer CAS at advance.
// First publication of a set may leave this nil. Required for enrich-only.
ExpectedParent *ExpectedParentToken
// WriteLease is required for any latest advance. Must be a held package-owned
// *WriteLease (not an external interface). Nil or released leases fail closed.
WriteLease *WriteLease
AfterStep func(PublishStep) error
// OnSegmentProgress is optional observational segment-write progress
// (counts only). Outside persisted artifacts; never a publish failure vector.
OnSegmentProgress OnSegmentProgressFunc
}
type PublishResult ¶
type PublishResult struct {
Journals []JournalSummary
Compaction CompactionResult
Manifest InternalManifest
// ManifestSHA256 is the digest of the committed manifest bytes (same value
// written into complete.json). Prefer this over re-hashing after publish.
ManifestSHA256 string
// SnapshotCompletedAt is the exact local complete-marker commit time.
SnapshotCompletedAt time.Time
// LatestAdvanced is true after latest.json was successfully written.
// Callers must treat this as committed even if a later post-advance hook fails.
LatestAdvanced bool
}
func PublishSnapshot ¶
func PublishSnapshot(config PublishConfig) (PublishResult, error)
PublishSnapshot publishes a durable snapshot with a background context. Prefer PublishSnapshotContext so cancellation propagates into the streaming merge.
func PublishSnapshotContext ¶
func PublishSnapshotContext(ctx context.Context, config PublishConfig) (PublishResult, error)
PublishSnapshotContext compacts the sealed journals against the prior state and publishes the resulting current-state snapshot. Compaction and segment writing run through the streaming spill/merge current-state source and the streaming segment writer so the full current-state row set is never materialized in memory. The row/artifact/digest contract is identical to the prior materialized Compact -> WriteSegmentSet path.
type PublishStep ¶
type PublishStep string
const ( PublishStepJournalsValidated PublishStep = "journal_footers_validated" PublishStepCoverageValidated PublishStep = "coverage_validated" PublishStepCompacted PublishStep = "compacted" PublishStepSegmentsWritten PublishStep = "segments_written" PublishStepManifestWritten PublishStep = "manifest_written" PublishStepCompleteWritten PublishStep = "complete_written" PublishStepLatestAdvanced PublishStep = "latest_advanced" )
type PublishedParentRowSource ¶
type PublishedParentRowSource struct {
// contains filtered or unexported fields
}
PublishedParentRowSource is a bounded pull ParentRowSource over a verified PublishedSnapshot's segments. It walks segments in manifest order, holding at most one open segment descriptor at a time with a small fixed row buffer, and verifies each segment's digest on the same open file descriptor before parsing it (never re-opening by path — no digest/parse ABA). It enforces strict bytewise-increasing unique RelKey across the whole stream plus declared per-segment and total row counts, and never materializes the full current-state row set.
It satisfies ParentRowSource. Parent selection and digest binding remain the caller's responsibility; this source only streams an already-verified parent.
func NewPublishedParentRowSource ¶
func NewPublishedParentRowSource(snap PublishedSnapshot) *PublishedParentRowSource
NewPublishedParentRowSource builds a bounded pull source over the snapshot's segments in manifest order. The snapshot must already be trust-verified (latest -> complete -> digest-checked manifest); this source additionally verifies each segment file digest as it is streamed.
func (*PublishedParentRowSource) Close ¶
func (s *PublishedParentRowSource) Close() error
Close releases any open segment file. It is idempotent and safe after a terminal error; disclosure is limited to category/phase/message.
func (*PublishedParentRowSource) Next ¶
func (s *PublishedParentRowSource) Next(ctx context.Context) (CurrentObjectRow, error)
Next returns the next parent row in strict bytewise RelKey order, or io.EOF after the last row. Pointer field ownership transfers to the caller.
type PublishedRunLookup ¶
PublishedRunLookup resolves a published complete.json path for a set/run. Callers must only return paths under trusted roots; the resolver does not follow ref-supplied arbitrary paths.
type PublishedSnapshot ¶
type PublishedSnapshot struct {
LatestPath string
// CompletePath is the complete marker path used for this open when known.
CompletePath string
// CompleteSHA256 binds the exact complete-marker bytes parsed for this open.
CompleteSHA256 string
Complete publishedCompleteDoc
Manifest InternalManifest
SegmentDir string
// AccountedMarkerBytes / AccountedManifestBytes are the exact on-disk byte
// lengths of the complete marker and manifest slices that were digested and
// parsed for this open (same-bytes trust). Used by ancestry aggregate budgets.
AccountedMarkerBytes int64
AccountedManifestBytes int64
}
PublishedSnapshot is a verified local durable snapshot opened from a latest pointer + complete marker + digest-checked manifest. Segments are verified per-file when walked.
func OpenLatestPublishedSnapshot ¶
func OpenLatestPublishedSnapshot(latestPath string) (PublishedSnapshot, error)
OpenLatestPublishedSnapshot opens and trust-checks the latest durable snapshot without materializing rows. Marker and manifest reads are size-bounded.
func OpenLatestPublishedSnapshotBounded ¶
func OpenLatestPublishedSnapshotBounded(latestPath string, maxMarkerBytes, maxManifestBytes int64) (PublishedSnapshot, error)
OpenLatestPublishedSnapshotBounded is OpenLatestPublishedSnapshot with explicit marker/manifest size bounds.
func OpenPublishedRunSnapshot ¶
func OpenPublishedRunSnapshot(completePath, expectedIndexSetID, expectedRunID string) (PublishedSnapshot, error)
OpenPublishedRunSnapshot opens a durable snapshot from a complete marker path without consulting latest.json. Use this for receipt-pinned set/run selection so a later latest advance cannot silently switch the opened snapshot.
When expectedIndexSetID / expectedRunID are non-empty they must match the complete marker (and the validated manifest identity).
func OpenPublishedRunSnapshotBounded ¶
func OpenPublishedRunSnapshotBounded(completePath, expectedIndexSetID, expectedRunID string, maxMarkerBytes, maxManifestBytes int64) (PublishedSnapshot, error)
OpenPublishedRunSnapshotBounded is OpenPublishedRunSnapshot with explicit bounds.
func OpenPublishedRunSnapshotMaterial ¶
func OpenPublishedRunSnapshotMaterial( completePath, manifestPath, segmentDir string, completeData, manifestData []byte, expectedIndexSetID, expectedRunID string, ) (PublishedSnapshot, error)
OpenPublishedRunSnapshotMaterial verifies caller-bound complete and manifest bytes without reopening their pathnames. completePath, manifestPath, and segmentDir are descriptive locations beneath the caller's retained filesystem capability.
func (PublishedSnapshot) AccountedBytes ¶
func (s PublishedSnapshot) AccountedBytes() int64
AccountedBytes returns marker+manifest bytes charged for this open.
func (PublishedSnapshot) ExactSnapshotCompletedAt ¶
func (s PublishedSnapshot) ExactSnapshotCompletedAt() (time.Time, error)
ExactSnapshotCompletedAt returns the verified completion time only for a corrected complete.v2 marker. Legacy markers remain structurally readable but cannot produce exact-time authority.
type ReachabilityInput ¶
type ReachabilityInput struct {
Manifests []InternalManifest
RetainedManifests []ManifestReference
LatestPointers []LatestPointerReference
}
type ReachabilityPlan ¶
type ReachabilityPlan struct {
ReachableSegments []ReachableSegment `json:"reachable_segments"`
DerivedRefcounts []DerivedRefcount `json:"derived_refcounts"`
}
func DeriveReachabilityPlan ¶
func DeriveReachabilityPlan(input ReachabilityInput) (ReachabilityPlan, error)
type ReachableSegment ¶
type ReachableSegment struct {
SegmentID string `json:"segment_id"`
Path string `json:"path"`
Digest SegmentDigest `json:"digest"`
ReferencedBy []ManifestReference `json:"referenced_by"`
ReferenceCount int `json:"reference_count"`
}
type ReclaimResult ¶
type ReclaimResult struct {
IndexSetID string
Path string
Verdict LeaseVerdict
// Reclaimed is true only when a provably-unheld lock file was removed.
Reclaimed bool
// Holder is attribution copied from the on-disk doc before any action.
Holder string
}
ReclaimResult reports the outcome of a reclaim attempt for one set-authority lock file.
func ReclaimUnheldSetAuthorityLease ¶
func ReclaimUnheldSetAuthorityLease(authorityRoot, indexSetID string) (ReclaimResult, error)
ReclaimUnheldSetAuthorityLease removes a provably-unheld set-authority lock file for indexSetID. It opens the existing file (never creating it), takes the OS file lock non-blocking, and only if that succeeds — proving no live holder exists — unlinks the file under the held lock. A held lease is refused with ErrSetAuthorityHeld and the file is never touched; its holder is reported where attribution is available (see the note on the attribution read below). A missing lease is reported as not-reclaimed with a nil error, so reclaim is idempotent.
The held/unheld decision is made solely by the lock probe. The on-disk doc, any job record, and PID liveness are attribution only and never authorize a removal.
Refusal contract (ADR-0007 typed lock-state), identical to the probe's: an artifact-grounded refusal — non-canonical target name, non-regular lock pathname, or a doc failing the schema/scope gate — returns LeaseInvalid with its error. An infrastructure failure — unusable authorityRoot, an unexpected (non-would-block) lock error, or a failed unlink — returns an error claiming NO artifact state. A held lease returns LeaseHeld with ErrSetAuthorityHeld.
type SegmentDescriptor ¶
type SegmentDescriptor struct {
SegmentID string `json:"segment_id"`
Path string `json:"path"`
Format string `json:"format"`
Compression string `json:"compression"`
Rows int `json:"rows"`
Tombstones int `json:"tombstones"`
SizeBytes int64 `json:"size_bytes"`
MinRelKey string `json:"min_rel_key,omitempty"`
MaxRelKey string `json:"max_rel_key,omitempty"`
DistinctETags int `json:"distinct_etags"`
Digest SegmentDigest `json:"digest"`
}
type SegmentDigest ¶
type SegmentProgress ¶
type SegmentProgress struct {
Segment int // 1-based index of the segment just written
Total int // planned segment count for this write
Rows int // rows in the segment just written
RowsDone int // cumulative rows written across segments so far
}
SegmentProgress is a sanitized, observational progress signal for segment writes. Counts/phase only — never object keys, rel_keys, or prefixes.
type SegmentSizing ¶
type SegmentWriterConfig ¶
type SegmentWriterConfig struct {
Dir string
IndexSetID string
RunID string
CreatedAt time.Time
TargetRowsPerSegment int
AllowExistingIdentical bool
ParentManifests []ManifestReference
Coverage []CoverageAttestation
// Continuity lineage inputs supplied by the durable build path: ordinary
// builds set these from the verified parent capture (a first publication
// emits a baseline lineage record with no state parent).
RunStartedAt *time.Time
StateParent *StateParent
Lineage *LineageRecord
// OnSegmentProgress is optional. Invoked after each segment file is written;
// outside persisted artifact bytes and ignored for failure control.
OnSegmentProgress OnSegmentProgressFunc
// contains filtered or unexported fields
}
type SetAuthority ¶
type SetAuthority struct {
// contains filtered or unexported fields
}
SetAuthority is the stable, whole-set cross-process exclusion primitive. Its lock file is outside the set-specific segment root, so quarantining that root cannot detach the held lock from the canonical writer pathname.
func AcquireSetAuthority ¶
func AcquireSetAuthority(ctx context.Context, segmentSetRoot, indexSetID, holder string) (*SetAuthority, error)
AcquireSetAuthority takes whole-set authority before any canonical substrate is opened or mutated. Acquisition is non-blocking; process exit releases the OS lock automatically.
func (*SetAuthority) AssertHeld ¶
func (a *SetAuthority) AssertHeld() error
func (*SetAuthority) AssertHeldFor ¶
func (a *SetAuthority) AssertHeldFor(indexSetID, segmentSetRoot string) error
func (*SetAuthority) IndexSetID ¶
func (a *SetAuthority) IndexSetID() string
func (*SetAuthority) Path ¶
func (a *SetAuthority) Path() string
func (*SetAuthority) Release ¶
func (a *SetAuthority) Release() error
Release drops whole-set authority and removes the holder's own lock file, so a completed run leaves no set-authority artifact behind. It is idempotent.
Cleanup goes through unlinkUnderHeldLock on the descriptor this SetAuthority already holds:
- The descriptor is never reopened and the lock never reacquired. An OS file lock belongs to an open-file description, so a second open would contend with this holder.
- The unlink happens under the held lock, never after releasing it, so no successor's pathname can be removed.
If the pathname no longer names the held inode, removal is refused and reported. The lock is released on every path, including that refusal, so a refused cleanup never strands authority. Removal is authorized by possession of the held descriptor and the path-to-inode identity check; the holder is removing its own artifact, so the document's schema is not re-proved here.
A returned error means the lock was released but the artifact remains. It stays visible through the lease surface, with the verdict its content warrants: an intact original reports unheld and is reclaimable, a swapped-in replacement reports invalid. Untrappable termination bypasses this path and leaves the unheld kind.
func (*SetAuthority) SegmentSetRoot ¶
func (a *SetAuthority) SegmentSetRoot() string
type SetAuthorityLease ¶
type SetAuthorityLease struct {
IndexSetID string
Path string
Verdict LeaseVerdict
Holder string
AcquiredAt time.Time
DocType string
ModTime time.Time
// Detail carries the reason for an invalid/indeterminate verdict, or an
// attribution note. It never affects the verdict.
Detail string
}
SetAuthorityLease is the read-only report for one set-authority lock file. Holder/AcquiredAt are attribution copied from the on-disk doc for operator clarity; they are never inputs to the held/unheld verdict.
func EnumerateSetAuthorityLeases ¶
func EnumerateSetAuthorityLeases(authorityRoot string) ([]SetAuthorityLease, error)
EnumerateSetAuthorityLeases probes every set-authority lock file under authorityRoot and returns one report per artifact, sorted by index-set ID for deterministic output. A missing authority root is not an error — it yields an empty slice. Enumeration is fully non-mutating.
func ProbeSetAuthorityLease ¶
func ProbeSetAuthorityLease(authorityRoot, indexSetID string) (SetAuthorityLease, error)
ProbeSetAuthorityLease returns the non-mutating lock-state verdict for one index set's authority lock within authorityRoot. It opens the existing file read-only and never truncates or rewrites it: the probe must never call AcquireSetAuthority, which rewrites the holder doc and would destroy the very provenance being reported. The lock file and every byte of its doc are identical before and after the probe.
Refusal contract (ADR-0007 typed lock-state): a refusal grounded in the artifact — a malformed or non-canonical target name, a lock pathname that is not a regular file, or a doc failing the schema/scope gate — returns LeaseInvalid, because the artifact was examined and judged. A failure of the surrounding infrastructure — an unusable authorityRoot, or an unexpected (non-would-block) lock error — returns an error with NO verdict claimed: no judgement was reached, and inventing one would be indistinguishable from an observed verdict. Callers must therefore check the error before trusting the verdict on the infrastructure paths.
type SliceOrderedRows ¶
type SliceOrderedRows struct {
// contains filtered or unexported fields
}
SliceOrderedRows adapts a pre-sorted unique slice as an OrderedRowSource. Order is not sorted here; the streaming writer refuses out-of-order keys.
func NewSliceOrderedRows ¶
func NewSliceOrderedRows(rows []CurrentObjectRow) *SliceOrderedRows
NewSliceOrderedRows returns a source over rows. Optional onClose is invoked once when Close is called (for spy/tests).
func (*SliceOrderedRows) Close ¶
func (s *SliceOrderedRows) Close() error
func (*SliceOrderedRows) Next ¶
func (s *SliceOrderedRows) Next(ctx context.Context) (CurrentObjectRow, error)
func (*SliceOrderedRows) WithCloseHook ¶
func (s *SliceOrderedRows) WithCloseHook(fn func() error) *SliceOrderedRows
WithCloseHook installs a Close side effect (tests).
type SliceParentRows ¶
type SliceParentRows struct {
// contains filtered or unexported fields
}
SliceParentRows adapts a pre-sorted unique slice as a ParentRowSource.
func NewSliceParentRows ¶
func NewSliceParentRows(rows []CurrentObjectRow) *SliceParentRows
NewSliceParentRows returns a parent source over rows. Order is not sorted here; prepare rejects out-of-order or duplicate keys.
func (*SliceParentRows) Close ¶
func (s *SliceParentRows) Close() error
func (*SliceParentRows) Next ¶
func (s *SliceParentRows) Next(ctx context.Context) (CurrentObjectRow, error)
type SpillMergeBudget ¶
type SpillMergeBudget struct {
MaxBufferedRows int
MaxBufferedBytes int64
MaxRecordBytes int64
MaxJournalSources int
MaxWorkspaceBytes int64
MaxSpillRuns int
MaxFanIn int
MaxMergePasses int
}
SpillMergeBudget bounds memory, workspace disk, and merge topology. Zero fields are filled by DefaultSpillMergeBudget.
func DefaultSpillMergeBudget ¶
func DefaultSpillMergeBudget() SpillMergeBudget
DefaultSpillMergeBudget returns the frozen spill-merge budget defaults.
func ResolveSpillMergeBudget ¶
func ResolveSpillMergeBudget(b SpillMergeBudget) (SpillMergeBudget, error)
ResolveSpillMergeBudget applies the substrate defaults to zero fields and validates the result: zero alone selects a default, while an explicit invalid field (negative or otherwise sub-1) refuses with a typed SpillMergeInvalidConfig. Capacity-sensitive callers (publish, Build, public Retry) resolve through this before any crawl, provenance read, or journal validation so an invalid caller budget can never degrade to unbounded reads.
type SpillMergeCategory ¶
type SpillMergeCategory string
SpillMergeCategory classifies stable spill/merge failures.
const ( SpillMergeInvalidConfig SpillMergeCategory = "invalid_config" SpillMergeParentOrder SpillMergeCategory = "parent_order" SpillMergeJournal SpillMergeCategory = "journal" SpillMergeBudgetExhausted SpillMergeCategory = "budget" SpillMergeWorkspace SpillMergeCategory = "workspace" SpillMergeSpillIntegrity SpillMergeCategory = "spill_integrity" SpillMergeIO SpillMergeCategory = "io" SpillMergeCanceled SpillMergeCategory = "canceled" )
type SpillMergeConfig ¶
type SpillMergeConfig struct {
IndexSetID string
RunID string
RunStartedAt time.Time
Parent ParentRowSource
JournalPaths []string
Coverage []CoverageAttestation
Mode PublicationMode
// SpillRoot is an explicit operator-controlled directory. Required.
SpillRoot string
Budget SpillMergeBudget
}
SpillMergeConfig configures prepare-then-drain current-state merge.
type SpillMergeError ¶
type SpillMergeError struct {
Category SpillMergeCategory
Phase string
Message string
AttemptID string
Cause error
}
SpillMergeError is the typed failure surface for prepare/drain/close.
func (*SpillMergeError) Error ¶
func (e *SpillMergeError) Error() string
func (*SpillMergeError) Is ¶
func (e *SpillMergeError) Is(target error) bool
func (*SpillMergeError) Unwrap ¶
func (e *SpillMergeError) Unwrap() error
type SpillMergeStats ¶
type SpillMergeStats struct {
ObservedRecords int
EnrichmentRecords int
EmittedRows int
NewTombstones int
PeakBufferedRows int
PeakBufferedBytes int64
PeakWorkspaceBytes int64
SpillRunCount int
MergePasses int
PeakOpenFiles int
Complete bool
}
SpillMergeStats are deterministic high-water counters for hermetic envelope proofs.
type StateParent ¶
type StateParent struct {
IndexSetID string `json:"index_set_id"`
RunID string `json:"run_id"`
ManifestSHA256 string `json:"manifest_sha256"`
}
StateParent is the exact single continuous-state parent binding. Distinct from parent_manifests (reachability/enrich heritage; digest optional there).
func NormalizeStateParent ¶
func NormalizeStateParent(parent *StateParent) *StateParent
NormalizeStateParent returns a trimmed copy; empty input stays empty-shaped.
type StreamSegmentCategory ¶
type StreamSegmentCategory string
StreamSegmentCategory classifies streaming segment-write failures.
const ( StreamSegmentInvalid StreamSegmentCategory = "invalid" StreamSegmentOrder StreamSegmentCategory = "order" StreamSegmentCanceled StreamSegmentCategory = "canceled" StreamSegmentWrite StreamSegmentCategory = "write" StreamSegmentCleanup StreamSegmentCategory = "cleanup" StreamSegmentSource StreamSegmentCategory = "source" )
type StreamSegmentError ¶
type StreamSegmentError struct {
Category StreamSegmentCategory
Phase string
Message string
// RowIndex is 1-based for row-phase failures; zero when not applicable.
RowIndex int
Cause error
}
StreamSegmentError is the typed failure surface for streaming segment writes. Error() never renders RelKey values, configured Dir paths, or provider URIs.
func (*StreamSegmentError) Error ¶
func (e *StreamSegmentError) Error() string
func (*StreamSegmentError) Unwrap ¶
func (e *StreamSegmentError) Unwrap() error
type WriteLease ¶
type WriteLease struct {
// contains filtered or unexported fields
}
WriteLease is an index-set-scoped exclusive lock for durable latest writers. Mutual exclusion is provided by an OS file lock held on an open FD for the lifetime of the critical section. Process crash releases the lock. Whether that lock is advisory or mandatory is platform-dependent, so nothing here may assume a held lease file stays readable to other processes.
The lease is bound at acquisition to a canonical segment-set root and index-set ID. PublishSnapshot must assert that binding against the latest path it is about to advance.
Metadata in the lock file is diagnostic only and is never used for reclaim.
func AcquireWriteLease ¶
func AcquireWriteLease(segmentSetRoot, indexSetID, holder string, _ time.Duration) (*WriteLease, error)
AcquireWriteLease takes an exclusive cross-process write lock under segmentSetRoot (cache/segments/<index_set_id>/). The ttl parameter is ignored; exclusivity is OS-lock-based for the process lifetime of the returned lease. The lease is bound to the canonical root and indexSetID for later AssertHeldFor.
func AcquireWriteLeaseForMaintenance ¶
func AcquireWriteLeaseForMaintenance(segmentSetRoot, indexSetID, holder string) (*WriteLease, error)
AcquireWriteLeaseForMaintenance takes the existing durable writer lock without creating or rewriting the diagnostic lock file. It is used by maintenance operations whose immutable plan already includes the complete segment-set tree: changing the diagnostic bytes after planning would destroy the plan's authority. A missing or unsafe lock file fails closed.
func (*WriteLease) AssertHeld ¶
func (l *WriteLease) AssertHeld() error
AssertHeld verifies the package-owned write lease is still held (FD live).
func (*WriteLease) AssertHeldFor ¶
func (l *WriteLease) AssertHeldFor(indexSetID, latestPath string) error
AssertHeldFor verifies the lease is held and authorizes advancing latestPath for indexSetID. latestPath's parent directory must be the lease segment-set root.
func (*WriteLease) Holder ¶
func (l *WriteLease) Holder() string
Holder returns the holder string supplied at acquire time.
func (*WriteLease) IndexSetID ¶
func (l *WriteLease) IndexSetID() string
IndexSetID returns the index-set ID bound at acquisition.
func (*WriteLease) Release ¶
func (l *WriteLease) Release() error
Release unlocks and closes the lease FD. Idempotent.
func (*WriteLease) Renew ¶
func (l *WriteLease) Renew(_ time.Duration) error
Renew is a no-op for OS-lock leases (hold is FD lifetime, not wall-clock TTL).
func (*WriteLease) SegmentSetRoot ¶
func (l *WriteLease) SegmentSetRoot() string
SegmentSetRoot returns the canonical segment-set root bound at acquisition.
func (*WriteLease) Token ¶
func (l *WriteLease) Token() string
Token returns the diagnostic ownership token for this lease instance.
Source Files
¶
- boundary.go
- compactor.go
- doc.go
- journal.go
- lineage.go
- parent_reader.go
- publish.go
- reachability.go
- segment.go
- segment_stream.go
- set_authority.go
- set_authority_probe.go
- set_authority_reclaim.go
- snapshot_time.go
- spillmerge.go
- spillmerge_journal.go
- spillmerge_open_unix.go
- spillmerge_run.go
- write_lease.go
- write_lease_unix.go