Deterministic FilterToFile
Audience: Go embedders that materialize filtered subsets of a canonical cohort and want to dedup the work across consumers.
Pulse.FilterToFileWithRequest reads a source .pulse cohort,
applies a predicate, and writes the surviving records to a new
.pulse file. Three guarantees make the operation dedup-safe:
- Deterministic output naming — same source + same predicate resolves to the same output path.
- Atomic write — the engine never leaves a partially-written
.pulsefile at the target path. - Pre-existence dedup — if the deterministic output already exists, the engine returns it without re-running the filter (never for a predicate running embedder code — see Registered tables and embedder code).
Shape
type FilterToFileRequest struct {
SourcePath string // Path to the source .pulse file
Expression string // FILTER_EXPRESSION-style predicate
Filterers []*types.Filterer // Structured-predicate alternative
OutputDir string // Where to write the result
OutputName string // Optional override; default: {srcHash}_{predHash}.pulse
Models []types.ModelRef // Saved models the predicate's coef() reads
TimeZone string // IANA zone to_day() and FILTER_DATE_RANGES read
Params types.Params // Constants the predicate reads as params.<name>
}
type FilterToFileResult struct {
OutputPath string
OutputHash string
RowCount int64
ElapsedMs int64
Reused bool // true when a pre-existing output was returned
InvalidatedSidecars []pulse.StaleSidecar // sidecars a replaced output invalidated
}
Exactly one of Expression or Filterers must be set — both empty
or both set is a configuration error so the predicate hash is
unambiguous.
Basic usage
res, err := p.FilterToFileWithRequest(ctx, &pulse.FilterToFileRequest{
SourcePath: "cohort-2025-Q3.pulse",
Expression: "age >= 18 && state in [\"CA\", \"NY\"]",
OutputDir: "derived/",
})
if err != nil {
return err
}
fmt.Printf("%s (%s) %d rows reused=%v in %dms\n",
res.OutputPath, res.OutputHash, res.RowCount, res.Reused, res.ElapsedMs)
On a fresh OutputDir the first call writes the file and reports
Reused: false. A subsequent identical call hits the pre-existence
check, reports Reused: true, and skips the filter work.
Predicate shapes
Expression
A string evaluated under the FILTER_EXPRESSION engine — same expr-
lang semantics as Request.Filterers[*].Expression:
Expression: "age >= 18 && (region == \"NA\" || region == \"EU\")",
Filterers
A slice of structured types.Filterer entries, AND-combined: a row
is written only when every entry passes. Useful when the predicate is
built programmatically:
Filterers: []*types.Filterer{
{Type: types.FILTER_RANGE, Field: "age", Values: []string{"18", "65"}},
{Type: types.FILTER_INCLUDE, Field: "state", Values: []string{"CA", "NY"}},
{Type: types.FILTER_NULL, Field: "email", Values: []string{"is_not_null"}},
},
FILTER_EXPRESSION (pass-through), FILTER_INCLUDE,
FILTER_EXCLUDE, FILTER_RANGE and FILTER_NULL are translated into
the equivalent expression. Every other filterer the instance has
registered — an extension filterer (Options.Extensions),
FILTER_TRUE / FILTER_FALSE, the FILTER_SET_* family,
FILTER_DATE_RANGES — is built through the engine’s filterer
registry exactly as Process builds it,
so it keeps the same rows Process keeps (an extension filterer reads
a u64 field’s exact word through extend.Record.Uint64Value, and
its FieldInputs hook drives the decode projection).
A type the instance’s feature profile hides, or a never-registered
name, is refused PROCESSING_CONFIG filter_to_file: unsupported filter type "<T>" with details {operator}.
Zones resolve exactly as Process resolves them, over the request’s
Filterers against the cohort schema, before any output is reused or
written: a zone-capable filterer (FILTER_DATE_RANGES) reads its own
tz, else its tz_field (a per-row zone field), else the request
TimeZone, else Options.DefaultTimeZone, else UTC — an inherited
zone is not applied to a date field. Every zone refusal is
Process’s own code, message and details (slot filterers[i]): a
tz / tz_field on an operator that is not zone-capable (a
translated built-in, FILTER_TRUE, an extension filterer — no
extension operator is zone-capable), a tz on a date field, tz
and tz_field together, an unknown zone (PULSE_TIMEZONE_UNKNOWN).
Each filterer’s Field is judged by the same field rule Process and
predict use, against the cohort schema (a shard archive’s canonical
schema) and before any filterer builds: an unknown or
empty Field is SERVICE_VALIDATION filter references unknown field: <f> with details {field, filter}, exactly as Process refuses it.
Bound models
Models loads saved model files (.pulse-model.json, written by a
regression save) under the same rule as Request.Models: each
{name, path} entry is read and decoded before any record is read,
and the predicate’s coef(name, term[, stat]) reads it exactly as a
Process filter does:
res, err := p.FilterToFileWithRequest(ctx, &pulse.FilterToFileRequest{
SourcePath: "cohort.pulse",
Expression: `spend > coef("mmm", "tv") * 4`,
OutputDir: "derived/",
Models: []types.ModelRef{{Name: "mmm", Path: "models/mmm.pulse-model.json"}},
})
A load fault carries the model codes (PULSE_MODEL_FILE_UNREADABLE,
PULSE_MODEL_FILE_INVALID, PULSE_MODEL_REF_INVALID, …); a
coef() naming a model the request does not load is
PULSE_MODEL_UNKNOWN. Models rides capability:models: an
instance whose feature profile hides it refuses a set Models as
PULSE_REQUEST_UNKNOWN_FIELD, as Request and FacetRequest do.
Time zone
TimeZone (time_zone) is the request-level IANA zone a to_day()
call in the predicate — and a FILTER_DATE_RANGES filterer without
its own tz / tz_field — reads, by the Request.TimeZone rule: it
wins over Options.DefaultTimeZone, which wins over UTC. An unknown
name is PULSE_TIMEZONE_UNKNOWN, refused before the source is read
whether or not the predicate reads it:
res, err := p.FilterToFileWithRequest(ctx, &pulse.FilterToFileRequest{
SourcePath: "orders.pulse",
Expression: `to_day(placed_at) == ship_day`,
OutputDir: "derived/",
TimeZone: "America/New_York",
})
The CLI’s pulse cohort filter --time-zone Zone gives to_day() the
same zone (as the instance default); see
--time-zone.
Params
Params (params) names constants the predicate reads, read-only, as
params.<name> — the Request.Params contract: the same value rules
and the same refusals (PULSE_PARAMS_INVALID,
PULSE_PARAMS_UNDECLARED, PULSE_PARAMS_FIELD_COLLISION), raised
before any record is read, with the code and message Process gives
the same predicate. Both predicate shapes read them, and an inline
model’s number expressions do too:
res, err := p.FilterToFileWithRequest(ctx, &pulse.FilterToFileRequest{
SourcePath: "survey.pulse",
Expression: `age >= params.min_age && wave in params.waves`,
Params: types.Params{"min_age": 30, "waves": []any{2, 3}},
OutputDir: "derived/",
})
Params rides capability:params: an instance whose feature profile
hides it refuses a set Params as PULSE_REQUEST_UNKNOWN_FIELD.
Deterministic output naming
When OutputName is empty, the basename is computed as:
{sourceHash[:16]}_{predicateHash[:16]}.pulse
sourceHashis the SHA-256 of the source file’s bytes.predicateHashistypes.CanonicalHashof the predicate payload (Expression or Filterers slice, normalised to the same canonical JSON form used byRequest.Hash). WithModelsset, each entry’s name, path and the SHA-256 of the model file’s content join the payload, so rewriting a model file (same name and path, a different fit) lands on a new output instead of silently reusing the one built from the old fit. A predicate callingto_day()reads the requestTimeZone, else the instance’sOptions.DefaultTimeZone, else UTC; a non-UTC zone joins the payload too, so two runs in different zones never share an output, while the same resolved zone named by either knob lands on the same one. Likewise every zone a structured filterer applies — a non-UTC zone on aFILTER_DATE_RANGESover adatetimefield (from itstz,TimeZoneor the instance default), or its per-rowtz_field— joins the payload with its slot, so a request differing only in resolved zone never reuses another’s output. A predicate that reads no zone, or reads UTC, or reads adatefield (no zone applies), adds no zone to the payload.- With
Paramsset, the block joins the payload (each value as the JSON text it marshals to), so a run with other values never reuses an output. - Every registered table the predicate references joins the payload as a content digest — see below.
Registered tables and embedder code
A table registered on the instance is read by name, but two instances may register the same name with different content. So the predicate hash keys on the content of every table the predicate references:
- a
RangeTablesentry named by aFILTER_DATE_RANGESparams.table; - a
LookupTablesentry named by alookup("name", ...)call; - a
ReferenceVectorsentry named by aref("name", ...)call.
Each joins as {kind, name, sha256}, the SHA-256 of a canonical
encoding of its rows (sorted keys, exact float bits — map order never
moves it). Two instances with a same-named table of different content
land on different outputs; identical content still reuses. Only
referenced tables join, so registering another table never moves the
hash. A lookup() / ref() whose table argument is not a string
literal may read any table of its kind, so every registered one of
that kind joins.
A predicate that runs embedder code has no identity a hash can
name — the same name can carry different code on another instance —
so its output is never reused: it re-runs on every call and
atomically replaces the file at the deterministic path (Reused is
always false). That is a predicate with an extension filterer
(Extensions.Filterers), a call of a registered
Extensions.ExprFunctions function, or a lookup() reaching a
function-driven table (LookupTable.Lookup). Use a Rows table
instead of a Lookup function when you want reuse.
LabelTables are output-time only and never read by a predicate.
Independent consumers building the same request reach the same path
without coordination. Combined with a Watch on OutputDir, this is
the foundation for shared materialization caches: many callers ask
for the same derived cohort, only the first request pays the filter
cost, every subsequent caller hits the pre-existence dedup.
Atomic write
The engine stages writes to OutputDir/.<name>.partial and renames
into place only after the filter completes. A failed run removes the
temp file and never publishes a partial result at the target path.
Combined with the Watch API’s rename coalescing, downstream
observers see a single ChangeCreated or ChangeRenamed event for
the completed file — no spurious intermediate states.
The write itself is atomic on every entry point, including the
explicit-path FilterToFile, FilterToFileBySetAndExpr and
FilterToFileWithOptions. A single-file or archive#shard source is
streamed: rows flow from the input through a fixed copy window into a
stage beside the output, <dst>.pulse.tmp-staged, which is fsynced and
renamed over dst. Memory does not grow with the row count. A failed
run leaves an existing dst byte-identical (an absent one stays
absent) and removes the stage. Opening a stage first sweeps every
<dst>.pulse.tmp-* an earlier crash left. The output is the source’s
header and schema bytes verbatim, then every kept row’s bytes in
source order; a truncated trailing record is dropped.
The only call that replaces an existing output is a re-run of a
predicate running embedder code. When the replaced output had a
point-lookup index or an SPSS metadata sidecar, InvalidatedSidecars
names each one (one entry per shard sidecar for an archive index) with
the command that rebuilds it, as Pulse.InvalidatedSidecars reports
them. Nothing is rebuilt.
A shard-archive source is filtered one shard at a time. The surviving
shards are spooled beside the output (<name>.pulse.tmp-spool) and
then streamed into the new archive, because _schema.pulse comes first
and carries the surviving total. The whole output is never held in
memory.
Flattening an archive (FilterToFileWithOptions)
Pulse.FilterToFileWithOptions(ctx, src, dst, opts) is the explicit-
path form behind pulse cohort filter. It writes to dst (no dedup
naming) and returns a FilterToFileReport:
type FilterToFileOptions struct {
Expression string // FILTER_EXPRESSION predicate; "" for none
IncludeField string // field Set is tested on
Set MemberSet // include-set from LoadMemberSetFromReader
Flatten bool // write an archive as ONE single-file cohort
}
type FilterToFileReport struct {
Output string
Records int64
Flattened bool // an archive was flattened
InvalidatedSidecars []StaleSidecar // when dst replaced a cohort
Warnings []*errors.CodedError // sidecar enumeration failure
}
Without Flatten at least one predicate is required, and a shard
archive yields a per-shard archive, as with FilterToFile. With
Flatten a shard archive yields ONE single-file cohort:
- Schema. The output schema is the archive’s canonical
_schema.pulseschema: widenedset_*rungs, union dictionaries, and for a grouped (0x02) archive the canonical parent-group dictionaries. Every shard’s dictionaries are prefixes of the canonical ones, and every shard has the canonical stride, so each surviving row is copied by position with no remap. - Order. Rows land in global archive order: shards in archive order, rows in shard order.
- Predicate. It is optional. With none, the call is a pure
flatten. With one, it keeps exactly the rows
Processkeeps under the same filter. - Memory and atomicity. Memory is O(one shard). A pure flatten
streams each stored shard’s records through a fixed copy window.
The output is streamed into
<dst>.pulse.tmp-stagedand published by one rename, sodstis untouched until the run succeeds.
On a single-file or archive#shard input Flatten is a no-op.
The input is already one file, so the output is what the same call
without Flatten writes; with no predicate every whole record is
kept. Flattened is then false.
rep, err := p.FilterToFileWithOptions(ctx, "sales.pulse", "sales_flat.pulse",
pulse.FilterToFileOptions{Flatten: true})
A flattened file is an ordinary single-file cohort, so a point-lookup index built on it is the single-file case.
Deduped (parent-group) sources
A grouped (0x02) source produces a grouped output. The header,
schema, group descriptors and group dictionaries are copied
byte-for-byte and the surviving physical rows are copied as-is, so
every row’s dictionary index stays valid. The output opens, inspects
and processes exactly like the same surviving rows deduped afresh
with the same groups.
The dictionary is carried, not pruned. After a selective filter
it still holds entries no surviving row references, so pulse inspect reports a group ratio of surviving rows ÷ carried entries.
A low ratio there is expected and is not a defect. Pulse does not prune:
it would cost a second pass and renumber indices. To prune,
re-dedup the output with the same groups (pulse dedup OUT --group ...). It regroups from scratch.
A filter that keeps no rows writes a valid, empty 0x02 cohort (the
preamble alone). The predicate’s field projection narrows only what
is DECODED to evaluate it. Output rows always carry every field,
group members included. A filter over one group’s members is
evaluated once per dictionary entry, not once per row.
Manifest annotation
filter_to_file appears in Manifest.Operations with annotations
{streamable: false, deterministic: true, expensive: true}. The
expensive: true hint marks it as worth caching; the pre-existence
dedup already does that, so call FilterToFileWithRequest repeatedly
and trust the result.
See also
- Request Hashing — the hashing primitives underlying the deterministic naming.
- Watch & WatchDir — observe derived-output changes.