Run one Engine per whole store. Production :sync requires an explicitly
validated local Linux filesystem with truthful file and directory sync,
advisory locking, and exclusive rename semantics. validated_filesystem: true
is the operator's attestation, not a filesystem probe or device certification.
Never silently downgrade to :write; production builds reject that mode.
macOS :write is for development and carries no power-loss promise. A release
must be built for its target OS/architecture with Elixir 1.20, OTP 29, and a
C11 compiler at build time; the deployed release runs its included native
helper without Mix or a compiler.
Initialize and inspect
Set a dedicated absolute data_dir in the consuming application's runtime
configuration, then initialize a genuinely new store once before supervising
the Engine:
MIX_ENV=prod mix tay.storage.init --data-dir /srv/tay/jobs --durability sync --validated-filesystem
MIX_ENV=prod mix tay.storage.inspect --data-dir /srv/tay/jobs --durability sync --validated-filesystem
Initialization is not an idempotent "ensure" or repair command. Normal startup
is existing-only; missing V2 authority metadata or required history is an error.
Only an explicitly intended empty pre-existing root permits
--bootstrap-existing. Never delete or replace a lock to bypass contention.
Offline inspection acquires the existing lock and performs complete physical
and supported Event-v1/Event-v2 semantic validation without activation. It returns aggregate
diagnostics, not jobs or a reusable recovery ticket. Use mix help tay.storage.inspect for state-memory and deadline options.
Explicit initialization is the default operational model (initialize: :never).
Embedding applications that need first-start creation, such as containerized
deployments, may opt into initialize: :if_missing on Tay.child_spec/1. The
native ownership layer initializes only when it creates the final storage root;
every pre-existing root remains existing-only and proceeds through normal full
recovery. This option is initialization only, never repair or a fallback after
recovery failure.
Local executor access
An Engine normally creates its Unix socket automatically outside data_dir.
The final automatic directory is private (0700), except for an existing shared
/run/tay directory whose permissions Tay preserves, and the socket defaults to
0600. An explicit path or TAY_SOCKET_PATH overrides discovery; prepare the
parent ownership and permissions yourself. Tay refuses a regular file at the
socket path and removes only a verified stale socket. Grant access only to
trusted local processes: a peer can submit, inspect, cancel, and execute tasks.
Bound connection, frame, task, result, and error limits for the workload. See
the protocol contract for the wire format and result lifetime.
Queue and lifecycle controls
Use name: when an Engine has a nondefault name. Pause is volatile and stops
new claims, not already-started effects. Drain closes new insertion/claim
admission and succeeds after active tasks and their outcomes settle; queued
jobs may remain. A timeout leaves the Engine draining. Stop normally drains;
forced stop is an explicit interruption, not successful drain. Restart creates
a fresh ownership, recovery, projection, and execution generation:
:ok = Tay.pause_queue(:default)
:ok = Tay.resume_queue(:default)
:ok = Tay.drain(timeout: 30_000)
:ok = Tay.stop(timeout: 30_000)
:ok = Tay.restart(timeout: 30_000)For stop, restart, and compaction, the guardian classifies expiry while still
draining as timeout and cannot authorize a later shutdown. Once closing,
replacement, or compaction has begun, expiry returns unknown_outcome and
retains the operation slot until the actual work finishes. A lost driver result
after effects begin is also unknown; a confirmed failure to start a replacement
remains unavailable. Losing the call/reply itself is unknown_outcome, even
if the last observed phase was draining. Inspect status before making another
explicit decision.
An unknown outcome after a submitted insert or control call does not prove no change. Reconcile by stable job ID, original definition, status, or a new explicit control decision; do not automatically allocate another job ID. Worker effects are at-least-once. Cancellation fences the durable execution token before best-effort termination but cannot undo an effect already made.
Live inspection and dashboard
Tay.jobs/1 returns public Tay.Job views in deterministic newest-first
insertion order. It accepts state, queue, exact worker-key (worker/workers),
partial worker-key (worker_contains), ID, limit, and opaque cursor filters.
Pages are capped at 100 results. Each response includes the exact matching
total_count plus opaque previous_cursor, next_cursor, and last_cursor
values for bidirectional and final-page navigation. The first page uses no
cursor. Cursors are tied to their filters. Concurrent inserts and state changes
produce a weakly consistent live view, so refresh after administrative actions
or engine restart.
Tay.stats/1 and Tay.queues/1 use reconstructable runtime counters rather
than scanning retained history. The dashboard included in the tay Hex package mounts
these APIs in a host Phoenix application. It is not an authentication boundary;
protect its router scope with the host application's administrator pipeline.
Store-v2 automatic compaction
The per-Engine policy is enabled when compaction: is omitted. It defaults to finite
terminal retention and conservative sealed-history estimates. Optional periodic
semantic checkpoints use the same crash-safe Store-v2 epoch publication; they
never serialize private ETS implementation details. Store-v2 candidate
construction runs online; only the final fenced publication switch closes
admission internally. Calls arriving during that short switch wait for the new
generation within their configured caller timeout instead of receiving an
immediate unavailable. New stores are initialized directly with an empty
Store-v2 generation. Store-v1 roots are refused and must be migrated with a
Tay 1.4.x release before upgrading to 1.5.0.
Retention compaction compares estimated reclaimable bytes with the cost of
rewriting the retained candidate and may run with active jobs. A due periodic checkpoint additionally requires at least one new
durable tail event. Cooldown uses the later
of the verified manifest capture time and post-publication recovered activation
time. Maintenance backoff follows the measured duration of the previous
operation rather than a configurable minimum interval. Backward clocks conservatively defer.
Configuration (milliseconds except the explicit retention unit):
compaction: [
terminal_retention: {:hours, 24},
checkpoint_interval: 0
]checkpoint_interval: 0 disables periodic checkpoints. A positive millisecond
value checkpoints only after at least one new durable tail event. The evaluator
schedules its own maintenance checks and respects the checkpoint interval. Automatic
checkpoints first flush the current group commit and rotate at an exact durable
sequence frontier. Periodic checkpoints capture the frontier at actual start:
new appends after the policy estimate do not invalidate it within the same Engine
generation and storage epoch. A different generation or epoch still defers the
checkpoint. Retention-based reclaim estimates retain their exact source check.
The background publisher reconstructs the candidate from the
sealed immutable Store-v2 generation on disk; it never scans, mutates, or copies
the Engine's ETS projections. Concurrent mutations after that frontier are
appended to an ordered candidate tail. The publisher performs repeated catch-up
rounds while admission remains open. It requests the final fence only when the
pending tail is at most 1,024 events and 1 MB; a new burst above that limit
becomes another online round. The in-memory delta is independently capped at
65,536 events and 64 MB. Exceeding that cap abandons the candidate, releases the
buffer, and leaves the source generation authoritative and writable. A builder
that cannot converge within the bounded round limit behaves the same way.
The new CURRENT is published only after the candidate and its incremental tail
are validated and synced. The post-publication authority check is bounded;
restart uses checkpoint metadata and addressed active/auxiliary reads when the
extended index is available, followed by tail replay. Older checkpoints use full replay. The durable sequence frontier, rather than a wall-clock timestamp, decides which
mutations are already covered.
All checkpoints operate on Store-v2 generations and prepare online.
Checkpoint format 3 reuses immutable index pages and data segments across source epochs even when the tail changes. The builder reads working jobs and the new tail, addresses affected archived jobs, and updates only changed tree paths. Retention walks the ordered expiry index through its cutoff. The first checkpoint of an older format bootstraps the new roots atomically.
Sparse-segment cleaning selects at most 16 segments and 64 MiB of input per checkpoint, using authenticated live-byte summaries. Retained records move to new segments; shared files remain until no published root references them. Native reclamation respects reader pins, rechecks CURRENT before each bounded batch, and syncs deletion directories. Cleanup errors defer GC; they never roll back CURRENT. Restart resumes cleanup. Cold backups include all referenced epoch files; copying only the CURRENT epoch is insufficient.
Checkpoint adoption removes expired IDs through metadata and rebinds cold readers to the new epoch. Startup loads active work and the bounded tail; terminal history/counts and result payloads remain behind authenticated disk indexes until queried.
Compaction pause_ms measures the final admission fence through immediate
reclamation, Engine adoption and resumed admission. total_ms includes
preparation and coordination. publication_pause_ms and publication_total_ms
preserve the narrower publisher measurements. candidate_bytes includes shared
data segments; reused_bytes counts those segments and rewritten_bytes counts
new logical bytes. cleaned_segments and cleaned_source_bytes describe selected
repacking input. Deferred older-epoch GC is excluded from immediate
reclaimed_bytes. These counts do not measure filesystem allocation or device
writes.
Unknown/duplicate keys and invalid checkpoint intervals fail configuration.
Checkpoint intervals fit unsigned 32 bits. Bounded hours use the shared manifest rule
1..2_562_047_788_015, not a separate configuration duration syntax. A manual
zero-retention request is a one-shot full terminal-history purge: it preserves
every non-terminal job and persists the minimum future retention of one hour.
Automatic retention also accepts :infinity, preserving all terminal history without disabling checkpoints or structural compaction. This does not retry terminal jobs.
Terminal jobs are removed from the hot ETS job projection as soon as they
finish and remain queryable through a disposable disk-backed inspection index.
Active-job and terminal-history counts are informational. max_state_bytes
(default 256 MiB) is one shared operational memory budget for active jobs,
in-memory schedules (including cancellation records), successful results and
admitted payloads awaiting processing. No percentages or per-feature pools are
reserved: each item consumes the shared remaining bytes. Accounting conservatively
includes copied BEAM heap shapes, binaries, schedule timers/indexes and lifecycle
headroom. External-capable jobs also reserve their bounded result representation
before admission; completion exchanges that reservation for actual result bytes.
Explicit local worker mappings do not need that reservation and remain
authoritative: an unavailable local callback cannot fall back to an external
executor with unreserved output.
Cancelling, reading and settling accepted work remain possible at capacity.
This is not a hard VM RSS ceiling: runtime stacks, GC, transport buffers and checkpoint construction need additional process/container headroom. Disk-only terminal jobs are outside this memory budget. Completed results remain charged until terminal-retention compaction removes them; cancelled declarations remain charged so cancellation/revision identity is preserved. Re-registering the same ID replaces its charge rather than adding a second declaration.
Admission returns capacity before accepting an operation that cannot fit.
Schedule operations have a bounded admission window derived from client_slots,
without another public configuration setting. A timed-out submitted request
retains its permit until its actual outcome, preventing abandoned payloads from
escaping the budget. Recovery uses the same data accounting; a smaller limit
refuses activation with max_state_bytes, the bytes required at the refusal
point and the configured limit. Increase the same setting and retry; no stored
data is silently discarded.
Aggregate terminal state and queue counters remain in memory. The append-only Store remains authoritative for both projections and rebuilds them on restart. When the last active job becomes terminal, Tay schedules an idle full collection for the Engine and Writer. This releases transient heaps and binary references grown by a burst; allocator/VM baseline memory is not forcibly returned below what the Erlang runtime still needs.
Time retention is eligibility, not an exact-time deletion guarantee: terminal jobs
expire at terminal_at <= captured_at - duration, but actual work waits for
sealed-history thresholds, cooldown, healthy ownership, successful execution
drain and sufficient additional disk. The estimator retains at most 128 oldest
hour buckets, conservatively counting only fully expired hours (up to one extra
hour of estimation delay). Small/idle stores may retain terminals indefinitely
below thresholds. Live, scheduled, available, executing, retryable and unsettled
jobs are protected. Expired IDs are not remembered: get/retry/cancel return
not-found, and a later submission with that ID is a new job.
A successful compaction makes its terminal_retention the durable runtime
setting stored with Store-v2. On subsequent recovery that value takes priority
over the startup configuration or standalone environment. Running compaction
from the Dashboard therefore both applies and persists the selected retention.
compaction: false disables the policy child/timer; terminal history may then
grow indefinitely and the operator assumes storage management. Manual work
remains available:
{:ok, stats} = Tay.compact(timeout: 900_000)
{:ok, stats} = Tay.compact(terminal_retention: {:hours, 0})
{:ok, stats} = Tay.compact(terminal_retention: {:hours, 48})
{:ok, stats} = Tay.compact(terminal_retention: :infinity)Manual/automatic/stop/restart share one fixed operation slot; a concurrent
administrative operation returns capacity/busy rather than queuing or forcing a
switch. operation_slot means one of those operations is already running; it is
not a RAM or terminal-history capacity failure. Supervisor shutdown cancels the evaluator's timer and asks the owner
to cancel construction before CURRENT. Once CURRENT is in flight, it waits for
verification/reconciliation before retiring Engine and defers reclamation.
No source bytes are deleted to obtain candidate headroom. Payload-free aggregate
events are structured Logger debug metadata under :tay_compaction; enable
debug logging to observe evaluation/gate/defer/start/completion/failure events.
Successful checkpoint measurements include catch-up rounds/events/bytes, peak
delta events/bytes, preparation/total time, final delta events/bytes, fenced
pause_ms, gross predecessor bytes, and net reclaimed bytes.
On Store v2, candidate construction runs in the background. The public status
is state: :compacting, phase: :preparing; admission, dispatch, and execution
remain live, and committed mutations are journaled for candidate catch-up. The
final fenced publication reports phase: :switching and closes admission while
the old tail is synchronized, the bounded final delta is appended, and CURRENT
is atomically replaced and authority-checked. Full candidate replay is kept out
of this fence, so switch duration is independent of retained-history replay.
The Engine process is retained. The qualification suite covers finite workload
measurements and the documented
operational limits.
Cold backup and restore
Stop and fence every Engine using the source before copying. The native tools hold its existing exclusive lock throughout inventory, hashing, and copy; they refuse a live owner. A cold copy is whole-store bytes, not a live snapshot, semantic validation, repair, or a proof that the backup contains the latest acknowledged history. Keep the SHA-256 catalog outside both stores. The source, destination parent, and catalog parent must exist; destination and output catalog must not. Do not run source and restored copies concurrently: they share a STORE_ID.
MIX_ENV=prod mix tay.storage.backup \
--source /srv/tay/jobs \
--destination /srv/backups/tay-2026-09-13 \
--catalog /srv/backups/tay-2026-09-13.json \
--durability sync --validated-filesystem
MIX_ENV=prod mix tay.storage.restore \
--source /srv/backups/tay-2026-09-13 \
--destination /srv/tay/restored \
--verify-catalog /srv/backups/tay-2026-09-13.json \
--catalog /srv/backups/tay-restored.json \
--durability sync --validated-filesystem
MIX_ENV=prod mix tay.storage.inspect \
--data-dir /srv/tay/restored --durability sync --validated-filesystem
For development copies use --durability development on backup/restore and
--durability write on inspection. Strict copying is Linux-only on a supported
validated persistent local filesystem. The tools reject symlinks, hard-linked
source files, unsafe aliases, unexpected file types, changed ancestors/source
identities, missing/extra archive files, malformed catalogs, checksum mismatch,
and exhausted file/byte budgets. Defaults are 100,000 inventory entries
(including segments) and 10 GB of file bytes; override only for a separately
qualified workload.
The destination is a new private 0700 sibling staging directory with 0600
files. In strict mode every copied file is fsynced,
followed by the segments and store directories, exclusive no-replace
publication, ancestor syncs, then exclusive external catalog creation and its
syncs. A failure preserves the source and any partial staging or published
destination. A complete-looking destination without a successful catalog is
not acknowledged backup success; never overwrite it or infer a recoverable
prefix. Restore always verifies the selected backup's catalog before creating
destination data. An older valid backup explicitly accepts lost later jobs and
possible repeated external effects. Inspect and activate it in a fresh Engine
generation before admitting work.
Incident boundary
On corruption, incomplete history, unsupported semantics, or an uncertain storage operation, stop admission and preserve the entire store and namespace. Do not truncate, pad, delete, rename-aside, skip records, or reuse sequence space. Distinguish ownership contention and operational budget refusal from bad bytes. Increase a budget only for a new full inspection of unchanged data. There is no automatic corruption repair or live backup. Automatic retention and compaction operate only on validated history; they do not repair corruption. Protect plaintext args, stores, catalogs, and backups with deployment access controls.
Execution rate limits
Set Engine rate_limits: [queues: %{"default" => %{limit: 100, interval_ms: 1000}}, tasks: %{"billing.capture.v1" => %{limit: 5, interval_ms: 1000}}] or standalone:
export TAY_RATE_LIMITS='{"queues":{"default":{"limit":100,"interval_ms":1000}},"tasks":{"billing.capture.v1":{"limit":5,"interval_ms":1000}}}'
Queue names must be configured; task keys are stable worker keys. Each map accepts
up to 1024 policies, each with limit 1..65536 and interval_ms 1..86400000.
Both applicable policies must allow an attempt. Credit is consumed by the committed
job-start transition, including retry attempts and starts whose worker later
fails. Validation and failed pre-start reservations consume no credit. A task
limit cannot block unrelated tasks in the same queue. Configured concurrency
continues to apply independently.
These are fixed windows anchored at the first start in each scope. A window boundary can permit a burst; the limit is not a sliding-window quota. Windows use monotonic time and reset on Engine restart, independently of persistent job recovery and wall-clock corrections. They are local operational controls, not a durable or multi-host lease. Observe queued work with oldest ready-job age and schedule lag; see metrics and alerts.
Gateway process failure
The scheduler coordinator, executor server and HTTP listener retain generation-local
PID references. An unexpected gateway child exit now fails the execution generation
closed instead of restarting that child with stale references. Status becomes
failed. Embedded Engines recover through the explicit
Tay.restart(name: engine, force: true) path (or a host restart), restoring
current durable schedules and replacing all connections together. Standalone
exits on failed so its container or service manager can start full recovery.
In-flight external work remains at-least-once.
External execution also reserves journal headroom for the maximum configured
successful result before START. If that headroom is unavailable, the job remains
available and worker capacity is not consumed.
The status field reserved_outcome_bytes includes both the fixed finish-record
allowance and reserved external-result journal bytes. Atomic completion encoding uses the fixed record-format ceiling and common Value checks.
Transports reject results exceeding their JSON byte limit as result_too_large.
The Engine checks the actual completion envelope against its existing storage
byte/depth/node limits before changing job state. A result that cannot be encoded
fails only that execution attempt with the standard invalid-result diagnostic
(code 6), following the job's configured retry/discard policy. The Engine remains
ready, the worker reservation is released and no successful result is recorded.
This applies to persistent and volatile jobs. Executor.Server has no separate
storage or Value-limit configuration.
Recovery, activation revalidation and offline inspection use the same fixed
record-format and Value checks. Each recovery pass verifies snapshot SHA-256
during segment parsing, without a separate digest read. Preparation and activation
revalidation each still read the complete retained snapshot and journal tail.
There are no separate recovery payload, Value,
insertion argument/depth/node, whole-event insertion or segment-count settings.
Insertions use the physical format ceiling and the shared admission byte pool;
admission does not divide the available bytes evenly between client slots.
Journal byte admission remains controlled by max_history_bytes.
Execution batch size and scheduler polling are internal implementation choices.
Recovery sessions expire internally if not activated. recovery.deadline_ms
controls each replay and activation/revalidation phase; storage_timeout controls
storage I/O during recovery and normal operation. Offline inspection accepts the
same storage_timeout option.
Shared platform verification
On macOS, run the core and standalone checks directly:
mix test --warnings-as-errors --seed 0
cd standalone
mix test --warnings-as-errors --seed 0
Run the same commands on Linux with the same seed, separately on ext4 and Btrfs.
For strict sync coverage, set TAY_TEST_SYNC=1 and TAY_TEST_DATA_ROOT to a
writable directory on the filesystem under test.
scripts/Dockerfile.test provides the Linux test dependencies. A disposable
loop-mounted filesystem requires privileged Docker; run the tests as the
unprivileged tester user and remove the test container when finished.
Production Engines always use sync storage durability; omit the Engine durability
option. Development/test builds and low-level storage commands retain explicit
modes for fixtures and measurements. Global :persistent/:volatile job policy
is configured separately and remains supported.
Dependency availability and unlimited retries
Jobs can opt into a shared, durable availability_key, such as reports-api or
smtp. Use a stable, low-cardinality service identifier, not a unique key per
request. Keyed jobs must use persistent durability. A key may span several queues.
Tay.insert(MyApp.SendReport, %{"report_id" => "123"},
availability_key: "reports-api",
max_attempts: :infinity,
durability: :persistent
)A worker returns {:unavailable, reason} when that dependency cannot be reached.
This outcome never discards a keyed job due to exhausted attempts. It atomically
closes the shared gate and records the next retry deadline. At that deadline Tay
allows one probe execution for the key across its queues; another unavailable
outcome moves the deadline forward. Executions already started are allowed to
settle. Ordinary errors and timeouts do not declare a service unavailable.
A successful execution or a newly accepted job with the same key opens the gate. A new job is a producer hint, not proof of connectivity: a subsequent unavailable outcome closes the gate again. Repeating an idempotent enqueue of an existing job does not count as a new insertion. Opening a gate makes its dependency-deferred jobs ready early, in journalled batches of 32. Other keys, explicit scheduled jobs and retries caused by ordinary errors keep their deadlines. Normal queue capacity, rate limits, cancellation and execution fences still apply; opening a gate does not impose strict FIFO completion order across concurrent queues.
Inspect gates through Tay.status().availability; each value contains status
("available" or "unavailable") and retry_at (UTC epoch milliseconds, zero
when available). Status snapshots have the API's usual bounded freshness. Gates
are charged to the Engine memory budget and survive checkpoints, compaction,
terminal-history expiry and restart. Their snapshots occupy semantic type 15,
schema 2, in the checkpoint's coordination index (historically schedules).
Existing definitions stay at version 1; keyed or infinite-retry definitions use
version 2. Older Engines cannot read these new definitions/records: retain a
backup and do not downgrade a store after using them.
Socket disconnects and expired HTTP worker sessions are infrastructure interruptions, not evidence that the external dependency is down. Existing session fencing still applies. For keyed work whose dependency is available, interrupted retries become ready without their backoff delay and dispatch when a compatible worker returns. A socket reconnect or HTTP registration alone does not mark an external API available. HTTP handlers must explicitly distinguish connection failures from business errors; HTTP status codes are not classified as dependency outages automatically.
max_attempts: :infinity (retries: "infinity" in SDKs) also retries ordinary
failures indefinitely. The persisted attempt ordinal saturates at 65,535 instead
of overflowing; execution tokens and logical revisions continue advancing.
The existing exponential retry curve remains 1, 2, 4, 8, 16, 32, then 60 seconds,
with its existing jitter. With a finite attempt limit, dependency-unavailable
outcomes saturate at that limit and keep retrying, while ordinary errors retain
their configured discard behavior. No retry mode guarantees exactly-once external
effects: use the same business idempotency key on every attempt.
To retain terminal history forever while keeping maintenance enabled, configure
compaction: [terminal_retention: :infinity], or set
TAY_TERMINAL_RETENTION=infinity (alias unlimited) in standalone/Docker. On an
existing checkpointed store, apply Tay.compact(terminal_retention: :infinity)
to change the persisted policy; a saved policy overrides the startup setting.
Active persistent jobs are protected regardless of terminal retention.