Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Managing a Shard Archive

Audience: Pulse internals contributors and embedders who manage a multi-shard .pulse archive — a Zip64 store-only cohort that fans out across N standalone .pulse shards under union semantics.

A shard archive is byte-distinct from a single-file .pulse cohort: Pulse.Open reads the first four bytes and chooses single-file (PULS) or archive (PK\x03\x04). Every read-side command (pulse api *, pulse cohort inspect, pulse export) accepts either.

For the union semantics, per-shard cohesion, and the memory multiplier of read paths see the Cohort schema design skill (Sharded cohorts).

1. Create the archive

The first include seeds the canonical schema; remaining includes are validated against it via structural cohesion + the dict prefix rule. Cohesion compares the type-derived layout (names, types, field widths, bit positions), never a shard’s stored byte offsets, so cohorts written with all-zero offsets or a pre-canonical bit-packed layout join without a re-import. Create runs in two passes: a plan read from each include’s header and schema (an include with parent groups is read whole, one at a time — its group dictionaries come from its rows), then each include streamed once into the staged archive, so memory is one include plus the plan, never the sum. An archive holds at most 65535 shards; more is PULSE_SHARD_COUNT_LIMIT, refused before anything is written. Atomic temp + rename:

pulse shard create q1_2019.pulse \
    --include 20190101.pulse \
    --include 20190108.pulse \
    --include 20190115.pulse

2. Append a shard

Validates cohesion + dict prefix and grows the canonical dict if needed. An ordinary add then appends in place (see The tail append): the new shard, a refreshed _schema.pulse and a new central directory are written after the archive’s old end, and nothing before it changes. An add that moves the archive (a set rung widen, a constant-group promotion) streams a new archive into a staged file beside the original instead and renames it over the original (see The rewrite contract):

pulse shard add q1_2019.pulse 20190122.pulse

Go embedders building shards from rows skip the intermediate files: Pulse.NewCohortBuilder with ShardSplit writes a new archive through one CreateShardArchive call, and an anchored target (q1_2019.pulse#20190122.pulse) appends one shard through one AddShard call, with the same cohesion checks and mandatory warnings. See Reading & Building Cohorts.

Vector fields

A vec_f32 / vec_f64 field’s dim is not in its type byte, so cohesion checks it explicitly: a shard whose vector has a different dim — or the other element type — is refused with PULSE_SHARD_SCHEMA_MISMATCH (details.dimension: vector_dim), even when the vector is the LAST field and no later offset moves. Element labels, kind and scale range may diverge: the shard is accepted, the canonical copy wins, and each divergence is a PULSE_SHARD_DESCRIPTION_DIVERGENCE warning naming vector_labels, vector_kind or vector_scale.

Nullability

Every shard decodes under the archive’s canonical null flags, so per-field nullability is part of cohesion and is never widened. A shard that declares nullable a field the archive declares non-nullable is refused with PULSE_SHARD_SCHEMA_MISMATCH (details.dimension: nullable): the canonical decode would ignore the field’s null bit and a stored null would read back as a value. The reverse — a non-nullable shard field under a nullable archive field — is admitted as-is only when both null bitmaps have the same width (equal strides) and the field is not a parent-group member; every Pulse writer leaves a non-nullable field’s null bit 0, so each row reads non-null. Otherwise it is refused the same way. shard add, shard create, shard verify, the anchored NewCohortBuilder pre-check and the archive record reader all apply the one rule (ValidateStructuralCohesion).

Default zone field

A cohort’s default per-row zone field (the 0x02 ZONE schema section, pulse import <format> --zone-field) is archive-wide: every shard is decoded under the canonical schema, so every shard must declare the SAME default, or none. A shard that disagrees is refused by that same rule with PULSE_SHARD_SCHEMA_MISMATCH (details.dimension: zone_field) on create, add, verify and the builder’s append pre-check — never adopted from either side. Every archive rewrite (add with a widen or a regroup, remove, compact, extract) carries it unchanged.

To declare or remove the default on an existing archive, run pulse cohort zone set ARCHIVE FIELD / pulse cohort zone clear ARCHIVE (Pulse.SetCohortZoneField / ClearCohortZoneField). It rewrites the canonical _schema.pulse AND every shard payload’s schema block (records are copied verbatim, the DIST counts carried), publishes the result by one rename — a failure leaves the archive byte-identical — and reports the mandatory PULSE_SHARD_ZONE_REWRITTEN warning (shards_rewritten) plus every per-shard point-lookup sidecar it staled. An anchored archive#shard path is refused: a shard cannot diverge from its archive.

Set-width auto-widen

Two conditions trigger it, and they compose:

  1. The dictionary union outgrows the bitmask. The field is promoted to the narrowest rung that holds the union.
  2. The arriving shard declares a different rung. A re-import of a new period infers the rung its own data needs, so a set_u128 shard legitimately meets a set_u64 archive with no dictionary overflow in sight.

Either way the add does not fail. The field is promoted across the canonical _schema.pulse and every shard payload already in the archive, and the merge proceeds. The alternative, refusing, forces a full re-import to reach a layout a mechanical re-stride already produces.

The promotion is only ever wider. A shard arriving at a narrower rung never narrows the archive — narrowing would drop every selection above the target’s ceiling, and it would do so silently, with the record still decoding to a smaller and entirely plausible selection. The arriving shard is promoted to the archive’s rung instead, and it is the only payload rewritten. SetWidening.From != To is the test for “the archive moved”; the warning’s details.archive_widened says the same.

Only the rung dimension relaxes, and it relaxes by order, not by loosening a validator: encoding.PlanSetWidening runs before encoding.ValidateStructuralCohesion, reconciles the rungs, and cohesion then runs strictly over the reconciled schemas. pulse shard verify calls the same validator without the plan, so an archive whose shards genuinely carry different strides (a corruption signature) stays fatal there.

pulse shard create widens on the same conditions, so the same files produce the same archive whether fed together or one at a time. Pulse.CreateShardArchive returns a *CreateShardArchiveResult (as AddShard returns a result) to carry the mandatory warning.

The rewrite is atomic (The rewrite contract), so a failure or crash mid-rewrite leaves the original archive byte-identical and openable at its old rung. It is also never silent: every widen emits a mandatory PULSE_SHARD_SET_WIDENED warning naming the field, the old rung, the new rung and the number of shards rewritten, on the --json envelope’s warnings array and on the text output.

Added 20190122.pulse to q1_2019.pulse (now 4 shard(s))
  WARN   [PULSE_SHARD_SET_WIDENED] set field "media" was widened from set_u64 to set_u128 ...

A union above set_u256 has nowhere left to widen to and still fails with PULSE_SHARD_DICT_WIDTH_OVERFLOW. Categorical widths never widen: a categorical’s width is fixed by the canonical schema.

pulse shard verify reports per-set-field width headroom so a widen is foreseeable before you pay for it.

Grouped (0x02) shards

Shards may be deduped cohorts (pulse import <format> --group, pulse dedup). Every shard is decoded with the canonical schema, so an archive has ONE parent-group layout, and create / add share one merge rule (internal/service/shard_groups.go, mergeShard):

  1. The arriving shard is flattened to its ungrouped twin and reconciled exactly as an ungrouped shard — set-rung plan, strict field cohesion, categorical union and remap (null placeholders keep their bytes, since they are part of a group entry’s identity).
  2. The archive’s layout wins. An ungrouped archive stores a grouped arrival flattened; a grouped archive re-encodes an arrival with other groups (or none) into its own.
  3. Group dictionaries union-merge canonical-first: the encoder is seeded with the canonical dictionaries, so stored shards are untouched and only the arrival is renumbered. A union past the u32 index space is PULSE_SHARD_DICT_WIDTH_OVERFLOW.
  4. A constant group the arrival disagrees with is promoted to an indexed group across every shard (a whole-archive rewrite); a declared key the arrival violates is refused with PULSE_GROUP_MEMBER_NOT_CONSTANT.
  5. Strict cohesion runs over the reconciled grouped schemas.

Layout changes emit the mandatory PULSE_SHARD_GROUPS_REWRITTEN warning (details.reason = incoming_flattened / incoming_regrouped / constant_promoted, details.archive_rewritten) and a regrouped entry in --json data. pulse shard verify refuses a shard whose group layout differs from the canonical one, applies the prefix rule to group dictionaries, and reports group_index_headroom.

3. List shards

Reads _schema.pulse + central directory, prints basenames + per-shard record counts:

pulse shard list q1_2019.pulse

4. Verify

Re-validates every shard’s header + cohesion against the canonical schema. A shard whose own magic or format version is wrong fails with PULSE_SHARD_HEADER_INVALID (also on its first read). A cached aggregate_record_count that disagrees with the shards’ own counts is the warning PULSE_SHARD_AGGREGATE_DRIFT (reads use the shard counts; compact refreshes the cache). Useful after manual archive surgery or when a build pipeline appends shards from multiple producers. --json also reports the dead bytes in-place adds left (data.dead_schema_copies, data.dead_bytes; see “Dead bytes” below):

pulse shard verify q1_2019.pulse

5. Compact

Reclaims the dead bytes in-place shard adds leave (every superseded _schema.pulse copy and old central directory; the result reports zero) and refreshes canonical metadata (aggregate_record_count, shard_count). Compacting an archive whose metadata is already current reproduces it byte for byte:

pulse shard compact q1_2019.pulse

The tail append

An ordinary shard add (no widen, no promotion, every entry stored uncompressed) writes only past the archive’s old end:

  • What is written. The new shard’s entry, a refreshed _schema.pulse, then a new Zip64 central directory listing the new _schema.pulse first, every stored shard’s old directory record verbatim, and the new shard last. The superseded _schema.pulse and the old directory stay in the file as dead bytes that no directory points at; pulse shard compact reclaims them. Bytes written are the new shard plus _schema.pulse plus the directory, whatever the archive’s size.
  • Readers. An append assumes no concurrent writer and takes no lock. A reader that opened the archive before the append keeps reading every shard it saw; a reader opening after sees the new one.
  • A refused write-open (a read-only file, or on Windows another process holding the archive without write sharing) fails the add with PULSE_SHARD_APPEND_REFUSED, nothing written.
  • A failed write truncates the archive back to its old length before the error returns.
  • A crash mid-append is caught by the append journal. Before the first byte the add writes <archive>.append (the old length and a checksum of the old tail, synced) and removes it once the append is synced. While it exists every open of the archive refuses with PULSE_SHARD_APPEND_INCOMPLETE, since the tail may be torn or read as the pre-append view. pulse shard verify --repair (library: RepairShardArchive) truncates the archive back to its pre-append bytes and removes the journal, with one mandatory PULSE_SHARD_APPEND_ROLLED_BACK warning whenever it truncated (re-run the add it names; none when there was nothing to roll back); it refuses with PULSE_SHARD_REPAIR_REFUSED, changing nothing, when the journal does not match the archive. A binary older than the journal ignores it, so repair with a current build before any older one touches the archive.
  • An archive whose tail the appender does not extend (data prepended to the zip, bytes after its end record, a multi-disk layout) or that holds a deflated entry takes the rewrite below instead.
  • Dead bytes. Each append leaves one superseded _schema.pulse copy plus the old directory and end record behind. pulse shard verify --json reports them (data.dead_schema_copies, data.dead_bytes: every byte no live directory record references). An add whose append would leave MORE than half the archive dead takes the rewrite below instead, reclaiming all of them (the result has one _schema.pulse and no dead bytes), with one PULSE_SHARD_DEAD_BYTES_RECLAIMED warning; the next add appends again. Many tiny single-shard adds are what trip it (each re-supersedes the whole directory) — batch them into one shard create where you can.
  • --rewrite (library: AddShardWithOptions with AddShardOptions{Rewrite: true}) forces the rewrite: no warning, and the archive is never opened for writing, which is the way past PULSE_SHARD_APPEND_REFUSED.

The writer is internal/encoding/archive_append.go; its bytes are the ones zip.Writer writes for the same entries. Layout contract: .claude/reference/byte-layout/archive-append.md.

Per-shard distinct counts

Every write — create, add, remove, compact and cohort filter to an archive — records in _schema.pulse, after the SHRD trailer, the exact number of distinct values per shard for each u32, u64, date, datetime, f32 and f64 field (on the stored bit pattern, so +0 / −0 and distinct NaN payloads count separately; nulls excluded). Under MaxEstimatedMemory, predict and the run’s pre-flight read them to bound a grouper’s keys without touching a record (the sum of the shards’ counts; see Tuning Limits). Readers that predate the trailer ignore it; single-file cohorts carry nothing.

  • Fresh vs carried. Create counts every include (each is read twice: once to count, once to copy). Add counts the arriving shard and carries every stored shard’s counts; remove carries the kept shards’. A shard from an archive written before the counts existed stays absent (no bound) until pulse shard compact, which counts every shard whose counts are absent.
  • Identity, not name. Each shard’s counts record the size and CRC-32 of the bytes they describe — the values in the shard’s zip directory record. A shard replaced outside Pulse under the same name no longer matches, so predict ignores the archive’s counts until the next write, and add, remove and compact recount that shard instead of carrying its old figures (unchanged shards are still carried without a read). An add that widens or regroups the archive re-encodes every stored shard twice: once to learn the bytes’ identity before _schema.pulse is written, once to store them. Counts written before identities existed are recounted the same way.
  • Cap and opt-out. pulse.Options.ShardDistinctLimit caps the keys held per field per shard (default 4,194,304 — up to 64 MiB per counted field, for one shard at a time); past it the shard records “more than the cap”. Options.DisableShardDistinct records new shards as opted out and reads nothing to count them.

Layout contract: .claude/reference/byte-layout/archive-append.md (“Per-shard distinct counts”).

The rewrite contract

create, a widening, promoting, dead-byte-fallback or --rewrite add, remove and compact (and cohort filter writing an archive) never edit an archive in place, and never build it in memory:

  • Streamed into a stage. The new archive is written to <archive>.pulse.tmp-staged in the same directory: the refreshed _schema.pulse first (its aggregate summed from each shard’s own header, never a decode), then each stored shard copied raw — zip.Writer.CreateRaw from a section of the old file, source CRC and sizes verbatim, no decode — then the new shard. Memory is the arriving shard plus fixed copy buffers, whatever the archive’s size; I/O is the archive’s size. A deflated entry (a third-party zip tool’s) is inflated and re-stored instead.
  • When the archive itself moves (an archive-level set widen, a constant-group promotion), each stored shard is read one at a time and re-encoded on its way into the stage; a promotion first runs a discovery pass over every shard to fix the final group dictionaries. The mandatory warning’s shards_rewritten / records_rewritten are exact.
  • Published by one rename. The stage is flushed and fsynced, renamed over the archive, and the directory fsynced. Until that rename the original is byte-identical; a crash before it leaves the original openable and the stage behind, and the next mutation of that archive sweeps every <archive>.pulse.tmp-* (other archives’ stages are left alone).
  • Not verified on the way through. A raw copy does not re-check a stored shard’s CRC; pulse shard verify is the diagnostic arm.

A widening or promoting add never appends: it relies on the “original byte-identical until the rename” guarantee.

cohort filter over an archive filters one shard at a time. It spools the surviving shards to <output>.pulse.tmp-spool, because _schema.pulse comes first and carries the surviving total, and then streams them into the stage. cohort filter --flatten writes ONE single-file cohort instead: the canonical schema, then each shard’s surviving rows in archive order, streamed into <output>.pulse.tmp-staged and published by the same rename. Either output that replaces a cohort with point-lookup sidecars reports them in invalidated_sidecars.

pulse export (every format, the .sav writer and pulse export predict included) reads an archive the same way without writing one: the canonical schema over every shard’s records in archive order (internal/io.OpenCohortRecords), so its output equals the flattened file’s export. The SPSS metadata sidecar beside the archive is fingerprinted over the archive’s bytes. An anchored source (archive.pulse#shard.pulse) exports that one shard the same way (encx.OpenArchiveEntryRecords): the canonical schema over its records, equal to the archive flattened and filtered to the shard. An unknown or reserved anchor is refused with pulse.Open’s code (PULSE_SHARD_MISSING / PULSE_SHARD_RESERVED_NAME, details.entry); a .sav reads the ARCHIVE’s sidecar (fresh, stale or absent exactly as for a whole-archive export), never a per-shard one.

Point-lookup indexes

An archive with point-lookup indexes (pulse index build archive.pulse) keeps them in step through add and remove (internal/service/index_upkeep.go):

  • Add builds before it publishes. Before the archive is written — from an in-memory copy of the new shard’s entry for an append, from the finished stage for a rewrite — the new shard is scanned once and its sidecar for every archive index is written to <sidecar>.pulse.tmp-staged, with the updated manifest beside it. If any of that fails, the add returns the error and the archive, every sidecar and the manifest are left byte-identical. Otherwise the archive is appended to (or renamed), then each sidecar, then the manifest is renamed.
  • Remove touches only the removed shard. The manifest without the shard’s record is staged first; after the archive rename it is published and that shard’s sidecars are deleted.
  • Both emit the mandatory PULSE_SHARD_INDEXES_UPDATED warning. A rename that fails after the archive rename cannot be undone; the result warns PULSE_INDEX_STALE and lookups refuse until the index is rebuilt.
  • A re-encoding add keeps nothing. When the archive itself moves, every stored shard’s CRC32 changes, so the add leaves the index as it was and lists every per-shard sidecar in invalidated_sidecars.
  • compact copies shards raw, so the sidecars stay valid.

6. Remove and extract

pulse shard remove ARCHIVE BASENAME rewrites the archive without one shard (see The rewrite contract); pulse shard extract ARCHIVE BASENAME writes one shard’s standalone .pulse bytes to stdout without changing the archive.

7. Anchor syntax

Anchor syntax archive.pulse#shard.pulse opens a single shard inside an archive as a one-shard cohort — useful for diagnostics, debugging, and tests that exercise the cohesion path against a known-good shard.

Concurrency caveat

Pulse does not provide writer locking. Two processes running pulse shard add against the same archive race; the last writer wins and the earlier writer’s shard is lost. Sharding is single-writer by design — the caller owns concurrency control (orchestrator coordination, an external advisory lock, or a single-writer architecture).

Implementation surface

For maintainers extending the sharding internals, the surface lives in:

FileRole
internal/encoding/archive.goZip64 read / write + EOCD
internal/encoding/schema_doc.go_schema.pulse parser / writer
internal/encoding/cohesion.goStructural + dict-prefix validators
internal/service/shard_iter.goMulti-shard row iterator
internal/service/shard_reduce.goParallel reducer for mergeable ops
internal/service/shard_admin.gocreate / add / remove / list / extract; both create and add plan set-rung reconciliation before strict cohesion
internal/service/shard_create.gostreaming create: the header-only plan, then each source replayed once into the stage; the PULSE_SHARD_COUNT_LIMIT check
internal/service/shard_widen.goSet-width auto-widen on create + add + the mandatory warning
internal/service/shard_groups.goThe shared create / add merge (mergeShard), grouped-shard reconciliation + PULSE_SHARD_GROUPS_REWRITTEN
internal/encoding/shard_groups.goFlattenCohortBytes, ValidateGroupCohesion, group prefix rule, GroupIndexHeadroomFor
internal/encoding/widen.goThe re-stride engine (WidenSetFieldBytes / WidenSchemaSetField)
internal/service/shard_compact.gocompact
internal/service/cohort_zone.gocohort zone set / clear over an archive: canonical + every shard re-declared, PULSE_SHARD_ZONE_REWRITTEN
internal/encoding/zone_rewrite.goThe schema-only zone rewrite (SetZoneFieldBytes / SetZoneFieldFile)
internal/service/index_upkeep.goPoint-lookup index upkeep on add / remove (build before publish)
internal/encoding/archive_append.goThe hand-written Zip64 tail writer: ReadArchiveDirectory, ArchiveAppender
internal/service/shard_append.goThe in-place tail append of an ordinary add
internal/service/shard_stream.goThe streaming archive writer (staged file, raw copy, sweep, fsync + rename + directory fsync) shared by every mutation
internal/service/shard_verify.goverify
internal/service/anchor_overlay.goAnchor-syntax overlay
internal/cli/shard.goCLI thin adapter

Width overflow on a categorical dictionary grown by an append surfaces as PULSE_SHARD_DICT_WIDTH_OVERFLOW; the stricter prefix-only validator (PULSE_SHARD_DICT_DIVERGENCE) is retained for the pulse shard verify strict path. The set-width auto-widen planner is encoding.PlanSetWidening and its executor is internal/service/shard_widen.go over the internal/encoding/widen.go engine; encoding.SetWidthHeadroomFor feeds verify’s headroom report.

Run the gates

go test ./internal/service/ -run 'TestShardArchive|TestShardGroups'
go test ./internal/encoding/ -run TestShardArchive
go test ./internal/encoding/ -run Cohesion