collections

package module
v0.47.0 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2026 License: Apache-2.0 Imports: 41 Imported by: 6 modules, 8 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package collections is an in-memory, sharded, memory-dense store of ClassAds with a compiled query engine. Ads are serialized to the compact wire form and packed into append-only arena segments; a per-shard directory maps a stable key hash to a record location. Updates are MVCC-stamped so table scans see every ad exactly once even while background compaction moves bytes.

Index

Constants

View Source
const (
	// CompositeRefusedUnresolvableComponent: Attr is neither indexed in its own right nor
	// declared a composite component, so there is no kind to fold it by.
	CompositeRefusedUnresolvableComponent = "unresolvable-component"
	// CompositeRefusedDuplicateComponent: Attr appears twice in the tuple. The second
	// occurrence pins nothing the first did not.
	CompositeRefusedDuplicateComponent = "duplicate-component"
	// CompositeRefusedTooFewComponents: fewer than two components, which is an
	// attribute index written as a tuple, not a composite.
	CompositeRefusedTooFewComponents = "too-few-components"
	// CompositeRefusedTooManyComponents: wider than maxCompositeAttrs.
	CompositeRefusedTooManyComponents = "too-many-components"
	// CompositeRefusedDuplicateTuple: these components in this order are already
	// configured. The same components in a DIFFERENT order are a different composite and
	// are not refused here.
	CompositeRefusedDuplicateTuple = "duplicate-tuple"
)

The reasons a configured composite tuple is refused.

A component that is not in the spec's id space at all (a name nothing was ever configured under) and one that is in it but carries no kind (indexed neither in its own right nor as a declared component) are ONE reason, not two. Which of the two a given name hits depends on the id space: an inline spec knows only the names its own configuration mentions, an interned one knows every name the store has ever interned. Splitting them would make the same configuration report a different reason in memory than on disk, which is a worse diagnostic than the slightly coarse one -- and the fix is the same either way.

View Source
const DefaultDictSize = 112 * 1024

DefaultDictSize is the target size in bytes for a trained dictionary's content.

View Source
const DefaultRetrainInterval = 15 * time.Minute

DefaultRetrainInterval is the suggested cadence for background dictionary retraining. A dictionary trained on a representative sample stays effective as long as the ad population's shape is stable, so retraining need not be frequent.

View Source
const MaxGroupCols = maxGroupCols

MaxGroupCols is maxGroupCols, for the db layer's eligibility test. A caller that groups by more columns than this must not be handed a truncated key, so it has to know where the limit is rather than discovering it as a decline it cannot explain.

Variables

View Source
var CompactUndecodableHook = func(e CompactUndecodable) {
	if e.Blocked {
		log.Printf("collections: compaction left shard %d of %q uncompacted: record %q cannot be read: %s",
			e.Shard, e.Dir, e.Key, e.Err)
		return
	}
	log.Printf("collections: compaction of shard %d of %q copied record %q unchanged: it does not decode: %s",
		e.Shard, e.Dir, e.Key, e.Err)
}

CompactUndecodableHook is called once for each record CompactPreservedUndecodable or CompactBlockedSegments counts. The default logs it with the standard library logger; a daemon with its own logger replaces it, and nil silences it. Set it before opening collections.

View Source
var DictFaultHook = func(err error) {
	log.Printf("%v", err)
}

DictFaultHook is called for every compression-dictionary fault a store does not handle itself -- a file missing, replaced, changed, or found not to be the dictionary its segments were written with.

The default logs it with the standard library logger; a daemon with its own logger replaces it, and nil silences it. Options.OnDictFault takes precedence for one store. Set it before opening collections. See CompactUndecodableHook, which works the same way.

View Source
var ErrDamagedTrailer = errors.New("collections: segment trailer is damaged and its extent cannot be determined")

ErrDamagedTrailer is returned for a segment whose trailer was written and will not read. Its arena's end is genuinely unknowable: the length that says where the trailer begins lives in the foot that just failed its own checksum.

Nothing may be written to such a segment's tail. Treating the damage as "no trailer" would put the arena's end at the file's end -- past the damaged trailer -- and append a second one after it, so every pass that tried would grow the file by another trailer and fold the last one into what recovery maps as the arena.

View Source
var ErrDictIDMismatch = errors.New("collections: a dictionary file does not match the id it is stored under")

ErrDictIDMismatch is returned by Open when a dictionary file's own id does not match the slot it is stored under -- dicts/3.zst holding the dictionary stamped 7.

It is distinct from ErrMissingDictionaries because the operator action is distinct: nothing is damaged and nothing is lost, the files are in the wrong places, and the fix is to work out which belongs where. Opening anyway would decode the segments naming 3 with a dictionary that is not theirs, and every one of their records would be skipped.

View Source
var ErrInvalidDataKey = errors.New("collections: invalid data key")

ErrInvalidDataKey is returned (wrapped) by Open, CreateArchive and OpenArchive, and is the panic New raises, when Options.DataKey is set but is not a key this package seals with: it must be exactly crypt.KeySize bytes, an AES-256 key.

It is refused when the store is built rather than when a value is first sealed. A key AES cannot use fails every Seal; refusing it up front means a store that claims encryption at rest (EncryptionEnabled) either has a working key or does not exist. A shorter AES key (16 or 24 bytes) would seal, but under a weaker cipher than the one Options.DataKey documents, so it is refused as well.

View Source
var ErrMissingDictionaries = errors.New("collections: segment files name dictionaries this store does not have")

ErrMissingDictionaries is returned by Open when segment files name compression dictionaries the store cannot supply. It is a distinct error because the operator action is distinct: the dictionaries have to be restored (dicts/attic/, a backup, the filesystem), and nothing a restart or a repair does will help.

Opening anyway is not an option worth offering by default. The records are intact and a restored dictionary brings every one of them back, so the damage is recoverable right up until something writes to the store believing those segments are gone.

View Source
var ErrNoRoomForReplica = errors.New("collections: segment cannot carry a dictionary replica")

ErrNoRoomForReplica is returned when a segment file cannot carry a dictionary copy: either the copy would dwarf the data it rides along with, or the arena is written so close to its end that a trailer would sit where a record walk still looks.

View Source
var ErrSeqCursorExpired = errors.New("collections: the cursor's snapshot has been reclaimed; restart the listing from the beginning")

ErrSeqCursorExpired reports that a paged read's cursor names a snapshot older than versions the store has since reclaimed, so the rest of the listing can no longer be read as of that snapshot. It is returned in SeqPage.Err before any row of the page. Resuming the same cursor fails the same way: restart the listing from the zero cursor.

View Source
var ErrTimeTravelDisabled = errors.New("collections: time travel is not enabled on this collection")

ErrTimeTravelDisabled is returned by the AS OF query paths when the collection has no time-travel configuration.

View Source
var ErrTooDeep = wire.ErrTooDeep

ErrTooDeep is wire.ErrTooDeep, the same error value: a write refused because a value nests deeper than any reader would read back (wire.MaxDepth). Every write path refuses such an ad before it changes anything -- Put, Update and UpdateOld return the error, and a transaction reports the key in CommitResult.Unapplied -- so the store never holds a record that cannot be read. The refusal is permanent; retrying the same write fails the same way.

View Source
var ErrUnsupportedColumnarVersion = errors.New("collections: columnar payload format version is not one this build reads")

ErrUnsupportedColumnarVersion is returned (wrapped, naming the segment) by Open when a columnarized segment's payload carries a format version this build cannot read -- a payload written by a newer build. The payload is the only copy of the values its records were written without, so the collection is refused rather than opened with those records missing; open it with a build that reads that version. Fsck reports such a segment (FsckSegment.ColumnarUnsupported) and Repair leaves it alone.

View Source
var OpenIndexDiagHook func(OpenIndexDiag)

OpenIndexDiagHook, when non-nil, is called once at the end of each Collection Open with a summary of sidecar adoption for that store. Set it (once, at process start) to log why a reopen rebuilds indexes -- the slow-startup path -- rather than adopting the persisted ones. Diagnostic only; the callback must not block (it runs on the Open path).

View Source
var OpenProgressHook func(OpenProgress)

OpenProgressHook, when non-nil, is called during each persistent Collection Open with the progress of the phase in flight, at most once per openProgressInterval per phase. Set it (once, at process start) to log that a long open is advancing. A package-level var rather than an Option, matching OpenIndexDiagHook, which answers the same question after the fact.

Diagnostic only; the callback must not block (it runs on the Open path, which holds no lock a caller could be waiting on but is the only thing standing between the process and serving requests).

Functions

func AggFanouts added in v0.37.0

func AggFanouts() int64

AggFanouts reports how many aggregate passes have fanned out across segments. Test-only observability; see aggFanouts.

func AggSegmentPaths added in v0.37.0

func AggSegmentPaths() (columnar, row int64)

AggSegmentPaths reports how many segments the aggregate value pass has answered from a columnar block and how many it has read record by record. See the note above the counters.

func BackgroundIndexCatchUps added in v0.46.1

func BackgroundIndexCatchUps() int64

BackgroundIndexCatchUps reports how many of IndexCatchUps background catch-up did, off any request's path.

func BatchKeyQuery added in v0.38.3

func BatchKeyQuery(attr string, keys []int64) *vm.Query

BatchKeyQuery builds the constraint a key batch stands for, `member(attr, {keys...})`, as a compiled query. It is exported because a caller measuring or explaining a batch needs the same query the lookup plans from, and because building it from an AST rather than from formatted text is what makes rebinding a batch cheap: the keys become literals directly, with no lexing.

func BatchKeyQueryWhere added in v0.38.3

func BatchKeyQueryWhere(attr string, keys []int64, where ast.Expr) *vm.Query

BatchKeyQueryWhere is BatchKeyQuery conjoined with a constraint of the caller's own, which is the query LookupKeysWhere plans from. A nil where gives BatchKeyQuery exactly.

The key term is the RIGHT operand so that the caller's constraint is evaluated first, which is what a reader of an explained plan expects to see, and both are parenthesized by construction because they are AST nodes rather than text.

func ColNativeBadRows added in v0.33.3

func ColNativeBadRows() int64

ColNativeBadRows reports how many record reads, since the process started, found the record's row in its segment's columnar payload unparseable -- a cold tail whose entries do not split, say. Each such read fails rather than return the part of the ad that preceded the damage; a scan skips the record. Nonzero means a payload is corrupt in a way its checksum did not catch.

func ColNativeCRCFailures added in v0.28.0

func ColNativeCRCFailures() int64

ColNativeCRCFailures reports how many columnar payloads have been refused for a bad checksum or an unparseable body since the process started. A payload in a format version this build does not read is not counted here; see ColNativeUnsupportedVersions.

func ColNativeOffsetMismatches added in v0.32.0

func ColNativeOffsetMismatches() int64

ColNativeOffsetMismatches reports how many columnar payloads, since the process started, verified but were refused because their offset map does not fit their segment's records (see colOffsetsFitRecords). Like a payload refused for its checksum, such a segment's records then fail to read rather than return another record's values. Fsck names the segment.

func ColNativeRowMisses added in v0.32.0

func ColNativeRowMisses() int64

ColNativeRowMisses reports how many record reads, since the process started, found a columnarized record whose segment's columnar payload has no row for it. Each such read fails rather than return the record's remnant as a whole ad; a scan skips the record. Nonzero means a segment's payload does not match its records.

func ColNativeUnsupportedVersions added in v0.32.0

func ColNativeUnsupportedVersions() int64

ColNativeUnsupportedVersions reports how many columnar payloads have been found, since the process started, in a format version this build cannot read. Each one makes Open fail with ErrUnsupportedColumnarVersion.

func CollapseDeferrals added in v0.30.0

func CollapseDeferrals() int64

CollapseDeferrals reports how many delta-chain collapses have been postponed to a later pass.

func ColumnarDeltaDisposition added in v0.30.0

func ColumnarDeltaDisposition() (dropped, materialized, unresolved int64)

ColumnarDeltaDisposition reports what columnarization did with the delta records it met: dropped as garbage, materialized into whole ads, and left alone because the chain would not resolve.

func ColumnarDeltasDropped added in v0.30.0

func ColumnarDeltasDropped() int64

ColumnarDeltasDropped reports how many delta records columnarization has dropped rather than carried into a rewritten segment.

func ColumnarFallbacks added in v0.28.0

func ColumnarFallbacks() int64

ColumnarFallbacks reports how many records the columnar accelerator has deferred to the row path since the process started.

It is a correctness-adjacent metric rather than a performance one. Deferring is always right, so a rising count is the only outward sign that the accelerator is being bypassed -- for instance because a block is addressing attribute ids from a previous process's intern table. A durability test that asserts this does not grow across a restart catches that; one that only compares query answers cannot, because the answers stay correct.

func ColumnarizedAtSeal added in v0.46.1

func ColumnarizedAtSeal() (converted, failed, skipped int64)

ColumnarizedAtSeal reports how many segments have been columnarized by the seal-time worker, how many it attempted and could not rewrite, and how many it was handed but did not reach (retired first, collection stopping, or the rewrite disabled meanwhile).

func ColumnarizedSegments added in v0.28.0

func ColumnarizedSegments() (segments, bytesSaved int64)

ColumnarizedSegments reports how many segments have been rewritten into columnar form, and how many arena bytes that removed, since the process started.

func CompactBlockedSegments added in v0.34.0

func CompactBlockedSegments() int64

CompactBlockedSegments reports how many segments, since the process started, held a record compaction could not read at all (an unusable dictionary, a damaged columnar payload, bytes that do not decompress). The shard holding such a segment is left uncompacted, and later passes skip it until the segment is gone (Repair, or every record in it superseded) or the process restarts.

func CompactDeferredLiveDelta added in v0.30.9

func CompactDeferredLiveDelta() int64

CompactDeferredLiveDelta reports how many shard compactions were deferred because the active segment still held a live delta. See compactDeferredLiveDelta.

func CompactInternPaths added in v0.30.0

func CompactInternPaths() (wirePath, astPath int64)

CompactInternPaths reports how many records compaction re-interned by transcoding the wire bytes versus by decoding into an ast and encoding it back.

func CompactPreservedUndecodable added in v0.34.0

func CompactPreservedUndecodable() int64

CompactPreservedUndecodable reports how many records, since the process started, compaction copied forward unchanged because they would not decode. Such a record reads exactly as it did before -- a reader that refused it still does -- and the rest of its shard compacts around it. Each record is counted once per process, by the pass that first meets it.

func CompareValues added in v0.43.0

func CompareValues(a, b classad.Value) int

CompareValues orders two ClassAd values totally: negative when a sorts before b, positive when it sorts after, zero when neither sorts before the other.

Equal-comparing values are not necessarily the same value. Two strings that differ only by case fold equal under ClassAd's own comparison and are then separated by their bytes, so distinct strings never report equal; but 2 and 2.0 do, as ClassAd says they should.

NaN sorts after every other number rather than comparing false in both directions. A comparator that reports a NaN neither less nor greater is not a total order, and the sorts and the top-k keep that use this one both depend on being able to name a worst element.

func ConflictChecks added in v0.6.0

func ConflictChecks() int64

ConflictChecks returns the cumulative number of per-key conflict checks committed transactions have performed -- zero while a single writer runs (the fast path).

func CorruptChainLinks() int64

CorruptChainLinks reports how many times a bucket-chain walk found a link naming a segment that does not exist, across every collection in this process.

It is exported so an operator can see it without a debugger. Nonzero means some reader walked a segment whose mapping it did not hold alive, and the walk read whatever replaced it; the records themselves are not corrupt on disk.

func DamagedRecordsDropped added in v0.32.0

func DamagedRecordsDropped() int64

DamagedRecordsDropped reports how many damaged records, since the process started, left the store with their segment: a rewrite (compaction, columnarization, a merge or a reseal) leaves them out, and retention or Truncate removes them with the rest. It counts the segment's damage set when the segment is retired, including the records a rewrite found failing their checksum (verifyForRewrite).

func DamagedRecordsSkipped added in v0.32.0

func DamagedRecordsSkipped() int64

DamagedRecordsSkipped reports how many damaged records, since the process started, Open found in the segments it loaded and set aside: every walk skips them, and none is read, superseded by, or supersedes another record. They are found by a recovery walk that continues past damage, by the directory rebuild, or from a damage set a sidecar recorded, and each open counts them again. OpenIndexDiag.DamageStops names the segments that recovery continued through.

func DeltaAnomalies added in v0.30.0

func DeltaAnomalies() (liveAtCompact, droppedFromHistory, flagMismatch int64)

DeltaAnomalies reports the three things that should all stay zero in a healthy delta store: live deltas met by compaction, superseded deltas dropped from the travel window, and records whose header and payload disagree about being a delta.

func DictFilesChanged added in v0.42.0

func DictFilesChanged() int64

DictFilesChanged counts dictionary files found with contents that no longer match what was loaded from them.

func DictFilesMissing added in v0.42.0

func DictFilesMissing() int64

DictFilesMissing counts dictionary files found gone by a maintenance check, process-wide since start. Nothing in this package removes one, so any count at all means something outside the process is deleting them. See DictsDirRecreated, which counts the coarser case of the whole directory going.

func DictFilesReplaced added in v0.42.0

func DictFilesReplaced() int64

DictFilesReplaced counts dictionary files found to be a different file than the one loaded (a different inode at the same path).

func DictFilesRestored added in v0.42.0

func DictFilesRestored() int64

DictFilesRestored counts missing dictionary files rewritten from the descriptor the store still held open.

func DictFingerprintMismatches added in v0.42.0

func DictFingerprintMismatches() int64

DictFingerprintMismatches reports how many segments have been found to name a dictionary that is not the one their records were written with. Any count at all means records are being skipped.

func DictsDirRecreated added in v0.41.1

func DictsDirRecreated() int64

DictsDirRecreated reports how many times, since the process started, persisting a dictionary found its directory gone and recreated it.

It is never expected to be non-zero. Nothing in this package removes that directory, so a non-zero count means something outside the process did -- and every dictionary that was in it is gone with it, including dicts/attic/, which lives inside it. The store keeps working on the codecs it already holds in memory and fails at the NEXT open, so this counter is the only warning available in between. A daemon should surface it.

func DictsPreserved added in v0.42.0

func DictsPreserved() int64

DictsPreserved reports how many dictionaries have been written aside because the file at their own path stopped being them.

func DictsRecoveredFromSegments added in v0.42.0

func DictsRecoveredFromSegments() int64

DictsRecoveredFromSegments reports how many dictionaries have been restored from a segment trailer because dicts/ no longer held them.

func DictsUnverifiable added in v0.42.0

func DictsUnverifiable() int64

DictsUnverifiable reports how many loaded dictionaries carry no distinguishing id of their own, process-wide since start. See legacyDictID.

func FallbackReasons added in v0.30.0

func FallbackReasons() (removal, bound, noBase, ineligible int64)

FallbackReasons reports why patch writes stored whole records rather than deltas.

func IndexCatchUps added in v0.33.3

func IndexCatchUps() int64

IndexCatchUps reports how many segment indexes have been brought up to their segment's end, by a read or by background catch-up.

func InternSkippedDictUnusable added in v0.34.0

func InternSkippedDictUnusable() int64

InternSkippedDictUnusable reports how many segments, since the process started, InternSealed (and RetrainDict, which runs it) has passed over because their attribute dictionary is unusable (SegDictsUnusable): their records are interned, so there is nothing to transcode, and none of them can be read to rewrite. Each segment counts once, however many passes skip it.

func IsSystemKey added in v0.9.0

func IsSystemKey(key string) bool

IsSystemKey reports whether key is a reserved internal system key (begins with a NUL byte). Exported so callers (and the db/dbrpc layers) can classify a key without duplicating the sentinel.

func KeylessResealStats added in v0.37.0

func KeylessResealStats() (records, values int64)

KeylessResealStats reports, of the whole records a transaction not entitled to sealed values composed from the stored bytes, how many carried sealed values from an interned record and so had the store re-seal them, and how many values that was in all.

func KeylessWriteStats added in v0.35.0

func KeylessWriteStats() (composed, overBoundDeltas int64)

KeylessWriteStats reports how a transaction not entitled to sealed values stored the writes that needed a whole record: composed counts every one composed from the stored bytes.

overBoundDeltas is always 0. It counted writes stored as a delta past the chain bound because the record held a sealed value only the key could re-key; the store now re-seals such a value itself (see KeylessResealStats), so no write takes that path. It is kept so existing callers still compile.

func LastDeltaDecodeFailure added in v0.30.5

func LastDeltaDecodeFailure() (stage, msg string)

LastDeltaDecodeFailure returns the most recently sampled decode error behind a refused chain merge, or ("", "") if none has happened.

func LastNoBaseDetail added in v0.30.7

func LastNoBaseDetail() (versions int, chainBroken bool, sealedSkipped int)

LastNoBaseDetail returns the shape of the most recent no-base chain: how many versions the walk did find, whether it truncated at a dead link, and how many sealed segments it could not probe.

func LatencyBucketBoundsNanos added in v0.12.1

func LatencyBucketBoundsNanos() []int64

LatencyBucketBoundsNanos returns a copy of the histogram's inclusive upper bounds (in nanoseconds). An OpStat's Buckets slice has one more entry than this: buckets[i] counts observations <= bound[i], and the final entry counts observations above the last bound.

func ListCellsMoved added in v0.38.0

func ListCellsMoved() (moved, keptNonCanonical int64)

ListCellsMoved reports how many list cells columnarization has moved out of their records, and how many it kept in their records because the column's re-encoding of the values was not the stored bytes, since the process started.

func MergedBytes added in v0.24.1

func MergedBytes() int64

MergedBytes reports the total source bytes rewritten by merges since this process started.

func MigrateSkippedLiveDelta added in v0.30.10

func MigrateSkippedLiveDelta() int64

MigrateSkippedLiveDelta reports how many shards the sealed-attribute migration skipped because their active segment still held a live delta. See migrateSkippedLiveDelta.

func ProjectionChecksum added in v0.5.2

func ProjectionChecksum(ad *classad.ClassAd, attrs []string) uint64

ProjectionChecksum returns a 64-bit FNV-1a checksum over the given attributes' literal expression text in ad, taken in the order given and delimited so two distinct projections cannot alias. A missing attribute contributes a fixed marker, so "absent" is distinguished from every present value.

This is the standalone, caller-supplied-attrs form of an ordered index's cluster Signature (OrderSpec.Cluster). Unlike that index-time signature -- whose attribute set is fixed when the index is opened -- ProjectionChecksum takes the projection at call time, for callers whose significant attributes vary per query (e.g. a schedd whose negotiator sends the significant-attribute set in each negotiation header).

It hashes each attribute's *expression text* rather than its evaluated value, matching HTCondor autocluster semantics: two job ads whose significant attributes are textually identical (same Requirements expression, same RequestMemory literal, ...) hash equal, so a run-length fold over a priority-ordered stream folds them into one resource request with a stored-value compare. A 64-bit collision could merge two adjacent runs; over the projected value bytes that is negligible.

func ProvisionalIndexBuilds added in v0.30.11

func ProvisionalIndexBuilds() int64

ProvisionalIndexBuilds reports how many sealed segments were given a provisional key index at seal time. See segment.keyIdxMem.

func ReadIndexCatchUps added in v0.46.1

func ReadIndexCatchUps() int64

ReadIndexCatchUps reports how many of IndexCatchUps a read paid for synchronously: a tail longer than the read threshold that the background had not reached. Steadily rising, it says background catch-up is not keeping up with the writes (or has stopped); the read's PhaseIndexCatchUp says what each one cost.

func RecordReadSkipReasonNames added in v0.32.0

func RecordReadSkipReasonNames() []string

RecordReadSkipReasonNames lists every reason RecordReadSkips can report, including those at zero.

func RecordReadSkips added in v0.32.0

func RecordReadSkips() map[string]int64

RecordReadSkips reports, by reason, how many record reads since the process started returned nothing because the stored record could not be turned into a whole ad. Only nonzero reasons are present.

Such a record is not an error to the caller: a scan or query skips it and carries on, and a point read reports the key as not found. A nonzero count therefore means some answers were short, which nothing in the answers themselves shows; Fsck is what says where. Each count is of reads, not records: a record two scans skip counts twice. VerifyReadSkips still counts the "record-crc" refusals of scans on its own.

func RecordsPastDamage added in v0.32.0

func RecordsPastDamage() int64

RecordsPastDamage reports how many keyed records, since the process started, were not loaded because Open's recovery walk stopped at damage in the middle of their segment: the records that verify after the stop, plus the damaged ones that still frame (the record the walk stopped at among them). It counts only stops with something readable after them. Recovery walks a segment whose sidecar does not supply a trusted extent and stops at the first record that fails its checksum; that is right for a torn tail and drops everything after damage in the middle. OpenIndexDiag.DamageStops names the segments. Fsck reports the damage, and Repair recovers the records of a segment it may rewrite.

func RemnantRefFailures added in v0.34.0

func RemnantRefFailures() int64

RemnantRefFailures reports how many record reads, since the process started, found a columnarized record whose remnant dictionary reference did not resolve. Each such read fails rather than return an ad holding the reference. Nonzero means a payload's dictionary does not match its records.

func RenderRawAdInline added in v0.16.4

func RenderRawAdInline(w, buf []byte, offs []int) (outBuf []byte, outOffs []int, myType, targetType string, ok bool)

RenderRawAdInline renders a wire-form row (a self-contained inline-names ad, e.g. one shipped by ScanRawWire over dbrpc) to old-ClassAd "Name = Value" expression text: each expression is buf[offs[i]:offs[i+1]], with MyType/TargetType lifted out exactly as the collection scans do -- the shape message.PutClassAdRawBytes consumes. This is the LAST-MINUTE conversion at the client edge; everything upstream of it stays in wire form. buf/offs are reset and reused (pass the previous call's returns to avoid allocation).

func RewritesColumnarized added in v0.47.0

func RewritesColumnarized() int64

RewritesColumnarized reports how many rewrite outputs (merges, retention trims) were columnarized before they were committed, since the process started.

func RewritesRefusedDamaged added in v0.32.0

func RewritesRefusedDamaged() int64

RewritesRefusedDamaged reports how many times, since the process started, a rewrite of a segment (compaction, columnarization, a merge or a reseal) was not done because of damage: a header walk of the segment did not land on its extent, or Open's recovery stopped at damage in it and left records past the stop (OpenIndexDiag.DamageStops). The segment is left as it is for Fsck and Repair.

func SealWalkStats added in v0.30.0

func SealWalkStats() (examined, deltas int64)

SealWalkStats reports what the collapse walk has examined and found: live records looked at, and live deltas among them. The ratio is the walk's yield -- whether it is finding chains to collapse or scanning a segment to conclude there is nothing to do.

func SealedInlineFormRecoveries added in v0.34.0

func SealedInlineFormRecoveries() int64

SealedInlineFormRecoveries reports how many sealed values were read from an interned record in the inline-names key form, because they did not parse in the interned form every other sealed value in such a record has. An earlier build's compaction copied sealed values unopened from inline-names records into interned ones; a value holding a record literal was then unreadable, and its shard could not compact. Each such value is now read in the form it was sealed in, and the next compaction of its shard re-seals it in the interned form, after which it stops counting. A count that keeps rising therefore means a shard that is not compacting. It counts reads, not records.

func SealedProbesSkipped added in v0.30.7

func SealedProbesSkipped() int64

SealedProbesSkipped reports how many sealed-segment probes were skipped for want of a key index. A rising count alongside delta-index-pending says reads are racing the reindex pass.

func SegDictCRCFailures added in v0.32.0

func SegDictCRCFailures() int64

SegDictCRCFailures reports how many segment attribute dictionary records have been refused for a bad checksum since the process started.

func SegDictsUnusable added in v0.32.0

func SegDictsUnusable() int64

SegDictsUnusable reports how many segments, since the process started, were opened with interned records and no usable dictionary: its record failed its checksum (SegDictCRCFailures), recovery stopped at damage before it, or it was not recognised. Every record of such a segment fails to read (RecordReadSkips reason "dict-unusable") rather than decode through a dictionary that may rename attributes, or through none.

func SeqCursorStats added in v0.33.0

func SeqCursorStats() (deferrals, revocations, expired int64)

SeqCursorStats reports, process-wide, how many reclamation passes a paged read's lease deferred, how many leases were revoked so a deferred shard could be reclaimed, and how many cursors were refused with ErrSeqCursorExpired.

func SetArchiveBlockCacheBudget added in v0.29.6

func SetArchiveBlockCacheBudget(bytes int64)

func SetMutatingBlockCacheBudget added in v0.29.6

func SetMutatingBlockCacheBudget(bytes int64)

SetMutatingBlockCacheBudget and SetArchiveBlockCacheBudget set the process-global shared block-cache byte budget for each workload kind. They are the config knob behind Options' {Mutating,Archive}BlockCacheBytes; db/ (and above it htcondordb) should call them once at startup from configuration. Safe to call at any time and concurrently: if the kind's cache already exists it is resized in place. A value ≤ 0 is ignored (keeps the current or default budget).

func SpliceStats added in v0.30.0

func SpliceStats() (spliced, spliceRefused, objectPath int64)

SpliceStats reports how delta merges were served: by splicing attribute bytes, by decoding after the splice refused, and by decoding because the caller asked for an object rather than bytes (a point read, or a collapse in a collection with an ordered index or a watcher).

func StrandedSealedDeltas added in v0.30.8

func StrandedSealedDeltas() int64

StrandedSealedDeltas reports how many live delta records were found in sealed segments at open. Any value above zero means the seal-collapse invariant is broken on disk, and the keys behind those records are on their way to becoming unreadable.

func SystemKey added in v0.9.0

func SystemKey(name string) string

SystemKey builds a system key from a name by prefixing the reserved NUL byte. The name is otherwise opaque; callers namespace it however they like.

func TrainDict

func TrainDict(samples [][]byte) ([]byte, error)

TrainDict builds a ZSTD compression dictionary from sample records (the wire-encoded bytes of a representative set of ads; see CollectSamples). The resulting dictionary can be handed to NewZSTDCodec. It uses DefaultDictSize.

func TrainDictSize

func TrainDictSize(samples [][]byte, dictSize int) (dict []byte, err error)

TrainDictSize is TrainDict with an explicit dictionary content size.

The pure-Go zstd.BuildDict does not perform ZDICT-style content *selection* (the cover algorithm); the dictionary content is whatever we supply as the builder's History. We therefore assemble the content ourselves by concatenating distinct samples up to dictSize — for a pool of similar ClassAds, this captures the shared attribute names and values that later ads back- reference. BuildDict then trains the entropy tables from the full sample set.

func UnreadableBaseReasonNames added in v0.30.3

func UnreadableBaseReasonNames() []string

UnreadableBaseReasonNames lists every reason name UnreadableBaseReasons can report, including the ones currently at zero. A consumer publishing these as metrics needs the whole set up front: a reason that appears only once it is non-zero reads as "no such counter" at exactly the moment someone is checking whether it is the one firing.

func UnreadableBaseReasons added in v0.30.3

func UnreadableBaseReasons() map[string]int64

UnreadableBaseReasons reports why patch writes were refused for an unreadable base, keyed by reason name. The values sum to UnreadableBaseRefusals.

func UnreadableBaseRefusals added in v0.30.1

func UnreadableBaseRefusals() int64

UnreadableBaseRefusals reports, process-wide, how many patch writes were refused because the key was present but its current record could not be read. Nonzero means the store failed to resolve a key it holds -- the write was reported as a conflict rather than stored as a fragment.

func VerifyReadSkips added in v0.31.3

func VerifyReadSkips() int64

VerifyReadSkips reports how many records have been refused because their checksum did not match, across every collection in this process. It is zero unless some collection was opened with DisableReadVerification.

Non-zero means reads are quietly incomplete, and fsck is what says where.

func WatchFilter added in v0.4.0

func WatchFilter(seq iter.Seq[WatchEvent], match func(*classad.ClassAd) bool) iter.Seq[WatchEvent]

WatchFilter wraps a Watch event stream to deliver only events for keys whose ad satisfies match. It keeps a set of the keys currently matching so a filtered view stays correct as ads change:

  • an Upsert whose ad matches is delivered (the key is marked matching);
  • an Upsert whose ad no longer matches, for a key that was matching, is converted to a Delete so the client drops it from its filtered view;
  • a Delete is delivered for a key known to be matching, and -- during catch-up (before Synced), where the prior match state of a resumed key is unknown -- forwarded conservatively (the client no-ops an unknown key);
  • Reset clears the matched set; Synced and Resync pass through.

A nil match returns seq unchanged (no filtering). match is called on each Upsert's ad and must be safe for concurrent-free sequential use.

Types

type AdUpdate

type AdUpdate struct {
	Key []byte
	Ad  *classad.ClassAd
}

AdUpdate is one insert-or-update in a batch.

type AggTier added in v0.32.1

type AggTier int

AggTier names WHICH strategy answered an aggregate -- the thing a caller previously had to INFER from the scan counts being zero. That inference was wrong in two ways: it rested on an accidental property (the fast paths happen not to reassemble records, so they leave the counts at zero) rather than on anything stated, and it could not tell a columnar answer from a constraint that was proved empty without reading anything, since both report all-zero counts.

The values ride on the wire as an int32 appended to the scan-stats trailer, so they are permanent: add new tiers at the end, never renumber. TierUnreported is the zero value so a response from a peer that never sent a tier -- an older server, or an op whose trailer predates the field -- reads as "did not say" rather than claiming a tier it never reported.

const (
	// TierUnreported means no tier was reported: the zero value, NOT a claim about the strategy.
	TierUnreported AggTier = 0
	// TierMatchNone: the constraint was proved to match nothing, so no data was read at all.
	TierMatchNone AggTier = 1
	// TierIndex: answered from per-segment metadata -- postings, stored record counts, zone maps
	// -- without opening a segment's records.
	TierIndex AggTier = 2
	// TierColumnar: answered from the columnar accelerator, reading only the columns the query
	// touches rather than reassembling records.
	TierColumnar AggTier = 3
	// TierScan: answered by walking records (the fall-through path); the scan counts in the rest
	// of ScanStats describe it.
	TierScan AggTier = 4
)

func (AggTier) String added in v0.32.1

func (t AggTier) String() string

String names the tier for a diagnostic (EXPLAIN ANALYZE prints it next to the counts).

type Archive

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

Archive is an append-only, larger-than-RAM, rotated store of ClassAds — the "condor history file" use case. Ads are appended once and never updated; old data is dropped in bulk by rotation, with whole-segment pruning via zone maps and newest-first + LIMIT queries.

It is a thin facade over a Collection configured as an append log (Options.AppendOnly) with newest-first scans, retention rotation, and zone maps. All the archive-specific machinery — sealed segments, per-segment sidecar indexes, zone pruning, O(segments) recovery, retention, and the append-stream watch — now lives in the mainline Collection, so the archive is "a persistent store with a few rules and no compaction" rather than a fork. See docs/history-archive.md.

func CreateArchive

func CreateArchive(opts ArchiveOptions) (*Archive, error)

CreateArchive creates a new, empty Archive. The directory must not already hold one (use OpenArchive to reopen).

func OpenArchive

func OpenArchive(opts ArchiveOptions) (*Archive, error)

OpenArchive reopens an existing Archive (or creates one if the directory is empty), recovering its segments. The same options must be supplied as at creation (the Collection recovers each segment with the codec it names).

func (*Archive) AcquireRead added in v0.33.0

func (a *Archive) AcquireRead() bool

AcquireRead registers the caller as an in-flight reader of the archive; see Collection.AcquireRead. Balance a true answer with ReleaseRead.

func (*Archive) AddHotAttrs added in v0.32.0

func (a *Archive) AddHotAttrs(names ...string) []string

AddHotAttrs pins the named attributes into the hot set, merging them with the current one, and returns the resulting hot attributes. As with RefreshHotSet this governs future writes only; existing records keep the header they were written with.

func (*Archive) AddIndex added in v0.18.0

func (a *Archive) AddIndex(categorical, value []string) bool

AddIndex adds per-segment indexes on the named categorical and/or value attributes and rebuilds every segment's index under the new set, so existing records are covered too. Returns false if the index set was unchanged.

Cost: the rebuild decompresses every record in the archive once. It does NOT rewrite any segment data -- a sealed segment's bytes are already correct and are left untouched; only the derived index sidecar beside them is rebuilt (see Collection.reindexSealed). That is the difference from Rewrite, which re-encodes and rewrites the whole store.

func (*Archive) AddSchemaRequireAttrs added in v0.32.0

func (a *Archive) AddSchemaRequireAttrs(names ...string) bool

func (*Archive) Append

func (a *Archive) Append(ad *classad.ClassAd) error

Append adds one ad to the archive: it is appended to the log (never superseding any prior record) and, when the active segment fills, a new one is started and the old one sealed with its index and zone maps. The ad is durable when Append returns. Safe for one writer concurrent with queries.

func (*Archive) AppendDeferred added in v0.32.1

func (a *Archive) AppendDeferred(ad *classad.ClassAd) error

AppendDeferred is Append without waiting for the ad to reach disk. The ad is readable by queries when it returns; it becomes durable at the next Flush, at the next durable Append, when its segment seals, or at Close (and, while a watcher is attached, at least every 256 appends). Until then a crash of the machine can lose it (a process crash leaves it in the page cache). What survives such a crash is always a prefix of the appends, since recovery cuts the log at the first torn record.

Watchers see a deferred ad only once it is durable: its event is published by the sync that makes it so, and a Watch or WatchCursor syncs before it reads. So nothing a watcher has seen, and no cursor it holds, can be lost to a crash.

A caller that records its own progress through the archive's source (a history file offset, a remote cursor) calls Flush before persisting it: Flush returning nil means every ad appended before it is on disk, so the persisted position never gets ahead of the archive. The loss window between Flushes is at most one segment, because a segment is synced before it seals.

func (*Archive) AttrNDV added in v0.38.1

func (a *Archive) AttrNDV(attr string) (NDVEstimate, bool)

AttrNDV reports how many distinct values attr takes, from the sealed segments' index summaries alone -- no record is read. ok is false when no segment indexes attr.

func (*Archive) AttrTypeProfiles added in v0.34.2

func (a *Archive) AttrTypeProfiles(sampleMax int) ([]AttrTypeProfile, int)

AttrTypeProfiles profiles what the archive's attributes hold (see Collection.AttrTypeProfiles). History is where attribute variety is widest -- a table that has accumulated every shape its submitters ever sent -- so this is the side a consumer declaring types most needs.

func (*Archive) AttrTypeProfilesWith added in v0.36.0

func (a *Archive) AttrTypeProfilesWith(o AttrTypeOptions) ([]AttrTypeProfile, int)

AttrTypeProfilesWith is AttrTypeProfiles with the measurement selected by o (see Collection.AttrTypeProfilesWith).

func (*Archive) AutoCompositeNames added in v0.38.1

func (a *Archive) AutoCompositeNames() [][]string

AutoCompositeNames returns the tuples of the archive's auto-created composites, the composite half of what AutoIndexNames persists.

func (*Archive) AutoIndexNames added in v0.25.0

func (a *Archive) AutoIndexNames() []string

AutoIndexNames returns the names of the archive's auto-created indexes, for persisting provenance alongside the index set itself.

func (*Archive) AutoTune added in v0.25.0

func (a *Archive) AutoTune(opts AutoTuneOptions) AutoTuneResult

AutoTune applies demand-driven index changes to the archive. See Collection.AutoTune.

func (*Archive) BackfillIndexes added in v0.33.0

func (a *Archive) BackfillIndexes(maxBytes int64) IndexBackfillResult

BackfillIndexes rebuilds, newest first and up to maxBytes of segment data, the sidecars of sealed segments that lack postings for an indexed attribute. See Collection.BackfillIndexes.

func (*Archive) BuildAndEnableSchemaScan added in v0.25.2

func (a *Archive) BuildAndEnableSchemaScan(sampleMax, hotTopN int) bool

BuildAndEnableSchemaScan builds (or extends coverage of) the per-segment columnar accelerator over the archive's sealed segments, as Collection.BuildAndEnableSchemaScan does for a mutable table. An archive is the natural target for it -- the segments are immutable once sealed, so a block never needs invalidating -- and the payoff is large: a numeric COUNT over 50k history records drops from ~50ms of row scan to ~1ms.

The first call reads every sealed record once to sample and to build a block per segment, which over a long history is the same "paid for by reading history back" cost an archive index backfill has. Later calls cover segments sealed since, re-derive the schema and adopt it when the change is material, and converge stale segments a budget's worth per call.

func (*Archive) CategoricalGroupCounts added in v0.23.1

func (a *Archive) CategoricalGroupCounts(attr string) (map[string]int64, bool)

CategoricalGroupCounts returns the exact number of records carrying each distinct value of a categorically indexed attribute, derived from the per-segment indexes instead of by scanning records. ok is false when the answer cannot be established from the indexes alone, in which case the caller must scan; see the package comment above for what makes it decline.

The counts are keyed by the value's exact spelling, matching what a scan would group by: ClassAd string comparison folds case, but two spellings of the same value are distinct groups, and the index keeps its exact-case run for precisely that reason.

func (*Archive) CategoricalGroupCountsBucketed added in v0.23.1

func (a *Archive) CategoricalGroupCountsBucketed(attr, bucketAttr string, width int64) (map[int64]map[string]int64, bool)

CategoricalGroupCountsBucketed is CategoricalGroupCounts split by a second, numeric dimension: it returns per-value counts keyed by the bucket floor(bucketAttr/width)*width. This is the "per group per day" shape, with width the bucket size in the attribute's own units (86400 for daily buckets over a unix-seconds attribute).

It is cheap for the same reason the ungrouped form is, plus one more: an archive is append-ordered, so a segment's values for a monotonically advancing attribute like a completion time span a narrow range. When a segment's zone map for bucketAttr falls wholly inside one bucket and every record holds a number for it -- the common case -- every record in it belongs to that bucket and its per-value counts are attributed wholesale, with no record read. Only the segments straddling a bucket boundary are scanned, and with buckets much wider than a segment's time span those are a small minority.

bucketAttr must carry a zone map (ZoneAttrs at creation); without one there is no way to place a segment in a bucket without reading it, and the whole point is lost, so this declines. It also declines for the same completeness reasons as CategoricalGroupCounts.

func (*Archive) CategoricalGroupCountsWhere added in v0.23.1

func (a *Archive) CategoricalGroupCountsWhere(attr, constraint string) (map[string]int64, bool)

CategoricalGroupCountsWhere is CategoricalGroupCounts restricted to the records matching constraint. ok is false unless the constraint is a pure conjunction of numeric comparisons against zone-mapped attributes AND the indexes fully account for every record (the same completeness bar as the unconstrained form) -- see the file comment for why the constraint's syntax is re-checked rather than its probes trusted.

Segments are decided by their zone maps: one whose bounds imply every condition contributes its postings wholesale, one that cannot satisfy some condition contributes nothing, and only the genuinely straddling ones are read.

func (*Archive) Close

func (a *Archive) Close() error

Close flushes and unmaps the archive, making every append durable, deferred ones included. It must not be used afterward.

func (*Archive) CodecStats added in v0.19.0

func (a *Archive) CodecStats(sampleMax int) CodecStats

CodecStats reports the archive's compression: codec, dictionary size, last retrain time, and the sampled compression ratio (up to sampleMax records).

func (*Archive) ColumnsServable added in v0.37.0

func (a *Archive) ColumnsServable(q *vm.Query, attrs []string) bool

ColumnsServable reports whether ScanColumns can serve this query (Collection.ColumnsServable).

func (*Archive) CompositeAttrs added in v0.38.1

func (a *Archive) CompositeAttrs() [][]string

CompositeAttrs returns the attribute tuples the archive indexes together. An archive's saved config is authoritative on reopen and rebuilds the whole index set from it, so the composites have to be in it or a tuple the tuner created is gone at the next start.

func (*Archive) CompositeRefusals added in v0.38.1

func (a *Archive) CompositeRefusals() []CompositeRefusal

CompositeRefusals returns the configured composite tuples this archive could not install, and why. The archive counterpart of Collection.CompositeRefusals, and the reason it is forwarded rather than left to the caller to reach through: an archive's configuration is supplied to OpenArchive on every open, so an archive is the store most likely to be carrying a tuple that resolved when it was created and does not resolve now.

func (*Archive) Count added in v0.7.0

func (a *Archive) Count() int

Count returns the number of records currently retained. Rotation reduces it in whole-segment steps.

func (*Archive) CountConstraint added in v0.27.0

func (a *Archive) CountConstraint(constraint string) (int, bool)

CountConstraint counts the records matching constraint via the columnar accelerator, returning ok=false when the columnar path cannot serve it (see Collection.CountConstraint) so the caller scans instead.

An archive is the big append-only scan target, and it is exactly where this was missing: a mutable table's COUNT(*) WHERE reaches the columnar count through DB.CountConstraint, while an archive's went to a wire-native scan of every record, even with an accelerator built over its segments.

func (*Archive) CountConstraintRedacted added in v0.35.0

func (a *Archive) CountConstraintRedacted(constraint string) (int, bool)

CountConstraintRedacted is CountConstraint read with no key.

func (*Archive) Discard added in v0.33.0

func (a *Archive) Discard() error

Discard is Close for an archive whose files are being DELETED (a dropped archive table): it releases the mappings without flushing or persisting anything. See Collection.Discard.

func (*Archive) DropIndex added in v0.18.0

func (a *Archive) DropIndex(names ...string) bool

DropIndex removes the named per-segment indexes. Returns false if none matched.

func (*Archive) DropSchemaRequireAttrs added in v0.32.0

func (a *Archive) DropSchemaRequireAttrs(names ...string) bool

func (*Archive) EncryptedAttrNames added in v0.29.0

func (a *Archive) EncryptedAttrNames() []string

EncryptedAttrNames reports the attributes this archive seals, mirroring Collection.EncryptedAttrNames.

func (*Archive) EncryptionEnabled added in v0.29.0

func (a *Archive) EncryptionEnabled() bool

EncryptionEnabled reports whether this archive holds a data key, so that the attributes the sealing policy names are sealed as they are appended (mirroring Collection.EncryptionEnabled).

func (*Archive) EnsureDictReplicas added in v0.42.0

func (a *Archive) EnsureDictReplicas() []DictReplicaState

EnsureDictReplicas brings every compression dictionary's copy count in segment trailers up to the target and reports where each one stands. See Collection.EnsureDictReplicas.

func (*Archive) EvictionAttr added in v0.40.1

func (a *Archive) EvictionAttr() string

EvictionAttr is the attribute size-driven eviction orders this archive by, or "" when it falls back to dropping the oldest segment by position.

func (*Archive) ExplainQuery added in v0.25.2

func (a *Archive) ExplainQuery(q *vm.Query) QueryExplain

ExplainQuery reports how the archive would execute q -- which conjuncts are index-usable and the resulting access path -- as Collection.ExplainQuery does for a mutable table.

Two archive-specific notes on reading the result. An archive's scan is newest-first over sealed segments, and whole segments are additionally skipped by zone map (see ZoneAttrs), which the plan string does not name: a "serial-scan" over an archive may still visit far fewer records than TotalAds. And TotalAds counts everything retained, so probe selectivity is against the whole history rather than a working set.

func (*Archive) Flush

func (a *Archive) Flush() error

Flush is the durability barrier for AppendDeferred: it returns once every ad appended before the call is on disk and published to watchers, or reports the sticky write or sync error that prevented it. The error is sticky: every later Append, AppendDeferred and Flush reports it until the archive is truncated or reopened. With no deferred appends outstanding Flush is cheap.

func (*Archive) GCFloor added in v0.21.4

func (a *Archive) GCFloor() float64

GCFloor returns the current runtime GC watermark (0 when unset).

func (*Archive) GroupCountAll added in v0.28.0

func (a *Archive) GroupCountAll(groupAttr string) ([]GroupCount, bool)

GroupCountAll returns the per-value record counts of groupAttr over EVERY record, read out of the columnar blocks. The caller must have established that its query matches all records. ok=false ⇒ not columnar-eligible; group by scanning records.

func (*Archive) GroupCountConstraint added in v0.28.0

func (a *Archive) GroupCountConstraint(constraint, groupAttr string) ([]GroupCount, bool)

GroupCountConstraint returns the per-value record counts of groupAttr over the records matching constraint, read out of the columnar blocks. ok=false ⇒ the shape is not columnar-eligible and the caller must group by scanning records.

func (*Archive) GroupSchemaAgreement added in v0.28.0

func (a *Archive) GroupSchemaAgreement(sampleMax, k int) GroupSchemaAgreement

GroupSchemaAgreement reports how well per-segment derivations agree with the archive-wide one (see Collection.GroupSchemaAgreement).

func (*Archive) GroupSchemaChanges added in v0.29.13

func (a *Archive) GroupSchemaChanges() []GroupSchemaChange

GroupSchemaChanges returns the archive's committed-group change log (see Collection.GroupSchemaChanges).

func (*Archive) GroupSchemaDrift added in v0.28.0

func (a *Archive) GroupSchemaDrift() GroupSchemaDrift

GroupSchemaDrift reports how the archive's derived groups have moved (see Collection.GroupSchemaDrift).

func (*Archive) GroupSchemaLastAgreement added in v0.29.13

func (a *Archive) GroupSchemaLastAgreement() (GroupSchemaLastAgreement, bool)

GroupSchemaLastAgreement returns the archive's last persisted per-segment agreement (see Collection.GroupSchemaLastAgreement).

func (*Archive) GroupSchemas added in v0.28.0

func (a *Archive) GroupSchemas(sampleMax, k int) GroupSchemaInfo

GroupSchemas derives and reports candidate group schemas for the archive (see Collection.GroupSchemas). Report-only: nothing about storage or reads changes.

func (*Archive) GroupStatsAll added in v0.28.0

func (a *Archive) GroupStatsAll(groupAttr string, aggAttrs []string) ([]GroupStats, bool)

GroupStatsAll is GroupStatsConstraint over EVERY record. The caller must have established that its query matches all records.

func (*Archive) GroupStatsAllAggs added in v0.33.2

func (a *Archive) GroupStatsAllAggs(groups []GroupSpec, aggCols []GroupAggCol,
	countFilters []string) ([]GroupStats, bool)

GroupStatsAllAggs is GroupStatsConstraintAggs over every record, for a constraint the caller has established is match-all. See Collection.GroupStatsAllAggs.

func (*Archive) GroupStatsAllAggsRedacted added in v0.35.0

func (a *Archive) GroupStatsAllAggsRedacted(groups []GroupSpec, aggCols []GroupAggCol,
	countFilters []string) ([]GroupStats, bool)

GroupStatsAllAggsRedacted is GroupStatsAllAggs read with no key.

func (*Archive) GroupStatsAllBucketed added in v0.32.0

func (a *Archive) GroupStatsAllBucketed(groupAttr string, bucket int64, aggAttrs []string) ([]GroupStats, bool)

GroupStatsAllBucketed is GroupStatsAll with the group column floored into buckets of bucket (0 = the raw value). See Collection.GroupStatsQueryBucketed.

func (*Archive) GroupStatsAllCols added in v0.33.0

func (a *Archive) GroupStatsAllCols(groups []GroupSpec, aggAttrs []string) ([]GroupStats, bool)

GroupStatsAllCols is GroupStatsAllBucketed over SEVERAL group columns. The caller must have established that its query matches all records. See Collection.GroupStatsQueryCols.

func (*Archive) GroupStatsConstraint added in v0.28.0

func (a *Archive) GroupStatsConstraint(constraint, groupAttr string, aggAttrs []string) ([]GroupStats, bool)

GroupStatsConstraint returns the per-group record count plus a NumStats per aggAttr over the records matching constraint, read out of the columnar blocks. ok=false ⇒ not columnar-eligible; group by scanning records. See Collection.GroupStatsQuery.

func (*Archive) GroupStatsConstraintAggs added in v0.33.2

func (a *Archive) GroupStatsConstraintAggs(constraint string, groups []GroupSpec, aggCols []GroupAggCol,
	countFilters []string) ([]GroupStats, bool)

GroupStatsConstraintAggs is GroupStatsConstraintCols where an aggregate column may carry a per-aggregate FILTER. See Collection.GroupStatsConstraintAggs.

func (*Archive) GroupStatsConstraintAggsRedacted added in v0.35.0

func (a *Archive) GroupStatsConstraintAggsRedacted(constraint string, groups []GroupSpec, aggCols []GroupAggCol,
	countFilters []string) ([]GroupStats, bool)

GroupStatsConstraintAggsRedacted is GroupStatsConstraintAggs read with no key.

func (*Archive) GroupStatsConstraintBucketed added in v0.32.0

func (a *Archive) GroupStatsConstraintBucketed(constraint, groupAttr string, bucket int64, aggAttrs []string) ([]GroupStats, bool)

GroupStatsConstraintBucketed is GroupStatsConstraint with the group column floored into buckets of bucket (0 = the raw value). See Collection.GroupStatsQueryBucketed.

func (*Archive) GroupStatsConstraintCols added in v0.33.0

func (a *Archive) GroupStatsConstraintCols(constraint string, groups []GroupSpec, aggAttrs []string) ([]GroupStats, bool)

GroupStatsConstraintCols is GroupStatsConstraintBucketed over SEVERAL group columns: the group is the tuple of their (individually bucketed) values. See Collection.GroupStatsQueryCols.

func (*Archive) GroupValuesAllAggs added in v0.37.0

func (a *Archive) GroupValuesAllAggs(groups []GroupSpec, aggCols []GroupAggCol,
	countFilters []string, newSink func() GroupSink, mergeSink MergeGroupSink) ([]GroupValues, bool)

GroupValuesAllAggs is GroupValuesConstraintAggs over every record. See Collection.GroupValuesAllAggs.

func (*Archive) GroupValuesAllAggsRedacted added in v0.37.0

func (a *Archive) GroupValuesAllAggsRedacted(groups []GroupSpec, aggCols []GroupAggCol,
	countFilters []string, newSink func() GroupSink, mergeSink MergeGroupSink) ([]GroupValues, bool)

GroupValuesAllAggsRedacted is GroupValuesAllAggs for a reader not entitled to sealed values.

func (*Archive) GroupValuesConstraintAggs added in v0.37.0

func (a *Archive) GroupValuesConstraintAggs(constraint string, groups []GroupSpec, aggCols []GroupAggCol,
	countFilters []string, newSink func() GroupSink, mergeSink MergeGroupSink) ([]GroupValues, bool)

GroupValuesConstraintAggs is GroupStatsConstraintAggs reduced into caller-supplied accumulators. See Collection.GroupValuesConstraintAggs.

func (*Archive) GroupValuesConstraintAggsRedacted added in v0.37.0

func (a *Archive) GroupValuesConstraintAggsRedacted(constraint string, groups []GroupSpec, aggCols []GroupAggCol,
	countFilters []string, newSink func() GroupSink, mergeSink MergeGroupSink) ([]GroupValues, bool)

GroupValuesConstraintAggsRedacted is GroupValuesConstraintAggs for a reader not entitled to sealed values.

func (*Archive) HasSealedSidecar added in v0.38.0

func (a *Archive) HasSealedSidecar() bool

HasSealedSidecar reports whether any segment carries a mapped sidecar index. See Collection.HasSealedSidecar for why this is not SidecarSizes().Segments > 0.

func (*Archive) HighMarkStats added in v0.40.1

func (a *Archive) HighMarkStats() (passes, dropped int64)

HighMarkStats reports the seal-time size evictions (see Collection.HighMarkStats).

func (*Archive) HotAttrNames added in v0.29.0

func (a *Archive) HotAttrNames() []string

HotAttrNames reports the attributes stored in the hot header, mirroring Collection.HotAttrNames. An archive has a hot set exactly as a mutable collection does; only the accessor was missing, which made an archive look like it had none.

func (*Archive) IndexBackfillPending added in v0.33.0

func (a *Archive) IndexBackfillPending() (segments int, bytes int64)

IndexBackfillPending reports the sealed segments, and their bytes, still lacking postings for some indexed attribute.

func (*Archive) IndexSizes added in v0.19.0

func (a *Archive) IndexSizes() IndexSizes

IndexSizes reports the per-attribute index byte footprint (heap postings) versus data.

func (*Archive) IndexedAttrs added in v0.19.0

func (a *Archive) IndexedAttrs() (categorical, value []string)

IndexedAttrs returns the categorical and value attributes the archive indexes.

func (*Archive) KeylessWithholds added in v0.35.0

func (a *Archive) KeylessWithholds(names ...string) bool

KeylessWithholds reports whether a read not entitled to sealed values withholds any of names -- reads them as undefined whatever their stored form -- because the sealing policy names it. Such an attribute's clear values from before it was sealed can sit in this archive's columns, zone maps and indexes, so a caller planning such a read must not answer it from those.

func (*Archive) KeylessWithholdsIn added in v0.35.0

func (a *Archive) KeylessWithholdsIn(constraint string) bool

KeylessWithholdsIn reports whether constraint references an attribute KeylessWithholds reports. A constraint that does not parse reports true: it reaches no answer either way.

func (*Archive) LookupKeys added in v0.38.3

func (a *Archive) LookupKeys(attr string, keys []int64) iter.Seq[*classad.ClassAd]

LookupKeys yields every ad of the archive whose attr equals one of keys, newest first, as Query does. Duplicate keys are harmless and an empty batch yields nothing.

It is the inner side of a nested-loop join expressed as one call: the caller hands over the keys of a batch of streamed rows and gets back the records that could join with any of them. Each ad is yielded once however many keys it matches, so the caller re-associates ads with its own rows by the key -- this reports what the archive holds, not a join.

func (*Archive) LookupKeysRedacted added in v0.38.3

func (a *Archive) LookupKeysRedacted(attr string, keys []int64) iter.Seq[*classad.ClassAd]

LookupKeysRedacted is LookupKeys for a reader not entitled to sealed values (see Collection.QueryRedacted).

func (*Archive) LookupKeysSegments added in v0.38.3

func (a *Archive) LookupKeysSegments(attr string, keys []int64) (surviving, pruned int)

LookupKeysSegments reports how many of the archive's segments a batch of keys can match in, and how many its span rules out, without reading any of them. It is the hoisted zone check on its own, for a caller sizing a batch or explaining a plan.

func (*Archive) LookupKeysStats added in v0.38.3

func (a *Archive) LookupKeysStats(attr string, keys []int64, stats *ScanStats) iter.Seq[*classad.ClassAd]

LookupKeysStats is LookupKeys that also fills stats (may be nil) with the per-scan work breakdown, as the explained reads do. It is how a caller sees what the batch's span actually ruled out, rather than what LookupKeysSegments predicts it would.

func (*Archive) LookupKeysWhere added in v0.38.3

func (a *Archive) LookupKeysWhere(attr string, keys []int64, where ast.Expr) iter.Seq[*classad.ClassAd]

LookupKeysWhere is LookupKeys narrowed by a constraint of the caller's own: the ads whose attr is one of keys AND which satisfy where. A nil where is LookupKeys exactly.

It exists because the alternative does not work. A caller holding a constraint could conjoin it itself and call Query, but that read is planned through planRead, whose gate is the one this whole file exists to get past -- so a join narrowing its inner side would lose the batched access path precisely by asking for less data. Carrying the constraint INTO the batch keeps planIndex, and the constraint's own probes join the key's in the candidate intersection rather than competing with it.

The span hoist is unaffected. It prunes on the KEY's zone map against [lo,hi] of keys, and a conjunction only ever removes records, so a segment the span rules out holds nothing the narrower query wants either.

func (*Archive) LookupKeysWhereStats added in v0.38.3

func (a *Archive) LookupKeysWhereStats(attr string, keys []int64, where ast.Expr,
	stats *ScanStats) iter.Seq[*classad.ClassAd]

LookupKeysWhereStats is LookupKeysWhere that also fills stats (may be nil), as LookupKeysStats does for LookupKeys.

func (*Archive) MaintProgress added in v0.34.0

func (a *Archive) MaintProgress() MaintProgress

MaintProgress reports the maintenance pass running on the archive's underlying collection. See Collection.MaintProgress.

func (*Archive) MaintenanceStopping added in v0.34.0

func (a *Archive) MaintenanceStopping() bool

MaintenanceStopping reports whether the archive's underlying collection has been asked to stop maintenance. See Collection.MaintenanceStopping.

func (*Archive) MarkAutoComposites added in v0.38.1

func (a *Archive) MarkAutoComposites(tuples [][]string)

MarkAutoComposites records existing composites as auto-created, restoring the provenance a saved config carries without rebuilding anything. See Collection.MarkAutoComposites.

func (*Archive) MarkAutoIndexes added in v0.25.0

func (a *Archive) MarkAutoIndexes(names []string)

MarkAutoIndexes records existing indexes as auto-created, restoring the provenance a saved config carries without rebuilding anything. See Collection.MarkAutoIndexes.

func (*Archive) MergePass added in v0.24.1

func (a *Archive) MergePass(opts MergeOptions) int

MergePass merges cold segment runs: undersized adjacent segments into ones of about opts.TargetSegmentBytes (the size tier), and, once the archive has reached opts.TriggerSegments, larger runs until it is at or below opts.TargetSegments (the count guard). It stops when nothing eligible remains, opts.MaxMerges merges have been done, or opts.MaxBytesPerPass source bytes have been rewritten. It returns the number of merges performed.

When there is nothing to merge a pass is a walk over the segment list under a read lock, so it is safe to call often.

Safe to call on a live archive: merges take the maintenance lock (so they never overlap a reseal or another pass), the writer's open segment is never a candidate, and an in-flight scan holding a source keeps its mapping alive through the usual pin/reap path.

func (*Archive) NumStatsQuery added in v0.25.2

func (a *Archive) NumStatsQuery(q *vm.Query, attr string) (NumStats, bool)

NumStatsQuery computes numeric aggregate inputs for attr over the archive's matching records via the columnar scan (see Collection.NumStatsQuery). Only meaningful once the archive carries a columnar accelerator; ok=false otherwise, and the caller scans.

func (*Archive) NumStatsQueryRedacted added in v0.35.0

func (a *Archive) NumStatsQueryRedacted(q *vm.Query, attr string) (NumStats, bool)

NumStatsQueryRedacted is NumStatsQuery read with no key.

func (*Archive) NumValuesQuery added in v0.37.0

func (a *Archive) NumValuesQuery(q *vm.Query, attr string, newSink func() func(NumValue), merge func()) bool

NumValuesQuery is Collection.NumValuesQuery for an archive (history) table.

func (*Archive) NumValuesQueryRedacted added in v0.37.0

func (a *Archive) NumValuesQueryRedacted(q *vm.Query, attr string, newSink func() func(NumValue), merge func()) bool

NumValuesQueryRedacted is NumValuesQuery for a reader NOT entitled to sealed values, on the same terms as NumStatsQueryRedacted: an attribute a keyless read withholds declines outright, and the constraint is planned as that reader evaluates it.

func (*Archive) OpStats added in v0.19.0

func (a *Archive) OpStats() OpStats

OpStats reports cumulative operational timing counters (write wait/hold, sync, retrain, reindex, ...) for the archive's writes and maintenance.

func (*Archive) ProfiledSegments added in v0.40.1

func (a *Archive) ProfiledSegments() (profiled, sealed int)

ProfiledSegments counts how many sealed segments carry a profile over attr, and how many are sealed in total. A size pass can only order the profiled ones; the rest fall back to position, so a large gap is why an archive is still evicting by arrival order.

func (*Archive) Query

func (a *Archive) Query(q *vm.Query) iter.Seq[*classad.ClassAd]

Query returns an iterator over the ads matching q, newest first.

func (*Archive) QueryLimit

func (a *Archive) QueryLimit(q *vm.Query, limit int) iter.Seq[*classad.ClassAd]

QueryLimit returns an iterator over the ads matching q, newest first, stopping after limit results (limit <= 0 ⇒ unlimited). Because the backing Collection scans newest-first, stopping early yields the most recent limit matches — a pushed-down LIMIT.

func (*Archive) QueryLimitRedacted added in v0.35.0

func (a *Archive) QueryLimitRedacted(q *vm.Query, limit int) iter.Seq[*classad.ClassAd]

QueryLimitRedacted is QueryLimit read with no key.

func (*Archive) QueryProject added in v0.20.0

func (a *Archive) QueryProject(q *vm.Query, attrs []string) iter.Seq[[]classad.Value]

QueryProject scans the matching records and yields each projected to just attrs' values, read wire-native where possible. See Collection.QueryProject.

func (*Archive) QueryProjectRedacted added in v0.36.0

func (a *Archive) QueryProjectRedacted(q *vm.Query, attrs []string) iter.Seq[[]classad.Value]

QueryProjectRedacted is QueryProject read with no key.

The stats form below had this and the plain one did not, which is a trap for the layer above: a history table is read by the same unprivileged peers a mutable table is, and a projected read that could only be made entitled would either refuse those peers or serve them the plaintext -- which is how the paged projection came to ignore its session's privilege.

func (*Archive) QueryProjectStats added in v0.29.6

func (a *Archive) QueryProjectStats(q *vm.Query, attrs []string, stats *ScanStats) iter.Seq[[]classad.Value]

QueryProjectStats is QueryProject that also fills stats (may be nil) with the scan's work breakdown, for an EXPLAIN ANALYZE of an aggregate that falls to the projected scan.

func (*Archive) QueryProjectStatsRedacted added in v0.35.0

func (a *Archive) QueryProjectStatsRedacted(q *vm.Query, attrs []string, stats *ScanStats) iter.Seq[[]classad.Value]

QueryProjectStatsRedacted is QueryProjectStats read with no key.

func (*Archive) QueryRawProjected added in v0.20.1

func (a *Archive) QueryRawProjected(q *vm.Query, projection []string, chaseRefs, redact bool) iter.Seq[RawAd]

QueryProject scans the ads matching q and yields each one projected to just attrs' values (aligned with attrs), read wire-native where possible -- so an aggregate does not pay the full-ad decode QueryLimit costs. The yielded slice is reused; copy to retain. QueryRawProjected yields each ad matching q as a raw projected subset (only the projection attributes, rendered from the stored representation), newest first — the archive-side of the server projection relay. It shares the backing Collection's projection walk, so the same newest-first ordering and pushed-down LIMIT (via early stop by the caller) apply. chaseRefs and redact are as in Collection.QueryRawProjected.

func (*Archive) QueryRawProjectedStats added in v0.29.0

func (a *Archive) QueryRawProjectedStats(q *vm.Query, projection []string, chaseRefs, redact bool, stats *ScanStats) iter.Seq[RawAd]

QueryRawProjectedStats is QueryRawProjected that also fills stats (may be nil) with the per-scan work breakdown for EXPLAIN ANALYZE.

func (*Archive) QueryRawWire added in v0.35.0

func (a *Archive) QueryRawWire(q *vm.Query, projection []string, redact bool) iter.Seq[[]byte]

QueryRawWire yields each record matching q as a self-contained wire-form row, newest first (Collection.QueryRawWire).

func (*Archive) QueryRawWireRefs added in v0.35.0

func (a *Archive) QueryRawWireRefs(q *vm.Query, projection []string, redact bool) iter.Seq[[]byte]

QueryRawWireRefs is QueryRawWire with the reference closure of ScanRawWireRefs.

func (*Archive) QueryRawWireRefsStats added in v0.35.0

func (a *Archive) QueryRawWireRefsStats(q *vm.Query, projection []string, redact bool, stats *ScanStats) iter.Seq[[]byte]

QueryRawWireRefsStats is QueryRawWireRefs that also fills stats (may be nil).

func (*Archive) QueryRawWireStats added in v0.35.0

func (a *Archive) QueryRawWireStats(q *vm.Query, projection []string, redact bool, stats *ScanStats) iter.Seq[[]byte]

QueryRawWireStats is QueryRawWire that also fills stats (may be nil) with the per-scan work breakdown.

func (*Archive) RefreshHotSet added in v0.32.0

func (a *Archive) RefreshHotSet(sampleMax, topN int) int

RefreshHotSet recomputes the hot set from accumulated query demand and installs it for FUTURE writes, returning how many attributes were chosen. See Collection.RefreshHotSet for the ranking.

It takes effect immediately for records appended from now on, and changes nothing already sealed. That is safe without any rewrite because the hot header is per RECORD and self-describing -- each record states its own hot count and pairs -- so records written under different hot sets coexist in one archive, and a reader resolving an attribute that is not in a given record's header simply misses and falls back to the entry scan.

Older records are not stranded on the old set forever either, though they converge more slowly than a mutable table's ads do. MergePass re-encodes the records it merges (resealSegments), under the hot set in effect AT MERGE TIME -- so a cold run picks the refreshed set up when it is next folded together. What that leaves behind is whatever the merge policy never merges: the KeepRecent tail (which was written under a recent set anyway) and any run the watermarks never select. Rewrite() is the way to force the rest, at the cost of re-encoding the whole history.

func (*Archive) Reindex added in v0.18.0

func (a *Archive) Reindex()

Reindex rebuilds the per-segment indexes over all segments: those sealed since the last build, and those whose sidecar was built under a superseded index configuration and lie within ArchiveOptions.IndexBackfillBytes of the newest data. Segment data is never touched.

func (*Archive) ReindexAll added in v0.33.0

func (a *Archive) ReindexAll() IndexBackfillResult

ReindexAll is Reindex carried to every segment regardless of the backfill horizon, so each sealed segment ends up holding postings for every indexed attribute. See Collection.ReindexAll.

func (*Archive) ReleaseRead added in v0.33.0

func (a *Archive) ReleaseRead()

ReleaseRead balances an AcquireRead that returned true.

func (*Archive) ReschemaScan added in v0.25.3

func (a *Archive) ReschemaScan(sampleMax, hotTopN int) bool

ReschemaScan re-derives the archive's schema and adopts it, rebuilding sidecar blocks now and converging columnarized segments over maintenance passes (see Collection.ReschemaScan).

func (*Archive) Retention added in v0.19.0

func (a *Archive) Retention() Retention

Retention returns the archive's current retention bounds.

func (*Archive) RetrainDict added in v0.18.0

func (a *Archive) RetrainDict(sampleMax int) (int, error)

RetrainDict trains a fresh ZSTD dictionary from up to sampleMax records and recompresses every segment in place under it (an append-only reseal that preserves order), returning the new dictionary's size in bytes. This is how an archive's compression adapts to the data it has accumulated.

func (*Archive) Rewrite added in v0.18.0

func (a *Archive) Rewrite() int

Rewrite recompresses and re-encodes every segment in place under the current codec and hot set (e.g. after a hot-set change), preserving order, and returns the number of records rewritten.

func (*Archive) Rotate

func (a *Archive) Rotate(now float64) (int, error)

Rotate drops whole oldest segments until the archive is back within its Retention bounds, returning the number dropped. now is the caller's wall clock (unix seconds) for age-based retention.

func (*Archive) RowGroupBytes added in v0.28.1

func (a *Archive) RowGroupBytes() int

RowGroupBytes reports the budget currently in effect (0 meaning the default).

func (*Archive) SaveDemand added in v0.25.0

func (a *Archive) SaveDemand()

SaveDemand checkpoints recorded query demand to the archive's directory, ageing it by the time since the last checkpoint, so index decisions are not restarted from zero every time the process is. See Collection.SaveDemand.

func (*Archive) ScanColumns added in v0.37.0

func (a *Archive) ScanColumns(q *vm.Query, attrs []string, fn func(*Batch) bool) (ColumnScanStats, bool)

ScanColumns yields the values of attrs for every record matching q, a column at a time (Collection.ScanColumns). The batch handed to fn is borrowed and valid only for that call.

func (*Archive) ScanColumnsRedacted added in v0.37.0

func (a *Archive) ScanColumnsRedacted(q *vm.Query, attrs []string, fn func(*Batch) bool) (ColumnScanStats, bool)

ScanColumnsRedacted is ScanColumns for a reader not entitled to sealed values (Collection.ScanColumnsRedacted).

func (*Archive) ScanRawWire added in v0.35.0

func (a *Archive) ScanRawWire(projection []string, redact bool) iter.Seq[[]byte]

ScanRawWire yields every retained record as a self-contained wire-form row, newest first (Collection.ScanRawWire).

func (*Archive) ScanRawWireRefs added in v0.35.0

func (a *Archive) ScanRawWireRefs(projection []string, redact bool) iter.Seq[[]byte]

ScanRawWireRefs is ScanRawWire whose projection also carries the attributes the projected expressions reference (Collection.ScanRawWireRefs). This is the form a consumer that EVALUATES what it receives needs.

func (*Archive) ScanRawWireRefsStats added in v0.46.0

func (a *Archive) ScanRawWireRefsStats(projection []string, redact bool, stats *ScanStats) iter.Seq[[]byte]

ScanRawWireRefsStats is ScanRawWireRefs that also fills stats (may be nil); see Collection.ScanRawWireRefsStats.

func (*Archive) ScanRawWireStats added in v0.46.0

func (a *Archive) ScanRawWireStats(projection []string, redact bool, stats *ScanStats) iter.Seq[[]byte]

ScanRawWireStats is ScanRawWire that also fills stats (may be nil); see Collection.ScanRawWireStats.

func (*Archive) SchemaFit added in v0.25.3

func (a *Archive) SchemaFit(sampleMax int) ([]SchemaFieldFit, int)

SchemaFit measures the archive's derived schema against a fresh sample, reporting per-field escape rates (see Collection.SchemaFit).

func (*Archive) SchemaRequireAttrs added in v0.32.0

func (a *Archive) SchemaRequireAttrs() []string

SchemaRequireAttrs returns the archive's effective required-attribute set, and SchemaRequireRuntimeAttrs the subset added at runtime (see Collection).

func (*Archive) SchemaRequireRuntimeAttrs added in v0.32.0

func (a *Archive) SchemaRequireRuntimeAttrs() []string

func (*Archive) SchemaRequireSkipped added in v0.32.0

func (a *Archive) SchemaRequireSkipped() []SchemaRequireSkip

SchemaRequireSkipped returns the required attributes the archive's last schema derivation refused, with the reason (see Collection.SchemaRequireSkipped).

func (*Archive) SchemaScanInfo added in v0.25.2

func (a *Archive) SchemaScanInfo() SchemaScanInfo

SchemaScanInfo reports the columnar accelerator's state for the archive.

func (*Archive) SealMigratePass added in v0.47.0

func (a *Archive) SealMigratePass(opts SealMigrateOptions) SealMigrateResult

SealMigratePass seals, a budgeted slice at a time, what the archive still holds in the clear under its current policy. See the file comment. Safe to call on an archive with nothing to do (it returns Done after a file read), with no key (Done), and concurrently with appends and queries.

func (*Archive) SealsValues added in v0.35.0

func (a *Archive) SealsValues() bool

SealsValues reports whether any value this archive stores can be sealed (see Collection.SealsValues).

func (*Archive) SegmentProfiles added in v0.40.1

func (a *Archive) SegmentProfiles() []SegmentProfile

SegmentProfiles reports every sealed segment's retention profile (see Collection.SegmentProfiles).

func (*Archive) SetEncryptedAttrs added in v0.35.0

func (a *Archive) SetEncryptedAttrs(attrs []string) error

SetEncryptedAttrs replaces the explicit set of sealed attributes, as Collection.SetEncryptedAttrs does: it errors without a key, and for an attribute that is currently indexed. Records appended from now on are sealed under the new set; earlier ones keep their form until maintenance rewrites their segment, and the *Redacted reads withhold an attribute the set names whatever form it is stored in.

func (*Archive) SetGCFloor added in v0.21.4

func (a *Archive) SetGCFloor(floor float64)

SetGCFloor installs a runtime GC watermark (in Retention.MinAgeAttr units) so Rotate may reclaim consumed records early -- above MinAge, below the configured ceilings (see Collection.SetGCFloor). Not persisted; re-assert it each maintenance pass. floor <= 0 clears it.

func (*Archive) SetRetention added in v0.19.0

func (a *Archive) SetRetention(r Retention)

SetRetention updates the retention bounds at runtime; the next Rotate enforces them.

func (*Archive) SetRowGroupBytes added in v0.28.1

func (a *Archive) SetRowGroupBytes(n int)

SetRowGroupBytes changes the archive's columnar row-group budget at runtime (see Collection.SetRowGroupBytes). It governs segments sealed from now on; nothing already written is rewritten or needs to be.

func (*Archive) SetSchemaRequireAttrs added in v0.32.0

func (a *Archive) SetSchemaRequireAttrs(names []string) bool

SetSchemaRequireAttrs / AddSchemaRequireAttrs / DropSchemaRequireAttrs change the required set (see Collection). Each reports whether the effective set changed; none re-derives anything itself -- the next maintenance review adopts the schema the new set produces and converges the sealed segments onto it, ColumnarSegmentBudget per pass.

func (*Archive) SidecarBytes added in v0.40.2

func (a *Archive) SidecarBytes() (segments int, mappedBytes int64)

SidecarBytes reports the archive's sidecar count and mapped bytes without the structural breakdown, which is the expensive half on a cold page cache. See Collection.SidecarBytes.

func (*Archive) SidecarSizes added in v0.8.0

func (a *Archive) SidecarSizes() SidecarSizes

SidecarSizes reports the archive's sealed-segment sidecar index bytes (mmap-backed, evictable page cache), broken out by structure. An operator diagnostic.

func (*Archive) StaleIndexSegments added in v0.21.2

func (a *Archive) StaleIndexSegments() (stale, sealed int)

StaleIndexSegments reports how many of the archive's sealed segments still carry an index built under an older configuration, and how many are sealed in total. Normally zero: AddIndex/DropIndex rebuild as they go. A non-zero count means a rebuild was interrupted or failed (it is best-effort per segment); a Reindex retries those segments.

func (*Archive) StaleIndexSegmentsByPolicy added in v0.25.0

func (a *Archive) StaleIndexSegmentsByPolicy() int

StaleIndexSegmentsByPolicy reports segments left on an older index configuration because they fall outside the backfill horizon: expected, and not actionable. Those among them that lack an indexed attribute are what BackfillIndexes works through (IndexBackfillPending).

func (*Archive) Stats added in v0.19.0

func (a *Archive) Stats() Stats

Stats reports storage accounting: record count, segment count, and arena/used/dead bytes (dead is ~0 for an append log, which never supersedes). The same struct the mutable store reports, so an archive's storage is visible on the same terms.

func (*Archive) StopMaintenance added in v0.30.4

func (a *Archive) StopMaintenance()

StopMaintenance asks the archive's underlying collection to stop maintenance. See Collection.StopMaintenance.

func (*Archive) SuggestIndexes added in v0.38.3

func (a *Archive) SuggestIndexes(sampleMax int) []IndexSuggestion

SuggestIndexes reports the attributes observed demand would justify indexing, from the same tracker AutoTune acts on. See Collection.SuggestIndexes.

func (*Archive) SupportsRawWire added in v0.35.0

func (a *Archive) SupportsRawWire() bool

SupportsRawWire reports whether the wire-form scans can serve this archive (Collection.SupportsRawWire).

func (*Archive) TopKOrderThreshold added in v0.29.4

func (a *Archive) TopKOrderThreshold(q *vm.Query, orderAttr string, desc bool, k int, stats *ScanStats) (float64, int, bool)

TopKOrderThreshold computes the ORDER BY orderAttr {DESC|ASC} LIMIT k cutoff over the archive's matching records via the columnar scan (see Collection.TopKOrderThreshold). stats (may be nil) records the cutoff scan's work for EXPLAIN ANALYZE.

func (*Archive) TopKOrderThresholdRedacted added in v0.35.0

func (a *Archive) TopKOrderThresholdRedacted(q *vm.Query, orderAttr string, desc bool, k int, stats *ScanStats) (float64, int, bool)

TopKOrderThresholdRedacted is TopKOrderThreshold read with no key.

func (*Archive) Truncate added in v0.20.1

func (a *Archive) Truncate()

Truncate drops every record, resetting the archive to empty in place: all segments are unmapped and their data + sidecar-index files unlinked (via the backing Collection's Truncate). Segment counters keep advancing, so a fresh Append starts a new segment. This is the destructive reset a from-scratch history re-sync uses -- empty the store, then re-ingest from the source. Retention/index/zone-map configuration is preserved. Safe against concurrent queries (a scan holding a pin reads its old data until it finishes); callers must serialize Truncate against the single Append writer.

func (*Archive) UpgradeCodecPass added in v0.25.0

func (a *Archive) UpgradeCodecPass(opts UpgradeOptions) int

UpgradeCodecPass re-encodes sealed segments that are still on an older dictionary, where measurement says the newer one compresses them meaningfully better. Returns the number of segments upgraded.

Segments measured as no better (or worse) are recorded and not measured again until the dictionary changes, so a pass over a fully-evaluated archive costs a directory read.

func (*Archive) VerifyDictFiles added in v0.42.0

func (a *Archive) VerifyDictFiles() []DictFault

VerifyDictFiles checks every compression dictionary file against what the archive loaded, rewrites any whose directory entry has gone, and reports what it found. An empty result is the healthy answer. See Collection.VerifyDictFiles.

func (*Archive) Watch added in v0.4.0

func (a *Archive) Watch(ctx context.Context, cursor []byte) (iter.Seq[WatchEvent], error)

Watch streams the archive as change data: a full replay of retained records (oldest first) then live appends, resumable from an opaque cursor. A cursor older than what rotation still retains yields a WatchReset and resumes from the current floor. See Collection.Watch and docs/WATCH.md.

func (*Archive) WatchCursor added in v0.29.12

func (a *Archive) WatchCursor() ([]byte, error)

WatchCursor returns an opaque cursor at the current head of the archive's change log, so a following Watch streams only subsequent appends rather than replaying what is retained. See Collection.WatchCursor.

func (*Archive) WatchRedacted added in v0.35.0

func (a *Archive) WatchRedacted(ctx context.Context, cursor []byte) (iter.Seq[WatchEvent], error)

WatchRedacted is Watch for a watcher NOT entitled to sealed values: every event's ad is decoded with no key. See Collection.WatchRedacted.

func (*Archive) WatchWatermark added in v0.40.0

func (a *Archive) WatchWatermark() uint64

WatchWatermark is the archive's closed watch clock: every change at or below it has been handed to every attached watcher. It is what a catch-up has caught up TO, and so the version a consumer gives the records a replay delivered, which carry no stamp of their own. See Collection.WatchWatermark.

func (*Archive) ZoneAttrs added in v0.21.2

func (a *Archive) ZoneAttrs() []string

ZoneAttrs returns the attributes carrying per-segment [min,max] zone maps -- the ones a range query prunes whole segments on, not just postings.

type ArchiveOptions

type ArchiveOptions struct {
	// Dir is the directory holding the archive's files. Required.
	Dir string
	// SegmentSize is the segment (mmap file) size in bytes; a segment rolls over when
	// the next ad will not fit. Default 8 MiB.
	SegmentSize int
	// Codec compresses stored ad bytes. Default identity. For recovery the codec must
	// match what a segment was written under (recorded per segment in its file).
	Codec Codec
	// HotAttrs front-loads these attributes in each ad's hot header (see Collection).
	HotAttrs []string
	// Unordered drops the archive's newest-first read order.
	//
	// An archive reads newest-first by default because that is condor_history's order and
	// callers depend on it. An archive that is not a history file -- one whose rows are only
	// ever aggregated, joined or filtered -- has no use for that promise and pays for it: a
	// reader that must preserve an order cannot choose freely among plans that produce the
	// same rows in a different one. Setting this says there is no order to preserve, and in
	// exchange a reader may reorder its work.
	//
	// It is a property of the archive, not of a query, because a per-query flag would let one
	// caller's "I do not care" reorder another caller's results.
	Unordered bool
	// CategoricalAttrs / ValueAttrs configure the per-segment indexes (see Collection),
	// including nested paths such as "Res.Mem".
	CategoricalAttrs []string
	ValueAttrs       []string
	// CompositeAttrs configures composite (multi-column) indexes over attribute tuples
	// (see Collection). Each tuple's attributes must also be in CategoricalAttrs/ValueAttrs
	// or in CategoricalComponentAttrs/ValueComponentAttrs.
	CompositeAttrs [][]string
	// CategoricalComponentAttrs / ValueComponentAttrs name attributes indexed only as
	// composite components, with no index of their own (see Options). A constraint naming
	// one of them alone scans.
	CategoricalComponentAttrs []string
	ValueComponentAttrs       []string
	// ZoneAttrs names numeric attributes to keep per-segment min/max on, so a query with
	// a range/equality constraint on one can skip whole segments. ValueAttrs are
	// automatically included.
	ZoneAttrs []string
	// ProfileBucketBytes is the quantile resolution of each sealed segment's retention
	// profile (see Options.ProfileBucketBytes). 0 means 1 MiB, lowered to an eighth of
	// SegmentSize when that is smaller.
	ProfileBucketBytes int64
	// Retention bounds what rotation keeps. Zero ⇒ keep everything.
	Retention Retention
	// OnHighMarkError reports a failed reclaim from the seal-time size eviction that keeps
	// the archive under Retention.MaxBytes between maintenance passes (see
	// Options.OnHighMarkError). nil discards it.
	OnHighMarkError func(error)
	// OnDictFault reports a compression dictionary's file found missing, replaced, or
	// changed underneath the archive (see Options.OnDictFault). nil discards it.
	OnDictFault func(error)
	// IndexBackfillBytes bounds how far back Reindex carries an index configuration change
	// (see Options.IndexBackfillBytes). 0 carries it across the whole archive.
	IndexBackfillBytes int64

	// RowGroupBytes is the uncompressed record-bytes budget for one columnar row group (see
	// Options.RowGroupBytes). 0 takes the default. It decides how much of a segment has to be
	// decompressed to read a single record, against how far compression can see across records, and
	// an archive is where that trade is worth tuning: its segments are immutable, so the choice is
	// made once per segment and lived with.
	RowGroupBytes int

	// SchemaRequireAttrs names attributes that enter the derived columnar schema whatever their
	// presence rate (see Options.SchemaRequireAttrs). It matters most on an archive: a record is
	// written once, in a final state, so attributes a record only acquires late in its life are
	// exactly the ones a history query reads and exactly the ones the presence floor keeps out.
	SchemaRequireAttrs []string

	// GroupSchemaCount and its companions enable secondary columnar schemas (see Options).
	GroupSchemaCount    int
	GroupStabilityRuns  int
	GroupMergeJaccard   float64
	GroupMaxPartialFrac float64

	// RemnantDictionary stores the values columnarized records repeat once per row group (see
	// Options.RemnantDictionary). On by default; negative turns it off.
	RemnantDictionary int

	// MoveListColumns stores qualifying list-valued attributes only in their typed list columns (see
	// Options.MoveListColumns). On by default; negative turns it off.
	MoveListColumns int

	// InternAtSeal interns each segment as soon as it seals (see Options.InternAtSeal), so an
	// archive gets the interning density/decode win immediately instead of only after a later
	// RetrainDict/Rewrite. Optional; default off. Trades a per-seal transcode (off the write
	// lock) for the win landing eagerly.
	InternAtSeal bool

	// BlockCacheBytes sets the PROCESS-GLOBAL shared archive block-cache budget (see
	// Options.ArchiveBlockCacheBytes). It is shared by ALL archives in the process, not scoped to
	// this one. 0 keeps the current/default archive budget. Setting it here is equivalent to
	// calling SetArchiveBlockCacheBudget.
	BlockCacheBytes int64

	// DataKey and EncryptedAttrs are encryption at rest, exactly as for a mutable collection (see
	// Options.DataKey and Options.EncryptedAttrs): with a key, every private attribute and every
	// attribute EncryptedAttrs names is sealed as it is appended. An attribute both sealed and indexed
	// is refused as it is there -- the caller must leave it out of CategoricalAttrs/ValueAttrs.
	//
	// Records appended before the archive had a key, or before an attribute joined the set, keep their
	// values in the clear until maintenance next rewrites their segment (a merge, a retrain, interning).
	// A read not entitled to sealed values treats those as sealed too, by name; see the archive's
	// *Redacted reads.
	DataKey        []byte
	EncryptedAttrs []string
}

ArchiveOptions configures an Archive.

type AttrTypeOptions added in v0.36.0

type AttrTypeOptions struct {
	// SampleMax bounds the records drawn; zero or negative leaves the sampler's default.
	SampleMax int
	// Evaluate fills each profile's Evaluated counts as well: the same cells measured by
	// what they EVALUATE to rather than by what they store. It is the only way to type an
	// attribute a pool stores as an expression (see the header), and it is the expensive
	// option -- roughly twice the stored pass on a 45-attribute fixture.
	//
	// Each cell is evaluated against its own record and nothing else. On a CHAINED
	// collection that means a PARENT reference resolves to undefined, because a sample is
	// one record rather than a chain, so an attribute written over its parent's is counted
	// as the undefined it evaluates to here. The stored counts have the same blindness and
	// report it as "expr"; neither is a reason to declare a type from.
	Evaluate bool
	// Redact evaluates as a reader NOT entitled to sealed values does: with no key, so a
	// sealed value is undefined in the scope an expression is evaluated against. It leaves
	// the stored counts alone, which never look through a sealed node in any case.
	Redact bool
}

AttrTypeOptions selects what AttrTypeProfilesWith measures.

type AttrTypeProfile added in v0.34.1

type AttrTypeProfile struct {
	Name string `json:"name"`
	// Present is the records in which the attribute appeared.
	Present int `json:"present"`

	AttrValueCounts

	// Evaluated is what the same cells EVALUATED to, or nil when evaluation was not
	// asked for. Its class counts sum to Present exactly as the stored ones do: a cell
	// that could not be evaluated is counted under its stored class, so a residual
	// "expr" entry is the share this measurement could not resolve rather than a gap.
	Evaluated *AttrValueCounts `json:"evaluated,omitempty"`
}

AttrTypeProfile is what one attribute held across a sample of records.

Counts are records, out of the sampled total that AttrTypeProfiles returns alongside. An attribute absent from a record is counted nowhere: Present is how many records had it at all, so Present < sampled is an absence rate, which is what decides whether a declared type has to admit nulls.

The embedded counts are the STORED forms. Evaluated, when it is there, is the same measurement over what those cells evaluate to; see AttrTypeProfilesWith.

type AttrValueCounts added in v0.36.0

type AttrValueCounts struct {
	// Classes counts the values by wire.NodeClass name ("int", "string", "expr", ...).
	// A single entry means the attribute is uniformly one kind in this sample.
	Classes map[string]int `json:"classes"`
	// Dominant is the most frequent class, and ties break toward the lexically smaller
	// name so the field is deterministic.
	Dominant string `json:"dominant"`

	// Ints counts integer values; IntMin/IntMax are their exact bounds.
	Ints   int   `json:"ints,omitempty"`
	IntMin int64 `json:"intMin,omitempty"`
	IntMax int64 `json:"intMax,omitempty"`
	// IntsLossyAsFloat counts integers whose magnitude exceeds 2^53, so they do not
	// round-trip through a float64. It is what decides whether an integer attribute may be
	// declared as a float type: zero means every value survives, non-zero means the
	// conversion would silently alter values.
	IntsLossyAsFloat int `json:"intsLossyAsFloat,omitempty"`

	// Reals counts real values. RealMin/RealMax exclude NaNs, which are a member of no
	// order and would otherwise make the bounds meaningless; RealNaNs counts them
	// separately. +/-Inf is ordered and so is included in the bounds.
	Reals    int     `json:"reals,omitempty"`
	RealNaNs int     `json:"realNaNs,omitempty"`
	RealMin  float64 `json:"realMin,omitempty"`
	RealMax  float64 `json:"realMax,omitempty"`
}

AttrValueCounts is the measured shape of a set of values: which classes they fell into, and the exact bounds of the numeric ones.

It is a separate type because the same measurement is taken twice over the same cells -- once on what they STORE and once on what they EVALUATE to -- and a consumer comparing the two wants the same fields on both, not a parallel set of names it has to keep aligned by hand.

func (AttrValueCounts) Nulls added in v0.36.0

func (p AttrValueCounts) Nulls() int

Nulls counts the sampled values that carry no type: stored `undefined` and `error`. Absence is NOT included -- that is Present against the sampled total, and a consumer that nulls both has to add them.

func (AttrValueCounts) Uniform added in v0.36.0

func (p AttrValueCounts) Uniform() bool

Uniform reports whether every sampled value that carries a type was the same class -- the case where a declared type needs no coercion. Nulls and absence do not break uniformity; they decide whether the declared type must admit nulls, which is a separate question.

False for an attribute that was never anything but undefined: there is no type to be uniform about, and reporting true would invite a caller to declare one. Distinguish that case with len(ValueClasses()) == 0.

func (AttrValueCounts) ValueClasses added in v0.36.0

func (p AttrValueCounts) ValueClasses() map[string]int

ValueClasses is Classes without the classes that carry no type -- undefined and error. It is the set a declared type has to cover.

type AutoTuneChange

type AutoTuneChange struct {
	Attr, Kind, Action, Reason string // Action: "add" | "drop"
}

AutoTuneChange records one add/drop AutoTune applied.

type AutoTuneOptions

type AutoTuneOptions struct {
	// SampleMax caps the ads profiled. Default defaultSampleMax.
	SampleMax int
	// MinDemand is the minimum equality+range probe count for an attribute to be
	// added as an index. Default 1 (any observed demand).
	MinDemand int64
	// DropUnused, if set, drops AUTO-created indexes that no query has filtered on
	// ("unused"). Off by default so AutoTune never removes an index a workload has
	// simply not exercised yet. Human-created indexes and low-cardinality indexes are
	// never auto-dropped (SuggestDrops reports them for manual review).
	//
	// Two guards keep this from thrashing, because rebuilding a dropped index is far more
	// expensive than carrying an idle one:
	//
	//   - It requires EVIDENCE. Demand counters are process-local and never decay, so
	//     right after a restart every attribute reads zero; dropping on that would discard
	//     the whole auto set on every restart and rebuild it as traffic returns. Nothing is
	//     dropped until the tracker has watched for DropUnusedMinWindow and seen at least
	//     DropUnusedMinQueries probes.
	//   - When a memory budget is configured it defers to it entirely. An unused index
	//     that fits costs little, and budgetTrim already evicts least-demanded first when
	//     space is actually short -- with hysteresis, which dropping on "unused" alone has
	//     none of. Reclaim when you need the room, not merely because you could.
	DropUnused bool
	// DropUnusedMinWindow and DropUnusedMinQueries are how much observation makes a zero
	// meaningful. Defaults: defaultDropWindow and defaultDropMinQueries. Negative values
	// waive the requirement (as with BudgetSlackBytes), which is for tests and for a caller
	// who has its own evidence that an index is unwanted.
	DropUnusedMinWindow  time.Duration
	DropUnusedMinQueries int64
	// BudgetHighFrac / BudgetLowFrac, when BudgetHighFrac > 0, bound index memory as a
	// fraction of the live data bytes: AutoTune stops adding demand-driven indexes once
	// index bytes reach the high mark, and trims the least-used AUTO indexes (never
	// human-created ones) until index bytes fall below BudgetLowFrac. This is a high/low-
	// watermark with hysteresis: grow until over the high mark, trim back to the low
	// mark. 0 disables the budget (unbounded). BudgetLowFrac defaults to 0.7*BudgetHighFrac.
	BudgetHighFrac float64
	BudgetLowFrac  float64
	// BudgetSlackBytes is absolute leeway on top of the high watermark: index bytes may
	// exceed BudgetHighFrac by up to this many bytes before any trim triggers, so a small
	// overage (or a small database, where the percentage is tiny in absolute terms) does
	// not cause churn. 0 uses defaultBudgetSlackBytes (10 MiB); set a negative value for
	// no slack (trim exactly at the fraction).
	BudgetSlackBytes int64
	// Reindex, if set, calls Reindex after applying changes so the new/removed
	// indexes take effect immediately instead of at the caller's next Reindex.
	Reindex bool
}

AutoTuneOptions configures AutoTune.

type AutoTuneResult

type AutoTuneResult struct {
	Changes []AutoTuneChange
	Changed bool
}

AutoTuneResult reports what AutoTune changed.

type BaseSchemaChange added in v0.33.3

type BaseSchemaChange struct {
	Unix    int64    `json:"unix"`
	Reason  string   `json:"reason"`
	Fields  int      `json:"fields"`
	Added   []string `json:"added,omitempty"`
	Removed []string `json:"removed,omitempty"`
	Changed []string `json:"changed,omitempty"`
	HotAdd  []string `json:"hotAdded,omitempty"`
	HotDrop []string `json:"hotRemoved,omitempty"`
}

BaseSchemaChange is one adoption of a different base schema: when, why, and what moved. Changed lists fields whose slot was re-laid-out, as "Name: kind/width -> kind/width".

type Batch added in v0.37.0

type Batch struct {
	N    int
	Cols []Column
}

Batch is one block's -- or one chunk of one window's -- surviving records, as columns.

BORROWED, AND ONLY UNTIL THE CALLBACK RETURNS. The slices are the producer's own and are refilled for the next batch, so a cell read after that is some later record's.

A STRING IN Str ALIASES THE BLOCK'S DECOMPRESSED REGION -- it is an unsafe.String over the dictionary entry, not a copy. Keeping one past the callback therefore pins that whole region for as long as the string lives, which on a scan of any size is a great deal more memory than the consumer thinks it is holding, and it stays valid only while that region does. A consumer that keeps anything past its callback copies it.

Cols is in the order the attributes were requested, one entry each, and that order and length are the same for every batch of a scan -- including a batch no column could be read for, which reports undefined rather than a short row. An encoder with a fixed schema can therefore bind its builders once.

type Codec

type Codec interface {
	// Compress appends the compressed form of src to dst and returns it.
	Compress(dst, src []byte) []byte
	// Decompress appends the decompressed form of src to dst and returns it.
	Decompress(dst, src []byte) ([]byte, error)
	// Name identifies the codec (for diagnostics).
	Name() string
}

Codec compresses and decompresses encoded ad bytes. It is a seam so the store can run with no compression (identityCodec, the default) in tests and benchmarks, and with ZSTD — optionally with a pre-trained shared dictionary — in production.

A codec's dictionary is fixed for the life of a collection: stored records are opaque compressed bytes that compaction copies verbatim, so every record must be decodable by the same codec. Re-training the dictionary between compactions (which requires versioning dictionaries per record and recompressing) is a future extension; a dictionary trained once from a representative sample (see TrainDict) already captures the cross-ad redundancy that dominates a pool of similar ClassAds.

func NewZSTDCodec

func NewZSTDCodec(dict []byte) (Codec, error)

NewZSTDCodec returns a ZSTD codec. If dict is non-empty it is used as a shared compression dictionary (see TrainDict). Pass nil for dictionary-less ZSTD.

type CodecStats added in v0.6.0

type CodecStats struct {
	// Codec is the current codec name: "identity" (no compression), "zstd", or "zstd+dict".
	Codec string `json:"codec"`
	// DictBytes is the trained ZSTD dictionary size (0 if none). Set by RetrainDict.
	DictBytes int64 `json:"dictBytes"`
	// LastRetrain is when RetrainDict last succeeded in this process (zero if never; note
	// a persistent collection recovers its codec but not this in-process timestamp).
	LastRetrain time.Time `json:"lastRetrain,omitempty"`
	// SampleRecords is how many live records were sampled for the ratio below.
	SampleRecords int `json:"sampleRecords"`
	// CompressedBytes / UncompressedBytes are the sampled records' stored (compressed) and
	// decompressed sizes; Ratio is UncompressedBytes/CompressedBytes (1.0 = no gain).
	CompressedBytes   int64   `json:"compressedBytes"`
	UncompressedBytes int64   `json:"uncompressedBytes"`
	Ratio             float64 `json:"ratio"`
}

CodecStats reports the storage codec's state and effectiveness, for the diagnostic question "is compression on, when was the dictionary last (re)trained, and how well is it compressing?". A collection defaults to the identity codec (no compression) until Options.Codec or RetrainDict switches it, so a Ratio near 1.0 with Codec "identity" means compression was never enabled.

type Collection

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

Collection is an in-memory, sharded, memory-dense store of ClassAds. It is safe for concurrent use.

func New

func New(opts Options) *Collection

New creates an empty Collection.

func Open

func Open(opts Options) (*Collection, error)

Open opens a persistent collection under opts.Dir, whose arenas are memory-mapped files. Committed data is flushed to disk on Close (per-commit msync durability is added in a later milestone). If opts.Dir is empty, Open is equivalent to New (an in-memory collection). Persistence is unix-only.

NOTE (P2): this creates a fresh persistent collection; recovering an existing directory (rebuilding the directory + index from the segment files) is the next milestone.

func (*Collection) AcquireRead added in v0.33.0

func (c *Collection) AcquireRead() bool

AcquireRead registers the caller as an in-flight reader of the collection and reports whether it may read. False means the collection is closed: a dropped table, say, whose segments are already unmapped or about to be. Every true answer MUST be balanced by ReleaseRead, or the collection's mappings are never released.

It exists because a close is not serialized against reads by anything else: a reader may be holding an iterator, or be between the per-shard pins a scan takes, and in either case the mapping it is about to read has no other thing keeping it alive.

func (*Collection) AddAutoComposites added in v0.38.1

func (c *Collection) AddAutoComposites(tuples [][]string) bool

AddAutoComposites installs composites over these tuples, marked auto, and reports whether any was installed. The composite counterpart of AddAutoIndex, and the restore path for a store whose composites are not re-derived from a saved configuration at open.

Fewer tuples may be installed than were asked for, silently -- and silently on purpose, where a configured tuple's refusal is reported (CompositeRefusals): a tuple whose component is not indexed in its own right is refused (newCompositeSpecs), as is one some composite already covers in any order. Both are the right answer for a restore -- the first says the component index did not come back, which leaves the composite nothing to fall back to for the conjunctions it cannot answer; the second says the tuple is already configured, and a configured composite is not the tuner's to claim.

func (*Collection) AddAutoIndex added in v0.6.0

func (c *Collection) AddAutoIndex(categorical, value []string) bool

AddAutoIndex adds indexes marked as auto-created (provenance auto), like AddIndex but eligible for automatic trimming by AutoTune's memory budget. Used by the persistence layer to restore auto provenance on restart.

func (*Collection) AddHotAttrs added in v0.6.0

func (c *Collection) AddHotAttrs(names ...string) []string

AddHotAttrs pins the named attributes into the hot set (front-loaded in future writes' hot headers), merging them with the current set, and returns the resulting hot attribute names. Unlike RefreshHotSet, which recomputes the set from sampled frequency, this forces specific attributes in regardless of how often they appear. Works in both RAM (interned) and persistent (inline) modes.

func (*Collection) AddIndex

func (c *Collection) AddIndex(categorical, value []string) bool

AddIndex adds categorical (string equality / membership) and value (numeric equality + range) indexes at runtime and returns whether the configuration changed. Names already indexed are ignored; a name given as both categorical and value, or already indexed as the other kind, is placed as categorical (equality on strings is the common case and categorical also serves it). The new indexes take effect for existing segments on the next Reindex; new segments pick them up when they are first indexed.

An attribute the collection seals at rest (EncryptedAttrs, or private, with encryption on) is skipped, as Open refuses it and SetEncryptedAttrs refuses to seal an indexed one: the index builds from the stored value, which for a sealed attribute is the ciphertext, so every record would be a candidate and the index would cost memory and answer nothing. Building it from the plaintext instead would write the secret into the sidecar on disk.

func (*Collection) AddSchemaRequireAttrs added in v0.32.0

func (c *Collection) AddSchemaRequireAttrs(names ...string) bool

AddSchemaRequireAttrs adds to the RUNTIME tier. Reports whether the effective set changed; see SetSchemaRequireAttrs on what a change implies.

func (*Collection) AttrNDV added in v0.38.1

func (c *Collection) AttrNDV(attr string) (NDVEstimate, bool)

AttrNDV reports how many distinct values attr takes, from the per-segment index summaries alone. ok is false when no segment indexes attr, which is a real answer and not a zero: the caller knows nothing about this attribute's cardinality and must not act as though it knows it is small.

COST. One pass over the segments, taking each shard's read lock briefly, reading only heap-resident summaries -- no posting, no record, no page of a sidecar's bitmaps. A single contributing segment answers from its exact count and allocates nothing. Several merge HyperLogLog registers, which is hllRegisters byte comparisons per segment; see BenchmarkAttrNDV for what that costs against the EXPLAIN a join already pays per side.

WHAT IT COUNTS. The values posted in each segment's INDEXED PREFIX. Three things follow, and each lands in Err rather than being smoothed away:

  • A segment the attribute is not indexed in, and the un-indexed tail of a segment the index has not caught up with, hold values nothing here has seen. The count can only be low for that reason, so it becomes a lower bound.
  • On a mutable collection the postings still carry SUPERSEDED record versions until compaction reclaims them, so a value only an overwritten version held is counted. The count can only be high for that reason, so it becomes an upper bound. A collection with both is bounded in neither direction and says so.
  • Records whose value the index cannot key are in Exceptions and in neither the count nor its bounds.

func (*Collection) AttrTypeProfiles added in v0.34.1

func (c *Collection) AttrTypeProfiles(sampleMax int) ([]AttrTypeProfile, int)

AttrTypeProfiles samples up to sampleMax records and reports, per attribute, the classes of value it held and the bounds of its numeric ones. It returns the profiles and the number of records actually sampled.

Profiles are ordered by Present descending, then by name, so the attributes a consumer is most likely to declare come first and the order is stable across calls on the same data.

It reads samples and classifies them; it decodes no expressions, evaluates nothing, and writes nothing. Returns (nil, 0) when there is nothing to sample. AttrTypeProfilesWith is the same measurement with the evaluated one alongside it.

func (*Collection) AttrTypeProfilesWith added in v0.36.0

func (c *Collection) AttrTypeProfilesWith(o AttrTypeOptions) ([]AttrTypeProfile, int)

AttrTypeProfilesWith is AttrTypeProfiles with the measurement selected by o.

func (*Collection) AutoCompositeNames added in v0.38.1

func (c *Collection) AutoCompositeNames() [][]string

AutoCompositeNames returns the tuples of the composites the auto-tuner created, a subset of CompositeAttrs. The composite counterpart of AutoIndexNames.

func (*Collection) AutoIndexNames added in v0.6.0

func (c *Collection) AutoIndexNames() []string

AutoIndexNames returns the names of auto-created indexes (provenance auto), so the human/auto distinction can be persisted and survive a restart.

func (*Collection) AutoTune

func (c *Collection) AutoTune(opts AutoTuneOptions) AutoTuneResult

AutoTune applies the advisory signals: it adds the demand-driven indexes from SuggestIndexes (those at or above MinDemand) and, if DropUnused is set, drops the unused ones from SuggestDrops. It is the "make it so" companion to the SuggestX methods — call it on whatever schedule you like (e.g. alongside Reindex). All suggestions are computed from one consistent snapshot before any change is applied.

func (*Collection) BackfillIndexes added in v0.33.0

func (c *Collection) BackfillIndexes(maxBytes int64) IndexBackfillResult

BackfillIndexes rebuilds the sidecars of sealed segments that lack postings for a currently indexed attribute, newest first, until maxBytes of segment data have been re-read (the pass overshoots by at most the last segment). maxBytes <= 0 means no bound.

Newest first because that is the end an archive is read from: a newest-first query with a limit stops early, so the segments it reaches first gain the most from an index.

It holds reindexMu for one segment at a time rather than for the pass. The archive's append path reindexes after every seal under the same lock, so holding it across a whole-archive backfill would stall ingest for as long as the backfill ran; per segment, an append waits at most one segment's rebuild. The segment is pinned while it is rebuilt, so a concurrent merge or rotation that retires it defers the unmap until the rebuild is done; the new sidecar is swapped in under the shard lock and the one it replaces is released once the scans reading it finish (see installSidecar).

func (*Collection) BaseSchemaChanges added in v0.33.3

func (c *Collection) BaseSchemaChanges() []BaseSchemaChange

BaseSchemaChanges returns the base-schema change log, oldest first: every adoption of a different base schema, with its reason and diff. Read from disk only, so it is available to a READ-level client.

func (*Collection) Begin added in v0.6.0

func (c *Collection) Begin() *Txn

Begin starts an optimistic transaction. Its snapshot for a shard is captured the first time the transaction reads or writes a key in that shard.

func (*Collection) BeginRedacted added in v0.28.0

func (c *Collection) BeginRedacted() *Txn

BeginRedacted is Begin for a caller NOT entitled to sealed values: reads through the transaction decode with no key, so a sealed attribute comes back undefined. It can still write: an ad it stores is sealed as the collection's policy says, and a patch (PatchAttrs) changes only the attributes it names -- a sealed value it does not name is kept as stored. One that sits in an interned record and has to move into the new whole record is re-sealed by the store in the form that record needs, without the transaction ever holding its plaintext; see redactwrite.go.

The entitlement lives on the transaction rather than on each read, so a new read method inherits it instead of having to remember it.

func (*Collection) BuildAndEnableSchemaScan added in v0.22.0

func (c *Collection) BuildAndEnableSchemaScan(sampleMax, hotTopN int) bool

BuildAndEnableSchemaScan samples the collection, builds an adschema, chooses the hot numeric tier as the top-hotTopN int/real fields by accumulated read demand (c.demand -- the same signal RefreshHotSet uses; the schema's hot tier IS the hot set), and enables the columnar scan over the sealed segments. Returns false if there is nothing to sample. Re-callable: this is the routine maintenance pass.

func (*Collection) Chained added in v0.21.3

func (c *Collection) Chained() bool

Chained reports whether the collection has structural (parent-only) ads that Scan/Query hide (HTCondor cluster/proc chaining). When false, Len is exactly the match-all row count, which the COUNT(*) fast path relies on.

func (*Collection) Close

func (c *Collection) Close() error

Close flushes all committed data to disk and unmaps the collection's segment files. It is a no-op for an in-memory collection. The collection must not be used after Close.

It does not wait for readers and does not defer: the write-out is what the returned error reports on, so it happens before Close returns. A reader in flight keeps the segments it has pinned (their unmap is deferred to its last unpin) and finds the rest of the collection empty, which is a short answer rather than a fault. A second Close does nothing.

func (*Collection) Closed added in v0.33.0

func (c *Collection) Closed() bool

Closed reports whether the collection has been closed.

func (*Collection) CodecStats added in v0.6.0

func (c *Collection) CodecStats(sampleMax int) CodecStats

CodecStats measures the storage codec's effectiveness over a sample of up to sampleMax live records: it decompresses each and compares the stored (compressed) size to the decompressed size. It takes each shard's read lock briefly, so it is safe alongside readers and writers.

func (*Collection) CollectRegionSamples added in v0.26.0

func (c *Collection) CollectRegionSamples(maxBytes, lookBackBytes int) [][]byte

CollectRegionSamples returns dictionary-training samples drawn from sealed segments' columnar block regions, in equal byte shares across the three kinds, up to about maxBytes in total.

For an APPEND-ONLY collection the draw is biased to recent segments: future writes resemble recent history far more than the oldest retained records, and an archive's oldest segments may predate schema or workload changes entirely. lookBackBytes caps how far back the draw reaches, measured in segment bytes from the newest; 0 means no limit.

Returns nil when no sealed segment carries a block -- there is nothing to sample from, and the caller should fall back to record samples (see CollectSamples).

func (*Collection) CollectSamples

func (c *Collection) CollectSamples(limit int) [][]byte

CollectSamples returns the decompressed wire bytes of up to max ads, for training a ZSTD dictionary (see TrainDict). It samples across shards, decoding each record with the codec it was stored under.

func (*Collection) CollectSamplesRecent added in v0.26.0

func (c *Collection) CollectSamplesRecent(maxRecords, maxBytes, lookBackBytes int) [][]byte

CollectSamplesRecent returns record samples drawn at random from the newest lookBackBytes of segment data, honoring MVCC visibility, bounded by BOTH a record count and a byte budget -- whichever binds first.

Both bounds exist because they answer different questions and callers supply different ones. maxRecords is what every existing caller has (RetrainDict's sampleMax), and keeping it a count means switching to this sampler cannot change what an existing call collects by reinterpreting its units. maxBytes is what the work actually scales with, since a record's size varies by two orders of magnitude across tables.

maxRecords <= 0 means no count bound; maxBytes <= 0 uses defaultSampleBytes; lookBackBytes <= 0 uses defaultLookBackBytes. Samples are flattened to inline wire exactly as CollectSamples does, so the two are interchangeable as TrainDict input.

Returns nil when the collection holds no visible records.

func (*Collection) CollectSamplesRecentN added in v0.26.0

func (c *Collection) CollectSamplesRecentN(maxRecords int) [][]byte

CollectSamplesRecentN returns up to maxRecords records drawn at random from the recent window, with no meaningful byte bound -- the sampler for decisions that need a representative COUNT of records rather than a fixed volume of bytes. See statSampleBytes.

func (*Collection) ColumnarEvalCount added in v0.27.0

func (c *Collection) ColumnarEvalCount(q *vm.Query) (int, bool)

ColumnarEvalCount counts the records matching q by evaluating q itself against each record's columns, for any NATIVE query.

ok=false when it cannot serve the query at all: the accelerator is off, or the query is not native (a delegated subtree needs a real ClassAd scope). Individual records whose stored value is an expression are re-evaluated the ordinary way; that never fails the query.

Because it evaluates the query rather than a summary of it, it is exact by construction -- the class of bug that required ExactProbes cannot arise here.

func (*Collection) ColumnarizeSealed added in v0.28.0

func (c *Collection) ColumnarizeSealed() int

ColumnarizeSealed rewrites sealed segments into columnar-native form as a maintenance pass: each attribute the schema carries is stored once, in the segment's own columnar payload, and removed from the records. Returns how many segments were rewritten.

Idempotent and bounded. An already-columnarized segment is skipped and the active write target is never touched, so re-calling is cheap; one pass rewrites at most ColumnarSegmentBudget segments, so a large existing archive converges over several passes instead of stalling on one.

Requires a derived schema, which BuildAndEnableSchemaScan produces and also calls this from -- so a caller on the ordinary schema-review interval gets this without asking for it. Holds maintMu, so it serializes against Compact/RetrainDict/Rotate/Rewrite and against a merge.

func (*Collection) ColumnsServable added in v0.37.0

func (c *Collection) ColumnsServable(q *vm.Query, attrs []string) bool

ColumnsServable reports whether ScanColumns can serve this query at all, without scanning.

Every reason ScanColumns declines is knowable before it reads anything -- there is no accelerator, the query is not native, nothing was asked for -- which is what lets a caller that must commit to an answer before the first row decide up front. A relay that returned a sequence and only then discovered it could not serve one would be indistinguishable from a query that matched nothing.

ScanColumns asks this same question rather than repeating the conditions, so the two cannot drift into disagreeing about what is servable.

func (*Collection) Compact

func (c *Collection) Compact() int

Compact reclaims space from superseded/deleted records. For each shard it first unlinks any fully-dead segment cheaply (no rewrite), then, if the shard's dead-byte ratio still warrants it, recompresses the live records into fresh segments. It is safe to call concurrently with reads and writes. Returns the number of shards where space was reclaimed (by either mechanism).

func (*Collection) CompositeAttrs added in v0.38.1

func (c *Collection) CompositeAttrs() [][]string

CompositeAttrs returns the attribute tuples the collection indexes together, in the spelling each was configured with and in tuple-identity order. The composite counterpart of IndexedAttrs: what a store persists so a reopen rebuilds the same composites.

func (*Collection) CompositeRefusals added in v0.38.1

func (c *Collection) CompositeRefusals() []CompositeRefusal

CompositeRefusals returns the configured composite tuples this collection could not install, and why -- the other half of CompositeAttrs, which reports only what survived.

It is fixed at construction and never changes afterwards, because it describes the configuration this store was opened with. A later AddIndex or DropIndex that would make a refused tuple resolvable does not install it: the tuple is not retried, and the entry here does not go away. Only reconfiguring and reopening does that, which is also the only action a caller should take on a non-empty result -- see CompositeRefusal.

The composites the AUTO-TUNER proposes are not reported here; see addCompositesAuto.

func (*Collection) CountConstraint added in v0.22.0

func (c *Collection) CountConstraint(constraint string) (int, bool)

CountConstraint parses a constraint string and, if it is columnar-eligible, counts via the columnar scan (see CountQuery). ok=false ⇒ use the normal count path.

func (*Collection) CountConstraintRedacted added in v0.35.0

func (c *Collection) CountConstraintRedacted(constraint string) (int, bool)

CountConstraintRedacted is CountConstraint for a reader NOT entitled to sealed values (see CountQueryRedacted).

func (*Collection) CountQuery added in v0.22.0

func (c *Collection) CountQuery(q *vm.Query) (int, bool)

CountQuery counts the records matching q using the columnar scan, when q is exactly (Native) one or more numeric comparisons on a single INT schema field -- the common count-where. It returns (count, true) on that fast path, or (0, false) to signal the caller to use the normal scan (schema-scan not enabled, or the predicate is not columnar-eligible). Correctness: the per-record numeric comparison matches the store's evaluation of `field OP number`; a value escaped out of the hot column is read from the cold tail, and Native() rules out any residual program the columnar path would miss.

func (*Collection) CountQueryRedacted added in v0.35.0

func (c *Collection) CountQueryRedacted(q *vm.Query) (int, bool)

CountQueryRedacted is CountQuery for a reader NOT entitled to sealed values: a sealed value counts as undefined. A sealed value is never a column, and every column tier declines a cell it cannot read as a literal, so the per-record fallback the vectorized tier hands such a cell to is keyless. A column can hold an attribute's values from before the policy sealed it, so the constraint is planned with every attribute the policy names read as undefined (keylessQuery), and a constraint on a field whose computed values are not trusted declines (keylessComputedHides).

func (*Collection) Delete

func (c *Collection) Delete(key []byte) bool

Delete removes key, returning whether it was present. The removal is an MVCC tombstone: scans already in progress still see the pre-delete version.

func (*Collection) DeltaStats added in v0.30.0

func (c *Collection) DeltaStats() (deltas, fulls int64)

DeltaStats reports how many records this collection has stored as deltas versus in full since it was opened. Both zero means delta mode is off (or nothing has been written).

Both count decisions made by the delta tracker, which is the write path -- NOT every whole record the store writes. A COLLAPSE does not appear here at all: collapseBatch writes its merged records with tx.putWireAd, which takes bytes that are already encoded and so never consults the tracker. So fulls does not move when a collapse rewrites thousands of chains, and a "did the collapse do anything" check built on it reads zero in every case -- which is exactly the wrong answer to take from a counter that looks like it should know. Use SealWalkStats for what the collapse examined and found.

func (*Collection) Discard added in v0.33.0

func (c *Collection) Discard() error

Discard is Close for a collection whose files are being DELETED (a dropped table): it releases the mappings without flushing anything, writing a directory snapshot, sealing sidecar indexes or vouching for the watch epoch.

Skipping that work is not only an optimization. The caller removes the directory right after, and the teardown may be deferred behind a reader for an unbounded time, by which point a table of the same name may have recreated the very paths a late dir-snapshot write would land on. Writing nothing is what makes deferring safe.

func (*Collection) DropIndex

func (c *Collection) DropIndex(names ...string) bool

DropIndex removes the given attributes from the configured indexes (categorical or value, whichever they were) and returns whether the configuration changed. The attributes stop being used by queries immediately; their postings are reclaimed from existing segments at the next Reindex. Names that were never indexed are ignored.

func (*Collection) DropSchemaRequireAttrs added in v0.32.0

func (c *Collection) DropSchemaRequireAttrs(names ...string) bool

DropSchemaRequireAttrs removes names from BOTH tiers. Reports whether the effective set changed.

Dropping one the application configured is effective for this process only: the next open re-asserts the configured tier, and the attribute is required again. That is the honest outcome -- the configuration still says to require it -- and the way to make it stick is to change the configuration.

func (*Collection) EnableSchemaScan added in v0.22.0

func (c *Collection) EnableSchemaScan(s *adSchema, hot []int)

EnableSchemaScan builds a columnar block over every currently-sealed segment (skipping the active append target) for the given schema and hot field set, publishes it on each segment, and records the state so CountQuery can auto-route matching queries. Additive and opt-in: with no state/block a query takes the normal row path, so a collection that never calls this is unaffected. Reads immutable sealed bytes only.

func (*Collection) EncryptedAttrNames added in v0.7.0

func (c *Collection) EncryptedAttrNames() []string

EncryptedAttrNames returns the explicit encrypted-attribute set (case-folded, sorted) -- the human-toggled attributes, not the always-on private ones. Used for persistence and diagnostics.

func (*Collection) EncryptionEnabled added in v0.7.0

func (c *Collection) EncryptionEnabled() bool

EncryptionEnabled reports whether this collection has a data key (encryption at rest is active). Without it, EncryptedAttrs is inert.

func (*Collection) EnsureDictReplicas added in v0.42.0

func (c *Collection) EnsureDictReplicas() []DictReplicaState

EnsureDictReplicas brings every dictionary's copy count up to the target and reports where each one stands.

Maintenance calls this on its own, rate-limited; this entry point runs it immediately. It is safe against concurrent readers: a trailer lives past the segment's mapping, so writing one touches no mapped byte, and it is safe against a concurrent reap because the write opens the segment file without O_CREATE -- a segment already unlinked simply fails and is skipped.

func (*Collection) EvictOverHighMark added in v0.40.1

func (c *Collection) EvictOverHighMark() (int, error)

EvictOverHighMark frees space when the store is over its MaxBytes ceiling, down to TargetBytes, applying only the SIZE bounds -- no age ceiling, no GC floor.

It exists because Rotate runs on the maintenance tick and nothing bounds growth between ticks: a spoke replaying a backlog can overshoot MaxBytes by however much arrives in one interval, which is the case the ceiling is there to prevent. This is called at segment seal, where the cost in the steady state is a counter and a comparison.

It takes no clock deliberately. The age rules need one and the store keeps none of its own (Rotate's now is the caller's), while the size rules need nothing but bytes -- so the one pass that has to run without a caller is the one that can.

func (*Collection) ExplainMatch added in v0.6.0

func (c *Collection) ExplainMatch(job *classad.ClassAd, targetConstraint string) MatchExplain

ExplainMatch reports how matchmaking job against this collection would execute: it rewrites the job's Requirements over the slot (baking the job's attribute values to constants), extracts the index-satisfiable probes, and reports which are covered by a configured index and the resulting access path. targetConstraint, if non-empty, is the MATCH's resource-side filter (WHERE TARGET, including NOPREEMPT's `State =!= "Claimed"`) -- already slot-scoped -- which is melded into the shown predicate, probes, and evaluation order so the explanation reflects the full effective slot filter. No I/O beyond reading the spec.

func (*Collection) ExplainQuery added in v0.6.0

func (c *Collection) ExplainQuery(q *vm.Query) QueryExplain

ExplainQuery reports how the store would execute q: which of its conjuncts are index-usable, and the resulting access path (indexed / parallel scan / serial scan). It performs no I/O beyond reading the current index spec.

func (*Collection) Flatten added in v0.4.0

func (c *Collection) Flatten(key []byte) (*classad.ClassAd, bool)

Flatten returns a standalone, self-contained copy of the ad at key with every inherited parent attribute materialized into it (the child's own values winning, parent-private attributes excluded) and no residual parent link. It is the form to archive as a history record: like condor_history, which stores each completed job flattened rather than as a live cluster/proc pair, so the record stays readable after its structural parent is gone. For a collection without parent chaining this is identical to Get.

func (*Collection) ForEachAd added in v0.7.0

func (c *Collection) ForEachAd(fn func(key string, ad *classad.ClassAd) bool)

ForEachAd calls fn with every stored (non-system) ad and its key, including structural (parent-only) ads -- a client-facing image, unlike Scan/Keys which hide structural ads. It is the driver for db.DeleteWhere's key matching, so it must NOT expose internal system records (they are neither client-visible nor client-deletable); system records are enumerated separately via ForEachSystemAd. Each ad is fully decoded (decompressed and, for encrypted attributes, decrypted). Iteration stops early if fn returns false. Per-shard consistent snapshot, like Scan.

func (*Collection) ForEachAdAt added in v0.24.0

func (c *Collection) ForEachAdAt(snapOf func(shardIdx int) uint64, fn func(key string, ad *classad.ClassAd) bool)

ForEachAdAt is ForEachAd over the versions visible at a caller-chosen snapshot sequence per shard, instead of each shard's current commit sequence.

snapOf is called once per shard, with the shard's index, and returns the sequence to read that shard at. It is a callback rather than a map so a transaction can capture a shard's sequence lazily on first touch -- and, having captured it, stay pinned to it for every later read of that shard.

This is what lets a transaction scan the committed store at its own snapshot: the same versions its point lookups see, rather than whatever has committed since.

func (*Collection) ForEachAdRedacted added in v0.35.0

func (c *Collection) ForEachAdRedacted(fn func(key string, ad *classad.ClassAd) bool)

ForEachAdRedacted is ForEachAd for a reader NOT entitled to sealed values: each ad is decoded with no key, so a sealed attribute is undefined -- to fn's evaluation of it as much as to anything fn returns. It is what a constraint-driven key scan (db.KeysWhere, db.DeleteWhere) runs on for such a reader; which keys match is an answer about the values the constraint read.

func (*Collection) ForEachSystemAd added in v0.9.0

func (c *Collection) ForEachSystemAd(fn func(key string, ad *classad.ClassAd) bool)

ForEachSystemAd calls fn with every internal system-keyed ad and its key -- the mirror image of ForEachAd, which hides them. It is the enumeration path a TTL reaper uses to find and expire durable bookkeeping records. Each ad is fully decoded; iteration stops early if fn returns false. Per-shard consistent snapshot, like Scan.

func (*Collection) GCFloor added in v0.21.4

func (c *Collection) GCFloor() float64

GCFloor returns the current runtime GC watermark (0 when unset).

func (*Collection) Get

func (c *Collection) Get(key []byte) (*classad.ClassAd, bool)

Get returns the current ad for key, decoded, or (nil, false).

func (*Collection) GetRedacted added in v0.28.0

func (c *Collection) GetRedacted(key []byte) (*classad.ClassAd, bool)

GetRedacted is Get for a reader NOT entitled to sealed values: the decode holds no key, so a sealed attribute comes back undefined rather than opened. See QueryRedacted.

func (*Collection) GroupCountAll added in v0.28.0

func (c *Collection) GroupCountAll(groupAttr string) ([]GroupCount, bool)

GroupCountAll is GroupCountQuery with no constraint: the histogram of the whole column.

func (*Collection) GroupCountConstraint added in v0.28.0

func (c *Collection) GroupCountConstraint(constraint, groupAttr string) ([]GroupCount, bool)

GroupCountConstraint parses a constraint string and, if the shape is columnar-eligible, answers the per-value counts of groupAttr over the matching records (see GroupCountQuery). ok=false ⇒ use the normal grouping path.

func (*Collection) GroupCountQuery added in v0.28.0

func (c *Collection) GroupCountQuery(q *vm.Query, groupAttr string) ([]GroupCount, bool)

GroupCountQuery answers `SELECT groupAttr, COUNT(*) ... WHERE q GROUP BY groupAttr` from the columnar blocks, returning the groups sorted by value. See GroupStatsQuery, of which this is the no-value- aggregate case.

func (*Collection) GroupSchemaAgreement added in v0.28.0

func (c *Collection) GroupSchemaAgreement(sampleMax, k int) GroupSchemaAgreement

GroupSchemaAgreement derives groups from each sealed segment independently and reports how often each table-level group reappears. Diagnostic only, and O(segments x sample) -- for an operator deciding whether to commit to a group, not for a maintenance pass.

func (*Collection) GroupSchemaChanges added in v0.29.13

func (c *Collection) GroupSchemaChanges() []GroupSchemaChange

GroupSchemaChanges returns the committed-group change log, oldest first. Reads the sidecar only -- no sampling -- so it is available to a READ-level client.

func (*Collection) GroupSchemaDrift added in v0.28.0

func (c *Collection) GroupSchemaDrift() GroupSchemaDrift

GroupSchemaDrift reads the checkpoint and reports what moved between the first and last retained derivations.

func (*Collection) GroupSchemaLastAgreement added in v0.29.13

func (c *Collection) GroupSchemaLastAgreement() (GroupSchemaLastAgreement, bool)

GroupSchemaLastAgreement returns the last persisted per-segment agreement, if any.

func (*Collection) GroupSchemas added in v0.28.0

func (c *Collection) GroupSchemas(sampleMax, k int) GroupSchemaInfo

GroupSchemas derives group schemas from a fresh sample and returns the report. It does not change how anything is stored or read; see deriveGroupSchemas.

k <= 0 uses defaultGroupSchemas. The report is also checkpointed to the collection's directory when it has one, so a later call can show what moved.

func (*Collection) GroupStatsAll added in v0.28.0

func (c *Collection) GroupStatsAll(groupAttr string, aggAttrs []string) ([]GroupStats, bool)

GroupStatsAll is GroupStatsQuery with no constraint: the whole column's histogram plus aggregates. The caller is asserting the query matches every record, which only it can know (see db.IsMatchAll) -- there is no predicate here to check that against.

This is not reachable through GroupStatsQuery: an unconstrained query has no probes to analyze, so the predicate analysis declines it. And the index path that answers other unconstrained grouped counts only covers CATEGORICALLY indexed attributes, so `GROUP BY <numeric>` with no WHERE fell to a record scan the same way the constrained form did.

func (*Collection) GroupStatsAllAggs added in v0.33.2

func (c *Collection) GroupStatsAllAggs(groups []GroupSpec, aggCols []GroupAggCol,
	countFilters []string) ([]GroupStats, bool)

GroupStatsAllAggs is GroupStatsConstraintAggs over every record, for a constraint the caller has established is match-all. See GroupStatsAllCols.

func (*Collection) GroupStatsAllAggsRedacted added in v0.35.0

func (c *Collection) GroupStatsAllAggsRedacted(groups []GroupSpec, aggCols []GroupAggCol,
	countFilters []string) ([]GroupStats, bool)

GroupStatsAllAggsRedacted is GroupStatsAllAggs for a reader NOT entitled to sealed values. It reads only columns, which never hold a sealed value, so it answers as GroupStatsAllAggs does -- except where the store may hold a sealed attribute's values in the clear (see hidesClearSealed): a group, aggregate or filter naming one, or reading a field whose computed values are not trusted, declines to the keyless scan.

func (*Collection) GroupStatsAllBucketed added in v0.32.0

func (c *Collection) GroupStatsAllBucketed(groupAttr string, bucket int64, aggAttrs []string) ([]GroupStats, bool)

GroupStatsAllBucketed is GroupStatsAll with the group column floored into buckets of bucket (0 = the raw value). See GroupStatsQueryBucketed for what bucketing changes.

func (*Collection) GroupStatsAllCols added in v0.33.0

func (c *Collection) GroupStatsAllCols(groups []GroupSpec, aggAttrs []string) ([]GroupStats, bool)

GroupStatsAllCols is GroupStatsAllBucketed over SEVERAL group columns. See GroupStatsQueryCols.

func (*Collection) GroupStatsConstraint added in v0.28.0

func (c *Collection) GroupStatsConstraint(constraint, groupAttr string, aggAttrs []string) ([]GroupStats, bool)

GroupStatsConstraint parses a constraint string and, if the shape is columnar-eligible, answers the per-group record count plus a NumStats per aggAttr over the matching records (see GroupStatsQuery). ok=false ⇒ use the normal grouping path.

func (*Collection) GroupStatsConstraintAggs added in v0.33.2

func (c *Collection) GroupStatsConstraintAggs(constraint string, groups []GroupSpec, aggCols []GroupAggCol,
	countFilters []string) ([]GroupStats, bool)

GroupStatsConstraintAggs is GroupStatsConstraintCols where each aggregate column may carry a per-aggregate FILTER, and countFilters asks additionally for a filtered RECORD COUNT per group -- SQL's `COUNT(*) FILTER (WHERE ...)`, which reads no column at all.

GroupStats.Stats stays aligned with aggCols and holds only the records that passed that column's filter; GroupStats.CountOf is aligned with countFilters. A filter narrows an aggregate and never a group: a group whose every record fails every filter is still returned, with zero counts and empty stats, which is what SQL specifies.

ok=false when any filter is a shape the columns cannot answer (see compileGroupFilters), and the caller then scans. That is a decline of the WHOLE query: half a columnar result cannot be stitched to half a scan.

func (*Collection) GroupStatsConstraintAggsRedacted added in v0.35.0

func (c *Collection) GroupStatsConstraintAggsRedacted(constraint string, groups []GroupSpec, aggCols []GroupAggCol,
	countFilters []string) ([]GroupStats, bool)

GroupStatsConstraintAggsRedacted is GroupStatsConstraintAggs for a reader NOT entitled to sealed values: a record whose constraint the columns cannot decide is matched with no key, so a sealed value is undefined to it. A sealed group or aggregate value is never a column, and a cell holding one declines the whole query, which then goes back to the (keyless) scan; a group, aggregate or filter on an attribute the policy names, or on a field whose computed values are not trusted, declines too (see keylessHidesGroupAggs), since a column may hold its values from before it was sealed.

func (*Collection) GroupStatsConstraintBucketed added in v0.32.0

func (c *Collection) GroupStatsConstraintBucketed(constraint, groupAttr string, bucket int64, aggAttrs []string) ([]GroupStats, bool)

GroupStatsConstraintBucketed is GroupStatsConstraint with the group column floored into buckets of bucket (0 = the raw value). See GroupStatsQueryBucketed.

func (*Collection) GroupStatsConstraintCols added in v0.33.0

func (c *Collection) GroupStatsConstraintCols(constraint string, groups []GroupSpec, aggAttrs []string) ([]GroupStats, bool)

GroupStatsConstraintCols is GroupStatsConstraintBucketed over SEVERAL group columns: the group is the tuple of their (individually bucketed) values. See GroupStatsQueryCols.

func (*Collection) GroupStatsQuery added in v0.28.0

func (c *Collection) GroupStatsQuery(q *vm.Query, groupAttr string, aggAttrs []string) ([]GroupStats, bool)

GroupStatsQuery answers `SELECT groupAttr, COUNT(*), <aggregates over aggAttrs> ... WHERE q GROUP BY groupAttr` from the columnar blocks, returning the groups sorted by value. Each group carries a NumStats per aggAttr, from which the caller renders MIN/MAX/SUM/AVG/COUNT(attr) -- the same inputs NumStatsQuery returns for the ungrouped case, so the rendering is shared and cannot diverge.

ok=false when the shape is not columnar-servable -- no accelerator, a non-native constraint, a predicate that is not a conjunction of scalar numeric comparisons, a group attribute the schema does not carry as a numeric or string field, or an aggregate attribute it does not carry as a numeric one -- and the caller then scans as before.

It also declines mid-flight if a matching record's GROUP value is one only EVALUATION can produce: an expression, a list, a nested ad. Such a record still forms a group -- the row path emits a group per distinct rendered value -- so dropping it would return a result silently missing groups, and the query goes back to the scan that can render it. Every SCALAR shape is now served instead of declined: a number, a string, a boolean, and `undefined` for a record whose attribute is absent, each rendering as the scan renders it.

An absent AGGREGATE value is different and is simply skipped: MIN/SUM/COUNT(attr) over a set that does not include the record is what the reference computes for a record whose attribute is undefined. Only the group column decides which rows exist.

Segments whose own schema lacks a field fall back to a row walk that reads only the attributes involved, so a schema change costs those segments and not the query.

func (*Collection) GroupStatsQueryBucketed added in v0.32.0

func (c *Collection) GroupStatsQueryBucketed(q *vm.Query, groupAttr string, bucket int64, aggAttrs []string) ([]GroupStats, bool)

GroupStatsQueryBucketed is GroupStatsQuery grouping by the group column FLOORED into buckets of bucket (0 = the raw value, i.e. GroupStatsQuery). This is the shape a time series asks -- "per day", not "per second".

Only a NUMBER can be floored, so a record whose group value is a string, a boolean, undefined or error is DROPPED from a bucketed result rather than declining it: that is what the scanning aggregator does with one (db.bucketKeyText runs number(v), which rejects all four). The unbucketed form groups all of them, because there a column read can render them.

A bucketed GROUP BY on a STRING column therefore has no groups at all, which is the scan's answer too.

func (*Collection) GroupStatsQueryCols added in v0.33.0

func (c *Collection) GroupStatsQueryCols(q *vm.Query, groups []GroupSpec, aggAttrs []string) ([]GroupStats, bool)

GroupStatsQueryCols is GroupStatsQueryBucketed over SEVERAL group columns: a record's group is the TUPLE of its group values, each bucketed on its own width, and the whole tuple identifies one group. "Per owner per day" -- one raw string column beside one bucketed time column -- is the shape this exists for, and it is the shape that fell to a record scan when only one column was served.

Each component keeps exactly the semantics the single-column form gives it, including the ones that drop a record: a bucketed component that is not a finite number has no bucket, and the RECORD then leaves the series, because the reference drops a row as soon as any one of its bucket keys fails to render. So one unbucketable component is enough to drop a record that every other component could have grouped.

ok=false for more than MaxGroupCols columns. The key holds a fixed number of components and truncating past it would merge groups that differ only in a dropped component, so the query goes back to the scan instead.

func (*Collection) GroupValuesAllAggs added in v0.37.0

func (c *Collection) GroupValuesAllAggs(groups []GroupSpec, aggCols []GroupAggCol,
	countFilters []string, newSink func() GroupSink, mergeSink MergeGroupSink) ([]GroupValues, bool)

GroupValuesAllAggs is GroupValuesConstraintAggs over every record, for a constraint the caller has established is match-all. See Collection.GroupStatsAllAggs.

func (*Collection) GroupValuesAllAggsRedacted added in v0.37.0

func (c *Collection) GroupValuesAllAggsRedacted(groups []GroupSpec, aggCols []GroupAggCol,
	countFilters []string, newSink func() GroupSink, mergeSink MergeGroupSink) ([]GroupValues, bool)

GroupValuesAllAggsRedacted is GroupValuesAllAggs for a reader NOT entitled to sealed values.

func (*Collection) GroupValuesConstraintAggs added in v0.37.0

func (c *Collection) GroupValuesConstraintAggs(constraint string, groups []GroupSpec, aggCols []GroupAggCol,
	countFilters []string, newSink func() GroupSink, mergeSink MergeGroupSink) ([]GroupValues, bool)

GroupValuesConstraintAggs is GroupStatsConstraintAggs reduced into caller-supplied accumulators instead of the built-in numeric statistics: one sink per group, made by newSink the first time a group is seen, fed the aggregate columns' values.

It declines on exactly the same terms as GroupStatsConstraintAggs, because it is the same plan and the same scan -- only the accumulator differs.

func (*Collection) GroupValuesConstraintAggsRedacted added in v0.37.0

func (c *Collection) GroupValuesConstraintAggsRedacted(constraint string, groups []GroupSpec, aggCols []GroupAggCol,
	countFilters []string, newSink func() GroupSink, mergeSink MergeGroupSink) ([]GroupValues, bool)

GroupValuesConstraintAggsRedacted is GroupValuesConstraintAggs for a reader NOT entitled to sealed values, on the same terms as GroupStatsConstraintAggsRedacted.

func (*Collection) HasSealedSidecar added in v0.38.0

func (c *Collection) HasSealedSidecar() bool

HasSealedSidecar reports whether any segment has flipped to a mapped sidecar index, which is what says an index is actually there to be probed rather than only configured.

It exists apart from SidecarSizes because the two questions cost different amounts. SidecarSizes is a diagnostic: it parses every sidecar to break the bytes out by structure, which is fine once a minute and is NOT fine on a query path. A join asks this question once per side while it is planning, and asking it through the byte breakdown made planning a chain cost more than running it.

func (*Collection) HighMarkStats added in v0.40.1

func (c *Collection) HighMarkStats() (passes, dropped int64)

HighMarkStats reports how many seal-time size evictions have actually dropped something and how many segments they dropped in total. A pass count that tracks the seal count means the archive is sitting ON its ceiling and evicting continuously -- which is what Retention.TargetBytes exists to prevent, by freeing down to a low mark instead of to just under the ceiling.

func (*Collection) HotAttrNames

func (c *Collection) HotAttrNames() []string

HotAttrNames returns the current hot attributes by name (for diagnostics).

func (*Collection) IndexBackfillPending added in v0.33.0

func (c *Collection) IndexBackfillPending() (segments int, bytes int64)

IndexBackfillPending reports how many sealed segments lack postings for some currently indexed attribute, and their stored bytes: what the backfill has still to do. It reads only resident sidecar directories.

func (*Collection) IndexSizes added in v0.6.0

func (c *Collection) IndexSizes() IndexSizes

IndexSizes measures each configured index's resident bytes across all live segments, tagged with provenance (human vs auto), against the live data bytes. It takes each shard's read lock briefly, so it is safe alongside readers and writers.

func (*Collection) IndexedAttrs

func (c *Collection) IndexedAttrs() (categorical, value []string)

IndexedAttrs returns the currently-indexed attribute names, split by kind, in the collection's canonical (interned) casing.

Component-only attributes (Options.CategoricalComponentAttrs / ValueComponentAttrs) are NOT reported, and that is the contract callers want: they ask this to decide whether a constraint on an attribute can be answered from an index, and a component-only attribute has no index of its own to answer one with. Nothing else reports them -- they are a property of the composites that use them, which IndexSizes already names.

func (*Collection) InternSealed added in v0.23.0

func (c *Collection) InternSealed()

InternSealed transcodes every sealed, still-inline segment of a persistent append-only collection to interned form under the current codec, swapping each in and rebuilding its indexes. It is the eager complement to interning-at-compaction (resealAppendOnly): an archive that never retrains still gets the density/decode win as soon as segments seal. Idempotent -- already-interned segments and the active write target are skipped, so re-calling is cheap and it composes with a later RetrainDict. Append-only only: a mutable segment's records can be superseded in place after seal, which this off-lock transcode would race (there interning rides compaction, which reconciles supersedes in a final critical section). Holds maintMu, so it serializes against Compact/RetrainDict/Rotate/Rewrite. Called opt-in from the Archive.Append eager-seal hook (Options.InternAtSeal) and available as a manual maintenance pass.

func (*Collection) Keys added in v0.6.0

func (c *Collection) Keys() []string

Keys returns every visible key in the collection at a consistent per-shard snapshot, in no particular order. Structural (parent-only) keys of a chained collection are excluded, matching Scan's output. Each key is a fresh copy the caller owns. Useful for administrative enumeration and for a replica that must clear its keyspace before a full re-sync.

func (*Collection) Len

func (c *Collection) Len() int

Len returns how many live keys a reader is shown. Records of the reserved system keyspace (syskey.go) are not among them, as they are not in any other client-facing path. Structural (parent-only) ads of a chained collection still are, though Scan/Query hide those too -- so Len equals the number of rows a match-all query returns only when the collection is not Chained. StoredLen is the count of everything the store holds.

func (*Collection) MaintProgress added in v0.34.0

func (c *Collection) MaintProgress() MaintProgress

MaintProgress reports the maintenance pass running on this collection, or the zero value when none is.

It takes NO lock -- not maintMu, not a shard lock -- so it answers promptly while the pass it describes holds both. See the package comment above for why staleness is the acceptable side of that trade.

func (*Collection) MaintenanceStopping added in v0.34.0

func (c *Collection) MaintenanceStopping() bool

MaintenanceStopping reports whether this collection has been asked to stop maintenance.

Exported for the ORCHESTRATOR of a maintenance pass, not for the pass itself. One "pass" at the server layer is half a dozen independent steps -- merge, reindex, index backfill, group derivation, schema scan, hot-set refresh -- each of which honours the signal internally but none of which knows it is one of six. Without this, stopping during the first step still paid for the other five, which on an archive at history scale is most of the shutdown an operator was waiting out.

func (*Collection) MarkAutoComposites added in v0.38.1

func (c *Collection) MarkAutoComposites(tuples [][]string)

MarkAutoComposites records the named EXISTING composites as auto-created. It changes only provenance: no composite is added, dropped or rebuilt, the index generation does not move, and a tuple no current composite covers is ignored.

Tuples are matched as SETS of folded component names, not as ordered keys. Order is part of a composite's identity but not of what it answers, and two orders of one set cannot both be configured (coversTupleIDs refuses the second), so a set names at most one composite and matching this way survives a saved tuple being written back in a different order than the live composite carries.

func (*Collection) MarkAutoIndexes added in v0.25.0

func (c *Collection) MarkAutoIndexes(names []string)

MarkAutoIndexes records the named EXISTING indexes as auto-created. It changes only provenance: no index is added, dropped, or rebuilt, and a name that is not currently indexed is ignored.

This is the restore side of AutoIndexNames for a store that rebuilds its whole index set at open (an archive does). Going through AddAutoIndex there would not work: the indexes already exist as human-created by then, and an auto add deliberately refuses to downgrade a human index. Adding them separately instead would restore provenance correctly but rebuild them, which for an archive means reading history back through the decompressor on every start.

func (*Collection) Match added in v0.5.2

func (c *Collection) Match(job *classad.ClassAd) iter.Seq[*classad.ClassAd]

Match returns every ad in the collection that symmetrically matches job, in no particular order. Use MatchSorted for a Rank-ordered result. job is not modified.

func (*Collection) MatchSorted added in v0.5.2

func (c *Collection) MatchSorted(job *classad.ClassAd, limit int) []*classad.ClassAd

MatchSorted returns the matching ads ranked by job's Rank expression, best (highest Rank) first. limit <= 0 returns all matches; limit > 0 returns at most the top limit. Ads whose Rank does not evaluate to a number sort after ranked ones. Ties in Rank are broken in an unspecified order (it depends on scan/fan-out order); a caller needing a deterministic tiebreak should apply its own. job is not modified.

func (*Collection) MatchSortedRanked added in v0.6.0

func (c *Collection) MatchSortedRanked(job *classad.ClassAd, limit int) []RankedMatch

MatchSortedRanked is MatchSorted that also returns each match's Rank, best (highest Rank) first, up to limit (<= 0 = all). Ads whose Rank is not numeric sort after ranked ones. Like MatchSorted, the job's Requirements is used to visit only index-candidate slots when an index covers it (the matchmaking pushdown), rather than bilaterally evaluating every slot.

func (*Collection) MatchSortedRankedFiltered added in v0.6.0

func (c *Collection) MatchSortedRankedFiltered(job *classad.ClassAd, targetConstraint string, limit int) ([]RankedMatch, error)

MatchSortedRankedFiltered is MatchSortedRanked restricted to slots that also satisfy targetConstraint (a constraint over the resource ad, e.g. `State =!= "Claimed"`). The constraint's index-satisfiable probes narrow the candidate scan (pushdown); the full constraint is then re-checked on each matched slot. An empty constraint is exactly MatchSortedRanked. Returns an error only if targetConstraint fails to parse.

func (*Collection) MatchSortedRankedFilteredRedacted added in v0.35.0

func (c *Collection) MatchSortedRankedFilteredRedacted(job *classad.ClassAd, targetConstraint string, limit int) ([]RankedMatch, error)

MatchSortedRankedFilteredRedacted is MatchSortedRankedFiltered for a reader NOT entitled to sealed values (see above): the resource-side constraint is evaluated on the keyless slot too.

func (*Collection) MatchSortedRankedRedacted added in v0.35.0

func (c *Collection) MatchSortedRankedRedacted(job *classad.ClassAd, limit int) []RankedMatch

MatchSortedRankedRedacted is MatchSortedRanked for a reader NOT entitled to sealed values (see above).

func (*Collection) MatchSortedRedacted added in v0.35.0

func (c *Collection) MatchSortedRedacted(job *classad.ClassAd, limit int) []*classad.ClassAd

MatchSortedRedacted is MatchSorted for a reader NOT entitled to sealed values (see above).

func (*Collection) MigrateSealedAttrs added in v0.28.0

func (c *Collection) MigrateSealedAttrs(workers int) int

MigrateSealedAttrs rewrites every sealed segment that still holds a value this collection would seal, so a store written before sealing was turned on stops carrying private attributes in the clear. Returns the number of segments rewritten.

Safe to call on a store that needs nothing: the scan finds no candidate and it returns 0. Safe to call twice, and safe to interrupt (see the file comment). A collection with no sealer, or no persistence, has nothing to migrate.

workers bounds the concurrent rewrites; <= 0 takes a default derived from GOMAXPROCS. Rewriting is decompress + re-encode + compress per record, so it is CPU-bound and worth parallelizing on a store with many segments -- but each rewrite also holds a whole new segment in memory, which is why it is bounded rather than one goroutine per segment.

func (*Collection) NumStatsQuery added in v0.25.2

func (c *Collection) NumStatsQuery(q *vm.Query, attr string) (NumStats, bool)

NumStatsQuery computes the numeric aggregate inputs for attr over the records matching q, using the columnar scan. A nil q means every record.

It returns ok=false when the columnar path cannot serve the request -- the accelerator is off, attr is not a numeric field of the current schema, or q is not a conjunction of scalar numeric comparisons ON attr ITSELF. That last restriction is the same one CountQuery has: a predicate over a different field would need a second column read per record, which this pass does not do. A caller that gets false scans instead.

func (*Collection) NumStatsQueryRedacted added in v0.35.0

func (c *Collection) NumStatsQueryRedacted(q *vm.Query, attr string) (NumStats, bool)

NumStatsQueryRedacted is NumStatsQuery for a reader NOT entitled to sealed values. Columns never hold a sealed value, so it answers as NumStatsQuery does -- except on a store that may hold a sealed attribute's values in the clear (see hidesClearSealed), where aggregating one declines to the keyless scan and the constraint is planned as that reader evaluates it (keylessQuery).

func (*Collection) NumValuesQuery added in v0.37.0

func (c *Collection) NumValuesQuery(q *vm.Query, attr string, newSink func() func(NumValue), merge func()) bool

NumValuesQuery feeds every numeric value of attr, over the records matching q, to sink -- through the same columnar pass that answers SUM and MIN, rather than by decoding records. A nil q means every record. It returns false when the columnar path cannot serve the request, on the same terms as NumStatsQuery, and the caller must scan instead.

VALUES ARRIVE IN BLOCK ORDER, AND ACROSS SEVERAL SINKS. That is not the order a record scan visits the same records in, and not insertion order: the pass walks segments, then blocks, skipping whole blocks a zone map rules out -- and when it fans out across segments, which sink sees which segment is a race. A sink whose answer depends on the order it is fed will therefore disagree with the scan over the same records, and may disagree with ITSELF between two runs. That is not a defect here but a property a caller has to be able to promise it does not have. The reference's own min()/max() cannot promise it over a column holding a NaN, which is why NumStats flags that case rather than answering it.

newSink is called once per worker and merge once at the end, both on the CALLING goroutine; each sink is fed by one goroutine only. See valuesPar for the full contract.

func (*Collection) NumValuesQueryRedacted added in v0.37.0

func (c *Collection) NumValuesQueryRedacted(q *vm.Query, attr string, newSink func() func(NumValue), merge func()) bool

NumValuesQueryRedacted is NumValuesQuery for a reader NOT entitled to sealed values, on the same terms as NumStatsQueryRedacted: columns never hold a sealed value, so it answers as NumValuesQuery does, except on a store that may hold a sealed attribute's values in the clear, where it declines -- and where attr or the constraint reads a field whose computed values are not trusted, since a value computed before a widen can be a function of a now-sealed attribute (keylessComputedHides).

func (*Collection) OpStats added in v0.11.0

func (c *Collection) OpStats() OpStats

OpStats returns a snapshot of the collection's operational timing counters -- where its callers spent time blocked in, or holding, each of the store's stall points (shard write lock, segment allocation, durability sync, and the maintenance passes). Per-shard counters are summed across all shards; every value is a monotonic cumulative total, so a scraper derives rate and mean latency from deltas. It reads atomics locklessly, so it never contends with readers or writers.

func (*Collection) Ordered added in v0.5.2

func (c *Collection) Ordered(index int, partition classad.Value, resume OrderCursor) iter.Seq[OrderedAd]

Ordered iterates one partition of the index-th configured ordered index in sort order, yielding each member ad with its resume cursor and cluster signature. Iteration is over an O(1) snapshot taken at the call, so it is stable even as the index churns; each ad is fetched live by key, so a member deleted since the snapshot is skipped. For an index configured without a Partition, the partition argument is ignored (there is a single global run). resume's zero value starts at the beginning.

func (*Collection) OrderedRedacted added in v0.28.0

func (c *Collection) OrderedRedacted(index int, partition classad.Value, resume OrderCursor) iter.Seq[OrderedAd]

OrderedRedacted is Ordered for a caller NOT entitled to sealed values: each ad is materialized with no key, so a sealed attribute arrives undefined. See Collection.QueryRedacted.

This is served over the RPC to unprivileged sessions (dbrpc's ordered op), so it needs the entitlement like any other client-facing read -- it is not only the negotiator's internal list.

func (*Collection) Persistent added in v0.33.2

func (c *Collection) Persistent() bool

Persistent reports whether this collection is backed by a directory, which is also what decides its record encoding: a persistent collection stores attribute names inline (so its segment files recover without a table), an in-memory one interns them against the shared table. Callers that used to read SupportsRawWire for this -- it was c.inline -- want this.

func (*Collection) PresenceCountQuery added in v0.27.0

func (c *Collection) PresenceCountQuery(q *vm.Query) (int, bool)

PresenceCountQuery counts the records matching a single `attr is undefined` / `attr isnt undefined` predicate over the columnar accelerator.

Returns ok=false when the columnar path cannot serve it -- the accelerator is off, the predicate is not a lone presence probe on a schema field, or some record's value for the attribute is an EXPRESSION, which needs evaluating. A caller that gets false scans instead.

func (*Collection) Put

func (c *Collection) Put(key []byte, ad *classad.ClassAd) error

func (*Collection) Query

func (c *Collection) Query(q *vm.Query) iter.Seq[*classad.ClassAd]

Query returns an iterator over the ads matching q, with the same scan-exactly-once guarantee as Scan.

Each ad is match-tested cheaply and only matching ads are fully decoded to be yielded. The match test uses, in order of preference: wire-native evaluation (the query reads scalar-literal attributes directly from the encoded ad, building no ClassAd); partial decode (decode only the attributes the query reads, transitively) when an attribute is a non-literal expression; or full decode for queries that read attributes by a runtime-computed name (eval()).

func (*Collection) QueryAsOf added in v0.12.0

func (c *Collection) QueryAsOf(q *vm.Query, t time.Time) (iter.Seq[*classad.ClassAd], error)

QueryAsOf runs q against the point-in-time snapshot at time t: it resolves t to a per-shard commit sequence and scans each shard at that sequence, so the result is exactly the ads that were current at t. It errors if time travel is disabled or t predates the retained window. v1 uses a serial full scan per shard (the index, parallel, and chained fast paths are current-time only); the query constraint is still applied to every candidate.

func (*Collection) QueryAsOfRedacted added in v0.35.0

func (c *Collection) QueryAsOfRedacted(q *vm.Query, t time.Time) (iter.Seq[*classad.ClassAd], error)

QueryAsOfRedacted is QueryAsOf for a reader NOT entitled to sealed values: q is matched, and each ad decoded, with no key, so a sealed value is undefined both to the constraint and in the result. An older version of a record is no less secret than the current one.

func (*Collection) QueryProject added in v0.6.0

func (c *Collection) QueryProject(q *vm.Query, attrs []string) iter.Seq[[]classad.Value]

QueryProject is Query specialized for aggregation and projection: for each ad matching q it yields just the named attributes' values, read wire-native (straight from the encoded ad, no *classad.ClassAd built) whenever they are scalar literals -- the common case for the numeric/string attributes an aggregate groups or sums by. Only an ad that stores one of the requested attributes as a non-literal expression falls back to a full decode, and only that ad.

This avoids the dominant cost of a GROUP BY / aggregate over Query, which fully decodes every matching ad (tens of allocations each) just to read one or two attributes.

The yielded slice is reused across iterations and aligned with attrs; the consumer must copy any value it needs to retain past the next step (the aggregate reads each value into its group state immediately).

func (*Collection) QueryProjectRedacted added in v0.35.0

func (c *Collection) QueryProjectRedacted(q *vm.Query, attrs []string) iter.Seq[[]classad.Value]

QueryProjectRedacted is QueryProject for a reader NOT entitled to sealed values: q is matched and attrs are read with no key, so a sealed value is undefined in both. Every aggregate and top-K over this scan is therefore an answer about what the reader may see, not about the plaintext.

func (*Collection) QueryProjectStats added in v0.29.6

func (c *Collection) QueryProjectStats(q *vm.Query, attrs []string, stats *ScanStats) iter.Seq[[]classad.Value]

QueryProjectStats is QueryProject that also fills stats (may be nil) with the scan's work breakdown -- how many segments were pruned by zone maps vs scanned, and how many records were answered from columns vs reassembled from the arena. It exists so an EXPLAIN ANALYZE of an aggregate that falls to this projected scan (an attribute the columnar accelerator does not cover numerically) can show WHERE the time went -- specifically a large RecordsReassembled, the slow per-record path. Stats accumulate as the returned sequence is consumed.

func (*Collection) QueryProjectStatsRedacted added in v0.35.0

func (c *Collection) QueryProjectStatsRedacted(q *vm.Query, attrs []string, stats *ScanStats) iter.Seq[[]classad.Value]

QueryProjectStatsRedacted is QueryProjectStats with QueryProjectRedacted's entitlement.

func (*Collection) QueryRaw

func (c *Collection) QueryRaw(q *vm.Query) iter.Seq[RawAd]

QueryRaw is Query, but yields each matching ad as RawAd (AST-free) instead of a *classad.ClassAd. It uses the same index/scan machinery -- an indexed lookup still visits only candidate ads -- so it does not regress selective queries. Inline-name (persistent) collections have no intern table, so QueryRaw yields nothing for them; callers that must support those should use Query.

func (*Collection) QueryRawFromSeq added in v0.29.5

func (c *Collection) QueryRawFromSeq(q *vm.Query, projection []string, after SeqCursor, limit int) (iter.Seq[RawAd], *SeqPage)

QueryRawFromSeq yields the records matching q that sort after the cursor, in (shard, seq, key) order, at most limit of them, projected to the named attributes. A nil query matches everything; an empty projection keeps the whole ad. It is the paginated form of QueryRaw: successive calls, each handed the previous page's Next cursor, visit every record exactly once.

The zero cursor starts at the beginning. Each shard is frozen at the sequence it had when its first page was taken, and is finished before the next shard is opened — so a record written during pagination is invisible if its shard had already started, and visible if it had not. That is the guarantee Scan already makes, which is likewise per shard.

A shard's snapshot stays readable for Options.SeqCursorLease after it is taken. A cursor resumed after maintenance has reclaimed versions its snapshot sees is refused rather than read short: the page yields nothing and its Err wraps ErrSeqCursorExpired (seqlease.go).

It reads the way a query does, only in a different order: a segment index that can serve the constraint narrows each segment to its candidates, the columns are asked before a record is rebuilt, and a projection the columns can serve is built from them (refVisitor). None of that changes which records match or the order they come in -- the candidates of a segment are a subset of its records in their arena order -- so the pages are the ones the whole walk gives. More may differ: it is set when the page is full and another CANDIDATE follows, which is a record the walk would have reached too, so it still never reports false while a match remains.

limit <= 0 means no limit, in which case More is always false.

It is an ENTITLED read: private attributes are kept and sealed values are opened. A caller serving anyone not entitled to them uses QueryRawFromSeqRedacted.

func (*Collection) QueryRawFromSeqRedacted added in v0.34.0

func (c *Collection) QueryRawFromSeqRedacted(q *vm.Query, projection []string, after SeqCursor, limit int) (iter.Seq[RawAd], *SeqPage)

QueryRawFromSeqRedacted is QueryRawFromSeq for a caller not entitled to secrets, redacted as QueryRawProjected redacts: private attributes are dropped, and the read holds no key, so a sealed value renders as undefined. The pages and cursors are the ones QueryRawFromSeq gives; only what a row carries differs.

func (*Collection) QueryRawProjected added in v0.16.3

func (c *Collection) QueryRawProjected(q *vm.Query, projection []string, chaseRefs, redact bool) iter.Seq[RawAd]

QueryRawProjected is QueryRaw with the same in-walk projection as ScanRawProjected (see there for chaseRefs/redact).

func (*Collection) QueryRawProjectedStats added in v0.29.0

func (c *Collection) QueryRawProjectedStats(q *vm.Query, projection []string, chaseRefs, redact bool, stats *ScanStats) iter.Seq[RawAd]

QueryRawProjectedStats is QueryRawProjected that also fills stats (may be nil) with the per-scan work breakdown, for EXPLAIN ANALYZE. Iterate the returned sequence to completion (or stop early) before reading stats; a partial iteration leaves partial counts.

func (*Collection) QueryRawRedacted added in v0.16.3

func (c *Collection) QueryRawRedacted(q *vm.Query) iter.Seq[RawAd]

QueryRawRedacted is QueryRaw with private (secret) attributes stripped from every yielded ad, using the intern table's precomputed per-id private flags (see wire.NewInternTableWithPrivacy): the redaction costs one bool check per attribute and private nodes are never rendered at all. Use it to serve a public query; QueryRaw preserves private attributes for trusted consumers (e.g. the negotiator's private-ad query).

func (*Collection) QueryRawWire added in v0.16.4

func (c *Collection) QueryRawWire(q *vm.Query, projection []string, redact bool) iter.Seq[[]byte]

QueryRawWire is ScanRawWire restricted to ads matching q.

func (*Collection) QueryRawWireRefs added in v0.33.2

func (c *Collection) QueryRawWireRefs(q *vm.Query, projection []string, redact bool) iter.Seq[[]byte]

QueryRawWireRefs is ScanRawWireRefs restricted to ads matching q.

func (*Collection) QueryRawWireRefsStats added in v0.33.2

func (c *Collection) QueryRawWireRefsStats(q *vm.Query, projection []string, redact bool, stats *ScanStats) iter.Seq[[]byte]

QueryRawWireRefsStats is QueryRawWireRefs that also fills stats (may be nil) with the per-scan work breakdown.

func (*Collection) QueryRawWireStats added in v0.32.0

func (c *Collection) QueryRawWireStats(q *vm.Query, projection []string, redact bool, stats *ScanStats) iter.Seq[[]byte]

QueryRawWireStats is QueryRawWire that also fills stats (may be nil) with the per-scan work breakdown. Iterate the returned sequence to completion (or stop early) before reading stats; a partial iteration leaves partial counts.

func (*Collection) QueryRedacted added in v0.28.0

func (c *Collection) QueryRedacted(q *vm.Query) iter.Seq[*classad.ClassAd]

QueryRedacted is Query for a reader NOT entitled to sealed values: the decode holds no key, so a sealed attribute comes back undefined rather than opened (see wire.DecodeResolveEncRedact).

This is the full-decode counterpart of QueryRawRedacted. Query decodes with the collection's key and leaves it to the SERIALIZER to drop private attributes -- so the secret was decrypted in this process for every unentitled read and then filtered on the way out. A caller that is not entitled to a value should not be able to obtain it, rather than obtain it and be trusted to drop it.

func (*Collection) RecordDemand added in v0.6.0

func (c *Collection) RecordDemand(probes []vm.Probe)

RecordDemand notes the attributes a constraint filters on (for SuggestIndexes) without running a scan. Query records demand automatically; this is for callers that filter outside the normal scan path -- e.g. cross-table MATCH applying a resource-side (WHERE TARGET) constraint to already-matched candidates -- so those attributes still surface as index suggestions.

func (*Collection) RefreshHotSet

func (c *Collection) RefreshHotSet(sampleMax, topN int) int

RefreshHotSet samples up to sampleMax live ads, tallies how often each attribute appears, and installs the topN most common attributes as the hot set used to front-load future writes' hot headers. It counts attribute ids directly from the wire form (no full decode). Existing ads keep the hot header they were written with; because daemons rewrite ads periodically, the population's hot headers converge on the refreshed set over time.

Returns the number of attributes chosen. A no-op (returns 0) when there are no ads yet.

func (*Collection) Reindex

func (c *Collection) Reindex()

Reindex (re)builds the per-segment value/categorical indexes for every live segment, covering all records written so far. It reads only immutable segment bytes, so it runs off the write path and does not block writers or compaction. Call it on whatever schedule you like: queries use whatever coverage exists and full-scan the rest, so Reindex only affects query speed, never results.

Reindex also reconciles segments with the current index configuration: a segment indexed before an AddIndex is rebuilt so the new attribute is backfilled, and one indexed before a DropIndex is rebuilt (or, if nothing is indexed anymore, its index is dropped) so the removed attribute's postings are reclaimed. A whole span of segments therefore evolves toward the current spec at whatever cadence the caller reindexes — no write-path or compaction coupling.

With Options.IndexBackfillBytes set, rebuilding an already-sealed segment for a configuration change is confined to the newest IndexBackfillBytes; BackfillIndexes and ReindexAll carry it further.

func (*Collection) ReindexAll added in v0.33.0

func (c *Collection) ReindexAll() IndexBackfillResult

ReindexAll is Reindex with no backfill bound: every sealed segment ends up covering every indexed attribute, however old. It is what an operator asking for a reindex means, and costs a decompression of every segment that lacks coverage -- for a large archive, a long time. The append path is not stalled for that long (see BackfillIndexes).

func (*Collection) ReleaseRead added in v0.33.0

func (c *Collection) ReleaseRead()

ReleaseRead balances an AcquireRead that returned true. The last reader out of a closed collection performs the deferred teardown, so this must be called with no collection or shard lock held.

func (*Collection) ReschemaScan added in v0.25.2

func (c *Collection) ReschemaScan(sampleMax, hotTopN int) bool

ReschemaScan derives a NEW schema from a fresh sample and adopts it as the committed one, unconditionally -- the deliberate counterpart of the maintenance review, which adopts a re-derivation only when the difference is material. Returns false if there was nothing to sample, leaving the existing schema in place.

What it does to existing segments:

  • Sidecar blocks (a segment whose records still hold every attribute) are rebuilt against the new schema before this returns, as they always were. Each block is replaced in place, so a concurrent query reads either the old block or the new one, never neither.
  • Columnarized segments hold their schema'd attributes ONLY in their payload, so adopting a new schema there means rewriting the segment. That is NOT done synchronously for the whole table: at archive scale it is hours of I/O behind one admin command. One budgeted pass runs here (ColumnarSegmentBudget segments) and routine maintenance converges the rest, the same budget per pass. Until a segment is rewritten it is read under the schema it was written with -- correct, only not yet accelerated for the new fields. SchemaScanInfo.StaleSegments reports how many remain.

The new schema is committed to disk before any segment is touched, so a restart mid-convergence resumes converging toward it rather than reverting to the old one.

func (*Collection) Retention added in v0.19.0

func (c *Collection) Retention() Retention

Retention returns the current retention bounds.

func (*Collection) RetrainDict

func (c *Collection) RetrainDict(sampleMax int) (int, error)

func (*Collection) Rewrite added in v0.6.0

func (c *Collection) Rewrite() int

Rewrite re-encodes every live ad with the current hot set (and match closure) so a changed hot set takes effect on existing ads, not just future writes, then force-compacts every shard to reclaim the superseded pre-rewrite records. Returns the number of ads rewritten.

It re-Puts ads on the normal write path, so it is a maintenance operation: an update to a key that races the rewrite may be overwritten by the pre-rewrite value. Run it during low write activity (or, in an HA deployment, on the sole writer).

func (*Collection) Rotate added in v0.17.0

func (c *Collection) Rotate(now float64) (int, error)

Rotate drops whole oldest segments until the append-only collection is back within its Retention bounds, returning the number of segments dropped. now is the caller's wall clock (unix seconds) for age-based retention -- the store keeps no clock of its own -- and is ignored unless Retention.MaxAgeAttr/MaxAge are set. Rotate is a no-op (returns 0) on a non-append-only collection or when Retention is the zero value.

The segment still being appended to is never dropped, so Rotate can bound a growing archive without racing the writer. A dropped segment's file is unmapped and unlinked once no in-flight scan still pins it (a scan that started earlier keeps reading a consistent snapshot until it finishes; the reclaim is deferred to its last unpin).

Retention honors MaxSegments, MaxBytes, and MaxAgeAttr/MaxAge (drop a segment whose newest value of the age attribute is older than now-MaxAge); MaxAge requires the age attribute to be a configured ZoneAttr so its per-segment max is available.

func (*Collection) RowGroupBytes added in v0.28.1

func (c *Collection) RowGroupBytes() int

RowGroupBytes reports the budget currently in effect (0 meaning the default).

func (*Collection) SaveDemand added in v0.25.0

func (c *Collection) SaveDemand()

SaveDemand checkpoints query demand to the collection's directory, decaying it first by the time since the last checkpoint. Call it from maintenance; it is a no-op on an in-memory collection.

Best-effort by design, as for the other sidecar metadata: a failed write costs the interval's demand, not correctness. Nothing reads this file except a later restore, and a restore that finds it missing or unparseable simply starts from what it has.

func (*Collection) Scan

func (c *Collection) Scan() iter.Seq[*classad.ClassAd]

Scan returns an iterator over every ad in the collection. It is scan-exactly- once: each key present at the moment a shard's scan begins is yielded exactly once (never duplicated, never skipped), even while concurrent updates and compaction run. An ad updated mid-scan is seen at whichever version was current when that shard's scan started.

func (*Collection) ScanColumns added in v0.37.0

func (c *Collection) ScanColumns(q *vm.Query, attrs []string, fn func(*Batch) bool) (ColumnScanStats, bool)

ScanColumns calls fn with the values of attrs for every visible record matching q, in batches.

ok=false means this collection cannot serve the query from columns at all -- no accelerator, a non-native query, nothing asked for -- and the caller should scan as before. It is decided before any batch is produced, so ok=false always comes with no callback having run.

Within a served query every tier produces values, including a window with no columnar block and a block the vector executor declines. A tier that contributed no rows would be a result silently missing records, which is worse than a slow one.

fn returning false stops the scan early; that is a caller's decision and still reports ok=true, with Rows counting what it was given.

func (*Collection) ScanColumnsRedacted added in v0.37.0

func (c *Collection) ScanColumnsRedacted(q *vm.Query, attrs []string, fn func(*Batch) bool) (ColumnScanStats, bool)

ScanColumnsRedacted is ScanColumns for a reader not entitled to sealed values: the constraint is rewritten so a sealed attribute is undefined to it (see keylessQuery), and a sealed cell is produced as ValueError rather than opened.

A sealed value is never stored as a column, so a column read cannot leak one; the record tier reads it unopened, which is where the refusal has to hold.

func (*Collection) ScanRaw

func (c *Collection) ScanRaw() iter.Seq[RawAd]

ScanRaw is Scan, yielding every ad as RawAd (AST-free).

func (*Collection) ScanRawProjected added in v0.16.3

func (c *Collection) ScanRawProjected(projection []string, chaseRefs, redact bool) iter.Seq[RawAd]

ScanRawProjected is ScanRaw restricted to the projected attribute names, applied INSIDE the wire walk: the projection is resolved to interned ids once per scan, and each ad is walked as raw (id, node) pairs -- a non-projected attribute costs one id comparison and a TLV length hop, and is never name- resolved or rendered. For a typical monitoring projection (10-20 attributes of a several-hundred-attribute ad) this skips the overwhelming majority of the per-ad decode work that a decode-everything-then-filter projection pays.

chaseRefs additionally resolves each emitted expression's attribute references against the same ad (transitively, per ad -- an "elevator" of linear passes that repeats only while new references surface), so a projected ad evaluates self-contained. HTCondor's query protocol sends exactly the requested attributes, so a protocol-compatible server passes false.

It applies to both representations: an interned collection resolves references by id, a persistent (inline-name) one by name.

redact strips private attributes exactly as ScanRawRedacted does. An empty projection means no attribute filter (the whole ad, matching QueryRawProject semantics upstream). Inline-name collections yield nothing, as with ScanRaw.

func (*Collection) ScanRawProjectedStats added in v0.46.0

func (c *Collection) ScanRawProjectedStats(projection []string, chaseRefs, redact bool, stats *ScanStats) iter.Seq[RawAd]

ScanRawProjectedStats is ScanRawProjected that also fills stats (may be nil) with the scan's work breakdown and, when stats.Phases is set, its phase timings.

func (*Collection) ScanRawRedacted added in v0.16.3

func (c *Collection) ScanRawRedacted() iter.Seq[RawAd]

ScanRawRedacted is ScanRaw with private attributes stripped (see QueryRawRedacted).

func (*Collection) ScanRawWire added in v0.16.4

func (c *Collection) ScanRawWire(projection []string, redact bool) iter.Seq[[]byte]

ScanRawWire yields each ad as a WIRE-FORM ROW: a self-contained inline-names ad holding only the selected entries, assembled by slice copies from the stored bytes (see wire.AppendAdSubsetInline) -- nothing is decoded or rendered here. It is the relay scan for shipping a persistent table's ads across a process boundary (dbrpc) with the old-ClassAd render deferred to the far edge (RenderRawAdInline); the consumer needs no intern table and no data key (at-rest-encrypted values are opened during assembly).

projection restricts the entries to the named attributes (case-insensitive; MyType/TargetType always ship so the ad stays typed); empty means every entry. redact drops private attributes -- pre-pruned from a projection, or tested per entry with a byte-gated predicate for the whole-ad case. The yielded row aliases a buffer reused across the iteration.

An IN-MEMORY collection serves this scan too. Its records are not self-contained as stored -- their keys are ids against the shared intern table -- but the difference from the persistent form is only how names are spelled, so the row is assembled by rewriting those ids back to names as it is built (see appendWireRow). Refusing RAM tables here was a property of the first implementation, not of what they store.

func (*Collection) ScanRawWireRefs added in v0.33.2

func (c *Collection) ScanRawWireRefs(projection []string, redact bool) iter.Seq[[]byte]

ScanRawWireRefs is ScanRawWire whose projection is closed under the projected expressions' own attribute references, so each row evaluates self-contained at the far end. An empty projection already ships every attribute and behaves exactly like ScanRawWire.

func (*Collection) ScanRawWireRefsStats added in v0.46.0

func (c *Collection) ScanRawWireRefsStats(projection []string, redact bool, stats *ScanStats) iter.Seq[[]byte]

ScanRawWireRefsStats is ScanRawWireRefs that also fills stats (may be nil) with the scan's work breakdown and, when stats.Phases is set, its phase timings.

func (*Collection) ScanRawWireStats added in v0.46.0

func (c *Collection) ScanRawWireStats(projection []string, redact bool, stats *ScanStats) iter.Seq[[]byte]

ScanRawWireStats is ScanRawWire that also fills stats (may be nil) with the scan's work breakdown and, when stats.Phases is set, its phase timings.

func (*Collection) SchemaFit added in v0.25.2

func (c *Collection) SchemaFit(sampleMax int) ([]SchemaFieldFit, int)

SchemaFit measures the current schema against a fresh sample of up to sampleMax records, reporting per-field escape rates and the number of records actually sampled.

It reads samples and re-runs the encoder's storability test on each; it encodes nothing and writes nothing. Returns nil when the accelerator is not enabled (there is no schema to judge) or there is nothing to sample.

func (*Collection) SchemaRequireAttrs added in v0.32.0

func (c *Collection) SchemaRequireAttrs() []string

SchemaRequireAttrs returns the effective required-attribute set: the attributes that enter the derived schema regardless of how often they appear. Folded, sorted, deduplicated.

func (*Collection) SchemaRequireRuntimeAttrs added in v0.32.0

func (c *Collection) SchemaRequireRuntimeAttrs() []string

SchemaRequireRuntimeAttrs returns only the entries added at runtime (AddSchemaRequireAttrs), which is the tier an embedding application persists -- the configured tier comes back from its own configuration on the next open, and persisting it too would freeze a config change out.

func (*Collection) SchemaRequireSkipped added in v0.32.0

func (c *Collection) SchemaRequireSkipped() []SchemaRequireSkip

SchemaRequireSkipped returns the required attributes the last schema derivation refused.

func (*Collection) SchemaScanInfo added in v0.23.1

func (c *Collection) SchemaScanInfo() SchemaScanInfo

SchemaScanInfo returns the columnar accelerator's current state (see SchemaScanInfo).

func (*Collection) SealsValues added in v0.35.0

func (c *Collection) SealsValues() bool

SealsValues reports whether any stored value can be sealed: a key, and a persistent collection. An in-memory collection may hold a key but never seals -- its records are interned against the shared table and encoded without one -- so a reader not entitled to sealed values is withheld nothing there.

func (*Collection) SegmentProfiles added in v0.40.1

func (c *Collection) SegmentProfiles() []SegmentProfile

SegmentProfiles reports the retention profile of every sealed segment, oldest segment first. Diagnostic only.

func (*Collection) SetEncryptedAttrs added in v0.7.0

func (c *Collection) SetEncryptedAttrs(attrs []string) error

SetEncryptedAttrs replaces the explicit encrypted-attribute set at runtime (the toggle meta-command). It is a no-op-with-error if encryption is disabled, and errors if any named attribute is currently indexed (an encrypted value is opaque, so it cannot be indexed). Private attributes are always encrypted regardless of this set. The named attributes' values must not refer to other attributes; see Options.EncryptedAttrs. New records use the new set immediately; existing records keep their prior form until MigrateSealedAttrs rewrites them. Compaction does not: it copies stored values as they are. The migration's marker records the set it ran under, so the next pass after a change runs it. Reads not entitled to sealed values withhold every attribute the set names from the moment it is installed, whatever form a record stores it in (see hidesClearSealed).

func (*Collection) SetGCFloor added in v0.21.4

func (c *Collection) SetGCFloor(floor float64)

SetGCFloor installs a runtime GC watermark, in Retention.MinAgeAttr units, that lets Rotate reclaim already-consumed records EARLY: a segment whose newest MinAgeAttr value is below floor may be dropped before it reaches MaxAge. It is how a change-feed source drains records every live subscriber has acknowledged (floor is the feed's GC floor, i.e. the min ack over live subscribers). It only ever shortens retention -- it can never keep data past the configured ceilings (a slow or absent subscriber holds a low floor, so its data simply ages out under MaxAge), and it never drops anything younger than Retention.MinAge. Requires MinAgeAttr set (and zone-mapped). Passing floor <= 0 clears it. Not persisted -- callers re-assert it each pass from the current live floor; a stale saved value must never GC data across a restart.

func (*Collection) SetRetention added in v0.19.0

func (c *Collection) SetRetention(r Retention)

SetRetention updates the retention bounds at runtime (an append-only collection). The next Rotate enforces them. Serialized against Rotate/maintenance via maintMu, so c.ret is only ever read or written under that lock.

func (*Collection) SetRowGroupBytes added in v0.28.1

func (c *Collection) SetRowGroupBytes(n int)

SetRowGroupBytes changes the uncompressed record-bytes budget for a columnar row group. 0 restores the default.

Safe on a live collection, and it needs no reconciliation pass: every block records the layout it was written with, so a new budget governs row groups sealed from now on while everything already on disk keeps reading exactly as before. That is what makes this tunable against a real archive rather than only at creation.

func (*Collection) SetSchemaRequireAttrs added in v0.32.0

func (c *Collection) SetSchemaRequireAttrs(names []string) bool

SetSchemaRequireAttrs replaces the CONFIGURED tier, leaving anything added at runtime in place. It reports whether the effective set changed.

A true return means the committed schema may no longer be the one this set produces. Nothing here acts on it -- a configuration reload must not start a rewrite of the table by itself. The next routine maintenance review (BuildAndEnableSchemaScan) re-derives the schema, adopts it when a required attribute the derivation admits is not yet a field, and converges the sealed segments onto it a budget's worth per pass. ReschemaScan adopts immediately.

func (*Collection) SetTimeTravel added in v0.12.0

func (c *Collection) SetTimeTravel(o *TimeTravelOptions)

SetTimeTravel enables, retunes, or (with a nil/zero option) disables point-in-time queries at runtime. Enabling starts recording checkpoints and retaining superseded versions from now on (it is not retroactive); disabling lets the next compaction reclaim the retained history. Safe to call concurrently with reads and writes.

func (*Collection) SetWatchRetain added in v0.38.3

func (c *Collection) SetWatchRetain(d time.Duration)

SetWatchRetain reconfigures Options.WatchRetain, so a server can change the window on a config reload rather than a reopen.

Widening it does not reach back: markers already reclaimed stay reclaimed, and delFloor records how far that went, so a cursor the old window had given up on is still refused rather than answered from a window that only looks wide enough.

func (*Collection) SidecarBytes added in v0.40.2

func (c *Collection) SidecarBytes() (segments int, mappedBytes int64)

SidecarBytes reports how many sealed segments carry a sidecar and how many bytes they map, without the MPH/bloom breakdown. That is the whole of the difference in cost: the totals are a length per segment off a pointer already in RAM, while the breakdown walks each sidecar's directory and reads two header words per categorical attribute. Those reads are scattered over a mapping that is only demand-paged, so on a large archive with a cold page cache they dominate -- roughly fifteen random faults per sealed segment, thousands of segments deep.

A caller that only prints "how much index is on disk" wants this one.

func (*Collection) SidecarSizes added in v0.8.0

func (c *Collection) SidecarSizes() SidecarSizes

SidecarSizes reports the live Collection's sealed-segment sidecar bytes: the mmap-backed index each sealed segment holds after the flip from the in-RAM segIndex -- a file mapping for a persistent collection (page-cache resident, evictable to disk) or an anonymous mapping for an in-memory one (off-heap, MADV_FREE-able to swap). Either way these bytes are NOT Go-heap memory, so they are reported apart from IndexSizes (which now measures only the active, still-in-RAM segments' postings). Together the two give the operator the full picture: heap postings on the hot active segment plus off-heap sidecar bytes on the sealed tail. It reads each segment's already-mapped bytes under the shard read lock -- no re-mapping.

The MPH/bloom breakdown costs more than the total does: it reads scattered header words out of every sealed sidecar, and on a cold page cache each of those is a fault that nothing else in a stats report needs. Ask SidecarBytes for the total alone.

func (*Collection) StaleIndexSegments added in v0.21.2

func (c *Collection) StaleIndexSegments() (stale, sealed int)

StaleIndexSegments reports sealed segments whose index was built under a superseded configuration and is still due a rebuild, out of the sealed segments total.

"Due a rebuild" is the operative part. With Options.IndexBackfillBytes set, Reindex deliberately carries a configuration change only to recent segments; older ones keep the index they have until BackfillIndexes reaches them, which on a large archive takes many passes. Counting those would leave the number non-zero for that long and say nothing about whether anything is wrong -- so they are excluded here and reported separately by StaleIndexSegmentsByPolicy (and, the ones missing an attribute, by IndexBackfillPending).

A persistent non-zero value from this therefore still means what it always meant: a reindex is failing, or never running.

func (*Collection) StaleIndexSegmentsByPolicy added in v0.25.0

func (c *Collection) StaleIndexSegmentsByPolicy() int

StaleIndexSegmentsByPolicy reports sealed segments left on a superseded index configuration because they fall outside the backfill horizon. Expected, not actionable: it is the size of the deliberate mixture. It includes segments that already cover every indexed attribute and differ only by postings for a dropped one, which nothing rebuilds; IndexBackfillPending counts the ones that are missing an attribute.

func (*Collection) StartAutoRetrain

func (c *Collection) StartAutoRetrain(interval time.Duration, sampleMax, hotTopN int) (stop func())

StartAutoRetrain runs periodic maintenance in a background goroutine every interval, until the returned stop function is called (stop blocks until the goroutine exits). Each tick:

  • retrains the ZSTD dictionary from a sample of up to sampleMax ads (RetrainDict), and
  • if hotTopN > 0, refreshes the hot-attribute set to the topN most common attributes (RefreshHotSet), so the store self-tunes which attributes it front-loads for fast queries.

Retrain errors (e.g. the pure-Go BuildDict declining a small/homogeneous corpus) are ignored — the previous codec keeps working.

Cost note: retraining recompacts every shard. Compaction is concurrent (the recompression runs without the shard lock), so writers and scanners are not blocked for its duration; only two brief per-shard critical sections take the lock. The 15-minute default still keeps the work rare.

func (*Collection) Stats

func (c *Collection) Stats() Stats

Stats returns a snapshot of the collection's storage. It takes each shard's read lock briefly, so it is safe to call concurrently with readers and writers.

func (*Collection) StopMaintenance added in v0.30.4

func (c *Collection) StopMaintenance()

StopMaintenance asks any maintenance pass running on this collection to stop at its next safe boundary. It does not wait, and it does not interrupt work already in progress on a single segment -- a pass abandoned mid-rewrite would be the one thing a caller must never do, since the shutdown that follows unmaps the segments a rewrite is still reading.

It exists because a maintenance pass is bounded but not short. The columnar budget caps a pass at 64 segment rewrites so a schema change converges over several passes instead of stalling on one, which keeps a pass unnoticeable in steady state -- but a caller closing the server waits for the pass in flight to finish, and on an archive at history scale that is tens of seconds of apparently-hung process after the logs say it stopped.

The abandoned work is not lost: every segment is rewritten at most once, so the backlog only shrinks, and the next pass after reopen picks up exactly where this one left off.

Once stopped a collection stays stopped; this is a shutdown signal, not a pause.

func (*Collection) StoredLen added in v0.38.0

func (c *Collection) StoredLen() int

StoredLen returns the number of live keys the store holds, system-keyed records included. It is what Stats reports as Ads, and it is the right figure for accounting what is on disk; Len is the right one for how many rows a reader sees.

func (*Collection) SuggestCompositeDrops added in v0.38.0

func (c *Collection) SuggestCompositeDrops() []CompositeDropSuggestion

SuggestCompositeDrops recommends composite indexes to remove: the ones no observed conjunction pins together, so the tuple they are keyed on is one nothing asks for. It is advisory, and it reports human-configured composites as well as auto-created ones -- only the caller knows whether a configured tuple is a policy to respect. AutoTune drops the auto ones and leaves the rest.

There is no low-cardinality analogue of the single-attribute rule. A composite is keyed on the tuple, so its cardinality is the tuple's, and a tuple of low-cardinality components can be the most selective key in the collection; the question of whether it prunes enough to be worth probing is already asked per query by compositeWins.

func (*Collection) SuggestComposites added in v0.38.0

func (c *Collection) SuggestComposites() []CompositeSuggestion

SuggestComposites recommends composite indexes from observed tuple demand. It is advisory: apply via Options.CompositeAttrs at creation, or let AutoTune apply it.

It takes no sample, unlike SuggestIndexes. A single-attribute suggestion has to profile the data to choose a KIND, and to establish that one literal kind dominates enough for an index to be worth building. A composite has neither question to answer: its components are already indexed -- that is a precondition, below -- so each one's kind is settled, and whether the tuple is selective enough to be worth probing is decided per query, at query time, by compositeWins. A composite the data does not suit is declined rather than used.

COMPONENTS FIRST. A tuple is suggested only once EVERY component is already indexed in its own right. The alternative -- suggesting the components alongside the tuple, so one pass creates all of it -- was not taken, for three reasons. newCompositeSpecs refuses a tuple whose component is unindexed, and it refuses it for a reason: everything the composite does not answer (one attribute alone, a range, a segment indexed before the composite existed) falls back to the components' own postings, and there has to be something to fall back to. A composite must therefore never be the reason an attribute is indexed, which is exactly what creating both at once would make it. And creating a composite bumps the index generation, so every sealed sidecar is rebuilt; doing that on the strength of demand that has been observed for one maintenance interval, in the same breath as committing to the component indexes, is a large bill for a young signal. Waiting costs one AutoTune pass, during which the demand either survives its decay or turns out not to have been there.

func (*Collection) SuggestDrops

func (c *Collection) SuggestDrops(sampleMax int) []DropSuggestion

SuggestDrops recommends configured indexes to remove, from observed query demand and a sample of up to sampleMax live ads. It flags two cases: an index no query has ever filtered on ("unused"), and one whose sampled values are effectively constant ("low-cardinality", ≤1 distinct value — the index cannot prune). It is advisory: apply via DropIndex. Demand is cumulative since the collection was created, so give a workload time to run before trusting "unused".

func (*Collection) SuggestIndexes

func (c *Collection) SuggestIndexes(sampleMax int) []IndexSuggestion

SuggestIndexes recommends value/categorical indexes from observed query demand and a sample of up to sampleMax live ads. It is advisory: apply the returned CategoricalAttrs/ValueAttrs via New (or a future dynamic Reindex). Attributes already indexed are not re-suggested. Results are ordered by demand, most first.

func (*Collection) SupportsRawWire added in v0.25.0

func (c *Collection) SupportsRawWire() bool

SupportsRawWire reports whether ScanRawWire/QueryRawWire can serve this collection. Every collection can: a persistent one stores inline names already, and an in-memory one's interned keys are rewritten to names while the row is assembled (see appendWireRow). It returned c.inline while that rewrite did not exist, and the relay scans then yielded nothing for a RAM table -- indistinguishable from a query that matched nothing, which is why the callers were made to check first. It is kept, always true, so those callers still compile and so a future storage form that genuinely cannot relay has somewhere to say so.

func (*Collection) TimeTravelConfig added in v0.12.0

func (c *Collection) TimeTravelConfig() (opts TimeTravelOptions, enabled bool)

TimeTravelConfig reports the collection's current time-travel settings and whether it is enabled (for persisting the runtime toggle; see db.saveIndexConfig).

func (*Collection) TopKOrderThreshold added in v0.29.4

func (c *Collection) TopKOrderThreshold(q *vm.Query, orderAttr string, desc bool, k int, stats *ScanStats) (threshold float64, seen int, ok bool)

TopKOrderThreshold computes the cutoff order value for ORDER BY orderAttr {DESC|ASC} LIMIT k over the records matching q: the k-th largest (desc) or k-th smallest (asc). It returns (threshold, seen, ok): seen is the number of matching records with a numeric order value, and ok reports whether the columnar path could serve the request at all (same gate as NumStatsQuery: accelerator on, orderAttr a numeric schema field, q a conjunction of scalar numeric comparisons).

The threshold is meaningful only when seen > k (the keep filled); at seen <= k there are k or fewer rows and the caller should just fetch them directly.

stats (may be nil) records the cutoff scan's work for EXPLAIN ANALYZE: which records were read from columns vs reassembled by the active-segment fallback, and how many matched -- the same ScanStats a projected scan reports, so the top-K path is no longer invisible to the diagnostic.

func (*Collection) TopKOrderThresholdRedacted added in v0.35.0

func (c *Collection) TopKOrderThresholdRedacted(q *vm.Query, orderAttr string, desc bool, k int, stats *ScanStats) (threshold float64, seen int, ok bool)

TopKOrderThresholdRedacted is TopKOrderThreshold for a reader NOT entitled to sealed values. The cutoff reads only literals, never a sealed value, so it is TopKOrderThreshold's -- except on a store that may hold a sealed attribute's values in the clear (see hidesClearSealed): there an order attribute the policy seals declines, and the constraint is planned as that reader evaluates it (keylessQuery).

func (*Collection) TrackedKeys added in v0.30.0

func (c *Collection) TrackedKeys() int

TrackedKeys reports how many keys the delta tracker holds. The tracker is the one new in-memory structure delta records add -- one small entry per key that has been written -- so this is what an operator checks when asking what the feature costs in RAM, and what a test checks to confirm the bound is doing something.

func (*Collection) Truncate added in v0.7.0

func (c *Collection) Truncate()

Truncate removes every ad from the collection, leaving it empty (an in-place reset used by a DB restore before it reloads a snapshot). It resets each shard's directory and count and retires its segments -- RAM segments are dropped for the GC; persistent segments are munmap'd + unlinked once no in-flight scan references them (the compaction pin/reap protocol). A concurrent scan that already captured its window reads the old data safely until it finishes; scans and writes that start after Truncate see an empty collection. Ordered indexes are cleared in place. Callers needing atomicity against concurrent writers must serialize Truncate with them (the db layer holds its DB-wide lock); at the shard level Truncate is itself consistent.

Watchers: the removal is too large to journal as per-key deletes (and the keys are gone), so every watcher that could otherwise miss it gets a Reset instead. Per shard, in the critical section that commits the truncate at seq T, the resume floor moves to T -- the delete journal's horizon for a mutable shard, the append floor for an append-only one -- so a cursor below T (issued before the truncate) is too old to resume and gets a Reset and a full snapshot, while a cursor at or past T resumes normally. Every attached watcher is told to resync (WatchResync) in the same critical section, before any later commit to the shard can publish, so no live cursor can advance past T on a watcher that has not seen the truncate. T carries no events and is not tracked for publication, so it holds no later cursor back. See docs/WATCH.md.

func (*Collection) Update

func (c *Collection) Update(batch []AdUpdate) error

Update applies a batch of inserts/updates and returns only once every ad is committed and visible to new scans. Ads are encoded (and compressed) outside the shard locks; each affected shard then applies its updates under one lock acquisition at a single new commit sequence.

func (*Collection) UpdateOld

func (c *Collection) UpdateOld(batch []OldAdUpdate) error

UpdateOld applies a batch of inserts/updates whose ads arrive in old-ClassAd form. It encodes each ad directly to the wire form, attribute by attribute, without materializing an intermediate ast.ClassAd: scalar-literal attributes (the common case) are written straight to wire, and only genuinely computed values are parsed with the expression parser. This is the efficient path for ads read from a socket. Commit semantics match Update.

func (*Collection) VectorEvalCount added in v0.27.0

func (c *Collection) VectorEvalCount(q *vm.Query) (int, bool)

VectorEvalCount counts records satisfying q, evaluating it a column at a time.

ok=false only when there is no columnar state at all; individual blocks that cannot be vectorized are served by colScope, and segments without a block by a row walk, so the answer is always complete.

func (*Collection) VerifyDictFiles added in v0.42.0

func (c *Collection) VerifyDictFiles() []DictFault

VerifyDictFiles checks every dictionary file against what the store loaded, rewrites any whose directory entry has gone, and reports what it found. An empty result is the healthy answer.

Maintenance calls this on its own (see beginMaint), rate-limited by dictVerifyInterval; this entry point runs the check immediately and is what a daemon with its own schedule, or an operator with a question, should use.

Every fault is also delivered to Options.OnDictFault as it is found, so a caller that wants to log rather than poll does not have to call this at all.

func (*Collection) VerifyingReads added in v0.31.4

func (c *Collection) VerifyingReads() bool

VerifyingReads reports whether this collection checks each record's stored checksum before using its bytes. It is true for a persistent collection unless Options.DisableReadVerification was set, and always false in memory.

Exported so a daemon can state which mode it is running in rather than inferring it from its own configuration parsing, which is the sort of thing that drifts.

func (*Collection) Watch added in v0.4.0

func (c *Collection) Watch(ctx context.Context, cursor []byte) (iter.Seq[WatchEvent], error)

Watch replays everything that may have changed since cursor (nil ⇒ a full replay from empty), then streams live changes until ctx is cancelled or the consumer stops. Requires Options.WatchHistory > 0. See docs/WATCH.md and WatchEvent.

func (*Collection) WatchCursor added in v0.7.0

func (c *Collection) WatchCursor() ([]byte, error)

WatchCursor returns an opaque cursor pointing at the current head of the change log, so a subsequent Watch(ctx, cursor) streams only changes from now on -- no initial replay of the current contents. Requires Options.WatchHistory > 0. It only snapshots each shard's commit sequence (no registration, no replay), so it is cheap.

func (*Collection) WatchRedacted added in v0.28.0

func (c *Collection) WatchRedacted(ctx context.Context, cursor []byte) (iter.Seq[WatchEvent], error)

WatchRedacted is Watch for a watcher NOT entitled to sealed values: every event's ad is decoded with no key, so a sealed attribute arrives undefined rather than opened. See Collection.QueryRedacted.

A watch streams ads continuously, so it is the read path with the longest exposure: decoding with the collection's key and trusting the serializer to drop private attributes means the secret is opened for every event of every unentitled watcher.

func (*Collection) WatchWatermark added in v0.38.3

func (c *Collection) WatchWatermark() uint64

WatchWatermark is the collection's closed watch clock: every change at or below it has been handed to every attached watcher, and no later change will be stamped at or below it. It is the version a catch-up has caught up TO, and the one value here that is both comparable across shards and non-decreasing in delivery order.

It is the minimum over the shards, because a change is only covered when EVERY shard has published past it. That makes an idle shard the limit: one with nothing to publish would otherwise pin the whole collection at its last write. A shard with nothing in flight is therefore advanced to the current reading first -- safe because its next commit takes a stamp past whatever it was advanced to, under the same lock.

Returns 0 when the collection has no watch (Options.WatchHistory == 0).

func (*Collection) ZoneAttrs added in v0.21.2

func (c *Collection) ZoneAttrs() []string

ZoneAttrs returns the attributes this collection keeps per-segment [min,max] zone maps on, in configuration order (explicit ZoneAttrs first, then the value-indexed attributes that are zoned automatically). Empty when none are configured. Diagnostic only -- it is how `.indexes` on an archive can show which range queries prune whole segments rather than only postings.

type Column added in v0.37.0

type Column struct {
	Name string
	Kind []ValueKind
	Num  []int64
	Str  []string
}

Column is one attribute's values for the rows of a Batch, in row order.

Kind, Num and Str are parallel and all of length Batch.N. Num carries an Int verbatim, a Bool as 0 or 1, and a Real as math.Float64bits -- which is how both classad.Value and the columnar block already store one, so a real reaches a consumer without a conversion in between. Int, Float, Bool and Text read a cell without the caller needing to know that.

func (*Column) Bool added in v0.37.0

func (c *Column) Bool(i int) bool

func (*Column) Float added in v0.37.0

func (c *Column) Float(i int) float64

func (*Column) Int added in v0.37.0

func (c *Column) Int(i int) int64

Int, Float, Bool and Text read cell i in its natural Go type. Each answers for the kind it names and a zero value otherwise; a caller that cares which it has reads Kind first.

func (*Column) Text added in v0.37.0

func (c *Column) Text(i int) string

type ColumnScanStats added in v0.37.0

type ColumnScanStats struct {
	Rows int // rows handed to the callback

	// ColumnCells and RecordCells are counted per CELL rather than per row, because a projection
	// mixes the two: a block hands over the columns its schema carries and the rest comes from the
	// record. Counting per row would have to pick one for a mixed row and would then report a
	// projection that reads six columns and one cold attribute exactly like one that reads seven
	// cold attributes.
	ColumnCells int // cells read from the block's columns
	RecordCells int // cells read from the record's own wire form

	// RecordReads is the number of records materialized from the wire -- the cost RecordCells
	// implies, paid once per row however many of its cells come from it.
	RecordReads int

	VectorBlocks int // the predicate ran as a vector over the block's columns
	ScopeBlocks  int // the executor declined this block; the predicate ran per record
	ChurnBlocks  int // mostly superseded, so per-record evaluation is cheaper
	PrunedBlocks int // a zone or dictionary ruled the block out
	EmptyBlocks  int // nothing in the block was visible to this snapshot
	RowWindows   int // no columnar block: the active segment, or one not yet columnarized
	PrunedSegs   int // the segment zone map ruled the whole window out

	// Unreadable counts records the predicate matched from the columns but whose own bytes
	// could not then be materialized. The predicate tiers already treat such a record as not
	// matching; counting it here keeps that from being a row that quietly went missing.
	Unreadable int

	// Phases, when non-nil, receives where the scan's wall time went, as ScanStats.Phases does.
	// Not on any wire. ScanColumns returns its counts by value and never sets this; a caller that
	// times a column scan carries it beside the counts it gets back.
	Phases *QueryPhases `json:"-"`
}

ColumnScanStats records which tiers answered, in the shape vecSplit records it for the count.

It is here for the reason vecSplit is there: a producer that quietly read every value from the records instead of the columns would return exactly the right answer, at the speed of the path it was built to replace, and nothing in the result would say so. ColumnRows and RecordRows are that question asked directly.

type CommitResult added in v0.6.0

type CommitResult struct {
	Committed int
	Conflicts [][]byte
	Unapplied [][]byte
	// UnappliedReasons is parallel to Unapplied: why each key could not be composed. A dropped
	// key reported without a reason is a bare fact with no action attached -- an operator reading
	// it had to go to the daemon ad's counters and correlate by hand.
	UnappliedReasons []string
	// UnappliedErrs is parallel to Unapplied: the error behind each key, or nil where the reason
	// alone says it. A refused write's error (ErrTooDeep, naming the attribute) is kept so a caller
	// can match it with errors.Is.
	UnappliedErrs []error
}

CommitResult reports a transaction's outcome. Conflicts holds the keys whose write lost a write-write race and were not applied; the caller may re-read and retry just those. The other buffered writes committed.

Under Txn.SetAtomic(true) the batch is all-or-nothing instead: Committed is either the whole batch or 0, and on an abort Conflicts names every key that conflicted (nothing was applied, so there is nothing else to report).

Unapplied is the OTHER kind of not-applied, and the distinction is the point: those writes could not be composed at all, and re-applying the identical write cannot change that. A patch whose stored base is unreadable is one case -- the key is present but the record behind it will not come back (a delta chain that no longer materializes, a segment that went away), so there is nothing to merge the patch onto. A write whose value nests too deeply to store (ErrTooDeep) is the other: nothing of it is written, and any earlier write to the same key in this transaction is dropped with it, so the key keeps exactly what it held before.

Reporting those as Conflicts made a caller that retries conflicts loop forever. On a production mirror each one rewound the tailer, re-applied, failed identically, and after three attempts escalated to a full 460-second replay of a 923 MB log that wrote nothing -- 285 times, which is why the mirror could never catch up. A caller must be able to tell "try again" from "this will never work"; nothing else about the commit changes.

func (CommitResult) Conflicted added in v0.6.0

func (r CommitResult) Conflicted() bool

Conflicted reports whether any buffered write lost a conflict.

func (CommitResult) HasUnapplied added in v0.30.2

func (r CommitResult) HasUnapplied() bool

HasUnapplied reports whether any buffered write could not be composed at all. Retrying it is futile; the caller should record it and make progress.

type CompactUndecodable added in v0.34.0

type CompactUndecodable struct {
	Dir     string // the collection's directory ("" in memory)
	Shard   int    // the shard's index
	Key     string // the record's key
	Err     string // why it could not be decoded or read
	Blocked bool   // true: the record could not be read and the shard was left uncompacted; false: copied unchanged
}

CompactUndecodable describes one record compaction could not re-encode.

type CompositeDropSuggestion added in v0.38.0

type CompositeDropSuggestion struct {
	Attrs []string // the components in canonical casing, in the composite's own order
	Label string   // the tuple as IndexSizes names it: "ClusterId+ProcId"
	Auto  bool     // created by the auto-tuner; only these are ever auto-dropped
	// Reason is "unused" -- the only reason there is. A composite is reported here when NO
	// observed conjunction pins its components together, counting the ones that pin a
	// superset of them (compositeDemand), so there is no count worth carrying: it is zero.
	Reason string
}

CompositeDropSuggestion recommends removing one configured composite, with the rationale.

type CompositeRefusal added in v0.38.1

type CompositeRefusal struct {
	// Attrs is the tuple exactly as it was configured, including spelling and order.
	Attrs []string `json:"attrs"`
	// Reason is one of the CompositeRefused* constants below.
	Reason string `json:"reason"`
	// Attr is the component at fault for the reasons that name one, and empty for the
	// reasons that are about the tuple as a whole. Only the FIRST offending component is
	// named: resolution stops at it, so a second one has not been looked at.
	Attr string `json:"attr,omitempty"`
}

CompositeRefusal is one configured composite tuple that was not installed, and why.

It exists because the failure it describes has no other symptom. A refused tuple does not break the store and does not fail the open: the table comes up, the queries that were meant to use the composite still answer correctly, and they answer by intersecting postings or by scanning. The only thing an operator sees is that something got slower, with nothing anywhere to point at -- which is how a typo in a component name, or dropping an index some composite depended on, survives for months.

WHAT A CALLER IS EXPECTED TO DO WITH IT. Log it at open and treat a non-empty slice as a configuration bug to fix in the configuration, not as a condition to handle at runtime. There is nothing to retry and nothing to repair: the store is already as configured, minus the tuple. Fixing the spelling (or restoring the component's index, or declaring it component-only) and reopening installs the composite. An empty slice is the normal state and the only one worth alerting on the absence of.

It is deliberately NOT an error. A collection's configuration is applied in New, which cannot fail, and again on every reopen of a persistent store -- so a refusal raised as an error would either have to be unreportable in the in-memory tier or stop an existing deployment from opening its own data because a tuple in its saved configuration stopped resolving. Turning a missing index into a refusal to start is the worse failure of the two.

func (CompositeRefusal) String added in v0.38.1

func (r CompositeRefusal) String() string

String renders a refusal as one log line: "ClusterId+ProcId: unresolvable-component ProcId".

type CompositeSuggestion added in v0.38.0

type CompositeSuggestion struct {
	// Attrs is the tuple in canonical (first-seen) casing, in the order the composite
	// would be created: the folded names sorted. Order is part of a composite's identity
	// but not of what it answers, so the order here is the one that makes the same tuple
	// from the same demand every time rather than one read off a query.
	Attrs []string
	// Queries is the conjunctions observed pinning exactly this tuple. A conjunction
	// pinning a SUPERSET of it demands its own, wider tuple and is counted there; it is
	// also demand this composite could serve, which is what keeps it from being dropped
	// (compositeDemand), but it is not a reason to create this one.
	Queries int64
}

CompositeSuggestion recommends a composite index over an attribute tuple, with the rationale (how many conjunctions pinned exactly that tuple) so the decision is explainable, as IndexSuggestion is for a single attribute.

type ConjunctExplain added in v0.6.0

type ConjunctExplain struct {
	// Text is the conjunct rewritten over the slot (job refs baked, TARGET scope dropped).
	Text string `json:"text"`
	// Probed is true when the conjunct is covered by an active index probe -- it prunes
	// the candidate set before the bilateral re-verify.
	Probed bool `json:"probed"`
	// Indexed is true when the conjunct's selectivity is estimable from an index (a
	// superset of Probed: it also covers bare boolean flags, which are estimable via
	// `attr == true` but are not extracted as pushdown probes).
	Indexed bool `json:"indexed"`
	// HasSelectivity reports whether TrueFrac is populated.
	HasSelectivity bool `json:"hasSelectivity"`
	// TrueFrac is the estimated fraction of slots for which the conjunct holds.
	TrueFrac float64 `json:"trueFrac"`
	// ResourceSide is true for a conjunct that came from the MATCH's resource-side filter
	// (WHERE TARGET / NOPREEMPT) rather than the job's Requirements. It is applied to
	// matched candidates as a post-filter, so it re-checks rather than prunes today.
	ResourceSide bool `json:"resourceSide,omitempty"`
}

ConjunctExplain is one top-level && conjunct in the match's evaluation order.

type DictFault added in v0.42.0

type DictFault struct {
	ID   uint32
	Path string
	Kind DictFaultKind
	// Repaired is true when a missing file was rewritten from the open descriptor. The
	// records were never at risk while this process lived; the next one would have lost
	// them.
	Repaired bool
	// Preserved is where the dictionary this store loaded can still be found, after a
	// fault showed the file at its own path is no longer it. It may be a copy this check
	// wrote (dicts/backup/) or one it found already there -- the attic, or a segment
	// carrying a replica. Empty when nothing was preserved and nothing needed to be.
	Preserved string
	// Segments is how many segment files reported this fault, when it is one a whole
	// store's worth of segments can report at once (DictFaultMismatch). 0 otherwise.
	Segments int
	// From is the segment file a repaired copy came out of, when the dictionary was not
	// rewritten from the open descriptor but found in a segment trailer at Open. Empty
	// otherwise.
	From string
	// Err is why a repair was not possible, or why the check itself could not finish.
	Err error
}

DictFault is one dictionary file that is no longer what the store loaded. It implements error so it can be handed to Options.OnDictFault, and carries the detail so a caller that wants to act on the kind can reach it with errors.As.

func (*DictFault) Error added in v0.42.0

func (f *DictFault) Error() string

func (*DictFault) Unwrap added in v0.42.0

func (f *DictFault) Unwrap() error

type DictFaultKind added in v0.42.0

type DictFaultKind int

DictFaultKind says what was found wrong with a dictionary file.

const (
	// DictFaultMissing: the directory entry is gone. The store still holds the bytes
	// through its open descriptor, so this is the one kind that repairs itself.
	DictFaultMissing DictFaultKind = iota + 1
	// DictFaultReplaced: something else occupies the path -- a different inode. The file
	// is NOT overwritten: a restore from a backup looks exactly like this, and clobbering
	// it would destroy the thing that was being put back.
	DictFaultReplaced
	// DictFaultChanged: the same file, different contents. Also not overwritten, for the
	// same reason.
	DictFaultChanged
	// DictFaultMismatch: the dictionary file is not the one a segment's records were
	// written with, according to the fingerprint that segment recorded at seal
	// (segtrailer.go). Unlike the three above this is not about the file CHANGING under a
	// running store -- it is noticed at Open, against a dictionary this process has only
	// just loaded, and it is the one state in which every record of that segment decodes
	// to nothing while everything else about the store looks correct.
	DictFaultMismatch
)

func (DictFaultKind) String added in v0.42.0

func (k DictFaultKind) String() string

type DictIDMismatchError added in v0.42.0

type DictIDMismatchError struct {
	Slot  uint32 // the id taken from the file name
	Found uint32 // the Dictionary_ID the file itself carries
	Path  string
}

DictIDMismatchError names the slot, what was found in it, and the file.

func (*DictIDMismatchError) Error added in v0.42.0

func (e *DictIDMismatchError) Error() string

func (*DictIDMismatchError) Unwrap added in v0.42.0

func (e *DictIDMismatchError) Unwrap() error

type DictReplicaState added in v0.42.0

type DictReplicaState struct {
	ID     uint32
	Copies int // how many segment trailers hold it now
	Target int
	// Written is how many copies this pass added.
	Written int
	// Err is why the target could not be reached: no segment with room, or a write that
	// failed. A store whose segments are all too small for a dictionary reports it here
	// every pass, which is the honest answer -- see replicaSizeRatio.
	Err error
}

DictReplicaState is where one dictionary's copies stand after a census.

type DictlessOptions added in v0.41.1

type DictlessOptions struct {
	// DryRun reports what would move and writes nothing. Everything else is identical,
	// so a dry run is a faithful rehearsal rather than an estimate.
	DryRun bool
	// Force runs even when a missing dictionary is sitting in dicts/attic/. The default
	// refuses, because restoring that file keeps records this pass would set aside.
	Force bool
}

DictlessOptions controls a QuarantineDictless pass.

type DictlessReport added in v0.41.1

type DictlessReport struct {
	Dir     string
	DryRun  bool
	Moved   []DictlessSegment
	Missing []uint32 // the dictionary ids involved, ascending
	// Recoverable are missing dictionaries that can be had back without setting any
	// records aside. Unless Force was set, the pass does nothing while this is non-empty.
	Recoverable []uint32
	// RecoverableFrom says where each recoverable dictionary is: dicts/attic/, or the
	// segment file carrying a copy of it.
	RecoverableFrom map[uint32]string
	// DroppedSnapshots lists the shard directory snapshots removed. They record record
	// OFFSETS for segments that are no longer there, and they rebuild on the next open;
	// leaving a stale one is how a readable store becomes a wrong one.
	DroppedSnapshots []string
}

DictlessReport is the outcome of a pass.

func QuarantineDictless added in v0.41.1

func QuarantineDictless(dir string, opts DictlessOptions) (*DictlessReport, error)

QuarantineDictless moves every segment file naming a dictionary the store does not have into quarantine/, and drops the directory snapshot of each shard it touched, so the store opens again without them.

It never deletes: the segments keep their bytes under quarantine/, which Open does not address (it reads shard directories by number) and Fsck skips by name. If the dictionary turns up later the segments can be moved back.

It refuses while any missing dictionary is sitting in dicts/attic/, since restoring that file keeps records this pass would otherwise set aside. Force overrides.

func (*DictlessReport) String added in v0.41.1

func (r *DictlessReport) String() string

String renders the report the way an operator wants to read it.

type DictlessSegment added in v0.41.1

type DictlessSegment struct {
	Path   string // where it was
	DictID uint32 // the dictionary it names and the store does not have
	// Quarantined is where it went, or "" for a dry run.
	Quarantined string
	// Sidecars are the derived files moved with it (.idx, .kidx), by name.
	Sidecars []string
}

DictlessSegment is one segment file the pass moved, or would move.

type DropSuggestion

type DropSuggestion struct {
	Attr   string // canonical attribute name
	Kind   string // "categorical" or "value" (how it is currently indexed)
	Reason string // "unused" (never queried) or "low-cardinality" (no pruning power)

	QueriesEq      int64
	QueriesRange   int64
	SampledPresent int
	// DistinctValues and Capped read exactly as IndexSuggestion's do: a count over
	// SampledPresent ads, and whether that count is only a floor.
	DistinctValues int
	Capped         bool
}

DropSuggestion recommends removing one configured index, with the rationale.

type FsckDamage added in v0.31.1

type FsckDamage struct {
	// Offset is where the unreadable run begins, and Length how far it extends
	// before a record verified again. A run that reaches the end of the written
	// data is reported with Trailing set.
	Offset int
	Length int
	// Records is how many record slots the run covers, when that could be
	// determined; 0 when the framing itself was unreadable.
	Records int
	// Trailing marks damage that runs to the end of the segment. This is the
	// ordinary shape of a crash (a half-written record), not corruption, and a
	// repair discards it rather than trying to recover past it.
	Trailing bool
	// Reason names what failed: "crc" (framing intact, contents corrupt) or
	// "framing" (the record header itself was not usable).
	Reason string
}

FsckDamage is one unreadable region of a segment.

type FsckDictCheck added in v0.42.0

type FsckDictCheck struct {
	Path   string
	DictID uint32
	// Recorded is whether the segment's trailer records which dictionary it was written
	// under. False for every segment sealed before fingerprints existed, and for one with
	// no room for a trailer.
	Recorded bool
	// Matches is whether that record agrees with the dictionary file in dicts/ now.
	// Meaningless when Recorded is false.
	Matches bool
	// Probed is how many records were decoded with that dictionary and ProbeFailures how
	// many of them refused. Probed is 0 when there was no usable dictionary to probe with,
	// or no record to probe.
	Probed, ProbeFailures int
}

FsckDictCheck is one segment's dictionary checked both ways. Only the segments where something disagreed are reported; a segment whose fingerprint matches and whose records decode says nothing worth saying.

func (FsckDictCheck) Verdict added in v0.42.0

func (c FsckDictCheck) Verdict() string

Verdict is the one line an operator needs, and it is written from BOTH signals because neither alone distinguishes a wrong dictionary from damaged records.

type FsckDictFile added in v0.41.1

type FsckDictFile struct {
	ID   uint32
	Path string
	Why  string
}

FsckDictFile is a dictionary file that is present but unusable. Why says what is wrong with it, in the terms an operator can act on.

type FsckDictLabel added in v0.42.0

type FsckDictLabel struct {
	Path    string
	FiledAs uint32 // the id in the file name
	Names   uint32 // the id the dictionary itself carries
}

FsckDictLabel is a dictionary file filed under an id that is not the one it names, which only became a detectable condition once a dictionary carried its own id.

type FsckReport added in v0.31.1

type FsckReport struct {
	Dir      string
	Segments []FsckSegment
	Strays   []FsckStray
	// DictsPresent are the dictionary ids with a file in dicts/, and DictsMissing
	// the ids some segment names but which have no file -- those segments cannot be
	// decoded at all until the dictionary is restored.
	DictsPresent []uint32
	DictsMissing []uint32
	// DictsInAttic are missing dictionaries whose file is sitting in dicts/attic/,
	// retired by pruning. Those segments ARE recoverable: move the file back. A file
	// there that does not itself load is reported in DictsDamaged instead, since
	// telling an operator to restore a dictionary that will not open is worse than
	// saying nothing.
	DictsInAttic []uint32
	// DictsInSegments are missing dictionaries a copy of which is carried in a segment
	// trailer. Those segments are recoverable too, and more cheaply than from the attic:
	// Open restores such a copy by itself. A file here that does not load is not offered,
	// for the same reason as the attic.
	DictsInSegments []uint32
	// DictReplicas counts, per dictionary id, how many segment trailers carry a copy. It
	// is the answer to "how close is this store to losing a dictionary for good": a
	// dictionary present in dicts/ and nowhere else is one deletion away.
	DictReplicas map[uint32]int
	// DictsMislabelled are dictionary files stored under an id that is not the one they
	// carry -- two files that swapped names, or one restored into the wrong slot. They
	// are not damaged and nothing is lost; they are in the wrong places, and Repair puts
	// them right by re-filing each under the id it names.
	DictsMislabelled []FsckDictLabel
	// DictChecks are the segments where the dictionary recorded in the trailer and the
	// records themselves disagree about which dictionary this is, or where one of the two
	// could not be had. Checking twice is what separates a wrong dictionary from damaged
	// records; see dictprobe.go. Segments where both checks are content are not listed.
	DictChecks []FsckDictCheck
	// Trailers is damage in the segment trailers: one whose directory will not read at
	// all, or sections inside one that failed their own checksum. A trailer that was
	// never written is not damage and is not reported here.
	Trailers []FsckTrailer
	// DictsDamaged are dictionary files that exist but cannot be used -- empty, truncated,
	// or not a zstd dictionary at all. They are NOT in DictsPresent: a file that does not
	// load is not a dictionary the store has, and Open fails on it exactly as it does on
	// one that is absent.
	DictsDamaged []FsckDictFile
	// Supersede lists records whose supersededBySeq is impossible. Each one is a key
	// that may silently not be returned.
	Supersede []FsckSupersede
	// MaxSeq is the highest commit sequence a record could legitimately name: the
	// shard commit sequences recorded in the directory snapshots when available,
	// otherwise the highest sequence written into any record.
	MaxSeq uint64
	// CommitSeqKnown is true when a directory snapshot supplied the real commit
	// sequence. Without one, MaxSeq is only a floor -- a delete advances the commit
	// sequence without writing a record, so a legitimate tombstone can name a
	// sequence higher than any record's -- and the "superseded by a commit that
	// never happened" check is skipped rather than reporting healthy deletes.
	CommitSeqKnown bool
}

FsckReport is the whole collection's census.

func Fsck added in v0.31.1

func Fsck(dir string) (*FsckReport, error)

Fsck examines the collection rooted at dir. It never writes, and it returns a report even when parts of the store are unreadable -- an error means fsck could not look, not that the store is bad.

func (*FsckReport) String added in v0.31.1

func (r *FsckReport) String() string

String renders the report the way an operator wants to read it.

func (*FsckReport) Totals added in v0.31.1

func (r *FsckReport) Totals() (records, damagedRuns, damagedRecords int)

Totals sums the per-segment counts. records counts only records that can actually be READ: a record in a segment whose compression dictionary is unusable is not among them, however well it verifies, because nothing can decode it. Those are reported by Undecodable instead.

The distinction is the whole point. Record framing and checksums say nothing about whether the bytes can be decompressed, so counting a dictionary-less segment's records as readable made the headline contradict the MISSING dictionary line in the same report -- and the headline is what an operator reads first.

func (*FsckReport) Undecodable added in v0.41.1

func (r *FsckReport) Undecodable() (segments, records int)

Undecodable reports the segments whose compression dictionary is unusable and the records in them. Those records verified -- they are intact on disk and a restored dictionary brings every one of them back -- but nothing can read them as the store stands, and Open refuses the collection rather than serve it.

type FsckSegment added in v0.31.1

type FsckSegment struct {
	Path   string
	Size   int
	DictID uint32 // the dictionary named in the file name

	// DictUnusable is set when DictID names a compression dictionary this store cannot
	// supply -- no file in dicts/, or a file that does not load. The segment's framing and
	// checksums are still checked and Records still counts what verified, because that is
	// what a restored dictionary would recover. Nothing in the segment can be DECODED
	// while it holds, though, so those records are reported separately from the readable
	// ones (see Totals and Undecodable) rather than counted among them.
	DictUnusable bool
	Records      int // records that verified
	Bytes        int // bytes those records occupy
	Damage       []FsckDamage
	// Sidecar reports the state of this segment's .idx: "absent", "ok", or a
	// rejection reason. A sidecar is derived state, so a bad one costs only the
	// rebuild -- it is never data loss.
	Sidecar string

	// ExtentTrusted is true when the sidecar's recorded extent was usable, which is
	// how Open avoids walking the segment. When it is true and damage was found, the
	// damage is INSIDE the trusted extent: Open will not notice it, and queries will
	// hit it one record at a time.
	ExtentTrusted bool

	// Columnar is true when the segment holds a columnar payload that verified, and
	// ColumnarVersion is that payload's format version: 0 for one written before
	// payloads carried a version.
	Columnar bool
	// ColumnarUnsupported is set when ColumnarVersion is one this build cannot read.
	// That is not damage: the payload is intact, and it is the only copy of the
	// values its segment's records were written without. Open refuses the collection
	// (ErrUnsupportedColumnarVersion), Repair leaves the segment alone, and a build
	// that reads the version opens it normally.
	ColumnarUnsupported bool
	ColumnarVersion     uint32
	// Columnarized is true when any record that frames carries the columnar flag --
	// the payload or a stripped remnant, whether or not it verified. Such a segment's
	// payload maps each row to its record by arena offset, so its records cannot
	// move, and Repair leaves it alone.
	Columnarized bool
	// ColumnarMismatch says how a verified columnar payload fails to describe this
	// segment's records, or is "" when it describes them or there is none to check. The
	// payload names each row's record by arena offset, so every row must name the start
	// of a keyed record and every keyed record must have a row. A segment whose records
	// were packed under an unchanged payload (by a Repair before columnarized segments
	// were left alone) fails this, and its reads would return other records' values; Open
	// refuses such a payload (ColNativeOffsetMismatches) when its ends do not fit. Rows
	// inside damage are not counted against it. The original is in quarantine/.
	ColumnarMismatch string
	// ColumnarMismatchRows counts the rows naming no keyed record plus the keyed records
	// no row names.
	ColumnarMismatchRows int
	// ListSectionDamage says which list column of a version 3 payload does not decompress or parse. Those
	// columns hold lists their records no longer do, so the records reading them fail; repair leaves the
	// segment alone, and the lists are not dropped.
	ListSectionDamage string
	// DictDamaged is true when the segment's attribute dictionary record failed its
	// checksum. Every record of an interned segment is keyed by it, so none can be read:
	// Open refuses the dictionary (SegDictCRCFailures), and Repair leaves the segment
	// alone rather than write one without it.
	DictDamaged bool
	// OpenStop is set when a normal open's recovery walk stops at damage in this segment
	// with something readable after it: the sidecar supplies no trusted extent, so Open
	// walks the records and stops at the first one that fails its checksum. When the
	// framing past the stop can be proven -- a verified columnar payload after it, or the
	// sidecar's key index -- Open continues past it and sets the damaged records aside
	// (OpenStop.Recovered). Otherwise what follows is not loaded, and when the dictionary
	// or columnar payload is among it, the records before the stop are unreadable too.
	OpenStop *OpenDamageStop
	// SidecarDamage is how many damaged spans the sidecar records for this segment. A normal
	// open that trusts the sidecar's extent skips them; they are not damage it fails to see.
	SidecarDamage int
	// contains filtered or unexported fields
}

FsckSegment is one segment data file's census.

type FsckStray added in v0.31.1

type FsckStray struct {
	Path string
	Why  string
}

FsckStray is a file in a shard directory that recovery will silently ignore.

type FsckSupersede added in v0.31.2

type FsckSupersede struct {
	Path string // the segment holding the record
	Off  int    // its offset within that segment
	Key  string
	Seq  uint64 // the record's own commit sequence
	Sup  uint64 // the superseding sequence it claims
	Why  string // which invariant it breaks
}

FsckSupersede is a record whose supersededBySeq cannot be true.

That field is one of the two the record checksum does NOT cover (it is rewritten in place when a later version supersedes this one), so corruption there is invisible to every other check. It matters because the field alone decides whether a record is live: a live record whose supersededBySeq is corrupted simply stops being returned. The key does not come back wrong -- it comes back missing, with nothing anywhere saying why.

type FsckTrailer added in v0.42.0

type FsckTrailer struct {
	Path string
	// Why says the trailer cannot be read at all. The segment's records are unaffected --
	// the trailer lives past them -- but nothing it carried can be recovered, and nothing
	// may be written to that tail again, since its extent is no longer knowable.
	Why string
	// Sections are the ids of sections whose body failed its own checksum. The rest of
	// the trailer is intact and still readable.
	Sections []uint16
}

FsckTrailer is damage in one segment's trailer. Exactly one of Why and Sections is set: a trailer whose directory will not read is lost whole, while a trailer that reads loses only the sections whose own checksum failed.

type GroupAggCol added in v0.33.2

type GroupAggCol struct {
	Attr   string
	Filter string
}

GroupAggCol is one aggregate column of a grouped columnar query: the numeric attribute it reads and the per-aggregate FILTER deciding which records feed it ("" = every record the WHERE clause kept). It mirrors the (Arg, Filter) pair db.AggSpec carries, so a caller translating between the two moves fields rather than reinterpreting them.

The SAME attribute under two different filters is two columns here, each with its own accumulator. Deduplicating aggregates is the caller's job and its key has to include the filter: MIN(x) beside MAX(x) still reads x once, but MIN(x) beside MIN(x) FILTER (...) cannot.

type GroupAgreementItem added in v0.29.13

type GroupAgreementItem struct {
	Attrs []string `json:"attrs"`
	Frac  float64  `json:"frac"`
}

GroupAgreementItem pairs a group's members with the fraction of segments that re-derived it.

type GroupCount added in v0.28.0

type GroupCount struct {
	Value classad.Value
	Count int
}

GroupCount is one group of a GROUP BY: the group column's value and how many records held it.

type GroupExplain added in v0.33.0

type GroupExplain struct {
	Probes      []ProbeExplain `json:"probes"`
	IndexUsable int            `json:"indexUsable"`
	// Unsatisfiable marks a disjunct whose indexed conjuncts contradict each other: it
	// contributes nothing to the union.
	Unsatisfiable bool `json:"unsatisfiable,omitempty"`
}

GroupExplain is one disjunct of a disjunctive plan: its index-satisfiable conjuncts and their index status, as ProbeExplain reports them for a conjunctive one.

type GroupSchemaAgreement added in v0.28.0

type GroupSchemaAgreement struct {
	Segments int `json:"segments"`
	// PerGroup[i] is the fraction of segments whose own derivation produced group i's exact
	// member set, for the table-level groups in report order.
	PerGroup []float64 `json:"perGroup,omitempty"`
}

GroupSchemaAgreement reports how well per-segment derivations agree with a whole-table one -- the other half of "is this a property of the data". A group derived from the table but absent from most segments is a sampling artifact, and a schema pointer spent on it would buy coverage in some segments and nothing in others.

type GroupSchemaChange added in v0.29.13

type GroupSchemaChange struct {
	Unix    int64              `json:"unix"`
	Reason  string             `json:"reason"`
	Added   [][]string         `json:"added,omitempty"`
	Removed [][]string         `json:"removed,omitempty"`
	Changed []GroupSchemaDelta `json:"changed,omitempty"`
}

GroupSchemaChange is one committed-group-set change, for reporting.

type GroupSchemaDelta added in v0.29.13

type GroupSchemaDelta struct {
	Before  []string `json:"before"`
	After   []string `json:"after"`
	Added   []string `json:"added,omitempty"`
	Removed []string `json:"removed,omitempty"`
}

GroupSchemaDelta is one surviving group whose membership shifted across a change.

type GroupSchemaDrift added in v0.28.0

type GroupSchemaDrift struct {
	// Derivations is how many candidate SNAPSHOTS the sampler has retained (capped at
	// groupHistoryMax), NOT how many times the committed set changed -- most snapshots are
	// identical. CommittedChanges is the count that answers "how much real churn": entries in the
	// committed-set change log (see GroupSchemaChanges).
	Derivations      int   `json:"derivations"`
	CommittedChanges int   `json:"committedChanges"`
	FirstUnix        int64 `json:"firstUnix,omitempty"`
	LastUnix         int64 `json:"lastUnix,omitempty"`
	// Retained is how many of the FIRST derivation's groups still appear, by exact member
	// set, in the last -- the number that matters, because a group whose membership changed
	// is a different group and its block would have to be rebuilt.
	Retained int `json:"retained"`
	OfFirst  int `json:"ofFirst"`
	// MaxPartialFrac is the worst partial fraction across the last derivation's groups.
	// Nonzero means co-occurrence has decayed: some ad now holds part of a group.
	MaxPartialFrac float64 `json:"maxPartialFrac"`
}

GroupSchemaDrift compares the earliest and latest retained derivations, so an operator can see whether the groups are holding without having captured the earlier report themselves.

type GroupSchemaEntry added in v0.28.0

type GroupSchemaEntry struct {
	Attrs []string `json:"attrs"`
	// InFrac / NoneFrac / PartialFrac are the sample's split over this group. PartialFrac is
	// the one to watch: it is the fraction that would fall back to a row decode, and it is 0
	// by construction at derivation, so any growth is drift.
	InFrac      float64 `json:"inFrac"`
	NoneFrac    float64 `json:"noneFrac"`
	PartialFrac float64 `json:"partialFrac"`
	// Cells is the attribute occurrences this group would make columnar, and CellsFrac that
	// as a fraction of every occurrence in the sample.
	Cells     int     `json:"cells"`
	CellsFrac float64 `json:"cellsFrac"`
}

GroupSchemaEntry is one group in a report.

type GroupSchemaInfo added in v0.28.0

type GroupSchemaInfo struct {
	// Sampled is how many ads the derivation looked at, and BaseFields the size of the base
	// schema it derived against.
	Sampled    int `json:"sampled"`
	BaseFields int `json:"baseFields"`
	// BaseCells / TotalCells are attribute occurrences the base schema covers, out of all
	// occurrences in the sample -- the coverage the groups are measured against.
	BaseCells  int                `json:"baseCells"`
	TotalCells int                `json:"totalCells"`
	Groups     []GroupSchemaEntry `json:"groups,omitempty"`
}

GroupSchemaInfo reports the derived group schemas, for diagnostics. Phase 1 is report-only: these are what WOULD be stored columnar per group, not what is.

type GroupSchemaLastAgreement added in v0.29.13

type GroupSchemaLastAgreement struct {
	Unix     int64                `json:"unix"`
	Segments int                  `json:"segments"`
	Groups   []GroupAgreementItem `json:"groups,omitempty"`
}

GroupSchemaLastAgreement is the last per-segment agreement result, read from the sidecar so a READ-level client can see it without recomputing (see GroupSchemaAgreement).

type GroupSink added in v0.37.0

type GroupSink interface {
	AddNum(agg int, v NumValue)
}

GroupSink is one group's set of caller-supplied aggregate accumulators, for a GROUP BY reduced by something other than the built-in numeric statistics. The grouping machinery makes one per group the first time that group is seen and feeds it the aggregate columns' values.

agg indexes the aggregate columns the query asked for, in request order, so one sink holds every aggregate of its group rather than one sink per (group, aggregate) pair -- which is what lets a group that was never fed still be reported, with whatever its accumulators say they are empty.

VALUES ARRIVE IN BLOCK ORDER, the same caveat NumValuesQuery carries, and only the column's NUMERIC values arrive at all: a record whose aggregate attribute is absent, non-numeric or an expression contributes to the group's COUNT and to no sink.

type GroupSpec added in v0.33.0

type GroupSpec struct {
	Attr        string
	BucketWidth int64
}

GroupSpec is one GROUP BY column: the attribute, optionally floored into fixed-width buckets. BucketWidth == 0 groups by the raw value; BucketWidth > 0 groups by floor(v/width)*width, and a record whose value is not a finite number leaves the series. It mirrors db.GroupCol, which is the shape the aggregate engine above carries, so a caller translating between the two moves fields rather than reinterpreting them.

type GroupStats added in v0.28.0

type GroupStats struct {
	Values []classad.Value
	Count  int
	Stats  []NumStats
	// CountOf is one record count per requested filtered COUNT(*) (see GroupStatsConstraintAggs),
	// in the order requested: how many of the group's records passed that filter. It is nil for a
	// query that asked for none, which is every query that predates per-aggregate FILTER.
	//
	// It is not derivable from Stats: a NumStats counts the records whose COLUMN held a number,
	// and a filtered COUNT(*) counts the records that passed the filter whatever they carry.
	CountOf []int
}

GroupStats is one group of a GROUP BY with value aggregates: the group columns' values (one per requested group column, in request order), how many records fell in the group, and one NumStats per requested aggregate attribute, in the order requested.

type GroupValues added in v0.37.0

type GroupValues struct {
	Values  []classad.Value
	Count   int
	Sink    GroupSink
	CountOf []int
}

GroupValues is one group of a GROUP BY answered into caller-supplied sinks: the group columns' values, how many records fell in the group, that group's sink, and the filtered record counts GroupStats.CountOf carries.

type Hasher

type Hasher interface {
	Hash(key []byte) uint64
}

Hasher maps a stable key to a 64-bit hash. The hash routes a key to a shard and indexes the per-shard directory; it is never used as the ad's identity (the full key is stored inline in each record and compared on lookup), so hash collisions are resolved exactly and never lose data.

type IndexBackfillResult added in v0.33.0

type IndexBackfillResult struct {
	// Rebuilt is how many segments now cover every indexed attribute, and RebuiltBytes their
	// stored size (what the budget is charged against).
	Rebuilt      int   `json:"rebuilt"`
	RebuiltBytes int64 `json:"rebuiltBytes"`
	// Failed is how many segments the pass tried and could not rebuild; they keep their
	// existing sidecar and are retried by the next pass.
	Failed int `json:"failed,omitempty"`
	// PendingSegments and PendingBytes are what still lacks coverage after the pass.
	PendingSegments int   `json:"pendingSegments"`
	PendingBytes    int64 `json:"pendingBytes"`
}

IndexBackfillResult reports one backfill pass.

type IndexSize added in v0.6.0

type IndexSize struct {
	Attr  string `json:"attr"`  // the attribute, or a composite's tuple ("ClusterId+ProcId")
	Kind  string `json:"kind"`  // "categorical" | "value" | "composite"
	Bytes int64  `json:"bytes"` // resident posting bytes (roaring bitmaps + keys) across all live segments
	// SketchBytes is the resident memory of this attribute's per-segment sketches --
	// the categorical bloom filter and the HyperLogLog distinct-count registers --
	// reported apart from Bytes so it is visible rather than hidden in the posting total.
	SketchBytes int64   `json:"sketchBytes"`
	Auto        bool    `json:"auto"` // created by the auto-tuner (vs human/Options)
	Frac        float64 `json:"frac"` // Bytes as a fraction of the live data bytes
}

IndexSize is the measured memory footprint of one attribute's index.

type IndexSizes added in v0.6.0

type IndexSizes struct {
	PerIndex   []IndexSize `json:"perIndex"`
	TotalBytes int64       `json:"totalBytes"` // posting bytes (the auto-tuner's budget denominator)
	// TotalSketchBytes is the sum of every index's SketchBytes (bloom + HLL). It is
	// reported separately and is NOT folded into TotalBytes/Frac, so the watermark and
	// auto-tuner budget stay calibrated on posting bytes; sketch memory is bounded and
	// small (<=8 KiB bloom + 1 KiB HLL per categorical attr per segment).
	TotalSketchBytes int64   `json:"totalSketchBytes"`
	DataBytes        int64   `json:"dataBytes"` // live compressed record bytes
	Frac             float64 `json:"frac"`      // TotalBytes / DataBytes
}

IndexSizes is the collection's index memory, per attribute and in total, against the live data bytes -- the denominator for the "index is N% of data" watermark.

type IndexSuggestion

type IndexSuggestion struct {
	Attr string // canonical (first-seen) attribute name
	Kind string // "categorical" (string equality/membership) or "value" (numeric + range)

	QueriesEq    int64 // equality/membership probes observed
	QueriesRange int64 // range probes observed

	SampledPresent int     // sampled ads with this attribute present
	StringFrac     float64 // fraction of present values that are string literals
	NumericFrac    float64 // fraction that are numeric literals

	// DistinctValues is how many distinct values the attribute took across the
	// SampledPresent ads, and Capped says whether that is the count or a floor under it.
	//
	// Capped is one-sided: a sample can only understate a distinct count, so when it is
	// set the truth is at least DistinctValues and may be far above -- on a 20,000-slot
	// pool a per-slot attribute reports a few thousand against a true count of ~20,000.
	// It is set when the sample ran out while the attribute's distinct set was still
	// growing, and when the distinct set overflowed its own ceiling; the first is what
	// binds at the sample sizes callers actually pass.
	//
	// Absence is not a small count: an attribute no sampled ad carried is not suggested
	// at all, so DistinctValues == 0 here cannot mean "never seen". SampledPresent is the
	// population the count describes.
	//
	// Neither field decides anything. The Kind below is chosen from literal-kind
	// dominance and observed demand; these two are the rationale a reader needs to judge
	// what an index on this attribute would cost, which is why their honesty matters even
	// though no branch reads them.
	DistinctValues int
	Capped         bool
}

IndexSuggestion recommends indexing one attribute, with the rationale (the two signals) so the decision is explainable.

type MaintPhase added in v0.34.0

type MaintPhase string

MaintPhase names one kind of maintenance pass, for progress reporting and for the cumulative per-phase timing counters in OpStats. The values are stable strings: they are exported as a Prometheus label.

const (
	// MaintColumnarize rewrites sealed segments into columnar-native form (ColumnarizeSealed,
	// recolumnarizeStale).
	MaintColumnarize MaintPhase = "columnarize"
	// MaintCompact reclaims dead space (Compact, Rewrite).
	MaintCompact MaintPhase = "compact"
	// MaintRetrain trains a fresh dictionary and recompresses under it (RetrainDict).
	MaintRetrain MaintPhase = "retrain"
	// MaintRotate drops whole oldest segments to honour retention (Rotate).
	MaintRotate MaintPhase = "rotate"
	// MaintMerge consolidates cold segment runs in an archive (MergePass).
	MaintMerge MaintPhase = "merge"
	// MaintReindex rebuilds segment sidecars (Reindex), including the one that follows a
	// compaction or a merge.
	MaintReindex MaintPhase = "reindex"
	// MaintBackfill carries a changed index set to older sealed segments (BackfillIndexes).
	MaintBackfill MaintPhase = "backfill"
)

type MaintProgress added in v0.34.0

type MaintProgress struct {
	// Phase is the pass that is running. Empty when Active is false.
	Phase MaintPhase
	// Active reports whether a pass is in flight right now.
	Active bool
	// Started is when the current pass began.
	Started time.Time
	// Done is the units of work finished so far (segments, for every pass that reports a
	// Total). Total is how many the pass budgeted, or 0 when the pass cannot say up front --
	// a merge, for instance, discovers each run as it goes, so it reports Done only.
	Done  int
	Total int
}

MaintProgress is a point-in-time view of the maintenance pass running on a collection, or the zero value when none is. It is published by the pass itself at each safe boundary and read locklessly, so reading it never contends with the pass it describes.

func (MaintProgress) Elapsed added in v0.34.0

func (p MaintProgress) Elapsed() time.Duration

Elapsed is how long the current pass has been running, or 0 when none is.

func (MaintProgress) Remaining added in v0.34.0

func (p MaintProgress) Remaining() int

Remaining is the units of work the pass still expects to do, or 0 when it did not report a total (never negative: a pass may finish early, and one that over-runs its own estimate should read as "nearly done", not as a negative backlog).

type MatchExplain added in v0.6.0

type MatchExplain struct {
	// HasRequirements is false when the job has no Requirements (it then matches every
	// slot -- a full scan with no pruning).
	HasRequirements bool `json:"hasRequirements"`
	// SlotPredicate is the job's Requirements rewritten over the slot: TARGET.attr
	// becomes the slot's own attribute and every job reference is baked to its value,
	// e.g. `Memory >= 4096 && Arch == "X86_64"`. This is the predicate whose probes
	// drive candidate pruning (the bilateral match still re-verifies every candidate).
	SlotPredicate string `json:"slotPredicate"`
	// Probes are the rewritten predicate's index-satisfiable conjuncts and their index
	// status on the resource collection.
	Probes []ProbeExplain `json:"probes"`
	// IndexUsable is how many probes prune via an index.
	IndexUsable int `json:"indexUsable"`
	// Plan is the access path over the resource slots: "empty" (the request contradicts
	// itself, so no slot can match), "indexed" (visit only candidate slots),
	// "parallel-scan", or "serial-scan" (match every slot).
	Plan        string `json:"plan"`
	Parallelism int    `json:"parallelism"`
	Shards      int    `json:"shards"`
	// TotalResources is the resource (slot) count, the denominator for selectivity.
	TotalResources int `json:"totalResources"`
	// EvalOrder is the top-level && conjuncts in the order the bilateral match evaluates
	// them (after short-circuit reordering), each tagged with its role: an active pruning
	// probe, or a re-check whose selectivity (from the index, when available) drove where
	// it sorts. It makes the ordering transparent -- e.g. an always-true capability flag
	// appears last as a ~99%-true re-check, not a candidate filter.
	EvalOrder []ConjunctExplain `json:"evalOrder,omitempty"`
}

MatchExplain describes how matchmaking a specific job against this (resource) collection would execute: the job's Requirements rewritten over the slot (with the job's attributes baked to constants), the index-satisfiable probes that rewrite yields, and which of them prune candidates via a configured index.

type MergeGroupSink added in v0.37.0

type MergeGroupSink func(dst, src GroupSink)

MergeGroupSink folds one group's caller-supplied accumulators into another's.

The collections layer cannot do it: a GroupSink only accepts values, and what it does with them is the caller's. So a caller that supplies newSink supplies this too, and it is required exactly when newSink is -- a fanned-out pass gives each worker its own sinks per group, and a group two workers both saw has two sets to fold into one. It is nil for a query using the built-in accumulators, which the storage layer folds itself.

It is called on the goroutine that started the pass, after every worker has returned, so an implementation needs no synchronization. It must be associative and commutative: which worker draws which segment is a race, so the fold order is not fixed.

type MergeOptions added in v0.24.1

type MergeOptions struct {
	// TargetSegmentBytes is the size tier's target. Adjacent cold segments each smaller than
	// half of it are merged into one of about this size on every pass, however many segments
	// the archive holds. Default defaultTargetSegmentBytes; negative turns the size tier off,
	// leaving only the count guard below.
	//
	// It is also capped at 1/retentionGranularity of the archive's Retention.MaxBytes, so a
	// size rotation still drops a small share of the archive at a time, and the tier is off
	// when that cap leaves less than minTierSeals seals' worth to merge into.
	TargetSegmentBytes int64
	// TargetSegments is the LOW watermark: once a pass starts it merges until the archive
	// is at or below this. Default defaultTargetSegments.
	TargetSegments int
	// TriggerSegments is the HIGH watermark: a pass does nothing until the archive reaches
	// it. The gap between the two is what stops the policy from merging a run on every pass
	// forever once it is sitting on the target -- rewriting data continuously to hold a line
	// that does not need holding to the segment. Default: TargetSegments plus a quarter.
	TriggerSegments int
	// MaxSegmentBytes caps a merged segment. Segment offsets are uint32 throughout the
	// record and sidecar formats, so 4 GiB is a hard structural ceiling; the default stays
	// well under it. A run stops before exceeding this.
	MaxSegmentBytes int64
	// MinMergeBytes is the smallest output the count guard aims for. A run below it is still
	// merged if it is the best available -- reducing the count is the point -- but the policy
	// prefers to keep accumulating.
	MinMergeBytes int64
	// MaxRun bounds how many segments one merge consumes, so a single merge's work and
	// memory stay predictable however small the segments are.
	MaxRun int
	// KeepRecent leaves the newest sealed segments untouched, keeping the hot end of the
	// archive finely divided (and away from the open segment the writer is appending to).
	KeepRecent int
	// MaxMerges bounds one pass, so maintenance stays interruptible and a large backlog is
	// worked down over several passes instead of one long stall.
	MaxMerges int
	// MaxBytesPerPass bounds the SOURCE bytes one pass rewrites. MaxMerges alone does not
	// bound the work, because a merge's cost is its inputs' size, not its count -- one pass
	// of large runs can move orders of magnitude more than another of the same length.
	//
	// This exists for the catch-up case: an archive that grew while merging was off has a
	// backlog measured in the size of the archive, and without a byte bound the first pass
	// would try to rewrite all of it at once. Steady state does not need it -- the size tier
	// merges about one target's worth per target's worth sealed -- so the default is sized to
	// cap one pass at a tolerable stall rather than to throttle.
	//
	// Bytes of a merge that FAILED count too: the work was spent, and a failing merge must
	// not let one pass attempt every run in the archive.
	//
	// Sustained RATE is the scheduler's job, not this: pace passes so the long-run average
	// stays within the byte budget the deployment allows.
	MaxBytesPerPass int64
}

MergeOptions tunes a merge pass. The zero value is usable: it fills in the defaults below.

type MissingDictionaryError added in v0.41.1

type MissingDictionaryError struct {
	// IDs are the missing dictionary ids, ascending.
	IDs []uint32
	// Example maps each id to one segment file naming it; there are usually many.
	Example map[uint32]string
	// Segments counts the segment files that cannot be decoded in total.
	Segments int
}

MissingDictionaryError says which dictionaries are missing and names a segment that needs each, so the message is actionable without a second investigation.

func (*MissingDictionaryError) Error added in v0.41.1

func (e *MissingDictionaryError) Error() string

func (*MissingDictionaryError) Unwrap added in v0.41.1

func (e *MissingDictionaryError) Unwrap() error

type NDVAccuracy added in v0.38.1

type NDVAccuracy string

NDVAccuracy says how to read NDVEstimate.Distinct. It is derived from Err, so the two cannot disagree; it exists because "exact" and "estimate" are what a planner branches on while Err is what it reasons with.

const (
	// NDVExact: Distinct is the count, over the records Records names.
	NDVExact NDVAccuracy = "exact"
	// NDVBound: Distinct bounds the count, in the one direction Err names.
	NDVBound NDVAccuracy = "bound"
	// NDVEstimated: Distinct may be wrong in either direction. RelErr quantifies it when a
	// sketch produced it, and is zero when nothing quantifies it.
	NDVEstimated NDVAccuracy = "estimate"
)

type NDVErr added in v0.38.1

type NDVErr string

NDVErr is the direction Distinct can be wrong in, stated as what it can NEVER do.

const (
	NDVErrNone   NDVErr = "none"   // Distinct is the count
	NDVErrLow    NDVErr = "low"    // never over the count: the truth is >= Distinct
	NDVErrHigh   NDVErr = "high"   // never under the count: the truth is <= Distinct
	NDVErrEither NDVErr = "either" // no direction holds
)

type NDVEstimate added in v0.38.1

type NDVEstimate struct {
	// Attr is the attribute as the index spells it.
	Attr string `json:"attr"`
	// Distinct is the count, read through Accuracy and Err.
	Distinct uint64 `json:"distinct"`

	Accuracy NDVAccuracy `json:"accuracy"`
	Err      NDVErr      `json:"err"`
	// RelErr is the relative standard error when a sketch produced Distinct, and 0
	// otherwise. A zero RelErr on an NDVEstimated answer means the error is unquantified, NOT that
	// there is none.
	RelErr float64 `json:"relErr,omitempty"`

	// Records is how many records carried an indexable value of this attribute in what was
	// counted -- the population Distinct describes, which is not the table's record count.
	Records uint64 `json:"records"`
	// Exceptions is how many records carry the attribute as something the index cannot key
	// (a list, a nested ad, an expression, the wrong literal kind). They are outside
	// Distinct entirely: a planner joining on such an attribute is joining on values no
	// statistic here has seen.
	Exceptions uint64 `json:"exceptions,omitempty"`
	// Segments is how many segments contributed a summary; Uncovered is how many hold
	// records this attribute is not indexed in, plus any segment whose index stops short of
	// its own records. Uncovered > 0 is what makes an otherwise exact count a lower bound.
	Segments  int `json:"segments"`
	Uncovered int `json:"uncovered,omitempty"`

	// Source is one sentence naming the metadata the answer came from, for EXPLAIN.
	Source string `json:"source"`
}

NDVEstimate is what the store can say about one attribute's distinct-value count without reading a record.

It is returned with an ok flag and never fabricated: an attribute no segment indexes yields ok == false, which a planner must be able to tell from Distinct == 1. The two lead to opposite decisions -- one distinct value is the degenerate key whose hash bucket IS the cross product, and "we do not know" is the case for measuring instead of assuming -- so conflating them picks the wrong plan with confidence.

type NumStats added in v0.25.2

type NumStats struct {
	N   int     `json:"n"`
	Sum float64 `json:"sum"`
	Min float64 `json:"min"`
	Max float64 `json:"max"`
	// IntSum accumulates the INTEGER contributions in int64, exactly as the reference SUM does
	// -- a float64 accumulator loses precision past 2^53, so an all-integer sum rendered from
	// Sum would disagree with the scanning aggregator on large values.
	IntSum int64 `json:"intSum,omitempty"`
	// IntMin/IntMax are the extremes of the INTEGER contributions, compared as int64 the way the
	// reference's min/max compare two integers. Min/Max are float64 and cannot tell integers past
	// 2^53 apart, so an all-integer MIN/MAX renders from these. Meaningless when no integer
	// contributed.
	IntMin int64 `json:"intMin,omitempty"`
	IntMax int64 `json:"intMax,omitempty"`
	// AnyReal records whether any contributing value was a REAL rather than an integer, which is
	// exactly the reference's promotion rule: SUM stays an integer unless a real appears, and
	// MIN/MAX keep their element's type. Without it the same query would print differently
	// depending on whether the accelerator was on.
	AnyReal bool `json:"anyReal,omitempty"`
	// AnyBool records that a boolean turned up in the column (only possible as an escaped value,
	// since a bool is not a numeric schema field). The reference coerces booleans to 1/0 and has
	// a further quirk for a lone boolean element; rather than reproduce that, a caller declines
	// and lets the scan answer. Pathological data, exact answer.
	AnyBool bool `json:"anyBool,omitempty"`
	// AnyNaN records that a NaN turned up in the column, which makes Min/Max unusable for MIN/MAX.
	// SUM and AVG are unaffected: NaN propagates through addition identically on both paths.
	//
	// Every comparison against NaN is false, so the reference's min()/max() -- which seed from the
	// FIRST contributing element and then keep whichever wins a `<` / `>` -- returns NaN when the
	// first element is NaN and ignores NaN entirely when it is not. Its answer therefore depends on
	// the order records are visited in, which no aggregate here promises and which a pass over
	// columns does not share with a record scan. There is no rule this fast path could follow that
	// matches the reference on every input, so a caller DECLINES a MIN/MAX over such a column and
	// lets the scan give its own order-dependent answer rather than a different wrong one. (What
	// the unflagged code did was report the seeds: an all-NaN group's MAX came back -Inf.)
	//
	// NaN is unreachable from old-ClassAd text -- `nan` lexes as a bare reference and evaluates to
	// UNDEFINED, and there is no literal for it -- so it only arrives programmatically.
	//
	// ±Inf needs no such flag. The seeds are +Inf for Min and -Inf for Max, which are exactly the
	// identities for min/max over the extended reals, so a column legitimately holding ±Inf
	// accumulates to the reference's answer; N == 0, not the seed value, is what tells a caller
	// there was nothing to aggregate.
	AnyNaN bool `json:"anyNaN,omitempty"`
}

NumStats is one columnar pass's worth of aggregate inputs for a single numeric attribute, from which MIN, MAX, SUM, AVG and COUNT(attr) all follow.

N counts the records whose value for the attribute is a number -- which is COUNT(attr)'s definition, and the divisor for AVG. Records where the attribute is absent or non-numeric contribute to none of these fields. Min/Max are meaningless when N == 0.

type NumValue added in v0.37.0

type NumValue struct {
	F    float64 // every kind as a float; for NumInt past 2^53 this is lossy, so use I
	I    int64   // the exact integer, for NumInt and NumBool; meaningless for NumReal
	Kind NumValueKind
}

NumValue is one value read from a numeric column.

type NumValueKind added in v0.37.0

type NumValueKind uint8

NumValueKind says how a column value was stored, which a sink needs in order to reproduce the reference's type rules: a sum over integers stays integral, and an integer past 2^53 survives only in I.

const (
	NumInt  NumValueKind = iota // an integer column value; I is exact
	NumReal                     // a real column value; only F is meaningful, and it may be a NaN
	NumBool                     // a boolean, coerced to 0 or 1 in both F and I
)

type OldAdUpdate

type OldAdUpdate struct {
	Key  []byte
	Text string
}

OldAdUpdate is one insert-or-update whose ad is supplied in "old ClassAd" serialization (newline-separated `Name = Value` lines, as sent over a TCP socket), rather than as a parsed *classad.ClassAd.

type OpStat added in v0.11.0

type OpStat struct {
	Count int64 `json:"count"`
	Nanos int64 `json:"nanos"`
	// MaxNanos is the longest single occurrence seen, and Buckets is the latency
	// histogram (see LatencyBucketBoundsNanos: buckets[i] counts occurrences <= bound[i],
	// the last entry counts the overflow above the final bound). Both surface the tail
	// the mean (Nanos/Count) hides. Omitted from JSON when empty so an older peer that
	// never populated them stays byte-compatible.
	MaxNanos int64   `json:"maxNanos,omitempty"`
	Buckets  []int64 `json:"buckets,omitempty"`
}

OpStat is one operation's cumulative call count and total wall-nanoseconds. Both are monotonic; a scraper derives rate and mean latency (Nanos/Count) from deltas.

type OpStats added in v0.11.0

type OpStats struct {
	ShardWriteWait OpStat `json:"shardWriteWait"`
	ShardWriteHold OpStat `json:"shardWriteHold"`
	SegmentAlloc   OpStat `json:"segmentAlloc"`
	Sync           OpStat `json:"sync"`
	// CommitSync is the per-commit durability wall time: how long a Txn.Commit blocked
	// flushing all of its shards to disk. Since those shard flushes now run in parallel,
	// this is the commit's critical path (≈ the slowest shard), which the per-shard Sync
	// total -- now the summed fsync WORK, not the latency -- no longer reveals. Count is
	// the number of durable commits; Nanos/Count is mean commit durability latency.
	CommitSync OpStat `json:"commitSync,omitempty"`
	Compact    OpStat `json:"compact"`
	Retrain    OpStat `json:"retrain"`
	Reindex    OpStat `json:"reindex"`
	// IndexBackfill counts sealed segments whose sidecar BackfillIndexes rebuilt to cover the
	// current index set, one occurrence per segment.
	IndexBackfill OpStat `json:"indexBackfill"`
	// Columnarize, Rotate and Merge are the remaining maintenance passes' wall time, one
	// occurrence per pass. Omitted from JSON when empty so a peer that predates them stays
	// byte-compatible, exactly as CommitSync does.
	Columnarize OpStat `json:"columnarize,omitempty"`
	Rotate      OpStat `json:"rotate,omitempty"`
	Merge       OpStat `json:"merge,omitempty"`
}

OpStats is a snapshot of a collection's operational timing counters -- the wall time its callers spent blocked in, or holding, each of the store's stall points. Shard counters are summed across all shards. See opMetrics for what each measures. OpStats reports, per stall point, the cumulative call count and total wall time. The collection-wide snapshot lock (Truncate/Restore) lives one layer up in the db package, which composes its own snapshot-lock counter onto this snapshot.

type OpenDamageStop added in v0.32.0

type OpenDamageStop struct {
	Path   string // the segment file
	Offset int    // where the walk stopped: the first record that failed its checksum
	// Records is how many keyed records after Offset verify and were not loaded, and Damaged
	// how many keyed records from Offset on frame but fail their checksum (at least the one at
	// Offset, unless that is the dictionary or payload). Records inside damage whose framing is
	// lost cannot be counted.
	Records int
	Damaged int
	// Dictionary is set when the segment's attribute dictionary is among them. Every record of
	// the segment is keyed by it, so the records before Offset fail to read too.
	Dictionary bool
	// ColumnarPayload is set when the segment's columnar payload is among them. The records
	// before Offset are remnants that need it, so they fail to read too.
	ColumnarPayload bool
	// Recovered is set when recovery continued past the damage because the framing past it
	// could be proven (a verified columnar payload after it, or the segment's sidecar key index).
	// Loaded is then how many keyed records after Offset verify and were loaded, Records is 0, and
	// Damaged is how many damaged spans every walk skips (DamagedRecordsSkipped): one per damaged
	// record, plus one for a damaged dictionary. Dictionary and ColumnarPayload still say whether
	// those lie past Offset; a dictionary that does not verify leaves the segment's records
	// unreadable (SegDictsUnusable).
	Recovered bool
	Loaded    int
}

OpenDamageStop is one segment whose recovery walk stopped at damage in the middle.

type OpenIndexDiag added in v0.29.0

type OpenIndexDiag struct {
	Dir              string // the collection's directory
	SealedSegments   int    // sealed (non-active) segments seen at open
	SidecarFiles     int    // of those, how many had a .idx sidecar file on disk
	KeyIndexAdopted  int    // key-index sidecar mmapped (the primary-key index; no key rebuild)
	AttrIndexAdopted int    // attribute-index sidecar mmapped -- THESE need no Reindex rebuild
	// Reasons counts, per segment whose attribute index was NOT adopted (and so will be rebuilt),
	// why it was not:
	//   "no-sidecar-file"              -- no .idx on disk (segment predates sidecar persistence)
	//   "sidecar-rejected"            -- .idx present but the container/key index was invalid
	//                                    (older on-disk format, truncation, or a version bump)
	//   "attr-section-missing-or-stale" -- key index adopted, but the attribute-index section was
	//                                    absent, CRC-bad, or did not cover the segment
	Reasons map[string]int

	// StrandedSealedDeltas is how many LIVE delta records were found in sealed segments, and
	// StrandedSealedKeys names up to openStrandedSampleMax of them. Both are zero on a healthy
	// store: the seal-collapse invariant says a live fragment only ever sits in an active
	// segment, and every collapse pass relies on that. A non-zero count means those keys are
	// invisible to the collapse and will lose their base to the next compaction.
	StrandedSealedDeltas int
	StrandedSealedKeys   [][]byte

	// CompositeRefusals names the configured composite tuples this open could not install,
	// and why (see CompositeRefusal). Empty on a store whose configuration resolves, which
	// is the only state worth having. A non-empty one says the store came up WITHOUT an
	// index its configuration asks for -- the queries that tuple was configured for still
	// answer, by intersecting postings or by scanning, so nothing else here will ever
	// mention it. It is reported alongside the sidecar reasons above because it is the same
	// question asked of the configuration rather than of the files: why did this store open
	// with fewer indexes than it was told to have?
	//
	// It is a property of this open's configuration, not an accumulation: the same tuple
	// refused at every reopen appears once per open, never twice in one.
	CompositeRefusals []CompositeRefusal

	// IgnoredFiles names files in a shard directory that recovery did not load because
	// their names do not parse as "seg-<n>.d<dict>.dat". Recovery skips them in silence,
	// which is how a mangled segment name becomes invisible -- and an invisible segment's
	// dictionary looks unreferenced, so pruning retires it. The data is still there and
	// still recoverable, but nothing says so. Non-empty means someone should look; see
	// Fsck, which reports the same files with the reason spelled out.
	IgnoredFiles []string

	// DamageStops lists, up to openDamageStopMax, segments whose recovery walk stopped at a
	// damaged record with records that verify after it. Those records are not loaded (see
	// RecordsPastDamage), unless the stop is marked Recovered: recovery then continued past the
	// damage and set the damaged records aside. Empty on a healthy store; Fsck reports the same
	// damage.
	DamageStops []OpenDamageStop

	// ChainLinksRepaired is how many bucket-chain links between records of a write-target
	// segment Open had to rewrite (see relinkActiveChains). Zero on a store this build wrote. A
	// non-zero count means an earlier crash recovery had cut those links, so until this Open a
	// read of the affected keys could merge too few delta records and return an older value.
	ChainLinksRepaired int
	// SupersessionsUndone counts supersession stamps crash recovery undid because the commit that
	// wrote them did not survive (see horizon.go), and DeletesReplayed delete markers whose stamp
	// it re-applied. Both are zero after a clean shutdown.
	SupersessionsUndone int
	DeletesReplayed     int

	// Timing breaks a persistent Open into its phases so a slow reopen names the phase that
	// dominated, instead of surfacing only as one elapsed number. Durations accumulate across the
	// collection's shards; all zero for an in-memory Open. See OpenTiming. Purely observational.
	Timing OpenTiming
}

OpenIndexDiag summarizes, for a single Collection Open, how each sealed segment's persisted index sidecar was handled: adopted (mmapped, no work) vs. left for the post-Open Reindex to rebuild -- which decodes every record the index covers and is the dominant reopen cost (~95% of reopen time on a large archive). It is emitted once per Open via OpenIndexDiagHook.

It exists to answer, from a production log, "why is startup rebuilding the archive indexes instead of adopting the ones on disk?" -- distinguishing an archive whose segments predate sidecar persistence (no files) from one whose sidecars are present but rejected (format/version) or whose attribute index is absent/stale. Purely observational; it changes no behavior.

type OpenPhase added in v0.34.0

type OpenPhase string

OpenPhase names a phase of a persistent Open, for OpenProgress.

const (
	// OpenMapSegments is the readdir + mmap pass over a shard's segment files.
	OpenMapSegments OpenPhase = "map_segments"
	// OpenLoadSidecars is the per-sealed-segment sidecar load. It is the phase that dominates
	// a large archive's open when sidecars cannot be adopted: such a segment has its index
	// rebuilt by decoding every record it holds, measured at ~95% of reopen time. When they
	// adopt -- the healthy case -- this phase is cheap and the other two are the cost.
	OpenLoadSidecars OpenPhase = "load_sidecars"
	// OpenRebuildDir is the record replay that reconstructs a shard's directory and commit
	// sequence when no directory snapshot could be restored (an unclean previous close, or a
	// shape that forces the full scan). It walks every record of every segment, so it is
	// reported per segment like the others. Measured at ~53% of the CPU of a hub reopen whose
	// sidecars all adopted, which is to say it is not a phase an operator can be left
	// guessing about.
	OpenRebuildDir OpenPhase = "rebuild_dir"
)

type OpenProgress added in v0.34.0

type OpenProgress struct {
	// Dir is the shard directory being loaded.
	Dir string
	// Phase is the phase doing the work.
	Phase OpenPhase
	// Done and Total are segments processed and segments in this phase for this shard.
	Done  int
	Total int
	// Elapsed is how long this phase has been running.
	Elapsed time.Duration
}

OpenProgress is one progress report from a persistent Open.

type OpenTiming added in v0.29.2

type OpenTiming struct {
	MapSegments    time.Duration // readdir + mmap each segment file + derive its write extent
	DirRestore     time.Duration // load the dir snapshot, or (on a miss) rebuild it by walking records
	DirRebuilt     bool          // true if the directory was rebuilt (snapshot missing/stale) not restored
	PublishDict    time.Duration // restore each interned segment's attribute dictionary
	PublishColumns time.Duration // publish each columnarized segment's columnar payload
	LoadSidecars   time.Duration // map each sealed segment's index sidecar (adopt zone map + indexes)
	ZoneRecompute  time.Duration // of LoadSidecars, time decoding records to rebuild a missing zone map
	// ZoneRecomputed is how many segments needed that rebuild, and ZoneUpgraded how many
	// then had the result written back into their sidecar so the next open adopts it
	// instead of decoding again.
	//
	// These exist because the two situations look identical in a timing log and are
	// completely different problems. Recomputed == Upgraded is a ONE-TIME cost that
	// disappears on the next start. Upgraded short of Recomputed means the write-back is
	// not sticking, and every start pays the full decode forever -- which is invisible
	// without this, since the upgrade is best-effort and its errors used to be discarded.
	ZoneRecomputed    int
	ZoneUpgraded      int
	ZoneUpgradeFailed int
	// TrailerFlagsUpgraded is how many sealed segments had the absence of their trailer
	// records written into their sidecar by this open (kidxNoDictRec / kidxNoColRec), and
	// TrailerFlagsUpgradeFailed how many could not be. Same reasoning as the zone counters
	// above: an upgrade that does not land leaves every start walking every record to learn
	// what the sidecar was supposed to say, and nothing else would show it.
	TrailerFlagsUpgraded      int
	TrailerFlagsUpgradeFailed int
	// RecordsWalked is how many records this Open examined ONE AT A TIME, summed over every
	// phase in this struct that has a per-record step.
	//
	// It is the invariant's own measurement: opening a store is O(segments), not
	// O(records), so this must stay bounded by the segment count (plus whatever the
	// one active segment holds, which has no sidecar and must be walked). A value that
	// tracks the store's record count means a phase is walking the whole archive --
	// the regression this counter exists to catch, which a wall-clock number hides
	// because it looks merely slow.
	RecordsWalked int

	Reindex        time.Duration // post-recovery rebuild of indexes not adopted from sidecars
	RebuildOrdered time.Duration // post-recovery rebuild of the maintained ordered indexes
	AdoptSchema    time.Duration // re-enable columnar schema-scan from persisted blocks
	LoadDicts      time.Duration // load on-disk dictionaries before segment recovery
	LoadDemand     time.Duration // load checkpointed query demand
}

OpenTiming records how long each phase of a persistent Open took, accumulated across shards. A reopen that adopts every sidecar (OpenIndexDiag reasons empty) but is still slow is explained here: the cost is in mapping segments, rebuilding the directory (a snapshot miss forces a full record walk), recomputing zone maps for segments that lack one, or the post-recovery index/order rebuilds -- and this says which.

type Options

type Options struct {
	// Shards is the number of independently-locked shards; rounded up to a power
	// of two. Default 16. Forced to 1 when AppendOnly (an append log is a single
	// ordered sequence: it needs one segment chain, not sharded key routing).
	Shards int
	// AppendOnly makes the collection a pure append log: every Put appends a new
	// record (no per-key supersession, no directory, no compaction, no deletes) --
	// the model a history archive needs. Records accumulate in commit order and are
	// reclaimed only by whole-segment retention, not compaction. Scan/Query see every
	// appended record; Get/Delete-by-key are not meaningful (there is no key index).
	AppendOnly bool
	// ReverseScan makes Scan/Query yield records newest-first (most recently
	// appended first) instead of in stored order. It walks segments from the last
	// (newest) backward and, within a segment, records back-to-front -- the natural
	// "last K" order a history archive presents (condor_history shows the most
	// recent jobs first). A consumer that stops early (yield/emit returns false)
	// after K records therefore gets the K newest, a pushed-down LIMIT. Reverse
	// scans always run serial (never fan out). Default false ⇒ stored order.
	// Most meaningful with AppendOnly, where stored order is commit order.
	ReverseScan bool
	// Retention bounds how much an AppendOnly collection keeps: Rotate(now) drops
	// whole oldest segments until the collection is back within these bounds (a
	// history archive's aging-out). The zero value keeps everything (Rotate is
	// then inert). Only meaningful with AppendOnly. See Rotate.
	Retention Retention
	// IndexBackfillBytes bounds how far back Reindex carries an index configuration change.
	// When set, Reindex rebuilds the existing index of only the segments within the newest
	// IndexBackfillBytes; older ones keep the index they already have until BackfillIndexes
	// (or ReindexAll) reaches them.
	//
	// The point is that rebuilding is not free -- it decompresses every record it covers --
	// while an out-of-date index is still perfectly usable for the attributes it does hold
	// (recovery uses whatever a segment's index covers, deciding per probe). Reindex runs
	// after every seal of an archive and inside every AddIndex, so it must not pay for the
	// whole history; BackfillIndexes pays for it a budgeted slice at a time instead.
	//
	// 0 carries a change across every segment, which is the historical behaviour.
	IndexBackfillBytes int64

	// InternAtSeal makes an AppendOnly collection intern each segment as soon as it
	// seals (when the active segment fills), rather than only when RetrainDict/Rewrite
	// later reseal it. Interning stores segment-local ids + a per-segment name dictionary
	// instead of inline names, halving raw mmap bytes and speeding decode (see the
	// interning design). This trades a per-seal transcode (off the write lock) for the
	// density/decode win landing immediately on an archive that never retrains. Only
	// meaningful with AppendOnly (a mutable segment's records can be superseded in place,
	// which an off-lock transcode would race -- there interning rides compaction instead).
	// Optional; default off preserves exactly today's behavior. See InternSealed.
	InternAtSeal bool
	// ZoneAttrs names numeric attributes to keep a per-segment [min,max] zone map on,
	// so a range/equality query on one (e.g. CompletionDate > T) skips whole sealed
	// segments whose span cannot match, and age-based Retention (MaxAgeAttr) can drop
	// a segment by its newest timestamp. Value-indexed attributes (ValueAttrs) are
	// zoned automatically. Only meaningful with AppendOnly. Optional. See zonemap.go.
	ZoneAttrs []string
	// OnHighMarkError is called when the seal-time size eviction fails to unmap or unlink a
	// segment it dropped. The eviction itself has already happened; the error is the
	// reclaim, so discarding it silently is how a store leaks files nobody looks for.
	// nil discards it.
	OnHighMarkError func(error)
	// OnDictFault is called when a maintenance check finds a compression dictionary's
	// file missing, replaced, or changed underneath the store (see dictpin.go). The
	// argument is a *DictFault, so errors.As reaches the id and the kind.
	//
	// This is the loud half of the check and the one worth wiring up. The counters say
	// how many; only this says which, and when. A missing file is rewritten from the
	// descriptor the store still holds, so by the time the callback runs the damage is
	// usually already undone -- but something outside the process is deleting
	// dictionaries, and that is worth an operator's attention before the restart that
	// would have made it permanent. nil discards it.
	OnDictFault func(error)
	// ProfileBucketBytes is the quantile resolution of each sealed segment's retention
	// profile, in stored bytes (see segprofile.go). 0 means 1 MiB, lowered to an eighth of
	// SegmentSize when that is smaller -- a bucket near or above the segment size leaves a
	// segment all-or-nothing to the eviction cutoff, so it can be dropped whole but never
	// trimmed. Finer buys a tighter cutoff and costs bytes in every sidecar.
	ProfileBucketBytes int64
	// SegmentSize is the arena segment size in bytes. Default 8 MiB.
	SegmentSize int
	// Hasher routes keys to shards / directory buckets. Default 64-bit FNV-1a.
	Hasher Hasher
	// Codec compresses stored ad bytes. Default identity (no compression).
	Codec Codec
	// DeltaMax turns on DELTA RECORDS and bounds the chain: it is IGNORED on an AppendOnly
	// collection, where there is no earlier version of a key to merge with and the tracker
	// would grow per record forever. A write that names the attributes
	// it changed stores only those, until a key has accumulated DeltaMax deltas, at which
	// point the next write stores the whole ad again. 0 (default) stores whole ads always,
	// which is the historical behavior.
	//
	// It trades write volume for read work. A live job ad averages ~7.3 KB while one
	// transaction's changes average ~150 B, so writes shrink by ~49x; a point read has to
	// merge up to DeltaMax fragments over a full record. Requires inline-name records (a
	// persistent store) and is not combined with columnarization, which assumes each record
	// holds a whole ad.
	DeltaMax int
	// HotAttrs names the "popular" attributes to front-load in each ad's hot
	// header, so a query filtering on them resolves each in O(1) instead of
	// scanning the ad body. Typically the attributes common queries filter on
	// (e.g. Cpus, Memory, Arch, OpSys, State). Optional.
	HotAttrs []string
	// MatchClosureRoots names attributes (typically "Requirements") whose transitive
	// self-reference closure is front-loaded into each ad's hot header at encode time,
	// so matching a wide ad reads only the match-relevant attributes (via the hot
	// header) instead of decoding the whole ad. Optional; enables the hot-closure match
	// fast path. The frequency/HotAttrs hot set is unioned in, so queries are unaffected.
	MatchClosureRoots []string
	// SchemaRequireAttrs names attributes that enter the derived columnar schema whatever their
	// presence rate -- the override on the rule that an attribute becomes a fixed-slot field only
	// when its dominant storable kind appears in at least 90% of sampled records.
	//
	// That floor bounds a real cost (a slot is bytes in EVERY record, including those that lack
	// the attribute) and it is the right default, but it is the only test of membership: the
	// demand ranking that picks the hot tier chooses among fields the schema already has, so no
	// amount of reading ever admits one. An attribute written only once a record reaches some
	// state can sit far below the floor and still be the most-queried attribute in the workload.
	//
	// Required bypasses PRESENCE only. The attribute must still have a dominant storable literal
	// kind -- one that is usually an expression is refused, because a slot that escapes in every
	// record is strictly worse than no slot: the value is read from the record either way, every
	// record pays the escape bit and the layout, and a numeric column of escaped expressions makes
	// the vectorized count hand the query back per record. An int's width is still chosen by Fit
	// from the sampled values. One with no occurrences at all
	// is skipped, since there is no kind or width to lay a slot out with. Both refusals are
	// reported (SchemaRequireSkipped, SchemaScanInfo.RequireSkipped).
	//
	// Nothing in this package reads an attribute NAME. Which attributes deserve a slot they have
	// not earned by presence depends on the lifecycle of the records being stored, which only the
	// use case knows; this is the knob it supplies them through.
	//
	// Changing the set on a live collection re-derives nothing by itself; the next maintenance
	// review (BuildAndEnableSchemaScan) adopts the schema it produces and converges the sealed
	// segments onto it, ColumnarSegmentBudget per pass. See SetSchemaRequireAttrs.
	SchemaRequireAttrs []string
	// GroupSchemaCount is how many SECONDARY columnar schemas to derive and build alongside the
	// base one, for attributes the base schema does not carry which are present or absent
	// together. 0 uses defaultGroupSchemas; a NEGATIVE value builds none.
	//
	// On by default because the base schema's coverage is otherwise hostage to the mix of ads in
	// the table: measured on a production AP, a history table's base schema covers 90.3% of
	// attribute occurrences until jobs removed before ever running are mixed in, at which point
	// it falls to 51.3%, while base plus four groups holds 87-94% across the range. Enabling by
	// default still commits no storage on the strength of one sample -- nothing is built until a
	// group's members have kept recurring across GroupStabilityRuns maintenance passes.
	GroupSchemaCount int
	// ColumnarSegmentBudget is how many sealed segments one maintenance pass may rewrite into
	// COLUMNAR-NATIVE form -- each attribute the schema carries stored once, in the segment's own
	// columnar payload, and removed from the records (see colnative.go). 0 uses
	// defaultColumnarBudget; a NEGATIVE value disables the rewrite and keeps every segment
	// whole-record with a columnar copy beside it in the sidecar.
	//
	// On by default because the duplication is pure cost: without it every value the schema
	// carries is stored twice, row-form in the arena and again in the sidecar block. Measured on
	// 1500 real OSPool machine ads, moving them removed 43% of the table (4104 -> 2327 bytes per
	// record), and the sidecar megabyte it reclaimed was entirely the duplicate copy.
	//
	// Budgeted rather than unbounded because turning it on over an existing archive rewrites every
	// sealed segment once, and at history scale doing that in a single pass is hours of I/O and a
	// flushed page cache -- the same failure a retrain caused when it resealed a whole archive.
	// Each segment is rewritten at most once, so a bounded budget still converges. The pass takes
	// the newest segments first, round-robin across shards.
	//
	// The budget is for that backlog only. A segment that seals while a schema is committed is
	// columnarized right away by a background worker, unbudgeted, rather than waiting its turn
	// behind the backlog (colseal.go). A negative value disables that too.
	ColumnarSegmentBudget int
	// RemnantDictionary decides whether columnarizing a segment also stores, per row group, the
	// non-literal values its records repeat -- expressions, nested records and lists such as a
	// cluster's shared Requirements -- once, with each record holding a short reference in their place
	// (see colremdict.go). Measured on a production AP's history, that removed 13-30% of columnarized
	// segment bytes (8-16% on epoch history). 0 takes the default, which is ON; a negative value turns
	// it off, and a positive one on.
	//
	// What an older build does with such a segment: it refuses to open the collection
	// (ErrUnsupportedColumnarVersion) rather than misread a reference, and its fsck reports the segment's
	// payload version as unsupported. Nothing is lost or modified, and rolling forward reads every
	// record. A caller that must stay openable by a build that predates dictionaries sets this negative.
	// Every build from this one on reads them whatever this is set to.
	RemnantDictionary int
	// MoveListColumns decides whether columnarizing a segment stores a list-valued attribute's qualifying
	// lists ONLY in the block's typed list column, leaving a short placeholder in each record where the
	// list was (see collistmove.go), rather than keeping the list in the record and a copy in the column.
	// Measured on pool slot ads, the lists are ~6.6% of the records' stored bytes. A cell moves only when
	// the column's re-encoding of its values is the record's stored bytes exactly. 0 takes the default,
	// which is ON; a negative value turns it off, and a positive one on.
	//
	// What an older build does with a segment holding a moved list: it refuses to open the collection
	// (ErrUnsupportedColumnarVersion), and its fsck reports the segment's payload version (3) as
	// unsupported. Nothing is lost or modified. To roll back to such a build, first run this one with the
	// option negative: each schema review then re-columnarizes the segments holding moved lists (within
	// ColumnarSegmentBudget) with the lists back in their records, until fsck reports no version 3
	// payload. A segment with no qualifying list is written as before whatever this is set to.
	MoveListColumns int
	// RowGroupBytes is the uncompressed record-bytes budget for one columnar row group. 0 uses
	// colGroupTargetBytes (128 KiB).
	//
	// This is the knob that decides how much of a segment has to be decompressed to read a single
	// record, against how far compression can see across records -- larger groups compress better and
	// cost more per point lookup. The default is measured (see colGroupTargetBytes); it is exposed
	// because the right point depends on the read mix and on how much of the working set fits the
	// block cache, which a large production table is the only honest place to find out.
	//
	// The row cap and the 8-row group alignment are deliberately not configurable.
	RowGroupBytes int
	// GroupStabilityRuns is how many consecutive derivations a group's members must have
	// co-occurred in before its blocks are built. 0 uses the default; 1 disables the gate.
	GroupStabilityRuns int
	// GroupMergeJaccard widens a group by absorbing attributes whose presence pattern is at least
	// this similar. 0 uses defaultGroupJaccard; a NEGATIVE value keeps exact co-occurrence only.
	// GroupMaxPartialFrac bounds the fraction of ads that may then hold only PART of a group and
	// take the slow path for it; 0 uses defaultGroupMaxPartial.
	//
	// Measured against a later snapshot of the same table, widening still recovered more than
	// exact grouping (25.14% of attribute occurrences against 23.53%), because a partial ad reads
	// from the cold tail -- where it would have read anyway -- rather than paying a penalty. The
	// in-sample partial rate does NOT predict the later one, though, and no widened member set
	// reproduced across snapshots, so the stability gate refuses to build one. See
	// mergeNearPatterns.
	GroupMergeJaccard   float64
	GroupMaxPartialFrac float64
	// DemandHalfLife is how quickly recorded query demand fades, so index decisions
	// track the current workload rather than everything the process has ever seen. 0
	// uses defaultDemandHalfLife; negative disables decay (counters accumulate for the
	// lifetime of the data, as they did before decay existed).
	DemandHalfLife time.Duration
	// CommitSync, if set, is called once per committed (possibly group-coalesced)
	// batch on a shard, after the writes are applied — the point at which a future
	// durable collection would fsync/serialize the batch. Group commit amortizes
	// this across all writers that commit together. It must be safe for concurrent
	// use across shards. Optional; default no-op (in-memory store).
	CommitSync func()
	// CategoricalAttrs names string-valued attributes to index for equality and
	// set-membership (`Attr == "x"`, `Attr == "x" || Attr == "y"`). ValueAttrs
	// names numeric attributes to index for equality and range (`Attr >= n`). A
	// query filtering on an indexed attribute visits only candidate ads instead of
	// scanning all of them. Optional.
	//
	// A name holding a dot indexes a NESTED PATH, written the way a query writes it:
	// "Res.Mem" indexes what `Res.Mem` selects, so a constraint on it is a probe rather
	// than a scan. An attribute whose own name contains a dot therefore cannot be indexed
	// as itself -- a path is what a dot means here, and that ambiguity is resolved once,
	// at configuration, rather than at every query (see indexSpec.paths).
	CategoricalAttrs []string
	ValueAttrs       []string
	// CompositeAttrs names attribute TUPLES to index together, so a conjunction of
	// equalities on all of them (`ClusterId == 7 && ProcId == 3`) is one index lookup
	// rather than a probe per attribute whose posting lists are then intersected. Each
	// tuple's attributes must also appear in CategoricalAttrs or ValueAttrs, or in
	// CategoricalComponentAttrs / ValueComponentAttrs; a tuple naming an attribute none of
	// those lists mentions is ignored, because there is then no kind to fold its values
	// with. A composite answers only the full tuple, and everything else (one attribute
	// alone, a range) is served by the components' own indexes -- or, for a component-only
	// attribute, by a scan. Order matters for identity: {"ClusterId","ProcId"} and
	// {"ProcId","ClusterId"} are two composites, and either answers the same conjunctions.
	// Optional.
	CompositeAttrs [][]string
	// CategoricalComponentAttrs / ValueComponentAttrs name attributes that are indexed ONLY
	// as composite components: they may appear in a CompositeAttrs tuple, and they get no
	// index of their own. Which list a name is in fixes its KIND, exactly as
	// CategoricalAttrs / ValueAttrs does for a real index -- a component's kind has to be
	// settled at configuration time so that the record side and the probe side fold its
	// values identically, and an attribute with no index of its own has nowhere else to get
	// one from. A name in both lists is categorical; a name that is also in CategoricalAttrs
	// or ValueAttrs is ignored here, since its own index already settles its kind.
	//
	// WHAT THIS GIVES UP, which is the whole point of the setting: a composite answers a
	// conjunction pinning EVERY one of its components and nothing else, so a constraint that
	// names a component-only attribute alone -- `ProcId == 5`, `ProcId >= 2`, `ProcId !=
	// 1` -- gets no index at all and scans. IndexedAttrs does not report these attributes,
	// because callers use it to decide whether a constraint can be index-answered and for
	// these the answer is no.
	//
	// It is worth it when nothing queries the attribute by itself and its standalone index
	// would be large: a history archive asking only `ClusterId == c && ProcId == p` per
	// record gets nothing from a ProcId index, and on a real pool one cluster carries nearly
	// three million distinct ProcIds to key. Optional.
	CategoricalComponentAttrs []string
	ValueComponentAttrs       []string
	// Ordered configures maintained, filtered, ordered indexes -- the schedd
	// priority-queue pattern (see docs/MATCH.md §3 and Collection.Ordered). Each
	// spec groups members into partitions and keeps them sorted on the write path,
	// so a negotiator can iterate a partition in order (and resume) without
	// re-sorting each cycle. A malformed expression in a spec panics New. Optional.
	Ordered []OrderSpec
	// DisableReadVerification turns OFF the check that a record's stored checksum
	// matches its bytes before they are used.
	//
	// Verification is ON by default, which is why this option is phrased as a
	// negative: Go's zero value is false, and the safe setting is the one you get
	// without thinking about it. Without the check, a bit flip inside a sealed
	// record's encoded ad is served as a plausible value -- Owner "urer3" where
	// "user3" was written -- with no error anywhere, because the checksum that would
	// catch it was only ever read at recovery.
	//
	// It covers point reads and the iterator path every scan and query goes through
	// (wire/wireAt and adBytes, the two places the package already reassembles a
	// partial record), so one switch governs both. A refused record is skipped, never
	// half-served, and counted by VerifyReadSkips -- a shrunken answer has to be
	// observable, since "fewer rows came back" is otherwise indistinguishable from
	// "there were fewer rows".
	//
	// The cost is about 17ns a record: a hardware CRC-32C over a 160-byte record,
	// against roughly 760ns to decode one on a scan. It adds NO storage -- the
	// checksum has always been written. Turn this on only for a read-bound workload
	// that has measured the difference and prefers a wrong answer to a slow one.
	//
	// What it is worth depends on the CODEC, and the difference is stark. A ZSTD frame
	// carries its own content checksum, so a flipped bit in a compressed ad is refused
	// either way and verification adds little for the ad body (it still covers the key,
	// the framing and the commit sequence, which no codec touches). Under the identity
	// codec nothing covers the ad, and the record CRC is the only thing between a
	// flipped bit and a plausible wrong value: Owner "urer3" where "user3" was written.
	// See TestVerificationValueDependsOnTheCodec, which measures both.
	//
	// That is not an academic distinction. db's chooseBaseCodec gives NEW stores ZSTD
	// but keeps identity for one that already held data, so the stores where this is
	// load-bearing are the oldest -- usually the largest and busiest.
	DisableReadVerification bool

	// Dir, if set, makes the collection persistent: arenas are memory-mapped files
	// under this directory and committed writes are flushed to disk (see Open).
	// Empty ⇒ in-memory (the default). Unix-only.
	Dir string
	// QueryParallelism controls cross-segment fan-out for large full-scan queries:
	//   0 (default) ⇒ auto — the library picks the policy (currently: up to 6 workers
	//                 per query, clamped to GOMAXPROCS). The meaning of auto may change
	//                 across releases.
	//   1           ⇒ serial (never fan out).
	//   N ≥ 2       ⇒ fan out with up to N workers per query.
	// In every non-serial case fan-out is still gated by a work-size threshold, never
	// exceeds the segment count, and draws from a machine-wide worker budget shared
	// across concurrent queries (so it degrades to serial under load rather than
	// oversubscribing). Small scans and indexed queries run serial regardless.
	// See parallel_scan.go / docs/PARALLEL_QUERY.md.
	QueryParallelism int
	// AggMinBytes overrides the live segment bytes an AGGREGATE pass must cover before it fans
	// out across segments. 0 takes the measured default; see defaultAggMinBytes, which carries the
	// numbers it was set from. A value below the default buys nothing on a real workload -- the
	// fan-out is measurably slower than staying serial under it -- so this exists for a test that
	// needs to exercise the fanned-out path without building the tens of megabytes the real gate
	// asks for, and for an operator who has measured their own hardware and disagrees.
	AggMinBytes int
	// WatchHistory enables the Watch subscription verb (see docs/WATCH.md). It is the
	// per-shard capacity of the delete journal — how many recent deletes are retained
	// so a resuming watcher can be told precisely which keys were removed. 0 (default)
	// disables Watch entirely (no journal, no live notification, zero write-path cost).
	// A larger value lets clients resume incrementally from further back before
	// falling to a full replay.
	WatchHistory int
	// WatchRetain, when > 0, is how far back in time a persistent collection keeps its
	// delete markers, so a watcher that reconnects after a restart can still be told which
	// keys went away. Reclamation drops a fully-superseded segment as soon as nothing can
	// read its records, and a delete marker is not a record anyone reads -- so without this
	// the replayable window is whatever compaction has not yet reclaimed, which is a
	// function of write volume rather than of anything a watcher was promised.
	//
	// It is a duration because that is the question a caller can actually answer: how long
	// a consumer may be away -- a restart, a redeploy, a network partition -- and still
	// resume incrementally. The equivalent in commit sequences is not a property of the
	// deployment at all, since the same count is hours of an idle shard and seconds of a
	// busy one.
	//
	// It is a ceiling on retention, not a consumer's position: a watcher that never comes
	// back cannot hold history open, and a cursor older than the window gets a Reset, which
	// is the honest answer. 0 (the default) retains nothing extra and leaves reclamation
	// exactly as it was. Requires WatchHistory > 0 to have any effect.
	//
	// Turning this on also starts the time->seq checkpoints (see timeseq.go) that resolve
	// the window, at most one per minute per shard, written into the segment arena as
	// markers that ride the existing msync.
	WatchRetain time.Duration
	// WatchBuffer is the per-watcher live event-channel capacity (default 1024). A
	// watcher that overflows it is told to resync rather than stalling writers.
	WatchBuffer int
	// WatchCoalesce, if > 0, batches live Watch events into windows of this
	// duration and emits only the newest event per key in each window (default 0 =
	// off, one event per change). It smooths bursty churn -- e.g. a freshly
	// submitted job that takes many SetAttribute updates in quick succession is
	// delivered as a single Upsert of its settled state. Only the last event of a
	// flushed window carries a cursor, so a mid-window consumer crash resumes from
	// the prior window and re-delivers (at-least-once is preserved). Catch-up is
	// never coalesced.
	WatchCoalesce time.Duration

	// ParentKeyFor, if set, gives an ad a parent: it maps a child's key to its
	// parent's key (return nil for a top-level ad with no parent). A child then
	// resolves attribute references it lacks by falling through to its parent --
	// the primitive "join" the job queue needs, where a proc ad chains to its
	// cluster ad so a query like `DAGManJobId == 42` sees the cluster's attribute.
	// A family (a root and all its descendants) is co-located in one shard -- the
	// collection routes every key to the shard of its ultimate root -- so chained
	// evaluation is consistent and lock-free. Parent bindings are immutable: a
	// key's parent must not change across updates. Default nil disables chaining
	// (every ad is standalone) and keeps the plain single-key routing/scan.
	ParentKeyFor func(key []byte) []byte

	// IsStructural, if set, marks a key as a structural (parent-only) ad that
	// exists solely to be chained to -- e.g. a job cluster ad. Structural ads are
	// stored and used as parents but are hidden from Query/Scan/Watch results by
	// default (like condor_q omitting cluster ads). Default nil treats every ad as
	// a normal, visible ad. Only meaningful together with ParentKeyFor.
	IsStructural func(key []byte) bool

	// ParentPrivateAttrs are parent attributes children do NOT inherit and that do
	// NOT trigger a watch fan-out when they change -- e.g. a job cluster ad's
	// factory bookkeeping (JobMaterializeNextProcId, ...), which mutates per proc
	// materialized but is meaningless to a proc. They are excluded from flattening
	// and from the parent-change diff, so high-frequency parent-internal churn does
	// not fan out to every child. Case-insensitive. Only meaningful with ParentKeyFor.
	ParentPrivateAttrs []string

	// DataKey enables encryption at rest: the named attributes' values are sealed with
	// AES-256-GCM under this key before being written to a segment. It must be the DB
	// master key's DataInfo subkey (crypt.Subkey(master, crypt.DataInfo)) -- distinct
	// from the master itself -- so a stolen database is useless without a pool key.
	// Empty ⇒ encryption disabled (EncryptedAttrs is then inert). Otherwise it must be exactly
	// crypt.KeySize (32) bytes: Open refuses any other length with ErrInvalidDataKey, and New
	// panics with it. See encrypt.go.
	DataKey []byte
	// EncryptedAttrs names the attributes to encrypt at rest (case-insensitive). Only
	// meaningful with DataKey set. An encrypted attribute may NOT also be indexed
	// (CategoricalAttrs/ValueAttrs) -- New panics on overlap -- since its value is
	// opaque at rest. The set can be changed at runtime via the toggle meta-command;
	// existing records keep their prior form until MigrateSealedAttrs rewrites them.
	//
	// An encrypted attribute's value must not depend on other attributes: it should be a
	// literal -- a token or a secret string, as every private attribute is. Reads rely on
	// this and treat a sealed value as referring to nothing: a reference inside one is not
	// followed by the projections that close over references (QueryRawProjected with
	// chaseRefs, QueryRawWireRefs), nor by the narrowed or partial decode a query is
	// evaluated on, so such a value is evaluated as if the attributes it names were absent
	// unless the read loaded them for another reason.
	EncryptedAttrs []string

	// TimeTravel, if non-nil, enables point-in-time ("AS OF") queries: superseded
	// record versions committed within MaxDistance of now are retained (not reclaimed
	// by compaction), and a sparse time->seq checkpoint is recorded so a wall-clock
	// time resolves to the commit sequence that was current then. Nil (default)
	// disables it with zero write-path cost -- retention collapses to the current seq,
	// exactly as before. See timeseq.go. It can be toggled at runtime.
	TimeTravel *TimeTravelOptions

	// SeqCursorLease is how long a paged read (QueryRawFromSeq) keeps a shard's snapshot
	// readable after taking it: compaction retains the versions it sees, or in a collection
	// with delta records defers reclaiming the shard, for at most this long. A cursor resumed
	// after maintenance has reclaimed past its snapshot gets ErrSeqCursorExpired rather than
	// a short listing. Zero means 10 minutes; negative disables the lease, leaving only the
	// refusal. See seqlease.go.
	SeqCursorLease time.Duration

	// MutatingBlockCacheBytes and ArchiveBlockCacheBytes set the PROCESS-GLOBAL shared
	// decompressed-columnar-block cache budgets, in bytes, for the two workload kinds: one budget
	// shared by ALL mutating (sharded, key-superseding) collections, and a separate one shared by ALL
	// append-only ARCHIVE collections. This replaces the old fixed 256 MB-per-collection cache, whose
	// footprint grew as 256 MB × (number of columnarized tables) with no knob. Both are global
	// ceilings, not per-collection budgets. A value ≤ 0 leaves the current/default budget
	// (defaultMutatingCacheBytes / defaultArchiveCacheBytes, 512 MiB each). Setting either here is
	// equivalent to calling Set{Mutating,Archive}BlockCacheBudget; the last non-zero setting wins and
	// resizes the live shared cache. Because the budget is global, prefer setting it once (e.g. from
	// db/ at startup) rather than per table. An archive collection uses the archive budget; every
	// other collection uses the mutating budget.
	MutatingBlockCacheBytes int64
	ArchiveBlockCacheBytes  int64
}

type OrderCursor added in v0.5.2

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

OrderCursor marks a position in an ordered scan. Its zero value starts at the beginning of a partition; the cursor yielded alongside an ad resumes strictly after that ad, so a negotiator can iterate a partition across several calls.

type OrderSpec added in v0.5.2

type OrderSpec struct {
	Partition string    // attribute partitioning the index; empty = one global partition
	Where     string    // membership predicate; empty = every ad is a member
	Keys      []SortKey // sort order within a partition
	// Cluster names the attributes whose combined value forms a member's cluster
	// signature -- a hash surfaced alongside each ad by Ordered. The schedd's RRL
	// fold groups the ordered stream into runs of equal signature (a stored-value
	// compare instead of re-hashing the requirement attributes each cycle). Computed
	// once on the write path. Empty = no signature (Ordered reports 0). Optional.
	Cluster []string
}

OrderSpec configures a maintained, filtered, ordered index over a collection -- the schedd's priority-queue pattern (§3 of docs/MATCH.md). Members are grouped into independent runs by Partition (e.g. per Owner); within a partition they are ordered by Keys, with insertion order as the final tiebreaker ("the order the job entered the queue"). Where restricts membership to the ads that matter (e.g. idle jobs), so the index tracks only the churn-prone subset.

type OrderedAd added in v0.5.2

type OrderedAd struct {
	Ad        *classad.ClassAd
	Cursor    OrderCursor
	Signature uint64
}

OrderedAd is one step of an ordered scan: the member ad, a cursor that resumes right after it, and the cluster signature (0 unless OrderSpec.Cluster is set). The signature lets an app run-length-fold the stream into RRLs with a stored-value compare instead of re-hashing each ad's clustering attributes.

type Phase added in v0.46.0

type Phase uint8

Phase names one place a query's wall time goes. The values are not on any wire and may be renumbered; Name is the stable spelling.

const (
	// PhaseParse is parsing the constraint text: the dbrpc private-attribute check and the db
	// layer's compile each parse it. Sequential: before anything is read.
	PhaseParse Phase = iota
	// PhasePlan is building the scan: the query's matcher and read plan, its projection and
	// selector, and the choice of index probes. Sequential: before any segment is touched.
	PhasePlan
	// PhaseIndexCatchUp is a read bringing the unsealed segments' indexes up to date before it
	// walks index candidates (catchUpIndexes). Sequential, right after planning.
	PhaseIndexCatchUp
	// PhaseSnapshot is taking a shard's snapshot: waiting for its read lock, then freezing and
	// pinning the segment windows. Once per shard, so interleaved with the shards' walks.
	PhaseSnapshot
	// PhaseZonePrune is testing each segment's zone map against the query. Once per shard.
	PhaseZonePrune
	// PhaseIndexProbe is reading the segment indexes for candidates: the postings intersection
	// (or its skip verdict) per segment and the delta scope a candidate walk adds to it.
	// Interleaved with the walk of the candidates it produced.
	PhaseIndexProbe
	// PhaseRecords is walking records on the query goroutine: framing, decompression, deciding
	// each record from its columns or reassembling it, evaluating the constraint, projecting, and
	// the consumer's own per-record work (encoding a row, folding it into an aggregate). These
	// alternate record by record, so they are one phase; ScanStats' counts say which dominated.
	// Frame writes the consumer makes inside the walk are PhaseWrite, not this.
	PhaseRecords
	// PhaseColumnar is a columnar producer's own work: reading a block's columns, running the
	// predicate over them and gathering the matches into a batch. The batches' consumer is not in
	// it. Interleaved, batch by batch, with PhaseEncode and PhaseWrite.
	PhaseColumnar
	// PhaseDeclined is an aggregate's strategies that looked at the request and declined it
	// before one answered. Sequential: the ladder tries them in order.
	PhaseDeclined
	// PhaseAggregate is the strategy that answered an aggregate, outside any record walk inside
	// it: the whole of a columnar or index strategy, or a scan strategy's final reduction. A scan
	// strategy's walk is PhaseRecords, its planning PhasePlan.
	PhaseAggregate
	// PhaseWorkerWait is the query goroutine blocked on its parallel workers for the next batch of
	// rows. Interleaved with PhaseEmit.
	PhaseWorkerWait
	// PhaseEmit is handing rows the workers assembled to the consumer, where that is separable from
	// the walk (a parallel scan's drain). In a serial walk the same work is inside PhaseRecords.
	PhaseEmit
	// PhaseEncode is building response frames from an answer the store has already produced: an
	// aggregate's rows, a top-K, a column batch. The writes themselves are PhaseWrite.
	PhaseEncode
	// PhaseWrite is handing response frames to the connection: waiting for its writer, then
	// writing. It is dbrpc's TraceResult.WriteBlocked, recorded as a phase so the walk it
	// interrupts is reported net of it.
	PhaseWrite

	// NumPhases is the number of phases, for iterating them.
	NumPhases
)

func (Phase) Name added in v0.46.0

func (p Phase) Name() string

Name is the phase's stable lower-case spelling, for a span attribute or a log field.

func (Phase) Sequential added in v0.46.0

func (p Phase) Sequential() bool

Sequential reports whether the phase runs as one stretch of the query rather than interleaved with others: planning before the first segment, the declined strategies before the one that answered. Only such a phase can honestly be drawn as an interval on a timeline, and only when QueryPhases.Contiguous confirms this query ran it in one piece. An interleaved phase's duration is a sum over many short stretches, and drawing it as one would show a waterfall that never happened.

type PhaseMark added in v0.46.0

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

PhaseMark is the start of an interval, from QueryPhases.Mark.

type PrefixDecompressor added in v0.16.4

type PrefixDecompressor interface {
	DecompressPrefix(dst, src []byte, want int) ([]byte, error)
}

PrefixDecompressor is an optional Codec capability: decompress only (approximately) the first want bytes of a record. With the hot region encoded as a physical prefix (see wire.EncodeInlineWithHotEnc), a hot-covered projected read decompresses a couple of KB instead of the whole record. The result may be shorter than want (the record ends first -- then it is the complete record) and is otherwise a TRUNCATED record: the caller must be prepared for parses to run off the end and fall back to a full Decompress.

type ProbeExplain added in v0.6.0

type ProbeExplain struct {
	Attr    string `json:"attr"`
	Op      string `json:"op"`
	Indexed bool   `json:"indexed"`        // this probe can use an index to prune
	Kind    string `json:"kind,omitempty"` // "categorical" | "value" | "" (attr not indexed)

	// Selectivity and EstCandidates are the planner's estimate of how much this
	// probe prunes, present only when Indexed: EstCandidates is the estimated
	// number of ads the index would visit for this probe (summed over the segment
	// indexes' selectivity stats), and Selectivity is that as a fraction of the
	// total (lower is more selective). HasSelectivity distinguishes a real 0 from
	// "not estimated".
	HasSelectivity bool    `json:"hasSelectivity"`
	Selectivity    float64 `json:"selectivity,omitempty"`
	EstCandidates  int64   `json:"estCandidates,omitempty"`

	// Coalesced marks a conjunct the planner folded into another probe on the same value
	// attribute: the opposite bound (`Memory > 1024 && Memory < 4096` becomes one two-sided
	// probe), a tighter same-side bound that subsumes it (`Memory > 1024 && Memory > 512`
	// probes only `> 1024`), or a range an equality absorbed (`Memory == 2048 && Memory >
	// 1024` probes only the equality). Selectivity/EstCandidates then describe the folded
	// probe, not this conjunct's own reach; the conjunct that IS the probe is left unmarked.
	Coalesced bool `json:"coalesced,omitempty"`
}

planIndex matches the query's probes against the configured indexes. Empty means no index-usable constraint (the store full-scans). ProbeExplain describes how one index-satisfiable conjunct of a query relates to the configured indexes.

type QueryExplain added in v0.6.0

type QueryExplain struct {
	// Native reports wire-native evaluation: the query reads scalar-literal
	// attributes directly from the encoded ads, building no ClassAd per ad.
	Native bool `json:"native"`
	// Probes are the query's index-satisfiable conjuncts and their index status.
	Probes []ProbeExplain `json:"probes"`
	// IndexUsable is how many probes can prune via an index.
	IndexUsable int `json:"indexUsable"`
	// Plan is the chosen access path: "indexed" (visit index candidates), "indexed-union"
	// (visit the union of the candidates of each disjunct in Groups), "parallel-scan",
	// "serial-scan" (full scan), or "empty" (a contradictory conjunct makes the query
	// unsatisfiable, so no records are visited at all).
	Plan string `json:"plan"`
	// Parallelism is the configured per-query worker cap; Shards is the shard count.
	Parallelism int `json:"parallelism"`
	Shards      int `json:"shards"`
	// TotalAds is the live ad count, the denominator for probe selectivity.
	TotalAds int `json:"totalAds"`
	// Groups are, for a filter whose top-level ORs (nested ORs distributed) give more than one
	// disjunct, each disjunct's index-satisfiable conjuncts. Set whether or not the plan reads
	// through them: an "indexed-union" plan does, and a scan's Reason says why it does not.
	Groups []GroupExplain `json:"groups,omitempty"`
	// EstCandidates is, for an indexed plan, the estimated records the index hands the scan:
	// per segment, the smallest of its probes' posting estimates, summed. IndexSegments is how
	// many segments answer from an index, IndexSkippedSegments how many the index proves hold
	// no candidate, and UnindexedSegments how many no index covers (an unsealed segment, or
	// one sealed before the attribute was indexed), which are walked in full.
	EstCandidates int64 `json:"estCandidates,omitempty"`
	// EstVisited is the estimated records a read of this plan VISITS: what the access path
	// hands the scan from the segments it answers, plus the whole of every segment it hands
	// over unfiltered. It is the number to COST a read with, and the one EstCandidates is
	// mistaken for.
	//
	// They differ in three ways, each of which makes EstCandidates too small: it is zero for
	// a plan that scans, it excludes the segments no index covers, and it excludes what a
	// segment's index does not yet cover. Pricing a read by EstCandidates therefore prices a
	// full scan -- the most expensive read there is -- at nothing.
	//
	// It is an estimate of records TOUCHED, not records matched: the predicate is re-verified
	// on each, so it bounds the rows that come back rather than predicting them.
	EstVisited           int64 `json:"estVisited,omitempty"`
	IndexSegments        int   `json:"indexSegments,omitempty"`
	IndexSkippedSegments int   `json:"indexSkippedSegments,omitempty"`
	UnindexedSegments    int   `json:"unindexedSegments,omitempty"`
	// CompositeSegments is how many of IndexSegments answered the conjunction from a
	// COMPOSITE index -- one lookup over the attribute tuple -- instead of probing each
	// attribute and intersecting. CompositeIndex names the tuple ("ClusterId+ProcId").
	// A segment indexed before the composite was configured is not counted and falls back
	// to the intersection, which is why this is a count rather than a flag.
	CompositeSegments int    `json:"compositeSegments,omitempty"`
	CompositeIndex    string `json:"compositeIndex,omitempty"`
	// ZonePrunedSegments is how many segments the zone maps rule out before any record or
	// posting is read, on either plan. An indexed plan's segment counts above cover only the
	// segments left after it.
	ZonePrunedSegments int `json:"zonePrunedSegments,omitempty"`
	// Reason says, in a sentence, why the plan is what it is: which index probe and how many
	// candidates, or why the scan won.
	Reason string `json:"reason,omitempty"`
	// CurrentTimeFolded reports a query that reads CurrentTime and has a folded form
	// (vm.Query.Folded): segments proven to hold no record defining CurrentTime evaluate the folded
	// form and may be pruned by its probes. CurrentTimeUnprovenSegments counts the segments not (yet)
	// proven, which evaluate the query as written and are never pruned by a probe on CurrentTime.
	CurrentTimeFolded           bool `json:"currentTimeFolded,omitempty"`
	CurrentTimeUnprovenSegments int  `json:"currentTimeUnprovenSegments,omitempty"`
}

QueryExplain is a description of how the store would execute a query, for the diagnostic ".explain" command -- what the planner sees and the access path it would choose.

type QueryPhases added in v0.46.0

type QueryPhases struct {
	// Start is the query's zero: First and End are offsets from it. The caller sets it to when the
	// query began; left zero, the first Mark sets it.
	Start time.Time

	// Dur is each phase's exclusive time, summed over every interval recorded for it.
	Dur [NumPhases]time.Duration
	// First and End are the offsets from Start at which the phase's first interval began and its
	// last ended. A phase run once, with nothing recorded inside it, has End-First == Dur; see
	// Contiguous.
	First [NumPhases]time.Duration
	End   [NumPhases]time.Duration

	// Workers is how many parallel workers ran for the query, and WorkerBusy the sum of the time
	// they spent walking segments. A sum over concurrent goroutines: it can exceed the query's
	// duration and is not part of the phases above, which account for the query goroutine alone.
	Workers    int
	WorkerBusy time.Duration
	// contains filtered or unexported fields
}

QueryPhases accumulates, for one query, the exclusive wall time spent in each Phase. Not safe for concurrent use: it belongs to the goroutine running the query, and parallel workers report through WorkerBusy instead (see the file comment).

func (*QueryPhases) Accounted added in v0.46.0

func (p *QueryPhases) Accounted() time.Duration

Accounted is the sum of every phase: the part of the query's wall time the phases explain.

func (*QueryPhases) Add added in v0.46.0

func (p *QueryPhases) Add(ph Phase, start, end time.Time)

Add records [start, end) as an interval of phase ph that encloses no other recorded interval (a leaf), for a caller that has already read both clocks -- dbrpc's frame writer, which times each write for TraceResult.WriteBlocked anyway. Nil-safe.

func (*QueryPhases) Contiguous added in v0.46.0

func (p *QueryPhases) Contiguous(ph Phase) bool

Contiguous reports whether phase ph ran as one unbroken stretch, [First, End), with nothing recorded inside it: then, and only then, it can be drawn as one interval on a timeline. Several back-to-back intervals count as one stretch; an interval enclosing another phase does not, since its Dur is net of what it enclosed. The tolerance absorbs the clock reads between back-to-back intervals.

func (*QueryPhases) Mark added in v0.46.0

func (p *QueryPhases) Mark() PhaseMark

Mark starts an interval. On a nil receiver it reads no clock and returns the zero mark.

func (*QueryPhases) Record added in v0.46.0

func (p *QueryPhases) Record(ph Phase, m PhaseMark)

Record ends the interval m started and adds it to phase ph, less whatever was recorded inside it. Nil-safe.

type RankedMatch added in v0.6.0

type RankedMatch struct {
	Ad      *classad.ClassAd
	Rank    float64
	HasRank bool
}

RankedMatch is a matched ad and the job's Rank of it (HasRank is false when the job's Rank does not evaluate to a number for that ad).

type RawAd

type RawAd struct {
	Exprs      [][]byte
	MyType     string
	TargetType string
}

RawAd is a query result rendered as old-ClassAd wire parts -- the "Name = Value" expression byte slices plus MyType/TargetType -- decoded straight from the stored form with no ast/classad ClassAd. A collector can hand Exprs to message.PutClassAdRawBytes to stream a result set without ever building an AST.

Exprs (and their backing bytes) alias a buffer reused across the iteration, so a consumer must finish with one RawAd -- e.g. write it to the wire -- before advancing the iterator to the next.

type RepairDict added in v0.42.0

type RepairDict struct {
	ID uint32
	// Path is where the dictionary is now, or where it would go in a dry run.
	Path string
	// From is where it came from: the name it was wrongly filed under, or the copy it
	// was restored from.
	From string
	// Action is "re-filed" or "restored".
	Action string
}

RepairDict is one dictionary file a repair run put right.

type RepairOptions added in v0.31.2

type RepairOptions struct {
	// DryRun reports what would change and writes nothing. Everything else is
	// identical, including reading and verifying every record, so a dry run is a
	// faithful rehearsal rather than an estimate.
	DryRun bool
}

RepairOptions controls a repair run.

type RepairReport added in v0.31.2

type RepairReport struct {
	Dir      string
	DryRun   bool
	Segments []RepairSegment
	// Untouched counts segments that needed nothing: either undamaged, or damaged
	// only at the tail, which is an interrupted write rather than corruption.
	Untouched int
	// Unsupported lists segments left alone because their columnar payload is a
	// format version this build cannot read (FsckSegment.ColumnarUnsupported),
	// whether or not they also hold damage. They are not counted in Untouched.
	Unsupported []string
	// Columnarized lists damaged segments left alone because they are columnarized
	// (FsckSegment.Columnarized). Their damage remains as Fsck reports it. They are not
	// counted in Untouched.
	Columnarized []string
	// DictDamaged lists damaged segments left alone because their attribute dictionary
	// record is damaged (FsckSegment.DictDamaged). They are not counted in Untouched.
	DictDamaged []string
	// Dicts lists the compression dictionary files this run put right: re-filed under
	// the id they name, or restored from a surviving copy. See dictrepair.go.
	Dicts []RepairDict
}

RepairReport is the outcome of a repair run.

func Repair added in v0.31.2

func Repair(dir string, opts RepairOptions) (*RepairReport, error)

Repair scans dir with Fsck's walk and rewrites every segment holding damage that a plain open would not survive cleanly. It returns what it did (or, for a dry run, what it would do).

func (*RepairReport) String added in v0.31.2

func (r *RepairReport) String() string

String renders the report for an operator.

func (*RepairReport) Totals added in v0.31.2

func (r *RepairReport) Totals() (kept, dropped int)

Totals sums the records kept and dropped across every rewritten segment.

type RepairSegment added in v0.31.2

type RepairSegment struct {
	Path           string
	RecordsKept    int
	RecordsDropped int
	BytesBefore    int
	BytesAfter     int
	// Quarantined is where the original was moved, or "" for a dry run.
	Quarantined string
	// DroppedSidecar and DroppedSnapshot record the derived files removed because
	// they describe offsets this rewrite invalidated.
	DroppedSidecar  bool
	DroppedSnapshot bool
}

RepairSegment is what happened to one segment file.

type Retention

type Retention struct {
	MaxSegments int   // keep at most this many sealed segments
	MaxBytes    int64 // keep at most this many bytes of sealed segment files
	// MaxAgeAttr names the numeric attribute (e.g. "CompletionDate", unix seconds) that
	// MaxAge is measured against. It must be a ZoneAttr so its per-segment max is available.
	// Now is supplied per Rotate call so the store needs no clock of its own.
	MaxAgeAttr string
	// MaxAge is a hard ceiling: drop a segment whose newest MaxAgeAttr value is older than
	// Now-MaxAge, regardless of anything else (a slow or absent consumer never keeps data
	// past it). Zero ⇒ no age ceiling.
	MaxAge float64
	// MinAgeAttr names the numeric attribute the minimum-retention floor and the GC floor are
	// measured against (a ZoneAttr). It is independent of MaxAgeAttr -- MinAge works with no
	// MaxAge configured -- though a change-feed queue typically points both at the same
	// entry-time attribute.
	MinAgeAttr string
	// MinAge is the minimum-retention floor, for using the store as a short-lived queue. The
	// GC floor (SetGCFloor) may reclaim already-consumed records early, but never any younger
	// than Now-MinAge -- so a consumer always has at least MinAge to drain a record. MinAge
	// only bounds the GC floor; it never overrides the hard ceilings, so MaxBytes / MaxSegments
	// / MaxAge still evict even younger-than-MinAge data under pressure. Zero ⇒ consumed
	// records may be GC'd as soon as the floor passes them.
	MinAge float64
	// EvictByAttr names the numeric attribute that SIZE-driven eviction orders by, lowest
	// value first. Empty falls back to MaxAgeAttr, and if that is empty too, to the
	// positional policy -- dropping the oldest segment by append order, which is correct
	// only while append order tracks the attribute being retained against.
	//
	// In a hub/spoke archive it does not: a spoke replaying a year of backfill appends
	// records far older than the ones already in the oldest segment, so a size-driven pass
	// evicts recent data and keeps the backfill. Setting this makes the pass order by the
	// records' own values, using each sealed segment's byte-weighted profile.
	//
	// There is deliberately no default. The attribute must be the one whose values mean
	// "how old is this record" in THIS store, and binding that in the library would point
	// eviction at whatever happened to carry a familiar name.
	EvictByAttr string
	// TargetBytes is the low mark for size-driven eviction: a pass triggered by MaxBytes
	// frees down to this rather than to just under the ceiling, so it runs rarely instead
	// of on every append that crosses the line. Zero ⇒ evict to just under MaxBytes.
	//
	// This is the hysteresis gap that MergeOptions.TriggerSegments/TargetSegments and the
	// index budget's high/low fractions both have, and that retention did not.
	TargetBytes int64
}

Retention bounds how much history an append-only store keeps. Rotate drops the oldest whole segments until every set bound is met. A zero field means "no bound on that axis". Shared with Collection (Options.Retention / Collection.Rotate).

type ScanStats added in v0.29.0

type ScanStats struct {
	SegmentsTotal   int // segments in the snapshot
	SegmentsPruned  int // dropped by zone maps before any record was read
	SegmentsScanned int // segments actually walked

	RecordsVisited       int // records the scan iterated
	RecordsColumnDecided int // WHERE answered without reassembling the record to test it
	// The two ways a record counted in RecordsColumnDecided was decided other than by evaluating the
	// whole query from its columns. RecordsConjunctRejected: one of the query's top-level conjuncts
	// was answered from the columns and was not true, so the record cannot match. RecordsNarrowMatched:
	// the query was evaluated on the record narrowed to the attributes it reads, gathered from the
	// columns, the cold tail and the remnant without rebuilding the rest.
	RecordsConjunctRejected int
	RecordsNarrowMatched    int
	RecordsReassembled      int // record rebuilt from the arena (the ~O(ad width) path)
	// RecordsClosureReassembled counts records that COULD have been projected straight from
	// their columns but were reassembled anyway, because the projected ad referred to an
	// attribute the projection left out and the consumer evaluates what it receives. A large
	// share here means the projection names expressions reaching outside it, and the columnar
	// fast path cannot serve that caller; zero means the closure costs nothing.
	RecordsClosureReassembled int
	RowsMatched               int // records that satisfied the WHERE and were emitted

	// The index probe, when the scan visited index candidates instead of every record:
	// SegmentsIndexed segments answered from their postings (IndexCandidates offsets in all),
	// SegmentsIndexSkipped proved by their index to hold no candidate, and SegmentsUnindexed
	// walked in full because no index covered the probe there (an unsealed segment, or one
	// sealed before the attribute was indexed). All zero on a plain scan.
	SegmentsIndexed      int
	SegmentsIndexSkipped int
	SegmentsUnindexed    int
	IndexCandidates      int

	// Tier is WHICH strategy produced the answer, for the query paths that fan out over several
	// (see AggTier). It is reported, not inferred: TierUnreported means nothing said, which is
	// what a plain scan path that never tags itself and an older server's response both leave.
	Tier AggTier

	// Phases, when non-nil, receives where the scan's wall time went (see QueryPhases). It is a
	// pointer the CALLER sets, apart from the counts above, for three reasons. Whether to time a
	// scan is a different question from whether to count it: a server counts every query it
	// aggregates, and times only the ones a trace asked about, so a non-nil *ScanStats cannot be
	// the switch. The counts are a value type that is copied into logs, exemplars and the dbrpc
	// trailer, and durations have no place in any of those: they are not on the wire, and they
	// would make two scans of the same data compare unequal. And a pointer is shared by every
	// sub-scan handed a copy of the counts -- a view's sealed half, an aggregate's strategies --
	// so they all time into the one query's phases. Add and mergeWorker leave it alone.
	Phases *QueryPhases `json:"-"`
}

ScanStats accumulates, for one query scan, how the work broke down -- so a diagnostic (EXPLAIN ANALYZE) can show WHERE a slow scan spent itself rather than leaving it to be guessed. All counts are for a single scan; pass a fresh &ScanStats to a *Stats query method.

The distinction that matters is RecordsReassembled vs RecordsColumnDecided: a scan that decides the WHERE from the columnar prefilter and emits only matches touches the record arena RowsMatched times; a scan that reassembles most of what it visits is the slow shape (the record is rebuilt from the arena -- ~O(ad width) each -- even for non-matches).

func (*ScanStats) Add added in v0.34.3

func (s *ScanStats) Add(o ScanStats)

Add folds another scan's counts into s, for a query answered by more than one scan -- a read of a view served from both its live backing and its sealed archive, say. Every field above is a count of work done, so the total is the sum.

Tier is the exception: it names WHICH strategy answered, and two strategies have no sum, so s keeps the one it already reported.

func (*ScanStats) SetTier added in v0.32.1

func (s *ScanStats) SetTier(t AggTier)

SetTier records which strategy answered. Nil-safe like the counters, so a path can tag itself without first checking whether the caller wanted stats.

type SchemaFieldFit added in v0.25.2

type SchemaFieldFit struct {
	Name string `json:"name"`
	Kind string `json:"kind"`
	// Width is the fixed slot's size in bytes (0 for a bit-packed bool).
	Width int  `json:"width,omitempty"`
	Hot   bool `json:"hot,omitempty"`
	// Escaped is the fraction of sampled records whose value was not in the fixed slot, for
	// any reason. This is the number that matters for speed.
	Escaped float64 `json:"escaped"`
	// Missing is the fraction absent from the record entirely -- an escape that no width or
	// kind change would fix. Escaped-Missing is the part a re-schema could recover.
	Missing float64 `json:"missing"`
}

SchemaFieldFit reports how well one schema field still fits the data, measured against a fresh sample rather than the one the schema was built from.

A field escapes when its value is not in the fixed slot -- either the attribute is absent (Missing) or it is present but unstorable in the slot: a different kind, or an int too wide for the width chosen (Escaped - Missing). Escapes are what the schema exists to avoid: a queried column that escapes forces the block's cold-stream decompression and a cold-tail walk, which is the slow path the accelerator was meant to skip.

Rates are fractions of Sampled (see SchemaFit), in [0,1].

type SchemaRequireSkip added in v0.32.0

type SchemaRequireSkip struct {
	Name   string `json:"name"`
	Reason string `json:"reason"`
}

SchemaRequireSkip is one required attribute the last derivation could not make a field of, and why. A required attribute that silently does nothing is indistinguishable from one that is present and not helping, so the refusals are reported rather than dropped.

type SchemaScanField added in v0.25.2

type SchemaScanField struct {
	Name     string `json:"name"`
	Kind     string `json:"kind"` // bool, int, real, string
	Width    int    `json:"width,omitempty"`
	Unsigned bool   `json:"unsigned,omitempty"`
	Hot      bool   `json:"hot,omitempty"`
	// Required marks a field admitted because it was named in the required set, rather than
	// because its presence cleared the floor. It says nothing about whether the slot is paying
	// for itself -- SchemaFit's Missing rate is where that shows.
	Required bool `json:"required,omitempty"`
}

SchemaScanField is one attribute in the derived schema: the name it was recovered under, the storable kind chosen for it, and the fixed width its slot occupies. Hot marks the numeric columns kept uncompressed for O(1) scan.

Width is bytes for an int (1/2/4/6/8, the narrowest that fits the sampled values), 8 for a real or a string slot, and 0 for a bool (bit-packed).

type SchemaScanGroup added in v0.29.13

type SchemaScanGroup struct {
	Fields []SchemaScanField `json:"fields"`
}

SchemaScanGroup is one committed secondary (group) schema: the co-occurring attributes stored columnar together, field by field in layout order. Its members are what `.schema groups` shows at READ; the candidate report from a fresh sample is a separate, DAEMON-level derivation.

type SchemaScanInfo added in v0.23.1

type SchemaScanInfo struct {
	Enabled         bool     `json:"enabled"`
	HotFields       []string `json:"hotFields,omitempty"`
	SchemaFields    int      `json:"schemaFields,omitempty"`
	SealedSegments  int      `json:"sealedSegments,omitempty"`
	CoveredSegments int      `json:"coveredSegments,omitempty"`
	// ColumnarSegments is how many of SealedSegments have been rewritten into columnar-native
	// form, where each schema'd attribute is stored once in the segment's own columnar payload
	// rather than repeated in every record.
	//
	// This is NOT CoveredSegments, and the difference is why it is reported separately. A
	// sidecar block is built for every sealed segment on the ordinary schema scan, unbounded,
	// so CoveredSegments reaches SealedSegments almost at once -- which reads as "fully
	// columnar" and is not. The native rewrite is bounded by ColumnarSegmentBudget, because one
	// unbounded pass over a real archive is hours of I/O, so a table that has just enabled the
	// accelerator keeps serving most reads from the record path for as many maintenance passes
	// as the backlog takes to clear.
	//
	// SealedSegments - ColumnarSegments is that backlog, and it is the figure to look at when
	// columnar reads are slower than expected on a table that reports full coverage.
	// ColumnScanStats.RecordReads counts the same shortfall from the read side.
	ColumnarSegments int `json:"columnarSegments,omitempty"`
	// StaleSegments is how many covered segments were built under an earlier committed schema, hot
	// tier or group set and are still to be brought current -- the backlog a schema change leaves,
	// which maintenance works through ColumnarSegmentBudget segments per pass. Such a segment reads
	// correctly under its own schema; it is only not yet accelerated the new way.
	//
	// It does NOT count segments that are behind only on COMPUTED CELLS -- values this build could
	// compute into their columns but whose payload was written by a build that could not (see
	// colSegment.computedBehind). Deciding that costs a read of the segment, and this figure is
	// reported for every segment on a path that has to stay cheap, so convergence asks that question
	// itself for a bounded number of segments per pass instead. Such a backlog therefore clears
	// without ever appearing here.
	StaleSegments int `json:"staleSegments,omitempty"`
	// BaseChanges is the base-schema change log, oldest first: each adoption of a different base
	// schema, with the reason it was adopted and what moved.
	BaseChanges []BaseSchemaChange `json:"baseChanges,omitempty"`
	// GroupSchemas is how many SECONDARY schemas are built alongside the base one, and
	// GroupSchemaFields their total field count. Zero when the feature is off, and also when it
	// is on but no group has yet kept its members together long enough to be committed to
	// storage -- which is the normal state for the first few maintenance passes, and the one
	// worth being able to tell apart from "not configured".
	GroupSchemas      int `json:"groupSchemas,omitempty"`
	GroupSchemaFields int `json:"groupSchemaFields,omitempty"`
	// Schema is the derived schema itself, field by field, in layout order. The counts above
	// say how much of the table the accelerator covers; this says what it decided the ads
	// look like -- which is what you need to judge whether the sampling recovered the shape
	// you expected, or picked up something odd.
	Schema []SchemaScanField `json:"schema,omitempty"`
	// Groups is the committed secondary schemas, field by field (the members that GroupSchemas /
	// GroupSchemaFields count). It is read from the live committed state -- no sampling -- so it is
	// available to a READ-level client, unlike GroupSchemas(sampleMax, k), which derives fresh
	// CANDIDATE groups from a new sample. Empty when no group is committed.
	Groups []SchemaScanGroup `json:"groups,omitempty"`
	// Require is the attribute set configured to enter the schema whatever its presence rate, and
	// RequireSkipped the members of it the last derivation could not make a field of, with the
	// reason. Both are reported because the alternative is an operator who asked for a column,
	// did not get one, and has nothing to look at: the Schema list above shows what IS a field,
	// and a required attribute that is absent from it looks exactly like one that was never
	// required. The per-field Required flag closes the other half -- which fields are here
	// because they were asked for rather than because they cleared the floor.
	Require        []string            `json:"require,omitempty"`
	RequireSkipped []SchemaRequireSkip `json:"requireSkipped,omitempty"`
}

SchemaScanInfo reports the state of the per-segment columnar (adschema) accelerator, for diagnostics. Enabled means a numeric COUNT(*) WHERE can take the columnar fast path; HotFields are the demand-hot numeric columns kept uncompressed for O(1) scan; SchemaFields is the schema's field count; and CoveredSegments of SealedSegments carry a columnar block (the rest row-fall-back until a rewrite/reindex reaches them). Coverage is not the same as ColumnarSegments -- see there, because the gap between the two is what makes a read fall back to whole records.

type SealMigrateOptions added in v0.47.0

type SealMigrateOptions struct {
	// MaxSegments bounds how many segments one pass examines. Each is read back whole; those that
	// hold a value the policy seals are also rewritten. Default defaultSealMigrateSegs.
	MaxSegments int
	// MaxBytesPerPass bounds the stored bytes of the segments one pass examines. Default
	// defaultSealMigrateBytes.
	MaxBytesPerPass int64
}

SealMigrateOptions bounds one Archive.SealMigratePass. The zero value is usable.

type SealMigrateResult added in v0.47.0

type SealMigrateResult struct {
	// Examined is how many segments the pass read back.
	Examined int
	// Rewritten is how many of them it rewrote under the current policy.
	Rewritten int
	// Failed is how many rewrites did not complete; their sources are left in place.
	Failed int
	// Done reports that the archive holds nothing the current policy seals in the clear, and the
	// marker says so: later passes cost a file read until the policy widens again.
	Done bool
}

SealMigrateResult reports one pass.

type SegmentProfile added in v0.40.1

type SegmentProfile struct {
	Segment int    // the segment's index, which is also its id
	Attr    string // the attribute profiled; empty when the segment has no profile
	// Bytes is the stored bytes the profile accounts for; Unknown is the part of it whose
	// value could not be bounded (an expression, a sealed value, a non-numeric, or absent).
	// Unknown bytes are never freed by value -- only the positional fallback reclaims them.
	Bytes   int64
	Unknown int64
	// ValueMin/ValueMax span the values that WERE bounded. Meaningless when HasValues is
	// false, which is a segment whose every record was unbounded.
	ValueMin, ValueMax float64
	HasValues          bool
	// Buckets is how many breakpoints the profile carries, i.e. how finely a cutoff can be
	// placed within this segment.
	Buckets int
	// ReceivedMin/ReceivedMax are the store's own clock when the segment was sealed (unix
	// seconds). They exist for ClockSuspect below, not for retention, which never consults
	// them -- evicting on when a store RECEIVED a record is how a replayed backlog looks
	// brand new and never ages out.
	ReceivedMin, ReceivedMax int64
	// ClockSuspect marks a segment whose profiled values sit inside its own receipt window.
	// Records' timestamps describe events that happened before this store heard about them,
	// so a segment whose values track its receipt time is one whose source stamped ITS OWN
	// clock rather than deriving the value from the record. Such a segment orders correctly
	// against others from the same source and wrongly against everything else.
	//
	// Advisory only: it never changes an eviction decision. A source that is genuinely
	// writing records as they happen looks the same, which is why this is surfaced for an
	// operator to interpret rather than acted on.
	ClockSuspect bool
}

SegmentProfile reports one sealed segment's retention profile for diagnostics. It is what makes a size-driven eviction explainable after the fact: which segments are orderable by value, how much of each sits below a given point, and which are not orderable at all.

type SeqCursor added in v0.29.5

type SeqCursor struct {
	Shard    uint32
	Snapshot uint64
	Seq      uint64
	Key      string
}

SeqCursor marks a position in a sequence-ordered scan: the last record the caller consumed. The zero value starts at the beginning.

It is per shard, because the commit sequence is: each shard stamps records from its own counter (`seq := sh.commitSeq + 1`), so sequences from different shards are unrelated numbers and only order records within one shard. A scan therefore finishes a shard before moving to the next, and the cursor names which shard it is in — the same shape as Scan's guarantee, which is likewise per shard ("each key present at the moment A SHARD's scan begins").

Snapshot is that shard's sequence when its first page was taken; carrying it forward is what keeps later pages from seeing writes that landed meanwhile. It is only meaningful together with Shard.

Key breaks ties within a commit, where several records share a sequence. It is compared bytewise, and only against records with the same sequence, so it imposes no ordering of its own beyond making the position unambiguous.

type SeqPage added in v0.29.5

type SeqPage struct {
	// Next is where a following page resumes: hand it back unchanged. It
	// carries the shard and that shard's snapshot as well as the position.
	// Meaningful only when More is true.
	Next SeqCursor
	// More reports whether the scan stopped at the page limit with records
	// still to come, as opposed to having reached the end of the collection.
	More bool
	// Err, when set, means the page could not be read and yielded nothing: it
	// wraps ErrSeqCursorExpired when maintenance has reclaimed versions the
	// cursor's snapshot sees. More is false and Next is the cursor handed in,
	// but the listing is NOT complete -- restart it from the zero cursor. Check
	// it after consuming the rows.
	Err error
}

SeqPage is one page of a sequence-ordered scan.

type SidecarSizes added in v0.8.0

type SidecarSizes struct {
	Segments    int   `json:"segments"`    // sealed segments with a sidecar
	MappedBytes int64 `json:"mappedBytes"` // total sidecar bytes (mmap-backed, evictable)
	MPHBytes    int64 `json:"mphBytes"`    // of MappedBytes, minimal-perfect-hash structures
	BloomBytes  int64 `json:"bloomBytes"`  // of MappedBytes, bloom filters
}

SidecarSizes reports the on-disk index bytes of an Archive's sealed sidecars, broken out so the minimal-perfect-hash and bloom overhead is visible. These are distinct from the live Collection's IndexSizes: those measure HEAP-resident postings + sketches, whereas sidecar bytes live in the page cache -- demand-paged and evictable under memory pressure. They are reported as a separate budget, never folded into a heap figure, so the "index is N% of data" watermark stays an honest measure of resident memory.

type SortKey added in v0.5.2

type SortKey struct {
	Expr string // attribute name or expression, e.g. "JobPrio" or "QDate"
	Desc bool   // sort this component descending
}

SortKey is one component of an ordered index's sort order: an attribute name or expression evaluated against each member ad, ascending by default.

type Stats

type Stats struct {
	// Ads is the number of live keys the store holds (== StoredLen). This is storage
	// accounting, so it counts the reserved system keyspace (syskey.go) too -- those
	// records occupy segments like any other. Len, the number of rows a reader sees,
	// excludes them and is the smaller figure wherever a table uses them.
	Ads int
	// Segments is the number of arena segments across all shards.
	Segments int
	// ArenaBytes is the total capacity of those segments -- the memory the
	// collection has reserved for record storage, and the dominant term in its
	// resident footprint. (RAM segments back this on the Go heap; persistent
	// segments back it with an mmap.)
	ArenaBytes int64
	// UsedBytes is the bytes written into segments: live records plus superseded
	// (dead) records not yet reclaimed by compaction.
	UsedBytes int64
	// DeadBytes is the bytes belonging to superseded records -- reclaimable by
	// Compact. LiveBytes = UsedBytes - DeadBytes.
	DeadBytes int64
}

Stats is a point-in-time summary of a collection's storage, for observability and capacity planning (e.g. Prometheus metrics). All byte counts are of the dictionary-compressed on-arena form, not the ads' decompressed text.

func (Stats) LiveBytes

func (s Stats) LiveBytes() int64

LiveBytes is the compressed size of the live records (UsedBytes - DeadBytes).

type TimeTravelOptions added in v0.12.0

type TimeTravelOptions struct {
	// MaxDistance is how far back queries may travel: versions superseded more than
	// this long ago are eligible for reclamation. Larger keeps more history (more
	// retained dead bytes). Must be > 0.
	MaxDistance time.Duration
	// CheckpointInterval is the granularity of the time->seq map: a checkpoint is
	// recorded at most once per interval, on the first commit that crosses the
	// boundary, so an AS OF time resolves to within one interval. Default 1 minute;
	// lower for finer resolution at proportionally more checkpoints.
	CheckpointInterval time.Duration
}

TimeTravelOptions configures point-in-time queries for a collection (see the TimeTravel option and timeseq.go).

type Txn added in v0.6.0

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

Txn is an optimistic, snapshot-isolation transaction over a Collection. Not safe for concurrent use by multiple goroutines; each goroutine uses its own Txn.

func (*Txn) Atomic added in v0.42.0

func (tx *Txn) Atomic() bool

Atomic reports whether this transaction commits all-or-nothing.

func (*Txn) Commit added in v0.6.0

func (tx *Txn) Commit() CommitResult

Commit applies the buffered writes, each independently: a write whose key is unchanged since the transaction's snapshot commits; one whose key was modified by another committer is reported in CommitResult.Conflicts and not applied (the successful writes are not rolled back). The transaction must not be used after Commit.

Txn.SetAtomic(true) makes the batch all-or-nothing instead -- every buffered write or none, across every shard it touches. See SetAtomic for the guarantee and what it reports.

func (*Txn) Delete added in v0.6.0

func (tx *Txn) Delete(key []byte)

Delete buffers a delete of key. Nothing is written until Commit.

func (*Txn) Get added in v0.6.0

func (tx *Txn) Get(key []byte) (*classad.ClassAd, bool)

Get returns the ad for key as the transaction sees it: its own buffered write if any (read-your-writes), else the version live at the transaction's snapshot. On a chained (parent/child) collection it resolves inherited attributes by merging the parent as of the same snapshot -- mirroring Collection.Get, transactionally.

func (*Txn) Has added in v0.29.11

func (tx *Txn) Has(key []byte) bool

Has reports whether key exists as the transaction sees it, without reading the stored record: it resolves the key to a live record location and stops there. Get is the wrong tool for a presence question -- it copies the record bytes out from under the shard lock and decodes them, and for a wide job ad that decode is the most expensive thing in an ingest -- so a caller that only needs presence (a diagnostic counter, an upsert-vs-insert branch) should ask here.

func (*Txn) KeysWhere added in v0.24.0

func (tx *Txn) KeysWhere(q *vm.Query) iter.Seq[string]

KeysWhere returns the storage keys of the rows matching q as the transaction sees them, with the same overlay and the same caveats as Query. It is what lets an UPDATE or DELETE inside a transaction address rows the transaction itself created.

func (*Txn) PatchAttrs added in v0.30.0

func (tx *Txn) PatchAttrs(key []byte, patch *classad.ClassAd, removed []string)

PatchAttrs buffers a change to key expressed ONLY as the attributes it changes -- the whole ad is never read, built, or buffered. That is the point: a mirror applying a schedd's attribute updates spends most of its time reading an ad back just to hand a copy of it to the encoder, and the update itself does not need it.

Commit stores this as a delta record. When it cannot -- the key has no full record yet, the chain has reached its bound, or the write removed an attribute -- Commit reads the stored ad and merges there, so the read happens once per re-materialization instead of once per write.

removed names attributes the write deletes. Reads through this transaction still see the merged view (Get applies the patch over the stored ad), so read-your-writes is unaffected.

func (*Txn) Put added in v0.6.0

func (tx *Txn) Put(key []byte, ad *classad.ClassAd)

Put buffers an insert or update of key. Nothing is written until Commit.

func (*Txn) PutOld added in v0.25.1

func (tx *Txn) PutOld(key []byte, text string) bool

PutOld buffers an insert or update of key whose ad arrives as old-ClassAd text, encoding it straight to the stored wire form here rather than building an ast.ClassAd for Commit to encode. Every transactional guarantee is unchanged -- the write is buffered, conflict-checked against the same snapshot, and committed identically; only the encoding path differs.

It reports whether the fast path was taken. False means the caller should parse the text and use Put.

An encrypted collection no longer refuses this path wholesale. The streaming encoder cannot seal, so encodeOld defers to the sealing path for an ad that HAS something to seal, and streams the rest -- which for job and history ads is nearly all of them. Refusing wholesale made encryption cost every ingest.

func (*Txn) PutPatch added in v0.30.0

func (tx *Txn) PutPatch(key []byte, ad *classad.ClassAd, changed []string, removed bool)

PutPatch is Put for a caller that knows which attributes it changed. The full ad is still buffered -- read-your-writes and the value lookup both need it -- but Commit may store only the named attributes as a delta record, which for a wide ad is the difference between encoding and compressing ~7.3 KB and ~150 B. removed reports that the write also deleted an attribute, which a delta cannot express, so the whole ad is stored instead.

It is always safe to call Put instead; a caller that does loses only the optimization.

func (*Txn) Query added in v0.24.0

func (tx *Txn) Query(q *vm.Query) iter.Seq[*classad.ClassAd]

Query returns the ads matching q as the transaction sees them: the committed rows, with the transaction's own buffered writes overlaid (read-your-writes). A row the transaction deleted is absent, a row it rewrote is matched and yielded in its rewritten form, and a row it created is included if it matches -- so a query inside a transaction observes the transaction's own work, which Collection.Query cannot.

Consistency: snapshot isolation plus read-your-writes. The committed half is read at the transaction's own snapshot sequence per shard -- the same sequence Get reads at -- so a scan and a point lookup in one transaction agree, and a row another transaction commits mid-scan is invisible to both. Scanning a shard captures its snapshot if the transaction has not touched it yet, which pins every later read of that shard too.

Cost: a full scan of the committed half, because reading at a past sequence and overlaying by key both need the per-record walk that the indexed query path (which yields ads without keys, at the current sequence) does not do. A transaction that has bought nothing from either -- no buffered writes, and content to read the live store -- is better served by Collection.Query, which is what Txn with an untouched write buffer used to fall back to; that fast path is gone now that the snapshot is the point.

func (*Txn) SetAtomic added in v0.42.0

func (tx *Txn) SetAtomic(a bool)

SetAtomic makes this transaction commit all-or-nothing (default false).

OFF (the default, and what every existing caller gets) Commit applies each buffered write independently: the writes whose keys are unchanged since the snapshot commit, and the ones that lost a write-write race are reported in CommitResult.Conflicts and simply not applied. Callers depend on that -- a mirror's retry loop re-reads just the conflicting keys, and a bulk loader wants the progress -- so it is deliberately unchanged.

ON Commit is atomic over every key it touches, across shards: either every buffered write is applied or none is. It acquires the write locks of all touched shards in ascending shard order (which is what keeps two concurrent atomic commits from deadlocking against each other), checks every key for a write-write conflict while holding them all, and only then applies -- so no committer can interleave between the check and the apply. On an abort nothing is written: no record, no delete, no watch event, no ordered-index change, and the shards' commit sequences do not move.

An aborted commit reports Committed == 0 and names in Conflicts EVERY key that conflicted, not just the first one found -- the check pass runs to the end across all shards so a caller can refresh its whole working set in one go rather than rediscovering the conflicts one commit at a time. (A shard on the single-writer fast path hides nothing: its commit sequence still being the transaction's snapshot is proof that none of its keys changed.)

An UNAPPLIED write -- one that can never succeed, such as a patch whose stored base is unreadable or a value too deeply nested to store -- also aborts an atomic commit, and is reported in Unapplied, never in Conflicts. Applying the rest of the batch while quietly dropping that one write is precisely the partial application atomic mode exists to prevent, so the whole commit is refused. Keeping it out of Conflicts matters just as much: a caller that retries conflicts would otherwise loop on a write that cannot ever be applied. With an empty Conflicts and a populated Unapplied, a retry loop can tell "try again" from "this will never work" and make progress.

Durability is unchanged: the sync runs after the apply, exactly as it does for a default commit, so a crash part-way through the apply phase needs no new recovery story -- unsynced records are the case existing recovery already handles (see horizon.go).

Which also bounds the guarantee. It is atomicity of APPLICATION: nothing is applied until every key has been checked, and the touched shards' commit sequences move together while this commit holds all their locks, so no watcher or ordered index ever sees part of a batch and a reader within ONE shard cannot see one either -- a shard's snapshot is a single sequence. A reader spanning two shards is a separate matter: Txn captures its snapshot lazily, per shard, on first touch (snapOf), so such a reader takes its snapshots at two different instants and can straddle any commit at all. That predates this mode and is not something an atomic commit can fix from the write side; nothing here makes cross-shard reads consistent.

It is also NOT crash atomicity across keys. A commit that has not yet synced is recovered per key -- horizon.go says so in as many words -- and even once the sync starts, a multi-shard commit syncs its shards in parallel, so a crash during that phase can leave one shard's half durable and another's not. Only a commit whose Commit has RETURNED is durable as a whole. Anyone who needs all-or-nothing across a crash needs a different mechanism than this one; what this gives is all-or-nothing against concurrent writers.

The cost is that the commit holds several shard write locks at once for the length of the check and apply passes, which blocks writers to those shards for longer than the default path's one-lock-at-a-time. That is the price of the guarantee; leave it off when you do not need it.

func (*Txn) SetDurable added in v0.6.0

func (tx *Txn) SetDurable(d bool)

SetDurable controls whether Commit runs the durability sync (default true). A nondurable commit is visible immediately (readers and watchers see it) but its disk flush is deferred to a later durable commit or flush -- the classad_log.h CommitNondurableTransaction batching. No effect on an in-memory collection, whose sync is already a no-op.

type UpgradeOptions added in v0.25.0

type UpgradeOptions struct {
	// MinGainFrac is the fraction of a segment's bytes a re-encode must be projected to
	// save before it is worth doing. Default defaultMinGainFrac.
	MinGainFrac float64
	// SampleRecords is how many records are decompressed and re-compressed to project the
	// gain. The estimate only has to separate "clearly worth it" from "not", so this stays
	// small; the cost of being wrong is one segment, not the archive.
	SampleRecords int
	// MaxBytesPerPass bounds the source bytes one pass re-encodes, as for merging. Zero
	// uses the default.
	MaxBytesPerPass int64
	// MaxSegments bounds how many segments one pass upgrades.
	MaxSegments int
}

UpgradeOptions tunes a codec-upgrade pass. The zero value is usable.

type ValueKind added in v0.37.0

type ValueKind uint8

ValueKind is the type of one produced cell.

A cell carries its own kind rather than the column carrying one, because an attribute is not obliged to hold the same type in every record and a producer that imposed one would be inventing values. A consumer with a declared schema coerces; a consumer without one can see what it got.

const (
	ValueUndefined ValueKind = iota // the record does not have this attribute
	ValueError                      // a value this path cannot produce: an expression, a list, a nested ad, a sealed value this reader may not open
	ValueInt
	ValueReal
	ValueBool
	ValueString
)

type WatchEvent added in v0.4.0

type WatchEvent struct {
	Kind   WatchKind
	Key    []byte
	Ad     *classad.ClassAd
	Cursor []byte
	// Stamp names this change in a clock shared by every shard, so two readers of the same
	// collection give the same change the same number and a consumer needing a single
	// comparable version (a Kubernetes resourceVersion, say) can take it from here rather
	// than inventing one. It is NOT a position: resuming is Cursor's job.
	//
	// Live events carry it. Catch-up data events do not, for the same reason they carry no
	// cursor; WatchSynced carries the collection's watermark, which is where a catch-up's
	// version comes from.
	//
	// Stamps from one shard strictly increase. ACROSS shards they are comparable but not
	// delivery-ordered -- two shards publish independently -- so a consumer that needs a
	// non-decreasing version takes a running maximum. WatchWatermark is the value that is
	// closed across every shard.
	Stamp uint64
	// Reason says why a WatchReset was issued; WatchResetNone on every other kind.
	Reason WatchResetReason
}

WatchEvent is one item in a Watch stream. Cursor, when non-nil, is an opaque token the client persists after processing the event and passes back to Watch on resume. Live events carry one, and so do catch-up upserts -- a long catch-up is resumable partway, so a consumer that reconnects re-reads only what it had not committed. The exception is the full replay a WatchReset opens on a mutable collection, whose events carry none: there the consumer rebuilds from empty and has nothing to resume to until WatchSynced. Deletes and WatchReset itself never carry one.

type WatchKind added in v0.4.0

type WatchKind uint8

WatchKind is the type of a WatchEvent.

const (
	// WatchUpsert carries the full ad for an added or updated key (Ad is set).
	WatchUpsert WatchKind = iota
	// WatchDelete signals a key was removed (Ad is nil).
	WatchDelete
	// WatchReset tells the client to discard its state (build into a shadow): an
	// authoritative full snapshot of Upserts follows, ending at WatchSynced. Emitted
	// when a precise incremental resume is impossible: first subscribe; a cursor older
	// than the delete-retention window or append floor, which includes every cursor
	// issued before a Truncate; a cursor ahead of the head; or a different store
	// generation -- any restart of a mutable collection and an unclean restart of an
	// append-only one (see watchepoch.go).
	WatchReset
	// WatchSynced marks the end of the initial catch-up/snapshot: the client is now
	// live. Its Cursor is a durable resume point (and, after a Reset, the point to
	// swap the shadow state live).
	WatchSynced
	// WatchResync tells the client the live stream fell behind, or the collection was
	// truncated, and it must reconnect with its last persisted cursor (which re-enters
	// catch-up; after a Truncate that cursor gets a Reset). No state is implied.
	WatchResync
)

type WatchResetReason added in v0.40.0

type WatchResetReason uint8

WatchResetReason says why a WatchReset was issued.

A Reset is one event kind with causes that call for completely different responses. "Your cursor is older than what I still keep" is a retention or lag problem; "my epoch changed" is a crash; "your cursor is ahead of my head" is a restored backup or a rollback, and is the alarming one. Without this they are indistinguishable at the client, which can only discard and rebuild and has nothing to tell an operator.

Set on WatchReset events only; WatchResetNone on every other kind.

const (
	// WatchResetNone is every event that is not a Reset.
	WatchResetNone WatchResetReason = iota
	// WatchResetInitial: no cursor was supplied. This is the first subscribe and the
	// snapshot that follows is the whole point, not a loss -- nothing was missed.
	WatchResetInitial
	// WatchResetEpoch: the cursor names a different store generation. For a mutable
	// collection that is any restart without a retention window; for an append-only one it
	// means the last shutdown was unclean (see watchepoch.go).
	WatchResetEpoch
	// WatchResetRetention: the cursor is older than what the store still holds -- below the
	// append floor, or past the delete horizon with no markers left to prove what went away.
	// Records between the cursor and the replay's start are GONE, not merely re-sent.
	WatchResetRetention
	// WatchResetAhead: the cursor is ahead of this store's head, so its sequences may be
	// reassigned to records it never saw. A store restored from a backup or rolled back
	// reaches this; so does one copied while open. It is the reason worth paging on.
	WatchResetAhead
	// WatchResetCursorInvalid: the cursor did not decode, or names a different shard count.
	WatchResetCursorInvalid
)

func (WatchResetReason) String added in v0.40.0

func (r WatchResetReason) String() string

type WorkerPanic added in v0.34.0

type WorkerPanic struct {
	Value any
	Stack []byte
}

WorkerPanic is a panic raised on one of a scan's worker goroutines, re-raised on the goroutine that started the scan. Value is what the worker panicked with; Stack is the worker's stack at the panic, which the re-raise would otherwise lose.

func (*WorkerPanic) Error added in v0.34.0

func (p *WorkerPanic) Error() string

func (*WorkerPanic) PanicStack added in v0.34.0

func (p *WorkerPanic) PanicStack() []byte

PanicStack returns the worker's stack. A method rather than only the field so a recovering caller can ask for it through an interface, without depending on this type.

func (*WorkerPanic) Unwrap added in v0.34.0

func (p *WorkerPanic) Unwrap() error

Unwrap returns the panic value when it is an error (a runtime error, typically).

Source Files

Directories

Path Synopsis
Package crypt is the encryption-at-rest key hierarchy for a ClassAd database.
Package crypt is the encryption-at-rest key hierarchy for a ClassAd database.
Package scriptudf registers a function written in ClassAd Script as a user-defined function, so an ordinary ClassAd expression can call it.
Package scriptudf registers a function written in ClassAd Script as a user-defined function, so an ordinary ClassAd expression can call it.
Package vm compiles ClassAd expressions to a linear instruction stream and interprets them against a scope, replacing per-query AST walks.
Package vm compiles ClassAd expressions to a linear instruction stream and interprets them against a scope, replacing per-query AST walks.
Package wire defines a compact TLV binary form of a ClassAd with attribute-key interning and a hot-attribute header, plus the encoder/decoder that convert to and from the fully-public ast.ClassAd representation.
Package wire defines a compact TLV binary form of a ClassAd with attribute-key interning and a hot-attribute header, plus the encoder/decoder that convert to and from the fully-public ast.ClassAd representation.

Jump to

Keyboard shortcuts

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