Point Lookup & Index Management
Audience: Go embedders resolving a single row (or a small duplicate set) by an exact key value instead of scanning or filtering a whole cohort.
Pulse.Lookup is a keyed point-lookup store: O(1) — flat latency
regardless of cohort size — against a prebuilt sidecar index
(Pulse.BuildIndex). It works against a single-file cohort and a
shard archive alike (see Shard archives), it is
equality-only (no ranges, no expressions), and it always resolves
the full key — no prefix or partial-key matching. For anything
else (ranges, expressions, unindexed ad hoc queries), use
Process with FILTER_INCLUDE / FILTER_EXPRESSION
instead.
Build then look up
package main
import (
"context"
"fmt"
"log"
"github.com/frankbardon/pulse"
"github.com/frankbardon/pulse/types"
)
func main() {
ctx := context.Background()
p, err := pulse.New(pulse.Options{DataDir: "/var/data/pulse"})
if err != nil {
log.Fatal(err)
}
// Build the sidecar index once — cheap to re-run (idempotent,
// byte-identical sidecar for an unchanged cohort), but there's no
// need to call it on every lookup.
if _, err := p.BuildIndex(ctx, "sales.pulse", []string{"order_id"}); err != nil {
log.Fatal(err)
}
result, err := p.Lookup(ctx, &pulse.LookupRequest{
Cohort: &types.Cohort{Filename: "sales.pulse"},
Field: "order_id",
Value: "42",
})
if err != nil {
log.Fatal(err)
}
for _, row := range result.Rows {
fmt.Println(row)
}
}
BuildIndex returns a *pulse.BuildIndexResult{IndexPath, ManifestPath, Index} —
IndexPath is the derived sidecar path, Index is the in-memory
*pulse.SidecarIndex that was serialized there, handed back in case you
want to inspect it without a round-trip read. Every type inside it has a
root spelling: Keys []pulse.SidecarIndexKeySpec (ordered key fields),
Buckets []pulse.SidecarIndexBucket whose Entries are
pulse.SidecarIndexEntry{Key, RowIDs}, and Fingerprint, a
pulse.CohortFingerprint (the SHA-256 of the cohort’s bytes).
Lookup’s single-key path is Field + Value, both strings. Value is
always text, the same string-literal convention Filterer.Values
uses for FILTER_INCLUDE/FILTER_EXCLUDE.
Composite keys
A multi-field key is an ordered tuple — field order matters end
to end, from the BuildIndex call that wrote the sidecar through
every Lookup that probes it. Use Keys instead of Field/Value:
if _, err := p.BuildIndex(ctx, "sales.pulse", []string{"region", "date"}); err != nil {
log.Fatal(err)
}
result, err := p.Lookup(ctx, &pulse.LookupRequest{
Cohort: &types.Cohort{Filename: "sales.pulse"},
Keys: []pulse.LookupKey{
{Field: "region", Value: "EU"},
{Field: "date", Value: "2026-01-01"},
},
ReturnColumns: []string{"order_id", "revenue"},
Multiplicity: pulse.LookupMultiplicityAll,
})
if err != nil {
log.Fatal(err)
}
Keys takes precedence over Field/Value when both are set.
{region, date} and {date, region} name the same two logical
values but resolve against two different sidecar indexes — build the
index with the same field order you’ll query with.
ReturnColumns projects the result down to named fields; empty means
every schema field (LookupResult.Rows[i] is a full
map[string]any), matching Sample’s no-projection default.
Multiplicity
Multiplicity controls what happens when the matched key resolves to
more than one row-id (a duplicate key value in the source cohort):
The mode type and its constants are re-exported on the pulse package,
so you never need to import types to set LookupRequest.Multiplicity:
| Constant | Wire value | Behavior |
|---|---|---|
pulse.LookupMultiplicityAssertUnique | assert_unique | Default (zero value). Fails with PULSE_LOOKUP_AMBIGUOUS on more than one match; a single match succeeds normally. |
pulse.LookupMultiplicityFirst | first | Takes the lowest row-id, never errors on a multi-row match. |
pulse.LookupMultiplicityAll | all | Returns every matched row in Rows, ascending row-id order. |
result, err := p.Lookup(ctx, &pulse.LookupRequest{
Cohort: &types.Cohort{Filename: "sales.pulse"},
Field: "region",
Value: "EU",
})
if err != nil {
if errors.HasCode(err, errors.PULSE_LOOKUP_AMBIGUOUS) {
// region isn't unique — rebuild the index on a real key, or
// opt into LookupMultiplicityFirst / LookupMultiplicityAll.
}
log.Fatal(err)
}
errors.HasCode(err, errors.CODE) (github.com/frankbardon/pulse/errors)
is the coded-error check used across the codebase — the same pattern
covers PULSE_INDEX_MISSING, PULSE_INDEX_STALE,
PULSE_INDEX_MANIFEST_INVALID, PULSE_INDEX_MANIFEST_STALE, and
PULSE_LOOKUP_NOT_FOUND.
Shard archives
BuildIndex on a shard archive writes one sidecar per shard — at the
shard’s anchor path archive.pulse#shard.pulse.<keyhash>.idx, the
same file an anchored build of that shard writes — plus an entry in
archive.pulse.indexes.json listing every covered shard by name, size
and zip CRC32. Nothing is written inside the zip.
BuildIndexResult.ShardIndexPaths names the files; IndexPath is
the index’s logical name (no file lives there) and Index is nil; the
counts (DistinctKeys, IndexedRecords) are per-shard sums, so a key
held by two shards counts twice: an exact union count would need every
key in memory, which the streaming build avoids (a known limit).
Lookup against the archive resolves the key literal once against the
archive’s canonical dictionary, probes every shard whose recorded key
range admits the key, and returns the hits in archive order — the same rows, in the same order, as the
single-file cohort holding the archive’s rows. Multiplicity applies
across shards: assert_unique refuses a key held by two shards, and
first takes the earliest row in archive order. A shard the index
does not cover — added after the build, or replaced under the same
name — refuses the lookup with PULSE_INDEX_STALE, naming the shards
in details.shards_uncovered; rebuild the index. VerifyIndex
reports the same shards (ShardsUncovered) and hashes every shard
against its sidecar (ShardsMismatched); ListIndexes and
DropIndex work on the archive path.
Key-range pruning. The build records each shard’s indexed-key
minimum and maximum on its manifest record (key_min / key_max, one
string per key field). A lookup skips a shard whose range excludes the
key without opening that shard’s sidecar, so a lookup over shards
clustered by key (one shard per period, say) opens only the shards
that can hold it. A composite key is pruned per field: one field out
of range is enough. The bounds are order-preserving hex — the
field’s value big-endian, with the sign bit flipped for date,
datetime and decimal128 and the IEEE-754 total-order transform for
floats — so u64 keys above 2^53 stay exact; a categorical range is a
dictionary-id range. Pruning only skips work: a shard whose record
carries no range (an empty shard, or a manifest record without the
fields) is always probed. A skipped
shard’s sidecar is not read, so a stale sidecar there does not refuse
a lookup that shard cannot answer; VerifyIndex still checks every
sidecar, and also checks each recorded range against its sidecar’s
keys (ShardsRangeMismatched, reason range_mismatch) — a wrong
range could hide a match.
Bloom pruning. The build also writes one Bloom filter per shard
(about 10 bits per distinct key, ~1% false positives), each stamped
with the shard’s name, size and CRC32, all in ONE file per index —
archive.pulse.<keyhash>.blooms — so a lookup reads its filters in a
single read (one GET on object storage) however many shards are in
play. When no .blooms file is present, a lookup uses per-shard
archive.pulse#shard.pulse.<keyhash>.bloom files if they exist; a
rebuild (or the next shard add) folds them into one .blooms file and
deletes them. After the range check, a lookup skips a shard
whose filter says the key is not there — again without opening its
sidecar — so a key that falls inside many shards’ ranges but lives in
few opens only those few (or one in a hundred extra). A filter never
hides a key that is present. A missing filter, a damaged one, or one
stamped with other shard bytes is ignored and the shard is probed.
VerifyIndex rebuilds each filter from its sidecar and reports one
that differs (ShardsBloomStale, reason bloom_stale; a .blooms
file whose header is unreadable names every shard); DropIndex
removes the filters; shard add and remove keep them in step;
CohortArtifacts lists the .blooms file and every per-shard sidecar
(archive.pulse#shard.pulse.<keyhash>.idx, and any per-shard .bloom).
Distinct keys across shards. On an archive, DistinctKeys is the
sum of the per-shard counts, so a key present in three shards counts
three times (IndexedRecords is exact either way). Each shard’s
manifest record therefore also carries a HyperLogLog sketch of its
keys (hll, 1024 registers, about 1 KB of base64), and
BuildIndexResult.DistinctKeysEstimate / IndexInfo.DistinctKeysEstimate
(--json distinct_keys_estimate) merge them into a union estimate —
about 3.25% relative standard error, clamped between the largest
shard’s count and the sum, so a one-shard archive is exact. On a
single file the field equals DistinctKeys. It is nil when any
covered shard’s record has no sketch: unknown, never 0; rebuild the
index to restore it. Shard add and remove keep the sketches in step; the
sketch never affects a lookup and VerifyIndex does not check it.
AddShard and RemoveShard keep every archive index in step. An add
builds the new shard’s sidecar for each index and the updated manifest
(the new shard’s record carries its key range)
before the archive is renamed: if any of that fails, the add returns
the error and the archive, the sidecars and the manifest are left as
they were. A remove drops the removed shard’s sidecar and manifest
record and touches no other file. Both report a
PULSE_SHARD_INDEXES_UPDATED warning on their result. An add that
re-encodes the stored shards (a set widen or a group promotion) keeps
nothing; it lists every per-shard sidecar in
AddShardResult.InvalidatedSidecars, and lookups refuse with
PULSE_INDEX_STALE until you rebuild. CompactShardArchive copies
shards unchanged, so their sidecars stay valid.
A u64 key is exact: ids above 2^53 that share one float64 are
distinct keys. A u64 cell in LookupResult.Rows (and in Sample
rows) is the exact stored value as a Go uint64, and JSON prints the
exact integer: 18446744073709551615, not its float64 neighbour.
Index lifecycle
Three more facade methods manage sidecars without a lookup:
// Freshness check — size fast-path before an authoritative
// full-content SHA-256 recompute.
verify, err := p.VerifyIndex(ctx, "sales.pulse", []string{"order_id"})
// verify.Fresh, verify.Reason ("stat_mismatch" | "fingerprint_match" |
// "fingerprint_mismatch"), verify.FastPath, verify.ModTimeDrift
// Enumerate every sidecar built against a cohort, with each one's
// ordered key tuple. Served from the keyless manifest when present, so
// it needs no directory listing.
indexes, err := p.ListIndexes(ctx, "sales.pulse")
// []pulse.IndexInfo{IndexPath, Keys, DistinctKeys, DistinctKeysEstimate,
// IndexedRecords, ShardIndexPaths}
// Remove a sidecar. Non-interactive — no confirmation prompt. Prunes
// the manifest entry in the same call.
err = p.DropIndex(ctx, "sales.pulse", []string{"order_id"})
Staleness has three outcomes, not two
- Size mismatch →
PULSE_INDEX_STALEimmediately, with no hash. This is conclusive rather than merely cheap: the sidecar’s fingerprint covers the whole file, so a file of a different length cannot produce the recorded digest. - Size and mtime both match → served hash-free. That is the O(1) property; a full hash per lookup would defeat the point of the store.
- Mtime moved while the size held → not staleness. It escalates to the sidecar’s own SHA-256 and refuses only if the content really differs.
That third case is the one worth knowing about. SourceModTime is
recorded as Unix nanoseconds; an S3 LastModified is whole
seconds, and every copy, restore and cache hop truncates somewhere
of its own choosing. Treating drift as proof of mutation would refuse
an unchanged cohort read through object storage on every lookup.
The escalation is memoised per (cohort path, size, mtime), so a
backend that never preserves nanoseconds pays one whole-file hash per
distinct stat, not one per lookup. The memo assumes exactly what the
stat fast-path already assumes (same path, size and mtime means the
same bytes), so it adds no freshness gap of its own.
VerifyIndex is the authoritative path: a matching size alone is
inconclusive (a same-size rewrite is possible), so it always falls
through to a full content-hash recompute before reporting
Fresh: true, and it never reads that memo — its whole job is the
verdict that does not rest on a stat pair. ModTimeDrift reports that
the mtime disagreed and the hash overruled it, on both a fresh and a
stale verdict. Run VerifyIndex explicitly wherever you need a
stronger guarantee than Lookup gives you for free — before a batch of
lookups against a cohort you don’t fully trust, or in a periodic health
check.
The one deliberate gap: an in-place edit that preserves both size
and mtime passes Lookup and is caught only by VerifyIndex.
Discovering which indexes exist
A sidecar’s filename embeds a hash of its ordered key tuple
(cohort.pulse.<keyhash>.idx), so the file cannot be opened without
already knowing the tuple — and key order is significant, so guessing
is a permutation search. On a local disk you could glob
<cohort>.*.idx and read each match’s key spec; object storage cannot
list a directory, so that escape is unavailable exactly where cohorts
are usually served from.
BuildIndex therefore also writes a keyless catalog beside the cohort
at a deterministic path — sales.pulse.indexes.json — holding every
index’s ordered key tuple with its field types and counts:
{
"format_version": "1",
"kind": "pulse.index-manifest",
"cohort": "sales.pulse",
"indexes": [
{
"index_path": "sales.pulse.42fdb66c2f329c5c.idx",
"key_hash": "42fdb66c2f329c5c",
"keys": [
{"name": "category_id", "type": "u16"},
{"name": "brand_id", "type": "u32"}
],
"distinct_keys": 480,
"indexed_records": 50000
}
]
}
ListIndexes reads it first, which is why discovery costs one read of
that document plus one existence probe per entry and no read of any
sidecar. BuildIndexResult.ManifestPath names the file. Its
format_version is the manifest’s own, independent of the .pulse
format and the sidecar index format, so a field can be added to it
without any rebuild.
Behaviour at the edges:
| State | Result |
|---|---|
| No manifest | Falls back to the directory listing |
| Manifest plus a sidecar it does not name | Both are listed (the union) |
| Manifest present, directory not listable | Manifest answers; not an error |
| Manifest unreadable | PULSE_INDEX_MANIFEST_INVALID — never a silent fall back to the listing, which would succeed locally and answer “no indexes” on a bucket |
| Manifest names a sidecar that is gone | PULSE_INDEX_MANIFEST_STALE; repair with BuildIndex or DropIndex (which prunes an orphaned entry) |
The manifest is one of Pulse’s own *.json sidecars, so a
PULSE_LABEL_TABLES_DIR or PULSE_RANGE_TABLES_DIR pointed at a data
directory skips it by suffix.
Keyable-type policy
Not every field type can serve as a lookup key — set_* is rejected
(a multi-select bitmask has no single unambiguous equality value; use
FILTER_SET via Process instead). See the full allow/reject table
in pulse api lookup or
skills/cohort-sidecar-index.md.
When to use this vs Process + FILTER_INCLUDE
Reach for Lookup when you have an exact key and want the fastest
possible single/few-row read; reach for Process with FILTER_*
for anything that isn’t a full-key equality match (ranges,
expressions, set_* membership, or querying a field you haven’t
built an index for). The performance shape is the load-bearing claim,
not any particular absolute number: indexed lookup is flat
regardless of cohort size, while an unindexed scan is linear in
record count — the gap widens, not narrows, as a cohort grows. Build
the index once with BuildIndex; every subsequent Lookup against
that key combination pays only the flat O(1) cost.
Comparing rows with a stored record
ATTR_PROFILE_SIMILARITY and ATTR_VEC_DISTANCE accept
reference: {record: {cohort?, keys: [{field, value}]}} — one record
looked up through this same index (the request’s own cohort when
cohort is omitted) before the run, assert-unique, and read by member
column name. Every refusal above refuses that Process with the same
code; there is no scan fallback, and Predict (which reads no index)
checks only the reference’s shape.
See also
pulse api lookup— the CLI leaf forLookup, pluspulse index build/list/verify/dropfor the lifecycle methods above.- Go API Overview — the rest of the public facade.