Skip to content

Latest commit

 

History

History
3370 lines (3085 loc) · 203 KB

README.md

File metadata and controls

3370 lines (3085 loc) · 203 KB

hoglake server

A lakehouse catalog as a service. Hoglake owns the metadata for tables whose data lives as parquet in object storage: what tables exist, which files back them at every point in time, per-file statistics for query pruning, row-level deletes, and where every consumer of a table's change stream is. Clients talk REST; nobody talks to the backing Postgres but the service itself.

Kotlin/JVM, Ktor, Postgres via JDBI + Flyway, S3-compatible object storage, Prometheus metrics, structured audit log. The OpenAPI contract lives at src/main/resources/openapi/hoglake.yaml and is served at /openapi.yaml.

 writers ──► POST /commit ──┐            ┌──► GET /files /scan /changes
 (parquet → S3, then        │            │    (read planning: metadata only)
  register w/ footer stats) │            │
                      ┌─────▼────────────┴─────┐
                      │      hoglake server     │
                      │  DDL · commits (OCC) ·  │──► Postgres (the catalog)
                      │  changefeed · offsets · │
                      │  retention · hydrator · │──► S3 (footer reads +
                      │  metrics · audit        │       physical cleanup only)
                      └─────────────────────────┘

The server never opens a data file to admit it, and touches object storage in exactly three places: the hydrator's footer reads, cleanup's physical deletes, and compaction's rewrite (the one background job that reads and writes data files — always outside the commit path).

Internal storage footprint

GET /v1/catalogs/{catalog}/storage-usage returns {"tracked_bytes":"1234","pending_delete_files":"2"}: decimal int64 strings, so a client must parse them losslessly. Application authentication is optional (HOGLAKE_AUTH_MODE, default off); under enforce this route needs read on the catalog, and a catalog the caller is not entitled to is 404. Under off, keep the service network-private, never expose this route publicly, and resolve a caller's catalog through the consuming service's own tenant authorization. Database predicates are bound to the resolved catalog id.

tracked_bytes sums all registered data and delete file sizes, including ended files, retained history and dropped tables awaiting retirement. It is deliberately not a live-table/read-snapshot metric. Removing a registration reduces the total even while its object awaits cleanup; the queue stores no size. Unregistered uploads, queued-only objects and object-store versions are excluded. pending_delete_files counts removal rows with drained_at IS NULL, including claimed and staging tickets, not distinct paths or only delete vectors. Settled tickets (deleted, absent, registered) do not count.

The exact aggregates run in one database statement, without the catalog commit lock or object-store I/O, and return one row. Exact sums visit manifest rows, not cached sampler estimates; the planner can also scan other catalogs' rows. Use low-frequency internal polling, not UI refreshes. A 15-second query deadline bounds work; a stricter database statement timeout still applies. A large catalog can fail this deadline: that is an explicit error, never a partial result or zero. Missing catalogs return 404, backend failures return 500, and snapshot/timestamp parameters return 400. The sampled live catalog/table totals remain the right choice for dashboards.

Dropping a catalog

DELETE /v1/catalogs/{catalog}?author=&message= drops an empty catalog and returns {"name":…,"data_path":…}; both query parameters are required and nonblank, as on the other destructive routes. Under the catalog's commit lock it is refused with 409 catalog_not_empty and a reason — live_namespaces, tables_pending_retirement, files_pending_expiry, removals_pending, active_compaction_claims, consumer_offsets, active_uploads, abandoned_uploads_unsettled, the first that applies in that order — unless no live namespace, file row, undrained removal row, unexpired compaction claim, consumer offset or upload in flight remains. Then one DELETE FROM hog_catalog and the thirteen ON DELETE CASCADE foreign keys remove the history with it, so there is no snapshot: the catalog_drop audit event carries the attribution. Nothing under data_path is deleted. Every cascade is an index probe; the removal ledger's needed hog_file_removal_catalog (V28), without which each drop was a sequential scan of the whole settled ledger. The drop locks the catalog's maintenance-summary row before the catalog row, the sampler's order, so a sampler tick cannot deadlock it. CatalogService.dropCatalog has the reasoning for each precondition and for what is left to cascade.

The data model

Everything hangs off five ideas (db/migration/V1__init.sql onward; the canonical schema.sql is the fold of the whole migration chain, and an integration test asserts the two stay structurally identical):

Snapshots are the clock. Every mutation — DDL, append, delete — commits exactly one hog_snapshot row with a dense, per-catalog monotonic id. A snapshot carries its schema version, timestamp, author/message, and a set of typed change rows (hog_snapshot_change: table_created, table_inserted_into, table_deleted_from, …, each with an object id). Those change rows are simultaneously the commit history humans read and the machine vocabulary conflict detection joins against.

DDL accepts caller-supplied author and message, stored verbatim on its snapshot. Create and alter keep them optional. Table, namespace and view drops, truncate, and atomic replacement of an existing table require both to be nonblank; a missing or blank field returns 422 naming it before mutation. DELETE routes take query parameters; truncate takes a JSON body and retains its mandatory UUID guard. Retention reductions also require both, including enabling finite retention from unlimited retention. Options patches are audited without creating a snapshot. Audit actor matches the author and operation_message carries the reason. Under HOGLAKE_AUTH_MODE=off these fields are caller attribution, not an authenticated identity; with a token (warn/enforce) author is filled from the token's actor or checked against it — a mismatch is 422, unless the token delegates, in which case it is recorded as <author> via <token actor>. Blank includes Unicode space characters and NEXT LINE (U+0085), matching Python. Atomic definitions carrying attribution use durable format v7; older servers cannot read those receipts. Complete the server rollout before preparing attributed atomic operations, and account for those receipts before downgrading.

Versioned rows give time travel. Mutable metadata (table name/namespace, columns, partition specs, data files, deletion vectors, views) is stored as rows with [begin_snapshot, end_snapshot) validity. One predicate defines all reads: begin_snapshot <= S AND (end_snapshot IS NULL OR S < end_snapshot). Reading the past is reading the present with a different S.

Identity is split from versions. hog_table is immutable identity: table_id plus a table_uuid that survives rename and changes on drop+recreate — the contract external consumers key their cursors to, so a recreated table is visibly a different thing. hog_table_version and hog_column carry the mutable, versioned parts. Column field_ids are stable for the life of the table and are embedded by writers into the parquet schema itself (PARQUET:field_id), so file columns bind to catalog columns by id, never by name.

Allocators are rows, advanced under the commit lock. Snapshot ids, table/file/view ids, per-table field ids, and per-table row-id ranges all come from counter columns (hog_catalog.last_snapshot_id, next_file_id, hog_table_stats.next_row_id, …) advanced with UPDATE … RETURNING inside the serialized commit tail. No sequences, no gaps, ids ordered exactly like commits.

Integrity is declared. Foreign keys with ON DELETE CASCADE, NOT NULL where code assumes it, partial unique indexes enforcing things like "one live table of this name per namespace" and "one live deletion vector per data file", CHECK-constrained vocabularies. The database rejects states the code shouldn't have to defend against.

The same model, one tenant per catalog (Hoglite)

hoglite/HogliteSchema.kt is schema.sql re-expressed for one SQLite tenant per catalog, foreign keys, cascades, deferred namespace edges and CHECKs included; its KDoc ("Referential integrity") has the edge-by-edge mapping, the statement-order rules the store follows, and what SQLite cannot express. hoglite enforces the constraints on every tenant connection (PRAGMA foreign_keys = ON, which no client can change); createCatalog checks that once, at bootstrap, and refuses a tenant without it (503 backend_unavailable). A FOREIGN KEY constraint failed refusal of any later transaction is HogliteIntegrityViolation, a 500: a store bug, never a client error. Tenants have no migrations, so a schema change (this one included) means dropping and recreating every development tenant.

Feature walkthroughs

Commits and concurrency control

commit/CommitService.kt. A commit is one SQL transaction that opens by taking a per-catalog advisory transaction lock (persistence/Locks.kt: pg_advisory_xact_lock((4740871::bigint << 32) | (catalog_id::bigint & 4294967295)) — the single-bigint form, and the key must be computed identically everywhere or serialization silently breaks). Every DDL and data commit tail serializes on it, which is what makes snapshot ids dense and allocator math trivial; everything expensive a client does (writing parquet) happened before the request, so the serialized section is milliseconds of metadata writes.

A commit's serialized section is TWO statements after the lock, whatever its shape (#393, commit/CommitTail.kt): one read of everything its checks decide on — receipt, head, table resolution, specs, live columns, the row-id allocators, the conflict rows, the upload claims (locked), the removal-queue collisions, DV targets — and one write of everything it publishes, every CTE hanging off an allocator UPDATE guarded by the values the read returned. The checks run between the two in Kotlin, in the order and with the refusals they always had. It used to be 14-24 statements, one round trip each, and on a catalog taking many small commits that fixed per-commit cost, not the per-file work, was the commits/s ceiling. The lock stays its own statement: under READ COMMITTED a statement's snapshot predates its own lock wait.

Conflicts are optimistic and typed. A writer says which snapshot it planned against (read_snapshot); the service runs one indexed query over hog_snapshot_change for changes after that point that actually matter to the write set — for appends, only table_dropped / table_altered on the touched tables (appends never conflict with appends); for deletes, additionally a per-file check that the deletion vector being superseded wasn't itself replaced after the read snapshot. A hit is HTTP 409 with the offending table named; the client refreshes and retries. Omitting read_snapshot is a blind append with no conflict window — except when the files carry partition_values, which HOGLAKE_REFUSE_BLIND_PARTITIONED_APPENDS (default false) will refuse with 422; today the server WARNs once per resolved table and counts hoglake_blind_partitioned_appends_total. A stated read_snapshot below the expiry floor is 410 Gone (the change rows that would prove the window clean were expired with their snapshots; the message names the floor and when it was reached), never a silently truncated conflict check. Validation failures (unknown table, bad field id, malformed stats) are 422 and roll back the entire commit — a multi-table commit is atomic.

Two more admission gates run under the lock. A commit may carry an expected_table_uuid per table — the incarnation guard: if the live table's uuid differs (drop+recreate raced the writer), the whole commit 409s with zero writes, under the typed code table_recreated. A conflict that is DDL on a touched table after the request's read_snapshot is 409 ddl_since_read_snapshot. Neither is retryable, and both carry tables and retry: re-prepare in the body: the recovery is to re-read the table and prepare a new request, which is also the recovery for the below-floor 410 above. And every registered path (data file or DV) is checked against undrained hog_file_removal rows: a path still scheduled for physical deletion is refused with 409 — otherwise cleanup's drain could delete an object a newer commit just made live (path reuse). Time itself is honest too: snapshot_time is stamped clock_timestamp() — statement time inside the serialized tail, after the lock — so recorded times order exactly like snapshot ids even when commits queue.

Admission is backpressured, not implicit: the commit transaction sets a lock_timeout (HOGLAKE_COMMIT_LOCK_TIMEOUT_MS, default 30s), and a writer that can't get the tail in time receives 503 commit_queue_timeout + Retry-After — an explicit, retryable "the catalog is convoyed" signal instead of unbounded queueing. Lock waits are measured (hoglake_commit_lock_wait_seconds) on every commit, DDL, and maintenance tail, so a forming convoy is visible before it's an incident; so are the queue (hoglake_commit_lock_waiting) and each holder's hold by kind of work (hoglake_commit_lock_hold_seconds{path}), which is what says WHO the queue is waiting behind (§Observability).

File registration: footer-shipping and deferred stats

The writer just wrote the parquet file, so it holds the footer in memory: it ships record_count, sizes, and per-column stats (value/null/nan counts and typed min/max bounds) in the commit body, and the server registers the file without ever opening it (hog_data_file + hog_file_column_stats). Bounds are stored in Iceberg single-value binary form (stats/IcebergSingleValue.kt) — typed bytes, not text — so downstream metadata consumers re-encode mechanically.

Stats may also be deferred: a file registers with only record_count (mandatory — row-id assignment needs it) and stats_state='pending'. The hydrator (hydrator/Hydrator.kt, parquet-java) sweeps pending files in the background: a ranged S3 read fetches the parquet footer (never data pages), stats aggregate across row groups, columns map by embedded field id (name fallback with a warning — resolved against the schema at the file's begin_snapshot, never live-at-hydration, so a drop+add-same-name between commit and sweep can't write the old incarnation's stats under a new field id), bounds encode by catalog type, and the file flips to provided — or failed, loudly, if the footer contradicts the registration (a lying record_count is fraud, not a discrepancy). One bad file never wedges a sweep, and a bound the codec can't represent safely (e.g. a timestamp whose unit conversion would overflow) stores as NULL — bounds are never guessed. Until hydrated, a pending file simply matches every scan: correctness holds, pruning quality lags. The sweep claims per catalog (#269): each catalog gets an even share of the sweep's limit off its own range of hog_data_file_pending (live pending rows only, V26), the order rotates so no catalog is always first, unused shares pass to catalogs with more work, and each claim runs under its own savepoint and timeout — a catalog whose claim is slow (a dropped table's pending backlog, walked and discarded until retirement deletes it) loses its share and is counted (hoglake_hydrator_claim_timeouts_total{catalog}); no other catalog waits on it. On a table with the object-prefix layout the sweep also checks the footer against the file's prefix value and quarantines a file it does not prove (see Partitioning).

The hydrator has a size floor for stats rows (#432): HOGLAKE_HYDRATOR_MIN_FILE_BYTES, default 1 MiB, 0 = rows for every file. It gates the ROWS, not the read. Every pending file is still claimed, its footer read, its field ids checked and its stats aggregated; a file under the floor then flips to provided with missing_field_ids and split_offsets set but no hog_file_column_stats rows, the "provided, no stats" state readers already treat as no bounds (a full read). The ledger row counts these as stats_skipped_below_floor, a subset of hydrated. The reasoning: the stats of a file that small never prune anything (one row group, cheaper to read than to skip), and compaction registers its output provided from the footer its own writer just produced (FooterStats.aggregate, §Sort orders and compaction), so a tiny input's ~26 rows were inserted only for the expiry purge to delete through the FK cascade once compaction ended the file (the purge ceiling of §Retention). gigahog-prod-us on 2026-10-22: millrace-prod-us had 24.7M files pending at ~13 KB each (a sweep compacts 2,382 of them, 30 MiB, into 64 outputs), millpond's stray-day files are ~0.1 MB, and the stats table was 136 GB of the RDS volume; 24.7M × 26 is ~642M rows the floor spares. The footer GET and the one UPDATE per file stay, at today's rate. What the under-floor read buys is the field-id audit flag (missing_field_ids) and split_offsets, and on a table with the object-prefix layout the prefix proof (see Partitioning), which is why that GET is not optional there; it no longer unblocks any DDL, because the guard below stopped refusing over pending files (#445).

For a writer, deferring has one cost and one upside. A deferred file under the floor above never gets stats rows: no bounds until compaction rewrites it. The upside is the field-id audit itself (missing_field_ids), which a file registered with inline stats never gets, because the server never opens it. add_column and rename_column are NOT held up by a deferred file: the guard refuses only over a file the sweep has already flagged, so a pending or failed file is trusted on field ids the way its stats and record_count are (and the way every inline-stats file always was). Registering "column_stats": [] is not deferring: the file is provided with no stats and the hydrator never claims it.

null_count is mandatory in hog_file_column_stats, so a leaf whose footer omits it in any row group gets no row — unless the leaf's max definition level is 0 (it and every ancestor REQUIRED), where the parquet format guarantees no nulls and the omitted count is taken as 0. That case is not hypothetical: ClickHouse writes its non-Nullable columns REQUIRED and omits their null_count (it does set it on Nullable ones), and before this rule such files hydrated to provided with no rows for those columns (for the benchmark dataset, no rows at all). A nullable leaf (OPTIONAL, or under an OPTIONAL/repeated ancestor) with no count still gets no row, with a warning naming it. Files hydrated before the rule are provided with those rows missing and are never swept again; POST /maintenance/rehydrate requeues only failed files, so backfilling them means flipping the affected provided files back to pending (the upsert makes a re-hydration idempotent) — not yet an endpoint.

Hydration failure has a two-class taxonomy. Transient fetch errors (S3 5xx/SlowDown, timeouts, connection resets) leave the file pending — logged and counted (hoglake_hydrator_transient_errors_total), retried on the next sweep. Structural errors (object missing, unparseable footer, footer contradicting the registration) go to failed — terminal to the sweep but operator-recoverable: POST /maintenance/rehydrate flips failed → pending (catalog-wide or scoped to one namespace+table), for when the cause was fixed (object re-uploaded, cap raised). Two guard rails on the fetch itself: files without a usable footer_size fall back to a whole-object read capped at HOGLAKE_HYDRATOR_MAX_WHOLE_OBJECT_BYTES (default 256 MiB — a larger file fails structurally with a fix-then-rehydrate message instead of becoming an OOM vector), and the sweep claims its batch FOR UPDATE SKIP LOCKED, so concurrent replicas hydrate disjoint sets instead of amplifying S3 GETs against the same head. The Hoglite rehydrate sweep (below) also holds its reads to the registration, which there the tenant writes; this hydrator does not.

The footer read doubles as the field-id audit: any leaf without a PARQUET:field_id flags the row (hog_data_file.missing_field_ids, gauged as hoglake_missing_field_id_files{catalog}; the reserved _hog_row_id id on compacted files is fine). Id-less files bind columns by name, so while a FLAGGED file is LIVE the table's add_column and rename_column fail with 409 idless_files_present — renaming would silently NULL that column's history in readers, and an added name could adopt an old column's values. The flag is an after-the-fact audit, not a timely guard: a file is trusted until the sweep reaches it, and the sweep is a queue (each catalog's pending files in data_file_id order, Hydrator.DEFAULT_SWEEP_LIMIT per replica per HOGLAKE_HYDRATOR_INTERVAL_MS, SKIP LOCKED across replicas, the limit split across the catalogs with work), so a new file waits behind the whole backlog — backlog / (limit × replicas) intervals at best, which for the 24.7M above is ~250 replica-days at 1,000 per 15 min; a file registered with inline stats is never read at all, and a failed file is trusted too unless its footer parsed far enough to write the verdict. Until #445 the guard also refused over pending/failed files; that verified only the deferred path, which the inline path never got, and on a busy deferred-stats table it never cleared. rename_table is unaffected, the 409 never clears on its own (rewrite or retire the file), and the flag leaves the count when the file is compacted away, dropped, or expired.

The same footer read also records the file's row-group start offsets (hog_data_file.split_offsets, served on GET /scan?include=split_offsets): per row group, where its first column chunk starts (the dictionary page when one precedes the first data page, else the first data page). They are written in the statement that flips the file to provided, and the footer is authoritative — it replaces any list the registration shipped. A file with more than 100,000 row groups, or whose footer gives no strictly increasing in-range list, stores none. Writers that hold the footer can ship the list themselves as split_offsets on the registration; it is validated (non-empty, strictly increasing, within [0, file_size_bytes), at most 100,000 entries) and a bad list is a 422, never stored or repaired. A provided-stats registration that ships no list never passes through the hydrator, so it simply has none — acceptable, because row-group alignment is an optimization and even cuts are always correct. Compaction registers the list for every output from the footer its writer just produced, at no extra IO.

One client-side note with a server cost: pyhoglake's prepare_append_tables uploads a commit's objects concurrently (the fast-upload extra, bounded by concurrency= or PYHOGLAKE_UPLOAD_CONCURRENCY, hoglake#234), so a faster client raises files-per-commit rather than commits per second. Every per-file cost here scales with that number — the hydrator's sweep, the expiry and retirement arithmetic, and the commit receipt, whose stored request body is the one that grows fastest (hoglake#240).

Row lineage

Every append gets a contiguous row-id range per file (row_id_start, width record_count) allocated server-side from hog_table_stats.next_row_id under the commit lock. Ranges tile [0, total-rows-ever) per table with no overlap and no reuse, ever — a row's id is stable for the life of the table incarnation, and the incarnation itself is pinned by table_uuid. This is what lets change consumers and (future) compaction reason about identity without guessing.

Row-level deletes: deletion vectors

Deletes never rewrite data files. A client writes a deletion vector file (a bitmap of deleted positions) to object storage and registers it against a specific data file in a commit (hog_delete_file). Rules, enforced in CommitService and by a unique partial index:

  • At most one live DV per data file. A new DV supersedes the old (end-snapshots it) and must cover it — delete_count only grows.
  • Registering a DV requires read_snapshot, and if the live DV was itself replaced after that snapshot, the commit 409s: you built on a stale vector, and merging bitmaps is the client's job. Lost updates are structurally impossible.
  • A DV must target a live file of the right table, can't shrink, can't exceed the file's record_count, and ordinary numeric references cannot target a file created in the same commit. The explicit transaction endpoint additionally permits private same-commit append references by path (below).

Read planning pairs each data file with its DV as of the requested snapshot (service/ScanService.kt, GET /scan) — historical scans see historical vectors, so time travel is delete-correct. Lifecycle is airtight at the edges too: DROP TABLE end-snapshots live DVs along with the data files (so expiry reclaims both row and object — nothing end_snapshot IS NULL survives a drop), and compaction end-snapshots a group's DVs together with the inputs they mask.

A plan can also carry each provided file's stored column statistics, so an engine prunes files before it plans splits for them: GET /scan?include=column_stats, narrowed by stats_fields to the field ids a pushed-down predicate names. Opt-in, because most scan consumers cannot prune and should pay neither the join nor the payload. Five things about it are worth knowing before you ask for it:

  • it is the one response whose size is a PRODUCT — provided files x requested visible leaf columns, at a measured 106 bytes an entry, which is 66 MB for a 20,000-file 30-column table. It is capped at ScanService.SCAN_COLUMN_STATS_MAX_ENTRIES (1,000,000 entries, ~100 MB) and a request past that is a 422 naming stats_fields as the way back under it, decided from file and column metadata before a statistics row is read. stats_fields divides only the second factor, so a table with more than a million files carrying statistics is past the cap at every narrowing — one column still costs one entry per file — and include=column_stats is unreachable for it: the engine plans without bounds. That is reachable at the top of the fleet, where 3M files x 15 columns is 45x the cap and one column of it is still 3x. The fix when a table needs it is a paged or filtered statistics surface, not a bigger number here, because the number bounds a response the server builds in memory;
  • the cap bounds the PAYLOAD, not the read. A narrowed request returns fewer entries; the statement still reads the catalog's whole statistics relation to find them, because hog_file_column_stats carries no table id and one column's rows sit one per file across every page. Measured at 45M stored rows: ~1.6 s warm, ~17 s cold, narrowed or not. It is a planning-time cost per scan, and stats_fields does not make it cheap;
  • the plan's file list is uncapped, deliberately and unchanged: a scan returning some of a table's files would be a wrong answer, where one returning all of them without bounds is a slow one. Only the statistics are bounded;
  • the counts and bounds are pre-deletion-vector. The plan hands you the file's live DV alongside and nothing subtracts it. Pruning stays sound (deletions only shrink the live set); answering count(*)/min()/max() from these numbers does not;
  • the narrowing is in the SQL, not applied afterwards — the field ids reach the statement as one array parameter, so a one-column request ships one row per file out of Postgres rather than thirty. See ScanColumnStatsQueryPlanIntegrationTest for the plans in all three shapes, for the four index candidates that were measured and rejected, and for the one alternative (CLUSTER) that does change the answer and why it is not taken.

A plan can also carry each file's row-group start offsets, so an engine cuts byte-range splits on row-group boundaries instead of at even offsets that land mid-row-group: GET /scan?include=split_offsets (combinable: include=column_stats,split_offsets). Entry i is where row group i's FIRST column chunk starts — parquet-java's ColumnChunkMetaData.getStartingPos(), never the thrift RowGroup.file_offset — and a list is only ever served whole, strictly increasing and inside [0, file_size_bytes); a file without one simply carries no property and is cut evenly. The offsets live on the file row (hog_data_file.split_offsets), so asking adds no statement to the plan. Like column_stats, it is a scan-plan-only property: the files listing and the changefeed never carry it. Where the lists come from is under "File registration" above.

Partitioning

A table carries a versioned partition spec (hog_partition_spec / hog_partition_field): ordered fields of (source field_id, transform, optional param), where transforms are the closed set identity | bucket(n) | year | month | day | hour. bucket uses a 32-bit Murmur3 with pinned semantics so every writer hashes identically. Writers compute transformed values themselves and ship one opaque string per spec field with each file registration; the server validates arity against the live spec, stamps the file with its spec_id, and stores values in hog_file_partition_value. Files remember the spec they were written under, so spec evolution never rewrites history — pruning just knows which vintage each file is.

Trust boundary: partition-value correctness is writer-trusted — the server validates structure (spec arity, key indexes) but never opens data files at commit time, so it cannot verify that a shipped value is the true transform of the file's rows (e.g. that a bucket value lies in [0, n)). A wrong value mis-prunes reads of that file. This is the one deliberate waiver of the server-validates-structure rule; registration paths, by contrast, are validated against the catalog's data_path prefix at commit.

Object-prefix layout (set_object_prefix_field, V29 hog_table_layout, capability object-prefix-layout-v1): a table may name a top-level integer column (int8 to long, uint8 to uint32; not uint64) whose identity partition value names every file's prefix, <data_path>/data/<ns>/<table>/<field>=<value>/, so one IAM statement on that prefix grants exactly one value's objects (model/ObjectPrefix.kt holds the path function; pyhoglake/tests/vectors/object_prefix_vectors.json holds the vectors it and any writer are held to). With the option on, the commit refuses (422 object_prefix_violation, naming the expected prefix, up to five paths, tables and retry: re-prepare) a data file whose value is missing or not canonical (042, +4, out of range), that is not under its value's prefix, or whose inline stats do not prove every row holds the value (both bounds equal to it, null_count 0); and a deletion vector that is not under its target's prefix. Here the partition value is checked, not trusted: the stats are the proof, because the prefix is a tenant boundary. A file with DEFERRED stats is held to the path and value rules at commit and registers pending; the hydrator makes the stats proof from its footer, before the size floor, and a file whose footer does not prove it (another value's rows in any row group, nulls, a bound the footer cannot state, the column absent) still flips to provided with its stats but with hog_data_file.prefix_quarantined set (V30; counted as the sweep's quarantined, hoglake_stats_hydrated_total{result="quarantined"}, and gauged live as hoglake_object_prefix_quarantined_files{catalog} off the V31 partial index). A reader that serves one value's files of such a table includes only stats_state = 'provided' AND NOT prefix_quarantined: pending, failed and quarantined files stay out. The served stream scan is such a reader (its ReadScope compiles the predicate, docs/auth-tenancy.md §6.5d). Nothing clears the flag, it is on no response, and GET /scan returns a quarantined file as provided. The DDL keeps the layout true: the option is set only on an EMPTY table whose spec has exactly one identity field on the column, once (the same field again changes nothing, though the request still commits its DDL snapshot like every alter, and there is no unset); while it is on, a spec change must keep that identity field, the column cannot be dropped or renamed, the table cannot be renamed, and an atomic replacement of it is refused at prepare. GET reports object_prefix_field as of the snapshot read. Compaction keeps the layout (2.1d): it takes as inputs only stats_state = 'provided' AND NOT prefix_quarantined files (the ReadScope predicate, added to the candidate read for such tables only), writes each group's output under the group's value's prefix (groups never span a partition), proves the output's footer stats for the field before it commits (a mismatch is invalid_data naming the inputs; an output without a footer is not registered), and re-reads the live layout and names under the commit lock, skipping the group as a conflict if the output is no longer under the prefix they name. A group whose prefix cannot be named is refused in metadata, uncharged (hoglake_compaction_skipped_total{reason="object_prefix_unresolvable"}). In a rolling deploy a 2.1b/2.1c replica still skips such tables while a 2.1d one compacts them, which is safe in both directions: outputs register provided, so an older hydrator never claims one, and an older commit path holds a DV on an output to the output's prefix like any other file. Set the option only once every server, compaction and hydrator replica runs a version that knows it: an older one ignores the row and would accept or compact files outside the prefixes. Deferred stats on such a table need more: a hydrator older than the quarantine check flips their files to provided UNCHECKED and unflagged, so send them only once every hydrator replica runs this version, and never roll one back below it afterwards. In a rollout, roll the maintenance (hydrator) Deployment to this version before the API replicas: an older API replica still refuses deferred stats on such a table, so no API replica accepts them while an older hydrator runs. If an older hydrator did flip such files, nothing marks them: re-pend them, in bounded batches on a large table, with UPDATE hog_data_file f SET stats_state = 'pending' WHERE f.catalog_id = <id> AND f.stats_state = 'provided' AND NOT f.prefix_quarantined AND f.end_snapshot IS NULL AND f.begin_snapshot >= <first snapshot of the exposure> AND EXISTS (SELECT 1 FROM hog_table_layout l WHERE l.catalog_id = f.catalog_id AND l.table_id = f.table_id AND l.end_snapshot IS NULL) AND EXISTS (SELECT 1 FROM hog_table t WHERE t.catalog_id = f.catalog_id AND t.table_id = f.table_id AND t.dropped_snapshot IS NULL). The next sweeps re-check each footer. That re-checks every inline-stats file in the window too (their stats rows are rewritten from the footer, the upsert being ON CONFLICT DO UPDATE), and POST .../maintenance/rehydrate is no substitute: it re-pends only failed files. Of the in-tree writers, millrace conforms: it writes each file as <build>/<index>.parquet under its value's prefix (built by pyhoglake.object_prefix.prefix), with its stats inline, never deferred (only the prefix field's below FOOTER_STATS_MIN_BYTES, 32 MiB; the full footer stats from there), so its files register provided and the hydrator-version rule above does not apply to them. Before upload it holds each file's own footer stats for the field to the file's value, and at decode it drops a row whose value is null or negative, which no prefix can hold (counted in millrace_records_dropped_total). duckdb-client's INSERT conforms too, but only on a spec of identity fields with the prefix field first: it writes hive <field>=<value>/ directories under the table root, keeps the partition column in the file and always defers stats, so its files register pending and the hydrator proves them. Because it always defers, that rule covers every DuckDB INSERT. Every other write is refused with object_prefix_violation: pyhoglake's Table.append (.../{table}/{uuid}.parquet), its prepare_append_* (.../{table}/{idempotency_key}/, hedgerow's and millpond's path), duckdb-client DELETE/UPDATE (deletion vectors at the table root, hoglake-dv-<uuid>.puffin) and Trino writes (their upload claims are not under a value's prefix). Enable the option only on a table whose writer is layout-aware, in this order: create the table with its spec, set the option, then start the writers. Never roll a server back below this version once a table has the option.

Schema evolution

service/AlterService.kt, POST /alter: a list of typed operations — add_column, drop_column, rename_column, promote_column, rename_table, set_partition_spec, set_sort_order, the V11 metadata ops add_column_with_metadata, set_table_comment, set_column_comment, set_properties (versioned-table-metadata-v1), set_object_prefix_field (see Partitioning) and set_variant_shredding (mutable-variant-shredding-v1, below) — applied in order, atomically, as one DDL commit (one snapshot, one table_altered change row, one schema-version bump). Renames keep the field_id (end the old row, begin a new one with the same id), so files written before a rename still bind correctly.

set_variant_shredding (name, shredding) replaces the layout a top-level variant column declares in type_params.shredding, or clears it (shredding: null; the column then has no type_params). The declaration is held to the rules of service/VariantShredding.kt exactly as at create_table and add_column (grammar, at most 1000 fields and arrays, 1024 bytes of names on a path, 16 levels), and a column of another type or a nested variant is refused with the same messages. It is a writer's and compaction's target, not a rule on files: the catalog checks no file against it and rewrites none for it; each file's footer carries its own layout and readers use that, so files written under the old declaration stay as they are and keep reading. Writers that honour a declaration (pyhoglake, the Trino connector, millrace through pyhoglake) read it from the live column and lay out the files they write after re-reading in the new one — the alter's DDL snapshot refuses a commit whose read_snapshot predates it (ddl_since_read_snapshot), which is what makes them re-read — and compaction copies each file's variant leaves in that file's own layout, grouping its inputs by layout (the declared one preferred), so files in an older layout compact among themselves (see Compaction). Re-declaring what the column already declares is a no-op: it writes no row and mints no snapshot, so writers holding an older read are not refused and a reconcile script may apply declarations on every deploy. "Already declares" compares JSON values, not spellings — key order and number spelling do not matter, and a STORED type_params that is absent, {} or {"shredding": null} declares nothing, so shredding: null on such a column is a no-op; the op's own shredding has one spelling for "none", null/absent — {} and {"shredding": null} as the argument are declarations, and invalid ones ($ has no type). A request of only such ops answers 200 with the table at the unmoved head and, like a head GET, the sampler's totals with their freshness fields (or none while the sampler has none) — never the exact aggregate under the commit lock that a changing alter's receipt pays for; in a request with other ops those commit while the equal declaration writes nothing. (This departs from set_column_comment / set_object_prefix_field, which commit a snapshot for a no-change request.) Both catalog backends (service/AlterService.kt, hoglite/HogliteAlters.kt) implement it identically: the column keeps its field_id, the live row ends and a replacement begins at the alter's snapshot, carrying a full copy of the declaration in its type_params — one row per change, at operator frequency, so the copies are not a storage concern. Type promotion is a strict widening lattice (int8→int16→int→long and uint8→uint16→uint32, any rung to any higher one, plus float→double) chosen so existing files remain readable under the new schema — and a promote re-encodes the table's existing stats bounds (4-byte → 8-byte Iceberg encoding) in the same transaction, so nothing downstream ever decodes old-width bounds under the new type. Validation runs against the state produced by earlier ops in the same request, so [add tmp, rename tmp→final] works and [drop x, rename x→y] fails precisely. You can't drop the last column, or a column the live partition spec depends on.

Time travel

Every point-in-time read (getTable, /files, /scan) takes ?snapshot= or ?at_timestamp= (mutually exclusive). Timestamp resolution is one indexed lookup: the largest snapshot with snapshot_time <= t; after head resolves to head; before the earliest retained snapshot is 410.

GET /catalogs/{c}/snapshots/resolve?at_timestamp=... returns the largest retained snapshot_id whose recorded snapshot_time is at or before the requested instant, together with that recorded time. This works without a table read, including a catalog containing only its initial snapshot. Missing or offset-less timestamps return 400, unknown catalogs 404, and timestamps before retained history 410. Resolving a snapshot does not prevent expiry.

Table.read_snapshot_id names the snapshot a read resolved at — the catalog head when the request named no snapshot/at_timestamp, the resolved snapshot otherwise. It is required and always present, on every path including totals=false, because it describes the READ and not the totals; a writer caches the response and sends it back as a commit's read_snapshot, which the existing OCC then validates.

The three table-level aggregates (record_count, file_count, file_size_bytes) are three-way, and OPTIONAL on the wire:

  • On a TIME-TRAVEL read (snapshot or at_timestamp), and on a createTable/alterTable receipt, they are aggregated from the manifest and exact at that snapshot, with no freshness fields — a scan is the only correct answer for a past snapshot, and an exact number has no age.
  • On a HEAD read they come from the maintenance sampler's published generation (the same source /maintenance/status and /stats/partitions read, summed per table — persistence/TierTotalsRepo.kt), so the request reads one indexed row set and never the manifest. totals_snapshot_id names the snapshot they are exact at and totals_as_of when it was captured; expect minutes to tens of minutes behind head. They are ABSENT when the published generation is not an answer for the table, and absent means NOT SAMPLED, never zero.
  • Under totals=false all five are absent. That is the identity read, and what a per-flush writer should send.

The namespace listing is the asymmetry: TableSummary's three totals are still required and still aggregated from the manifest, exact at the catalog head, so the two endpoints can disagree by the sample's age for the same table (#235).

The changefeed and consumer offsets

GET /changes?from_snapshot&to_snapshot returns the metadata plan for what happened in (from, to]: data files appended and deletion vectors registered, in snapshot order, with row-id ranges. The client reads the parquet itself — the feed is planning, not data. Paired with it, consumer offsets are catalog state (PUT /consumers/{id}/offsets/{table_uuid}): monotonic (regression is a 409), never below the expiry floor (410 — an expired offset would otherwise wedge the consumer-floor sweep at zero work forever), keyed by table_uuid so incarnation changes are visible, and — critically — respected by retention (below). Together these are the log primitives: a replicator's entire state machine is "changes → apply → commit offset."

Offsets survive a drop by design, so a consumer can finish reading a dropped table — but an incarnation that atomic replacement retired is a different case: the consumer reconciles onto the new table_uuid and never looks at the old one again, so its row there would pin the consumer-floor sweep at a pre-replacement snapshot forever, with nothing left that could ever advance it. Such rows are released — deleted, not advanced — in two places, both in persistence/OffsetRepo.kt. On the commit path, releaseAncestorsOf walks backward from the row just committed, following replaced_table_id: a primary-key lookup per hop and, on the overwhelming majority of commits, zero hops. (Walking forward there would cost O(that consumer's offset count) on every offset commit, including on the catalogs — most of them — that have never had a replacement.) The expiry sweep has no row in hand, so it uses the forward releaseSupersededOffsets across every consumer, clearing rows stranded by replicas predating this so its floor is honest rather than merely filtered. A row releases when a replacement descendant of its incarnation carries an offset for the same consumer at or past that descendant's created_snapshot; both walks are recursive, because a consumer down across two replacements reconciles straight to the newest and both ancestors must go. Same-consumer is load-bearing: another consumer that has not reconciled keeps its position and keeps pinning.

The sweep releases superseded offsets even when retention or consumer protection is disabled. A released row disappears from GET /consumers. An unreconciled consumer keeps its position.

Hoglite supports POST /v1/catalogs/{catalog}/maintenance/expire through the token's placement. Each call runs one bounded sweep for that catalog. The operation advances the retention floor, purges expired metadata, and queues ended files in the removal ledger. It does not delete objects. HOGLAKE_EXPIRY_PURGE_PAGE and HOGLAKE_EXPIRY_PURGE_BUDGET_MS bound the purge. PostgreSQL keeps its background sweeps. Hoglite has no background sweep, catalog registry, or loop lease.

The lineage is recorded, not derived: V14 adds hog_table.replaced_table_id, written by CatalogService.createTable when it publishes a replacement, so the hop is one indexed equality (hog_table_replacement_lineage, partial on replaced_table_id IS NOT NULL). The derivation old.dropped_snapshot = new.created_snapshot is used exactly once, in V14's one-time backfill, which has run in all three environments. The derivation is not used at runtime, for two reasons. Nothing enforces it, and the cost of it being wrong is deleting a consumer's position on a table it is still draining. And it is unindexable in the direction the walk needs: the hop seeks the successor, whose own dropped_snapshot is NULL at the end of every chain, so a partial index on dropped_snapshot cannot serve it and the walk degrades to a sequential scan of hog_table per hop — in the commit tail, on catalogs holding tens of thousands of dropped tables. The walk terminates on created_snapshot strictly increasing rather than a hop cap, because a cap made an origin more than N replacements behind permanently unreleasable, which is the bug being fixed.

Retention, expiry, and safe file removal

Retention is a catalog property (PATCH /options: snapshot_retention_seconds, consumer_floor), enforced continuously by background sweeps (service/ExpiryService.kt), not by an external scheduler. A sweep is two phases, and the split is the fix for the 2026-10-01 prod-us incident (see below).

Phase A — the floor advance, under the commit lock, one bounded transaction carrying its own statement_timeout (derived: min(session/4, admission/2) / 11 statements, 1,363 ms each at the defaults, so the whole hold is at most half the 30 s admission window). Compute the new floor as the minimum of (age cutoff, head−1, current floor + batch, and — when consumer_floor — the minimum consumer offset, so expiry can never outrun a lagging consumer; the pinning consumer is named in the result and the audit line). Then snapshots are removed with range deletes, never id lists, and earliest_snapshot_id advances — capturing the new floor snapshot's snapshot_time into hog_catalog.earliest_snapshot_time in the same update, so once the rows below the floor are gone the catalog can still say WHEN the floor was reached; requests reaching below it get 410 Gone with reconcile instructions citing that time — a consumer is told its feed has a hole (and since when) rather than silently skipping one. A fifth step applies the same reachability rule to the accumulating versioned DDL tables (hog_table_version, hog_column, hog_sort_spec, hog_view, hog_table_layout): rows with end_snapshot <= earliest_snapshot_id are invisible at every retained snapshot and are deleted (sort fields cascade), so DDL churn cannot grow the metadata without bound. hog_partition_spec is kept: a file row names its spec by spec_id at every snapshot, and spec ids are allocated as MAX(spec_id) + 1, so deleting a retired spec would strip the labels from the live files written under it and, when it held the table's highest id, let the next spec reuse that id and relabel them. Those tables are bounded by DDL volume rather than by file volume — thousands of rows on prod-us, not millions — which is why they stay in the locked transaction while the file rows do not.

Phase B — the file purge, outside every lock, paged. A hog_data_file or hog_delete_file row whose end_snapshot is at or below the committed floor is unreadable (a read below the floor is refused 410) and its eligibility is immutable: every writer of end_snapshot either carries end_snapshot IS NULL or takes only ids it re-read as live under the commit lock, and a commit tail writes the NEW HEAD there, which is above the floor by definition. So the rows need no lock to delete — and the page's data-file DELETE repeats the eligibility predicate beside its ctid array anyway, because a ctid array is not a qual a concurrently-updated row gets re-checked against. What that buys is a SKIPPED ROW: the page purges one fewer than it examined, the walk carries on, and the row waits for a later sweep. It is a complete defence only because the vector delete keys off what the data-file delete actually removed, so a skipped file keeps its vectors instead of losing them to a statement that assumed it was going.

Each page is one statement in one transaction under its own 5 s statement_timeout: it picks up to HOGLAKE_EXPIRY_PURGE_PAGE eligible data files, deletes them, deletes the delete vectors of the files it actually removed (live or superseded — the FK cascade would otherwise take them with no hog_file_removal row, which is a permanently leaked puffin object), and inserts every path into the cleanup queue, all in the same statement. So a path is queued iff its row is gone, the vector ordering is a fact about that page rather than a claim about a whole table, and a crash between the phases can orphan nothing. A second, separate arm pages the superseded vectors — the ones whose own end_snapshot is below the floor and whose data file is still live — and is probed with an EXISTS first, because it has no index yet (the partial (catalog_id, end_snapshot) index that the arm split now makes choosable is ticketed with the migration it needs).

A page is HOGLAKE_EXPIRY_PURGE_PAGE data files, not that many ROWS. Each file brings its cascade (~26 hog_file_column_stats rows and its partition values) and its vectors, and while hog_delete_file_one_live_per_data_file bounds live vectors to one per file, nothing bounds superseded ones — vectors only grow, and each supersession leaves an ended row. So one page deletes page × (1 + supersession depth) vector rows and queues that many paths. On every table any writer in the fleet produces today that depth is 0–1 (millpond appends and never deletes; a delete commit supersedes at most once per flush), which is why the default page is sized on the stats cascade — but a table with deep vector history is the shape that makes a page expensive in a way the row count does not show, and the 5 s statement bound plus the halving ladder are what bound it. The vector delete probes the (catalog_id, data_file_id) prefix of hog_delete_file_snapshot_lookup once per deleted file, so the lookup cost is O(page) whatever the depth; it is the rows it finds that are not.

A floor of 0 skips phase B entirely — nothing can satisfy end_snapshot <= 0 — so a catalog that has NEVER expired pays nothing at all. One that expired before its retention was switched off keeps its floor, and still pays an index-only data-file page plus the superseded probe every sweep; that is deliberate, because its backlog still has to drain.

The rate, done properly — BackgroundLoops is fixed delay, not fixed period, and runOnceAllCatalogs sweeps serially:

rows/sweep      = HOGLAKE_EXPIRY_PURGE_BUDGET_MS / page cost
period          = HOGLAKE_EXPIRY_INTERVAL_MS + Σ (every catalog's sweep)
rows/min (hot)  = rows/sweep × 60000 / period

At the compiled defaults (page 1,000, budget 10 s) and production's measured 700–870 µs per file that is 10,000–14,000 rows a sweep. With K catalogs behind on one maintenance pod and prod-us's 15 s interval the hot catalog gets 12,000 × 60/(15 + 10K) rows a minute: ~29k at K=1, ~16k at K=3, ~11k at K=5 — not the 40–56k a fixed-period reading would suggest. Compaction retires ~12,288 files per ~110 s wave (six groups of 2,048), i.e. ~6,700 a minute, so the margin is ~4× at K=1 and is gone somewhere around K=8. When it goes, the symptom is a standing purge_truncated and a rising hoglake_expiry_purge_remaining, and the levers are fewer catalogs per maintenance pod or a larger budget — not a larger page.

The per-row cost is the row plus its cascade, not a constant of the code: ExpiryPurgeCostMeasurement measures a 100,000-row fixture with all three cascades a production row carries (26 hog_file_column_stats rows, one hog_file_partition_value, the vector probe) and prints the figure and the ratio on every run — production's stats relation is 66 GiB and does not fit cache, which is the distance from tens of microseconds to 870. A page that cannot finish inside its 5 s bound is halved and retried inside the same run, down to a page of one, with the halvings counted in hoglake_expiry_halvings_total{phase="purge"}; without that, one poison page would be retried first on every sweep forever and nothing would drain. HOGLAKE_EXPIRY_PURGE_PAGE (default 1,000, refused above 50,000 at boot) and HOGLAKE_EXPIRY_PURGE_BUDGET_MS (default 10,000; 0 with the loop ON is refused at boot, because it would advance the floor forever and purge nothing while every ledger row read healthy) are the knobs. Neither has a chart template today, so changing one in an environment needs chart work first. HOGLAKE_EXPIRY_BATCH is unchanged in meaning: it bounds SNAPSHOTS, and therefore phase A's hog_snapshot_change cascade — and it is halved and retried the same way when phase A's own statement bound fires (hoglake_expiry_halvings_total{phase="advance"}).

The stats cascade is where a page's time goes, and no way of deleting the dependents moves it (#419, measured). Production's cancelled pages carry CONTEXT: … DELETE FROM ONLY "hog_file_column_stats" WHERE $1 = "catalog_id" AND $2 = "data_file_id" — the RI trigger, one call per doomed file. Two alternatives were measured and neither shipped: deleting hog_file_column_stats and hog_file_partition_value explicitly in the page's CTE (keyed off the rows the page actually deleted) beside the cascade, which leaves the trigger nothing to delete but not nothing to do — it still fires per file, descends the stats pkey and fetches each dead heap tuple, because index entries outlive the delete until VACUUM; and the same explicit delete with the three FKs into hog_data_file made NOT ENFORCED (PG 18), so no trigger runs at all. ExpiryPurgeCostMeasurement (100,000 files, 26 stats rows + 1 partition value each, one page of 1,000 from an evicted pool, every buffer the transaction touched including trigger work):

page shape buffers read page
production (cascade deletes) 83,436 3,922 28.1 ms
explicit = ANY (ARRAY(SELECT … FROM doomed)) beside the cascade 112,564 3,947 34.1 ms
explicit, FKs NOT ENFORCED 73,515 3,947 22.4 ms

The reads — ~3.9 cold pages per file, the dependents themselves on the stats primary key and its heap, the whole of the cost on a stats relation that does not fit cache — are the same pages in every shape. At RDS random-read latency they are why a 1,000-file page meets the 5 s bound and halves. NOT ENFORCED saves the per-row probe, 12% of the buffers and no reads, and was not shipped for that: its ALTER takes ACCESS EXCLUSIVE on hog_data_file, every deleter of file rows (expiry, retirement, the catalog drop) would have to delete dependents itself, and a pod on the older code would orphan them during the rollout. ExpiryPurgeIntegrationTest pins the cascade set into hog_data_file, and its enforcement, against pg_constraint.

What to alert on. A sweep that spends its budget, hits a failed page, or cannot read the floor reports purge_truncated with purge_remaining (saturating at 100,000) and purge_failures on its ledger row, and the same facts are series: hoglake_expiry_purge_truncated_total (the one to alert on — a chronically budget-starved purge never fails, so …_purge_failures_total stays at zero and …_purge_rows_total looks healthy forever), hoglake_expiry_purge_remaining (a gauge: how far behind), hoglake_expiry_purge_failures_total (a page that could not finish even at one row), hoglake_expiry_advance_failures_total (the floor itself is stuck — retention is not being enforced at all) and hoglake_expiry_halvings_total{phase} (a knob is wrong for the work). The halvings are also on the ledger row (purge_halvings, advance_halvings) and badged in the console, because for a sweep whose every page hit the 5 s bound they are the only count that moves: the rows are zero and the pages are the rungs. A reduced page size is carried to the next sweep, so that ladder converges in a few sweeps instead of restarting from the configured page every time. Phase B runs even when phase A throws, and even when phase A advanced nothing, so a failed advance does not starve the purge; the ledger row is failed and still carries what the purge did.

The consequence for observers: ended rows below the floor can now exist for a few sweeps. #262 taught /verify's expiry_floor to assert its hog_data_file / hog_delete_file arm only against a sweep whose own ledger row reported the purge DRAINED (and, after that PR's review round, only when that row's floor covered the catalog's current one), so that a drained purge which still left rows below the floor — the purge's predicate and the floor advance disagreeing — stayed a violation while the designed lag did not. #261 removed the check, so that invariant is unwatched until the paged scrubber lands. What still holds is the BACKLOG signal, which never went through verify: purge_truncated, purge_remaining and purge_failures on every ledger row, plus hoglake_expiry_purge_truncated_total and hoglake_expiry_purge_remaining. ExpiryPurgeIntegrationTest.a drained purge's ledger row names the floor it drained AT, not the catalog's current one pins the ledger fact the comparison stands on, so the scrubber has something to build against. And one counter can now fire from normal operation: two file rows may legitimately share one path (V16's index is non-unique for exactly this reason), and purging one while the other survives queues a path the catalog still claims, which is what removal_queue and the drain's still_referenced report — a counter AGENT.md's invariant 4 calls alerted. Where the surviving row is LIVE that was already true before this change; what is new is that two rows both eligible can land in different pages, so the window can also last a page (a sweep, if the budget stops between them). Nothing is deleted in either case — refusing is the drain's whole purpose — and closing it means expiry taking each page's whole path-closure, which is a separate change.

Why it is two phases. It used to be one, and the file GC rode it: one unbounded DELETE FROM hog_data_file WHERE end_snapshot <= floor under the commit lock, plus its cascade into hog_file_column_stats (26 rows per file, 66 GiB), hog_file_partition_value and hog_delete_file. Compaction 1.3.7 commits six groups of up to 2,048 files, so each sweep met one whole compaction wave: 12,288 rows, 17–25 s of lock hold per minute, ten commits queued behind it when sampled, the commit-lock wait p99 pinned at the 30 s admission bound for sixteen hours, and API p99 of 20–60 s across routes because parked commits held the API pods' pool connections — with RDS idle at 8% CPU the whole time. Shortening the sweep interval to 15 s shortens each hold and leaves the duty cycle where it was.

Hoglite supports POST /v1/catalogs/{catalog}/maintenance/cleanup for the catalog in the token's placement. Each call drains bounded bulk and staging queues, then purges old run records, receipts, and drained removals. The drain checks live and historical file references and active uploads. It uses the server's object-store configuration, as PostgreSQL cleanup does. Per-call AWS identity remains separate work. Hoglite has no cleanup loop, catalog registry, or loop lease.

Hoglite supports POST /v1/catalogs/{catalog}/maintenance/compact for the catalog in the token's placement. Its CompactionStorage adapter uses the same CompactionExecutor as PostgreSQL. The executor owns packing, VARIANT layout probing, budget admission, Parquet rewriting, and result aggregation. The adapter reserves individual inputs and publishes with transaction-local guards. Each table plan reads at most CompactionConfig.candidateBudget candidates, in bucket, size, and file-ID order. The next window overlaps the trailing bucket by at most minInputFiles - 1 files. This overlap prevents interleaved partitions from permanently stranding a static backlog. A bounded process-local cache retains fetch cursors and shared VARIANT layout observations across manual calls. A process restart can repeat work. Correct claims and publication do not depend on this cache. New tenant schemas include the live bucket-order index. Without that index, each plan uses one capped read instead of repeated sorted pages. Run manual cleanup to drain old staged-output tickets. The server owns the shared object store and its configured credential provider. Per-call AWS identity remains separate work. Hoglite has no compaction loop, catalog registry, fleet sweep, or loop lease.

Physical deletion is decoupled and paranoid (service/CleanupService.kt): the queue is a suggestion. At drain time every path is re-checked against live references — a still-referenced path is skipped and counted as an invariant violation (alertable), never deleted. Missing objects count as done. That re-check is ONE statement per sub-batch and it is INDEXED: it probes hog_data_file, hog_delete_file (V17's (catalog_id, path)) and hog_upload (V12's unique key) by path, so its cost sizes with the sub-batch and not with the catalog's manifest — before V17 it read every file row the catalog has ever registered, once per sub-batch (190,884 buffers and 692 ms at 5M rows, against 8,728 and 33 ms after).

The drain is a claimed work queue, and it takes no catalog lock anywhere (V21). Each sub-batch is three steps with the transaction boundaries as the design:

  1. CLAIM — UPDATE hog_file_removal SET claimed_at = now(), claimed_by = :worker WHERE removal_id IN (SELECT ... FOR UPDATE SKIP LOCKED) RETURNING, one statement in its own transaction, committed before the first object-store call. So no transaction is open while a worker waits on S3, and idle_in_transaction_session_timeout bounds nothing here.
  2. WORK — the reference check, then the deletes. No transaction, no lock, nobody waiting.
  3. SETTLE — one short transaction, fenced on drained_at IS NULL AND claimed_by = :worker and RETURNING the rows it actually took. The ones it did not are settled_elsewhere.

The lock it used to hold protected nothing, and cost ~19 s per 1,000-row sub-batch on gigahog-prod-us (2026-09-24), during which every commit on the catalog waited — which is why cleanup was off in production until the lock came out. Cleanup is ON in prod-us since 2026-09-29, at 60 s / batch 10,000 / 1 worker; dev and prod-eu carry no maintenance: block at all and so run the chart defaults (30 min / batch 2,000). The queue stood at ~2.6M undrained rows growing ~190k/h on 2026-09-29, about 9.4k of them orphaned compaction_staging tickets past their grace, and the drain-down cleared it that day.

The reason the lock was unnecessary is the pair it was half of: a commit passes the path-reuse guard only when no UNDRAINED row names the path, and the drain reads only undrained rows — a claimed row is still undrained, so the refusal covers the whole time a path is somebody's work. What remains is a queue INSERT racing a registration, and there are four inserters with three serializers, which is worth stating because two of them take no commit lock:

  • ExpiryService and RetirementService insert under the commit lock, and only for paths whose file rows they have just deleted;
  • CompactionService.stageOutputPath's initial stage takes no lock (autocommit, before the rewrite): safe because the path is a UUID that sweep just minted and nobody else knows. Its re-stage runs inside commitGroup and so under the lock;
  • UploadService.fenceAndQueue takes no commit lock either, and deliberately — taking one would convoy the catalog. It is serialized against a concurrent registration by the hog_upload row lock: UploadService.register takes SELECT ... FOR UPDATE on the claim rows inside the commit transaction and raises CommitConflict unless the claim is still active, while the sweep re-evaluates its candidate predicate after waiting on that lock. This is the arm the removed commit lock was actually standing in for.

The standing constraint that falls out: a commit that registers a path with no hog_upload claim has no serializer against a concurrent queue insert for that path. It is unreachable today because paths are never reused and every externally-supplied path arrives through an upload claim — a future path that is neither must bring its own serializer.

FOR UPDATE SKIP LOCKED is what lets HOGLAKE_CLEANUP_WORKERS (default 1) workers per run — and any number of replicas — partition the queue with no coordination and no single-flight lock: a row another claim holds is skipped rather than waited for. HOGLAKE_CLEANUP_BATCH is a budget per worker, so a run asks for workers x batch rows and the standing rate is

rows/h = workers x batch x 3600000 / HOGLAKE_CLEANUP_INTERVAL_MS

which is 4,000 rows/h at the compiled defaults — a deliberately conservative floor, and nowhere near a busy catalog's arrivals. The defaults do not clear a backlog; the values that do live in the chart, and they are a pair (a batch large enough to keep the workers busy, an interval near a run's own duration, which the reference check sets at ~20 s cold for 4 x 1,000 rows). A worker holds a pooled connection across that check, so the draw of the loops that are on — HOGLAKE_COMPACTION_PARALLEL_GROUPS + HOGLAKE_CLEANUP_WORKERS + 1 for the reindex loop, each counted only when its interval is > 0 — is refused at boot above HOGLAKE_DB_POOL_SIZE - FOREGROUND_CONNECTION_RESERVE: at the default pool of 10 with reserve 4 and 6 groups, no worker count is legal, which is why prod-us raised dbPoolSize to 16 — that is what makes 1 worker (and up to 6) legal. A claim is a lease, not a lock (HOGLAKE_CLEANUP_CLAIM_LEASE_SECONDS, 900 s): a worker killed between its claim and its settle leaves rows claimed until the lease lapses, and DeleteObjects is idempotent so the re-drain settles exactly as the first attempt would have. Note that HOGLAKE_CLEANUP_SUB_BATCH, HOGLAKE_CLEANUP_CLAIM_LEASE_SECONDS and HOGLAKE_CLEANUP_STAGING_GRACE_SECONDS are server-default-only today: the chart has no template for any of them, so they cannot be set in any environment, and changing one needs chart template work first. The claimed_by fence is the other half of that: a worker whose lease lapsed while it was talking to S3 can no longer write the ledger, so it cannot stamp its outcome over the worker that took the row from it. The fence is also where still_referenced is COUNTED from — the attempts bump returns the rows it really touched, and a compaction group that commits between a claim and its reference check makes the path live without being a violation.

Two writers can settle a hog_file_removal row: this drain, and a compaction group's commit settling its own staging ticket 'registered'. CompactionService.commitGroup re-reads the ticket FOR UPDATE and takes it only if nobody has touched it — drained_at IS NULL AND claimed_at IS NULL AND attempts = 0, the same three terms in its settle — otherwise it re-stages the path and skips the group. A LAPSED claim counts as touched, and that is the point: an expired claim does not mean the object survived, it means nobody knows, and the row lock cannot stand between a DELETE no transaction holds and a registration. The three routes to a touched-but-unsettled ticket are a worker past its lease, a worker killed after its DELETE, and a lost DeleteObjects response (which bumps attempts and releases the claim); each costs one group's CPU and a fresh UUID path next sweep, rather than a live file row pointing at a deleted object. Compaction therefore never reads the lease — it is cleanup's alone. The re-read's wait is at most one claim transaction (a single UPDATE), because the claim skips locked rows and never waits on compaction.

The drain also reads back the rows its settle did not match and classifies them: another writer's 'registered' over a path this sub-batch had not deleted is ordinary contention (settled_elsewhere), a claim that moved is a lapsed lease (a WARN naming both workers), and a 'registered' over a path this sub-batch had deleted is an invariant violation — an ERROR, a cleanup_violation audit event and a counted still_referenced. That last case is unreachable given the re-read above; it is instrumented because nothing else in the system could see it (every staging_tickets arm passes once the file row exists).

A bulk sub-batch's deletes are one DeleteObjects call per bucket chunk — 1,000 keys is S3's own ceiling on one request, which is where the default sub-batch (and therefore the size of one claim) comes from — rather than the 25 x (HeadObject + DeleteObject) it used to be. That old shape held the commit lock ~3.2 s per sub-batch and ~255 s per 2,000-row run, which took commit latency on gigahog-prod-us from 200-400 ms to 12-22 s against a 30 s admission bound and got both API pods liveness-killed. What scales the work is the number of REQUESTS, not the sub-batch: keys past 1,000, or spread across buckets, chunk into more requests, so raising the knob past the ceiling buys nothing.

reason = 'compaction_staging' rows are the carve-out, on three counts, and they are claimed by their own statement so that the lease bounds the work one claim carries: 25 tickets is 50 round trips (500 s at the call bound, inside the 900 s lease), where a single claim of 1,000 tickets would have been 20,000 s of calls under one lease. They keep HeadObject + DeleteObject, because a DeleteObjects response cannot distinguish a key it removed from one that was never there, and that distinction is recorded as 'absent'. Its reader was /verify's staging_tickets check, removed in #261, so the value is written and unread today — kept because it cannot be reconstructed after the delete. Because that costs two round trips per row, they are claimed and settled 25 at a time — a unit of progress (each sub-batch settles in its own transaction) and the unit the lease bounds. And the drain leaves them alone until they are past HOGLAKE_CLEANUP_STAGING_GRACE_SECONDS (1 h), because the ticket is inserted before the rewrite starts and settling a fresh one while its group is still uploading leaves the object with no ticket naming it; that grace used to have a ceiling — it plus the cleanup interval had to stay well under /verify's 6 h staging-ticket age, or the check alerted on tickets the drain was deliberately leaving alone — and #261 removed the check, so nothing bounds it today. Every other reason settles 'deleted', whether or not the key was there.

The object-store call bound (RemovalStore.apiCallTimeout) is min(10 s, admission bound / 3), so an operator who lowers HOGLAKE_COMMIT_LOCK_TIMEOUT_MS gets shorter calls with it. An unbounded admission wait (0) leaves the 10 s cap in effect. The cap is independent of database session timeouts: no transaction is open across a call. What a hung call costs is one parked worker holding a claim until its lease expires. The deadline_skipped counter and the HOLD_BUDGET arithmetic it belonged to bounded that hold and are gone; the counter stays on the wire, always 0, because the maintenance ledger holds rows that carry it.

hoglake_files_removed_total counts objects_removed — DISTINCT paths physically deleted — and not removed, which counts ledger rows: two undrained rows over one path are legitimate state and one batched delete settles both.

The ledger's own retention purge is a loop of bounded deletes that pages the primary key from the bottom, where an append-only queue keeps its oldest rows: up to LEDGER_PURGE_PAGE ids per page through the key, delete the ones past the cutoff, stop at the first page with nothing to purge or when the wall budget expires. It used to be one DELETE ... WHERE catalog_id = :c AND drained_at < cutoff, which no index on this table can serve — both are partial on drained_at IS NULL, the complement of the rows it deletes — so it was a sequential scan with an unbounded row count, once per catalog per run, against a ledger heading for ~137M rows at 190k/h drained and the 30-day default. That is the shape of the 2026-09-28 expiry-lock outage, and it is why this is bounded before cleanup is re-enabled rather than after. The cost of the early stop is stated rather than hidden: a page with nothing to purge ends the walk, so rows above a long-undrained row wait for the run after it settles.

Draining soft-deletes: a settled hog_file_removal row keeps its place with drained_at + drained_outcome ('deleted' for a physical removal, 'absent' for verified-already-gone), so "what did cleanup touch, when, after how many attempts" is queryable instead of dying with the row; skips and transient failures bump attempts/last_attempt_at and stay queued. The drain reads only undrained rows (partial index), and each sweep purges drained rows older than HOGLAKE_REMOVAL_LEDGER_RETENTION_SECONDS (default 30 days) so the ledger never becomes its own unbounded-growth problem.

Sort orders and compaction

A table may carry a versioned sort order (hog_sort_spec / hog_sort_field, set via the set_sort_order alter op) — advisory for writers (the server never verifies file sortedness), binding for compaction. Compaction (compaction/CompactionService.kt, POST /maintenance/compact + an off-by-default loop) merges small live files: candidates share (spec_id, partition_values) and pack to a byte target — row-id adjacency is NOT required, which is why outputs materialize their row ids as an explicit _hog_row_id int64 column (reserved field id 2147483646, flagged by data_file.explicit_row_ids) instead of relying on position. That makes sorting on rewrite safe — the predecessor's sorted-compaction rowid remap is structurally impossible. The rewrite (parquet-java — the project's one parquet library, shared with the hydrator's footer reads) happens entirely before the commit transaction; the commit re-verifies each input is still live under the exact planned identity (plan-to-commit races skip the group), end-snapshots inputs (time travel keeps them; expiry reclaims them later), registers the output's stats from the footer the rewrite just wrote — the same FooterStats.aggregate the hydrator runs, so the counts and bounds are exactly the rows the writer emitted and no input stats row is read at all — and the changefeed excludes compacted outputs so consumers never see merged rows re-appear as fresh appends. On a table with the object-prefix layout the output goes under its group's prefix and its footer must prove the value before it registers (see Partitioning).

A group with no survivors registers no output. When every input's live deletion vector deletes every row it holds, the rewrite still runs — reading each input through its vector is the proof the group is dead, and the commit's rowsWritten == survivingRecords check stands behind it; the planner never skips a group on its registered counts, because a mis-registered delete_count would then retire live rows. It writes an empty parquet, and the commit, past every plan-to-commit guard above (a DV superseded since the plan is still dv_superseded), RETIRES the group: one snapshot with a table_compacted change (message retired N fully-deleted files of ns.table), inputs and their DVs end-snapshotted, and no hog_data_file row, partition values, column stats or file id. It used to register the empty file — a live record_count = 0 row whose row_id_start no row owned. The empty object's compaction_staging ticket is left undrained, exactly as a lost race leaves it, and the cleanup drain deletes the object. Counted as groups_retired (hoglake_compaction_groups_retired_total{catalog}), not in groups_compacted, files_in, files_out, bytes_in or bytes_out; charged to the run's group budget like any attempt.

Grouping is ONE PASS of ordinary bin packing, the shape Iceberg's rewrite_data_files uses. For each partition/spec bucket, sort the candidates by size and close a group as soon as its input bytes reach HOGLAKE_COMPACTION_TARGET_BYTES (512 MiB) or it holds HOGLAKE_COMPACTION_MAX_INPUT_FILES (default 64); carry on with the rest, and emit the trailing remainder as a group as well.

By size, not by row id, and that is load-bearing. A compaction output takes row_id_start = min surviving id of its inputs, so it sorts in front of the newer, smaller files. Packed in row-id order, a large output ate most of the group's quota, the group closed a file or two later, and the whole group was then discarded for holding too few files — permanently, because row-id order never changes. Simulated over 300 ticks of steady ingest and a full drain, 100 MiB ingest files left 373 small files stranded forever; size-ordered, the same workload drains to none. Row-id adjacency is not required (outputs carry explicit row ids), so nothing else depends on the old order.

A group is then dropped unless it holds min(HOGLAKE_COMPACTION_MIN_INPUT_FILES, target / its largest file) files, floored at 2. The minimum scales with the files it judges, because a fixed file count cannot judge a byte target: no group can hold five files that are each over a fifth of the target, so a fixed 5 silently means "never compact this bucket" for any bucket with files that big (before hoglake#134 that included every SORTED table, whose target was derated to fit an in-memory sort). Silently, because no group forms, so nothing is refused and nothing is logged.

The minimum is a write-amplification knob, not a termination condition: compaction terminates at any value >= 2, since a group turns N >= 2 files into at most one (none, when every row was deleted) and the bucket's file count strictly decreases. What a low value costs is repeated rewriting — compression puts every output back under the target, so at 2 it converges on the target from below one rewrite at a time, roughly 4x the bytes moved. That is the ladder by another name.

Measured at the default of 5: draining a static backlog costs about 2x the input bytes, because ingest-sized files reach the target band in one rewrite and the outputs consolidate pairwise from there. So the claim is one rewrite to reach the target band, not one rewrite per file for all time — and without the dominance split described above, steady state is a 5.6x LOSS. This replaced a geometric ladder of size tiers (#151, V10), which rewrote the same bytes once per rung while every rung above the first saved nothing.

HOGLAKE_COMPACTION_MAX_GROUPS_PER_RUN (default 1) caps executed attempts per catalog, including failures and skips.

Concurrency: the fixed per-group cost, and the two knobs for it

A compaction group costs a fixed amount of wall time almost regardless of what it holds, because the cost is object-store LATENCY rather than bytes: measured on gigahog-prod-us (2026-09-24, main.events_raw) at about 8.5 s per group — the serialized input opens, the plan, the commit. A sweep that runs those groups one at a time drains files at a rate set by that constant and by nothing else.

HOGLAKE_COMPACTION_PARALLEL_GROUPS (default 1, which is the sequential sweep this server has always run: no executor, groups on the calling thread) rewrites and commits that many of a sweep's planned groups at once. Groups share no input file by construction — one pass of bin packing over disjoint buckets — so the only serialization point between them is the per-catalog commit lock, and the commit transaction takes that lock ALONE: never across the rewrite or the upload.

The sweep plans and executes per table, in name order, and that ordering is deliberate: a plan is metadata-only and cheap, and its value decays fast, so it is taken as late as it can be. Planning every table up front would leave the last table's plan as old as every rewrite before it — at 64 groups a sweep and ~8.5 s a group, minutes of ingest and of a sibling replica's commits between the read and the attempt.

A wave is joined WHOLE before the next one starts, so the slowest group in a wave bounds it, and a wave is drawn from ONE table's queue — a table holding fewer groups than parallelGroups runs at its own group count, not at the knob's. Both follow from planning per table, and both mean the knob is a ceiling rather than a promise.

Three things to raise with it: the maintenance pod's CPU (the rewrite is CPU-bound on zstd), the sorted-path heap, which this knob DIVIDES (below), and HOGLAKE_DB_POOL_SIZE (default 10).

The pool is not optional. Every in-flight group holds a pooled connection across its commit-lock wait, and taking too much of a pool the foreground shares turns a writer's commit backpressure from the typed 503 the admission contract promises into a connection-pool timeout served as a 500 — with nothing in the 500 naming the knob that caused it. So the server refuses to boot when

compaction draw + cleanup draw + reindex draw > HOGLAKE_DB_POOL_SIZE - 4

where each draw counts only if its loop is on (interval > 0): compaction is HOGLAKE_COMPACTION_PARALLEL_GROUPS, cleanup is HOGLAKE_CLEANUP_WORKERS, and reindex is 1. The failure names every variable involved. The four are a FLOOR, not a model of demand: the hydrator, expiry, cleanup, retirement and the metrics sampler draw on the same pool, and a busy instance's foreground wants more than four of its own. Raise the pool with the knob — at the defaults (pool 10, cleanup on with 1 worker, reindex off) the HOGLAKE_COMPACTION_PARALLEL_GROUPS ceiling is 5.

HOGLAKE_REQUEST_THREADS (default HOGLAKE_DB_POOL_SIZE) is the pool's other customer, and it is sized against the same arithmetic (#218). It is the width of the blocking dispatcher every route handler runs on, so it is the ceiling on concurrent requests inside a blocking call — and nearly every handler's first act is to borrow a connection. Handler threads ABOVE the pool therefore buy no concurrency for those routes: they queue inside HikariPool.getConnection, which gives up after 5 s and throws a 500, instead of queueing in the dispatcher where the wait is FIFO, measured (hoglake_request_queue_wait_seconds) and shed with the typed 503 once it passes the admission bound. The server refuses to boot on

HOGLAKE_REQUEST_THREADS > HOGLAKE_DB_POOL_SIZE

for the same reason it refuses the compaction inequality: raising it is a pair of knobs, and forgetting the second one converts dispatcher queueing into Hikari timeouts fleet-wide.

What the default does NOT promise is a reserve for the loops. On the API workload the chart turns every background loop off, so the foreground is the pool's only customer and requestThreads == dbPoolSize is exact. On a pod that runs loops AND serves traffic — the maintenance Deployment, a dev stack, anything on the defaults — the foreground alone can take every connection, and a hydrator or expiry iteration then waits Hikari's 5 s and fails (logged, counted as hoglake_background_loop_failures_total, retried next interval: a delay, not a loss). FOREGROUND_CONNECTION_RESERVE bounds COMPACTION's draw, not the foreground's. Such a workload should set HOGLAKE_REQUEST_THREADS below the pool by the number of loops it runs.

Compaction's own commits now pass HOGLAKE_COMMIT_LOCK_TIMEOUT_MS like every other acquirer of that lock. It is transaction-local, so it bounds the whole commit tail rather than only the advisory lock: a group whose commit — or whose row locks inside that tail — times out is counted with the plan-to-commit races, and its staged output is left undrained for the cleanup drain, exactly as a lost race leaves it.

HOGLAKE_COMPACTION_PARALLEL_INPUT_OPENS (default 8) opens that many of ONE group's input files at a time. Opening a parquet input costs at least one round trip before a row can be read, and a 64-file group used to pay 64 of them end to end — twice over, since the rewriter opened each input once for its schema and again for its rows. It now opens each once, with a bounded window ahead of the consumer. Merge order is preserved (the rewrite still consumes inputs in order, on one thread; only the open overlaps) and so is the streaming memory bound: an input that is open but not yet being read holds its parsed footer, not a readahead buffer. Measured on a synthetic 64-file group against a MinIO container, where per-open latency is a fraction of what a real object store charges: 435 ms sequential, 74 ms at 8.

Its footprint is worth stating because it is the knob that is ON by default. The worst case is parallelGroups x inputOpenParallelism readers each holding a parsed footer, and a footer read is capped at S3InputFile.DEFAULT_MAX_PREFETCH_BYTES (64 MiB) — so at the highest parallelGroups a default pool allows, 5 x 8 x 64 MiB is the arithmetic bound, against kilobytes per footer for every real file. The window is per GROUP and is not divided by parallelGroups; an operator running both knobs high on a small pod should lower one of them.

HOGLAKE_COMPACTION_CLAIMS_ENABLED (default on) enables group claims. Each execution plan reads candidates and packs groups with NO lock held, then takes a per-catalog advisory lock for its claim transaction only: under it, the transaction re-reads the table's live claims, drops every planned group that overlaps one (claimed_elsewhere), and claims the selected queue, limited to the remaining run budget. The lock is released after that transaction commits, so the next holder's re-read sees these claims. Planning and claims use one connection and separate transactions; packing has no open transaction. The lock is separate from the commit and retirement locks. Its wait is bounded by a 15 s lock_timeout and queues only behind siblings' claim transactions. A claim transaction that fails plans nothing for the table (the catalog's run fails and the ledger records it); it never falls back to an unclaimed plan. File I/O starts after unlock. Metadata-only plan previews do not lock or claim work.

Until #418 the lock was taken before the candidate read and held through every probe. On gigahog-prod-us (1.4.1, 2026-10-22, nine planners) one pod in a 15 s probe made the other eight queue on pg_advisory_lock and hit their own 15 s bound there — 38 of 40 millpond-prod-us sweeps failed, most of them on the lock wait. What the lock protected is two plans reserving different group keys for the same files; the in-lock re-read protects that on its own. What concurrent planning costs instead: two planners can probe the same hot bucket at once, pack the same groups, and the later one drops them in phase (c) or the in-lock re-read — a wasted probe, never a duplicate rewrite. Excluding live-claimed files inside the probe's SQL was measured and rejected: it is O(claimed ids) per probe and goes linear past work_mem (576 live claims of 5,000 ids, 2.88M ids, work_mem 4 MB: the NOT IN probe ran over 10 minutes; NOT EXISTS / NOT IN against a materialized CTE were still running at a 120 s cancel), so collisions between planners on one hot bucket are left to phase (c) and the in-lock re-read.

  • HOGLAKE_COMPACTION_PLAN_STATEMENT_TIMEOUT_MS (default 60,000, the session's bound; at least 1,000) replaces the fixed 15 s plan statement bound. That was a fail-fast for a slow probe under the lock; without the lock a slow probe costs one pod one sweep and yields the bucket's whole window. It bounds the probe only: the claim transaction keeps a fixed 15 s, equal to the lock wait, so a waiter never outlives the holder's bound.

HOGLAKE_COMPACTION_CLAIM_TTL_SECONDS defaults to 3600 seconds. Set it above the longest full run, including queue time. Each group refreshes its live claim before execution. An expired or replaced claim skips execution. Each run has its own claimant ID, including concurrent runs on one server. Cancellation and heap refusal release claims for groups that did not start.

The next planner sees all queued claims and excludes groups with overlapping inputs. Claim skips increment claimed_elsewhere and do not consume the run budget. Existing explicit TTL settings override the new default. Update shorter settings before adding concurrent compactors. A fleet mixing this version with 1.4.1 is safe: 1.4.1 holds the planning lock across its read and its claims, and this version re-reads the live claims under the same lock. Only a version from before the planning lock existed is unsafe beside either.

How N maintenance pods share one catalog. Group claims make EXECUTION disjoint; three more pieces make PLANNING disjoint, after gigahog-prod-us on 2026-10-21. With the maintenance Deployment raised from 2 to 8 replicas, every pod's planner walked the same buckets in the same order: six millpond-prod-us sweeps started within two seconds with identical buckets_considered 123 / candidates_fetched 50,029 and claimed_elsewhere 0, 64, 128, ... 320 — each pod, in turn under the planning lock, re-probed the buckets its predecessors had already claimed and dropped their groups only after reading them. The sweeps then finished together and re-planned together on their 30 s interval: nine copies of the expensive day-bucket probes at once, every one past the 15 s plan timeout, 19 failures in nine minutes.

  • Bucket claims, checked before the probe. An execution plan that claims EVERY free group a bucket packed into (and probed the bucket in full, not cut by the candidate budget) also writes a bucket claim: a hog_compaction_claim row keyed bucket: + a hash of the spec id and partition values, with an empty input_file_ids. No new table and no migration — the row has the same lease, claimant fence, expiry takeover and purge as a group claim. The next planner reads the table's live bucket claims on its candidate snapshot and skips those buckets without probing them (buckets_skipped_claimed in the run result, hoglake_compaction_buckets_skipped_claimed_total{catalog}). Planning takes no lock (#418), so a marker committed after a planner's snapshot is missed by that planner: it probes the bucket, and phase (c) or its claim transaction's in-lock re-read drops the overlapping groups. The claim is released when the last of the bucket's groups settles (committed, skipped, failed, or released unstarted). Its lease is SHORT — HOGLAKE_COMPACTION_BUCKET_CLAIM_TTL_SECONDS, default 600, against the group claims' hour — and is renewed in the same UPDATE as each of its groups' pre-IO refresh, so a live queue keeps it and a dead one loses it in minutes. That matters because a pod SIGTERMed mid-sweep releases nothing (BackgroundLoops.close abandons the sweep after 5 s), and a leaked bucket claim hides a whole bucket, new files included; on the group lease a rolling deploy would take a share of a hot table's buckets out of compaction for an hour. Because every group's refresh renews ALL of the run's outstanding markers, a marked bucket stays hidden until the last of its own groups settles, wherever they sit in the run's queue — that is the intent: the marker means "this run holds all of it". A bucket with a group left over (the run's room ran out, or a claim insert lost) is NOT marked, so a sibling can still take what is left, and finds the held groups by overlap as before. Like group claims it is an optimization: ignore it and the cost is the old re-probe, never a wrong commit. The tier rows carry no file ids, so a cheaper per-file check was not available.
  • Per-pod cursor start. Each pod's bucket cursor starts, per (catalog, table), at a position hashed from its identity (POD_NAME, else HOSTNAME, else local) and the table, then advances as before. The server does not know N and the pods have no ordinal, so this is a hash rather than k x len / N; the overlaps a hash leaves are what the bucket claims cover. HOGLAKE_INSTANCE_NAME is not used: it names the deployment and is the same on every pod.
  • Loop jitter, compaction only. The compaction loop sleeps HOGLAKE_COMPACTION_INTERVAL_MS x (1 ± 0.25), drawn from a generator seeded by the pod identity, so sweeps that end together do not re-plan together; the mean interval is unchanged. Every other loop keeps its exact interval — the sampler's tick cadence and expiry's interval are sized arithmetic.

Read the pair buckets_skipped_claimed / claimed_elsewhere together: a fleet dividing a catalog shows the first and keeps the second near zero; both at zero with more than one pod means claims are off or the pods are not planning the same buckets.

A claim is an optimization and never authorization. Correctness against a concurrent rewrite is, and stays, the plan-to-commit re-verification under the commit lock; turning claims off costs work and nothing else. The claim key is a hash of the group's spec, partition values and sorted input file ids — the identity of the WORK, so two replicas compute it with no coordination — while the planner's skip is by input-file OVERLAP, because a replica planning a moment later packs the same files into differently-keyed groups. A claim is released when its group does not commit and deliberately kept when it does: the inputs are dead, and the other maintainer's older plan still names them. A kept claim goes on its own lease (HOGLAKE_COMPACTION_COMMITTED_CLAIM_TTL_SECONDS, default 600), sized for the thing it has to cover: the age of a SIBLING'S PLAN, which is one whole sweep. At the measured 8.5 s a group, 64 groups is about 544 s — so the lease has to clear that, and a shorter one (the first draft used 120 s) leaves most of the sibling's plans arriving at an expired claim and rewriting anyway. The cost is rows whose input_file_ids the planner reads on every pass: committed groups per sweep x lease / sweep duration, about 70 per table at those settings.

expires_at is the only liveness protocol — no heartbeat, so a killed maintainer costs one lease on those files and nothing else — and a bulk purge at the head of each sweep clears what the releases did not. That purge is not gated on HOGLAKE_COMPACTION_CLAIMS_ENABLED, so turning the CLAIMS off still clears the rows they left. It does live at the head of a SWEEP, though, so turning compaction itself off (HOGLAKE_COMPACTION_INTERVAL_MS=0) stops it like everything else in a sweep — which used to be one of the two things /maintenance/verify's compaction_claims check redded on (the other being an expired claim outliving its table). #261 removed that check, so a purge that stops running is unobserved.

HOGLAKE_COMPACTION_CODEC (default zstd, with HOGLAKE_COMPACTION_ZSTD_LEVEL default 3) is the compression the rewrite writes its OUTPUT with; the legal set is zstd, snappy, gzip, lz4_raw and uncompressed, case-insensitive, and an unknown name is refused at boot. It is not a per-file detail. Compaction rewrites a table's rows into target-sized files and then leaves them alone, so this is the codec a compacted table is stored and scanned under — permanently. The writer used to take ExampleParquetWriter's UNCOMPRESSED default, which made every merge a one-way decompression of clients that all write snappy (pyarrow's and DuckDB's default, so pyhoglake and the duckdb-client) or zstd (hedgerow): one dev-catalog run merged 67.6 MiB of inputs into 80.1 MiB of output.

zstd over snappy because the cost falls on the side paid once. Measured on event-shaped data (CodecMeasurement, four files of 200k pageview rows, inputs written snappy): high-cardinality strings compact to 1.41x the input bytes uncompressed, 1.03x under snappy and 0.60x under zstd; low-cardinality enums to 1.84x, 1.27x and 0.84x. Against the uncompressed output, zstd is 0.43-0.45x and snappy 0.69-0.74x. The rewrite's wall time for that group was 0.85 s uncompressed, 0.86 s snappy, 1.25 s zstd and 3.5 s gzip — so zstd costs roughly 25-30% more CPU than writing raw, for less than half the bytes, while gzip pays 4x the CPU for a worse ratio than zstd. The level is pinned rather than inherited because the sweep is CPU-bound on a shared maintenance pod and a parquet-java bump must not move that budget without a diff. parquet-java's zstd workers stay at 0 (in-thread).

The level is 3, parquet-java's own default. hoglake#134 package D lowered it to 1 on a synthetic measurement: a JFR profile of the rewrite with native frames (16 inputs x 50k rows) put zstd at 11-16% of the rewrite's CPU on the event shape and 41-48% on JSON-heavy rows at level 3, level 1 cut the rewrite's wall time by ~12% and ~20-25% respectively, and CodecMeasurement (same four 200k-row files as above, printing both levels) showed level 1 SMALLER on the high-cardinality strings (50.6 against 52.1 MiB) and the mixed table (51.9 against 53.4 MiB) and 7% larger only on the low-cardinality enums (10.2 against 9.5 MiB). Real data disagreed: on 2026-10-10 the gigahog-dev catalog re-merged pairs of level-3 compaction outputs at level 1 and every pair grew 12-13% (968 MiB -> 1.1 GiB, 872 -> 974 MiB, 3.8 -> 4.3 GiB over four pairs), where the synthetic rows had predicted no change. Compression is paid once per rewrite; the bytes are paid in S3 until expiry and by every scan, so the default went back to 3. Decompression speed does not depend on the level. An operator who measures their own data the other way sets HOGLAKE_COMPACTION_ZSTD_LEVEL=1; no chart sets it today.

A sorted rewrite is an external merge sort (hoglake#134). It used to read the whole group into an ArrayList<Group> and call sortedWith, so a sorted group had to fit in heap and the planner bounded it in rows; a dense sorted table never reached the target. Now a sorted group packs to HOGLAKE_COMPACTION_TARGET_BYTES like any other, and the rewrite works in two phases that never overlap:

  • Chunks. Survivors of every input not read in place are read in input order into a chunk, sorted by (sort keys, row id), and written to a local parquet spill file — snappy, the OUTPUT schema, 16 MiB row groups — under HOGLAKE_COMPACTION_SPILL_DIR (default java.io.tmpdir, the chart's /tmp emptyDir), one hoglake-compaction-spill-<uuid> directory per rewrite, removed on every exit path. A group with no trusted run whose survivors fit one chunk is sorted in memory and written straight to the output: no disk at all.
  • Merge. A k-way merge of RUNS through a priority queue into the output, on the caller's thread. A run is a spill file, or an input read in place, which is one of two kinds:
    • METADATA-TRUSTED: a compaction output (explicit_row_ids) registered at or after the live sort spec's begin_snapshot. Its order is not checked. The commit re-reads the live sort_id under the catalog lock and refuses the group if the spec moved during the rewrite, so an output can only be trusted by the spec it was sorted under.
    • VERIFIED: any other input the sortedness pre-pass found already in order (below). A client's declared sort order is still never believed; its rows are.

The sortedness pre-pass: streaming in practice for pre-sorting writers. Before admission, every input that is not metadata-trusted and is at least HOGLAKE_COMPACTION_VERIFY_MIN_BYTES (default 16 MiB, the spill block) is checked by reading ONLY its sort-key columns: a projected parquet read (setRequestedSchema) of the key leaves, resolved in the file's own schema by field id (struct leaves included), plus the _hog_row_id carrier for a compaction output — whose ties must also be in row-id order. Every physical row is checked, deleted or not, and the read stops at the first row out of order. A file that passes is a run candidate exactly like a trusted output (same largest-first admission, same footer confirmation) and is reopened in place by the merge; one that fails is spilled, which is not an error. A writer that sorts its files (millpond's flushes) therefore compacts with files_verified = n and spill_bytes = 0; a Trino INSERT's files fail the check and are the spill. Keys compare in the file's own physical domain, which is equivalent because the only conversions the rewrite makes (int32→int64, float→double, uint32 zero-extension) preserve order. A file with columns lacking field ids is not checked (they bind by name, which the check does not follow), and a sort column a file lacks is null in every row — sorted.

The guarded pre-pass profiles one row group at a time. It checks key-page headers before decoding projected chunks. A sort violation stops both decoding and later row-group profiling. Memory refusals leave the file unverified, rather than marking it unsorted.

A checked file can require 1 + 2 x keys x row groups ranged GETs. This covers its footer, key-page header scans, and projected chunk reads. Adjacent reads and the 256 KiB key-stream readahead can reduce that count. The 8 MiB merge readahead would unnecessarily fetch intervening columns. A verified file also needs a footer reopen for its ordinary input pipeline. hoglake_compaction_sort_check_bytes_total records delivered bytes, including header scans.

The open window bounds simultaneous footer opens with HOGLAKE_COMPACTION_PARALLEL_INPUT_OPENS. Only the caller decodes a projected row group at a time. The same reader and allocation guards protect this pass before admission. The two projected key rows share the configured row allowance.

The 16 MiB size floor keeps tiny inputs on the chunk path. Below that floor, another remote read usually costs more than local spilling. It also prevents millions of tiny verified inputs from becoming merge heads. 0 checks every known-size input; unknown-size inputs remain unchecked. Metadata admission assumes no input verifies and still uses runtime feedback for payloads it cannot predict.

Key order is exact whenever every trusted run is key-sorted. Ties break by row id when every trusted input was itself written that way — true of every output this rewriter writes — and otherwise deterministically but unspecified (outputs written before #134 broke ties in input order).

HOGLAKE_COMPACTION_SORTED_HEAP_BYTES defaults to 1 GiB. Parallel groups divide this allowance. Each group can use its full allowance for retained chunk rows or decoded merge runs. The existing 192-byte node estimate remains an advisory row ceiling. Nested schemas retain their 64-fold row-count derate. Neither estimate replaces runtime byte checks.

The row charge includes group headers, empty field lists, present values, binary payloads, sort keys, row wrappers, and reference-array growth. Absent values cost field slots, not imaginary value objects. Guards run before group, value, and key allocations. Byte pressure spills the existing chunk before an incoming allocation. The row ceiling flushes only when another surviving row arrives. A deleted tail therefore does not force a boundary spill.

Input decoding has a structural reserve: the byte target plus 2 MiB per output leaf. A header profile charges projected compressed chunks, actual pages, decoder state, dictionaries, and source buffers. It does not charge every row-group value or all uncompressed bytes. Positive reader excess uses the retained-row allowance. Existing rows spill before a larger reader loads pages. Reader plus retained memory remains below the budget plus structural reserve.

Indexed row-group reads release the previous store before reading another. Codec and value guards check allocation controls before decompression or materialization. The sortedness pre-pass uses these guards too. Memory refusals leave a file unverified for the ordinary chunk path.

A decoded merge run costs its reader profile plus twice its largest charged row. The second row covers replacement overlap. Spill writers measure the emitted representation, including carrier fields and keys, without building another row graph. Trusted reader profiles and head caps are installed before spilling. A shared ledger checks observed trusted-row maxima before allocating larger heads. Spill profiles and measured row maxima replace their metadata estimates.

The spill estimate includes packed scratch for the producer's 20,000-row pages and fixed column/page objects, plus 2% rounded-up headroom for observed calibration variation. An eleven-leaf run estimates 19,600,896 bytes; four runs reserve 78,403,584 bytes. Previous measurements include 76,385,594 bytes and, on macOS ARM64, 76,945,723 bytes. This remains an estimate, not a universal page-count or dictionary bound; actual profiles still govern the merge.

Owned converters release completed nested groups. They transfer root ownership when records return. Absent fields cannot pin earlier rows through converter state. Deleted rows leave their decode frame before another row starts.

Writer-only allocations remain separate from emitted-row maxima. Slab capacities, compression output, checksum copies, and retained extrema share the fixed writer reserve. Overflow competes with retained rows or merge heads. Large rows enable per-row page checks within their row group. The 128 MiB output target and 1 MiB pages remain unchanged. Ordinary rows keep their existing check cadence.

Dictionary hash arrays, encoded-ID lists, and fallback scratch share the ledger. A per-row-group values factory guards actual growth before allocation. Page resets keep dictionary capacity charges until their references are released. Binary dictionary keys include retained payloads. The ledger gives no source ownership credit.

A whole-row forecast can flush a pending group before writing. Forecasts alone never refuse a row.

Ordinary forecasts add next-row growth to current capacities. They do not multiply already-buffered pages. Rare large-row forecasts remain separate.

A schema bound avoids another graph walk for ordinary flat rows. Potentially large emissions receive a dry consumer walk before writing. This walk counts bytes without constructing an output row graph. Closed footer metadata follows serialized statistics semantics, rather than retaining omitted full binary bounds. Completed row groups keep only bounded extrema metadata. Aggregate bounding preserves serialized statistics and page indexes.

Native codec buffers remain outside the heap ledger. Container sizing must retain headroom for those buffers and codec contexts.

Byte-appended runs do not open decoded readers or reserve decoded heads. A potential byte append triggers a bounded, footer-only range pass. The range pass reuses supplied footers. It closes transport streams promptly. Unknown, truncated, or non-order-preserving bounds cannot prove an append. Final spill ranges are checked again before copying row groups.

A mixed spill can span an empty gap between disjoint source ranges. The original source proof remains valid across that gap. Actual merge boundaries are checked before each raw copy. Groups without potential append candidates do not pay this extra range pass.

Planning, remembered-layout parts, borrowing, and execution use the same metadata estimate. Runtime guards check actual spill bytes, decoder allocations, and merge heads. The rewrite can refuse an admitted group. The refusal cache prevents repeated work for an unchanged group. The rewrite uses one merge pass. It adds no operator setting.

Remembered layouts use their actual leaf counts when sizing the same reader reserve.

Byte and row totals saturate instead of wrapping. Overflow never fits, even under maximum-valued budgets. Negative registered sizes or survivor counts are invalid data, not cacheable memory refusals.

Deterministic memory and spill-budget refusals enter a worker-local cache of 50,000 identities, below 8 MiB with ordinary JVM object alignment. Entries retain a digest and reason, not input or schema graphs. The digest covers file and DV identities, survivors, schema, layout, sort version, and effective budgets. Changed identities retry immediately.

Entries have no TTL. Eviction or restart permits a fresh attempt. Other workers do not share these entries. A different group composition permits a new attempt. An unchanged cached refusal performs no object-store I/O. It consumes no rewrite slot.

Refusal counters retain their existing aggregate meaning:

  • spill_budget_exceeded and metric reason spill_budget cover the per-group disk allowance, 4 GiB by default. Registered spill bytes are checked before IO. The writer also meters every emitted byte. Crossing the allowance discards the output. Size the spill volume as parallelGroups x spillBytes, with margin, because emptyDir overruns can evict the pod.
  • merge_budget_exceeded covers decoded readers, merge heads, and rows that cannot fit their allowances. Ordinary merge refusals use metric reason merge_budget. They can occur during metadata admission, header preflight, or guarded decoding.
  • oversized_row_groups is a subset of merge_budget_exceeded, not an additional skipped group. It identifies an oversized materialized row or binary value. Cached refusals preserve this distinction. The merge_budget metric excludes oversized_row. Add both reasons to compare the metric with the ledger's merge_budget_exceeded counter.

heap_budget_exceeded (reason="heap_budget") is HISTORICAL: nothing produces it any more. It stays on the wire and in the ledger, reading 0. An OutOfMemoryError mid-rewrite is still caught, ends the sweep and is counted in failed_groups: it now means the chunk accounting or the merge admission under-counted that table's shape.

The spill directory must exist and be writable at boot on a pod whose compaction loop runs (the server refuses to start otherwise — a missing one would fail every sorted group at its first spill, forever). At startup, before any loop, the server removes every hoglake-compaction-spill-* directory it finds there — a previous container's leftovers, since an emptyDir survives a container restart. The sweep deletes only directories hoglake created: the prefix is hoglake's own because the default directory is the shared java.io.tmpdir. Two live servers must not share one spill directory, or each sweeps the other's in-flight rewrites. hoglake_compaction_spill_dir_bytes is the MEASURED size of the spill directories (alert on it against tmpSizeLimit), hoglake_compaction_spill_bytes_total{catalog} what was spilled, hoglake_compaction_merge_runs_total{catalog,kind=trusted|spilled|demoted} the runs merged (trusted counts verified runs too), hoglake_compaction_sort_check_total{catalog,outcome=sorted|unsorted} the pre-pass's verdicts, hoglake_compaction_sort_check_bytes_total{catalog} the bytes it read, and hoglake_compaction_spill_cleanup_failures_total the spill directories that could not be removed. The ledger carries runs_trusted, runs_spilled, runs_demoted, spill_bytes, spill_budget_exceeded, merge_budget_exceeded, spill_cleanup_failures, files_verified, files_unsorted, files_unchecked (inputs under the size floor), row_groups_appended, bytes_appended and files_unranged (below), and — not a merge-sort counter, but added with them — groups_retired (above).

What a spilled byte costs. One extra snappy encode, one local read and one extra materialize; the object-store input is still read once. On the byte-proportional part of a rewrite that is roughly +30-50% CPU (an estimate from CodecMeasurement's encode times, not a fleet measurement); a trusted or verified run costs none of it, which is why admission takes the largest first.

When a group appends instead of rewriting (hoglake#134 package D1). An input's row groups are copied into the output byte for byte — never decoded — when ALL of these hold:

condition why
no live deletion vector an appended row group cannot skip rows
explicit_row_ids the ids ride the _hog_row_id carrier; positional ids live only in the catalog
its parquet schema EQUALS the output schema (field ids, physical types, repetition, annotations, the carrier) in practice: a prior compaction output of the same live schema; anything else needs the column plan
every row group is at least 32 MiB compressed (ParquetRewriter.APPEND_MIN_ROW_GROUP_BYTES, a constant) a small row group is re-encoded into a big one, which is what compaction is for
every row group has statistics on the row-id carrier the output's smallest row id is read off them

Each column chunk is copied with its column index, offset index (re-based to its new position) and bloom filter — through ParquetFileWriter.appendColumnChunk, because appendRowGroups drops the column index — and keeps its own CODEC, so an output can hold zstd row groups beside snappy ones (legal parquet, per column chunk) when an operator has changed HOGLAKE_COMPACTION_CODEC since the input was written. Statistics come along unchanged, so the commit's footer-derived stats stay exact.

On an UNSORTED table every qualifying input appends; the other inputs' rows keep filling the current encoded row group across it, so the encoded rows land after the appended row groups instead of being cut into a small row group at each one (row order in an unsorted output carries no meaning; ids ride the carrier). On a SORTED table a qualifying trusted run appends only when the range of its FIRST sort key, read from its footer statistics, is STRICTLY disjoint from every other run's and every spill file's range: then its rows are one contiguous block of the sorted output, written in key order between the merged rows (which are flushed as their own row group first). Anything ambiguous merges as before: a tie on the first key at a boundary, a run whose statistics cannot give a range (none recorded, or a float/double first key — parquet leaves NaN out of min/max), or a key leaf of another type. A run with a DV never appends, and its range counts its deleted rows, so it can only look wider than it is. A run of unknown range blocks EVERY append in its group, and that is counted: files_unranged in the ledger and hoglake_compaction_append_skipped_total{catalog,reason="unknown_range"} count such runs, only in groups where they cost an append: at least one run passed every other condition AND its range was strictly disjoint from every KNOWN range — every other ranged run and every spill chunk — so it would have appended had the unranged runs not been there. A group with nothing appendable, or whose candidates overlap something known anyway, lost nothing to them and counts nothing. A standing rate on a table sorted by a double is that table never appending.

Measured (SortedRewriteCpuMeasurement append-*, local files, median of 7, zstd-1): sixteen prior outputs of 50,000 event rows (3.2 MiB row groups, append floor lowered to 0 for the fixture) rewrite in 80 ms appended against 997 ms decoded and re-encoded with no sort order, and 100 ms against 1,027 ms sorted with disjoint ranges; four 600,000-row outputs (38 MiB row groups, the production floor) in 252 ms against 3,068 ms. The ledger counts row_groups_appended and bytes_appended; hoglake_compaction_appended_bytes_total{catalog} is the byte rate.

Sizing it against the pod

Measured (SortedRewriteHeapMeasurement, flat event rows, 50,000-row chunks, retained heap at a full GC):

group rows spilled runs output writer alone (unsorted path) chunk phase merge phase (runs + writer)
3,200,000 64 148 MB 82 MB 567 MB
6,400,000 128 147 MB 82 MB 992 MB
8,000,000 160 147 MB 82 MB 1,206 MB

The chunk phase is FLAT in group size. The merge held ~6.6 MB per spilled run (above the writer) against the current ~18.7 MiB estimate. The output writer also stays flat. It buffers one output row group until close. The historical buffered cost is about 140 MiB for a 128 MiB target.

These measurements use ordinary binary extrema. Large extrema require explicit writer accounting, even when footer serialization omits them. Writer guards include those lifetimes. Emitted spill-head charges do not.

It used to grow, by ~40 MB per million rows with no plateau (310 MB at 3.2M rows, 519 MB at 6.4M, 643 MB at 8M), and the cause was not the writer's own buffering. The reader decodes plain-encoded strings as slices of the decoded input PAGE, Binary.copy() returns such a slice unchanged, and the output writer's column statistics and per-page column index keep a min and a max per page until the footer — so each kept value pinned a whole input page. The rewrite now copies every binary value into its own array when the row is materialized (the materializer every input, trusted run and spill file is read through), and nothing the writer keeps can pin a page. Measured with SortedRewriteHeapMeasurement before and after; the class histogram at the old peak was ~500 MB of byte[] under ~80k live ByteBufferBackedBinary.

The earlier measurements above remain the baseline for the row-only model. They do not justify discounting the new retained-row allowance. The current deployment envelope charges the full configured budget. For the default flat event schema, eleven output leaves give a 512 + 11 x 2 = 534 MiB structural reader reserve. A large uncompressed row group is not necessarily a large reader: compressed chunks and live pages determine the profile. Conversely, compressed candidate files must remain below the byte target.

For one parallel group, the chunk envelope includes the 1,024 MiB row budget, 534 MiB reader, 32 MiB spill writer, and 5 MiB sorter. The sizing reserve adds 16 MiB for ordinary flat-schema footer metadata, 40 MiB for both worker caches, and 256 MiB for the hydrator. The resulting 1,907 MiB is below 70% of the deployment's 2,867 MiB heap. The merge envelope instead adds the output writer and multipart buffer to the full merge allowance. A single-chunk output has no live input reader or spill writer beside its output writer.

The bounded-child calibration verifies two million event rows from eight inputs totaling 83,110,081 bytes. It keeps the 1 GiB budget and exactly four spills. The integrated writer calibration sampled 1,459,723,936 heap bytes. Earlier intermediate snapshots sampled up to 2,241,339,624 bytes, above 70% of the fixture heap. These samples include uncollected allocations, unlike full-GC retained measurements. The 1,907 MiB sizing assertion remains the charged-envelope gate, not a sampled-occupancy guarantee.

Separate cases verify 400,000 rows in one input row group and a 151-column sparse schema with 200,000 rows. The sparse case uses six spills. A 507,579,537-byte near-target source consumes 24,037,751 bytes of coordinated reader excess. After five spills, two million output rows pass payload verification. Its sampled heap peak is 2,614,492,832 bytes, or 87% of the child heap. That measurement underscores the difference between live charges and total occupancy.

This is a flat-schema charged-allocation envelope, not a universal bound for arbitrary footer graphs. Retained variant footers and unusually large metadata require their own measured reserve. Header parsing, footer retention, and open concurrency remain bounded. Keep the existing heap-percentage assertion when changing any term. Do not replace it with an inequality that merely fits the entire heap.

For P parallel groups and L output leaves per group:

reader = targetBytes + 2 MiB x L
merge = SORTED_HEAP_BYTES + P x (144 MiB + 16 MiB)
chunk = SORTED_HEAP_BYTES + P x (reader + 32 MiB + 5 MiB)
single = SORTED_HEAP_BYTES + P x (144 MiB + 5 MiB)
peak = max(merge, chunk, single) + P x 16 MiB + 40 MiB + 256 MiB

The reader reserve is per group. It is outside SORTED_HEAP_BYTES. Use the actual leaf count for wide or shredded schemas.

The table retains the earlier compression calibration: approximately 70 B per zstd row and 119 B per Snappy row. Row counts are advisory ceilings. Larger actual rows can spill earlier. The merge column uses metadata estimates, while runtime uses actual profiles and emitted-row maxima. The full target and default output settings remain unchanged.

pod heap SORTED_HEAP_BYTES peak chunk rows spill files zstd / snappy merge estimate (zstd)
4 GiB 2.8 GiB 1 GiB 1907 MiB, 67% 508,400 16 / 9 293 MiB
8 GiB 5.6 GiB 2 GiB 2931 MiB, 51% 1,016,800 8 / 5 147 MiB
16 GiB 11.2 GiB 4 GiB 4979 MiB, 43% 2,033,601 4 / 3 73 MiB
32 GiB 22.4 GiB 8 GiB 9075 MiB, 40% 4,067,203 2 / 2 37 MiB
64 GiB 44.8 GiB 16 GiB 17267 MiB, 38% 8,134,407 1 / 1, no spill 0

Every row retains the 512 MiB target. More heap buys fewer spills and more decoded trusted runs, not larger groups. At six parallel groups, the last row becomes approximately 20,200 MiB, or 44% of its heap. Raise the pod before raising the sorted allowance.

The multipart upload needs a lifecycle rule

Compaction's output goes up as a multipart upload. Parts that are neither completed nor aborted are billed and invisible: they are not objects, so hog_file_removal cannot address them and the cleanup drain cannot see them. Nothing in this repo reclaims them.

The server aborts on every failure path it controls, and counts the aborts that themselves fail (hoglake_multipart_abort_failures_total — a sustained nonzero value means storage is growing silently, usually IAM missing s3:AbortMultipartUpload). What it cannot cover is a process that dies between starting an upload and aborting it: a kill, an OOM-kill, a node eviction. Under a crash loop the ceiling is one dangling upload per process lifetime, bounded by the compaction target.

Every bucket hoglake compacts into wants an AbortIncompleteMultipartUpload lifecycle rule — a few days is plenty, since a live upload finishes in minutes. Without one the leak is permanent and unobservable.

Group bytes are close to column-count independent: the budget divides by node count and multiplies by bytes-per-row, and both scale with the number of columns. A 20-column table whose rows really do carry twice the bytes lands in the same 34-58 MiB band. The exception is a wide table whose extra columns are nearly free (low-cardinality, dictionary encoded): those add nodes without adding bytes, and the same 1 GiB budget yields 17.8 MiB (zstd) / 30.2 MiB (snappy).

HOGLAKE_COMPACTION_MAX_NODES_PER_ROW (default 1,000,000) bounds one ROW's materialized object graph, which no group-level budget can: both rewrite paths materialize a row whole, so a single row holding a hundred-million-element list is an OOM, and an OOM in a background loop takes the request path down with it. A row past the budget is refused as invalid_data — one counted skip instead of a process kill. The allowance is spent inside the parquet record materializer as the row is decoded; counting it after read() returned would only have reported the allocation that already happened. Nothing else is charged: the output record is written straight from the decoded row into parquet's record consumer (hoglake#134 package D2), which visits each decoded node at most once and allocates none, so it cannot exceed what the decode was allowed. And the decode reads only what the output keeps: every input is read PROJECTED (parquet's requested schema) to the columns its plan maps plus the row-id carrier, so a column the live schema has dropped is never decoded or held — which is what keeps a sorted chunk, sized from the LIVE schema's node count, inside its budget for files written before the drop (and took a rewrite of inputs carrying ten dropped string columns from 1,526 to 940 ms, SortedRewriteCpuMeasurement dropped).

Calibrate in NODES, not elements: a scalar column costs 1 per row, a list element costs 2 (its synthetic entry group plus the value), a map entry 3. The default therefore admits roughly half a million list elements in a single row — far above any honest row, and far below what a heap holds at ~50-100 bytes a node.

Peak live heap is one decoded row, 1x the budget. It was up to 2x while every row was copied into a second, output-shaped graph before being written; measured then, a 999,999-node row rewrote under -Xmx192m.

Three non-success outcomes carry a counter, all under hoglake_compaction_skipped_total{catalog, reason} (beside the sorted rewrite's spill_budget and merge_budget, above): unconvertible_schema rising means a table has stopped compacting, invalid_data rising means a writer produced something its own registration or schema forbids — bad values, or a file whose schema contradicts its explicit_row_ids registration — and failed is the outright failure that gets retried next run. The first two never show up as failures — a sweep with either can look perfectly healthy — which is why they get a line rather than only a log and a ledger row. The self-healing skips (commit conflicts, DV supersession) stay uncounted: they re-plan on the next run. A fourth reason, object_prefix_unresolvable, counts groups of a table with the object-prefix layout (see Partitioning) refused before any IO because their prefix cannot be named (no spec, no single identity key on the field, a missing or non-canonical value), or because the layout's column is not live or not of an allowed type, which refuses every group of the table; it is a broken invariant, refused again every sweep, so alert on any of it. A fifth, claimed_elsewhere, counts groups dropped because another run already claimed them — duplicated work that did not happen, not a failure. (object_prefix_layout, one per sweep per option-on table, was the 2.1b/2.1c servers' skip of such tables; a 2.1d-or-later server never emits it, so after a rollout that series names a replica that is still older.)

reason="failed" is a FAILURE filed under a metric named skipped. That is deliberate — one series for "groups that did not compact, by reason" beats three — but it means sum(rate(hoglake_compaction_skipped_total[5m])) now includes failures, so an alert written against the two-reason version has silently changed meaning. Alert on the label: {reason="failed"} is the page-worthy one, {reason="unconvertible_schema"} is a backlog that will not clear on its own, and {reason="invalid_data"} is a bug report against whoever wrote the file. The axis separating the last two is DURABILITY AND FAULT, not values-versus-schema: an invalid_data group is re-planned and re-refused every sweep, because nothing about it will change.

VARIANT tables compact only with HOGLAKE_COMPACTION_VARIANT=true (default false), in the catalogs HOGLAKE_COMPACTION_VARIANT_CATALOGS names (comma-separated; empty means all). The rewrite copies each variant's storage leaf by leaf as plain Parquet groups, never through parquet-java's Variant reader (hoglake#70), into the layout the column's type_params.shredding declares (compaction/VariantLayout.kt, pinned to pyhoglake's by pyhoglake/tests/vectors/variant_layout_vectors.json). The copy is positional, so every input of one rewrite must hold the layout its output is written in. A group whose inputs hold MORE THAN ONE layout — the files a partition holds after set_variant_shredding changed a declaration, or files a writer laid out itself (prepare_append_files) — is rewritten PER LAYOUT rather than refused (compaction/VariantLayoutGroups.kt): before the rewrite, the service reads every input's footer (the tail read the rewrite's open would make; the footer is handed on so it is read once, up to 16 MiB of registered footer_size per group) and partitions the inputs by the layout of every variant column. Each partition that still meets the group-size rule (minInputFiles, scaled as CompactionGrouping scales it) is rewritten on its own, its output in ITS layout — the declared layout's partition first; a partition in a layout the declaration no longer names still compacts, into that layout, with no decoding and no re-shredding. Compaction CONSOLIDATES WITHIN each layout and never converts rows from one to another: an output is a new live file in its inputs' layout, and expiry removes only ended files, so an old layout's rows stay in it until they are deleted or rewritten by a writer. A partition too small is left alone, uncompacted and unrefused, and a file DuckDB wrote (Trino reads its top-level Variant nulls as SQL NULL by created_by, which an output does not keep) is excluded on its own and never blocks the rest. Only a variant field that is no VARIANT group at all (a leaf, a REPEATED group, no annotation, no REQUIRED BINARY metadata), or one holding a REPEATED node outside a LIST or MAP layer, still refuses its group as unconvertible_schema. metadata is found by name, so it may come before or after value; the layout keeps the file's field order, so a value-first file (Spark's) never matches the declared layout, which lays out metadata first, and compacts only with files of its own order.

Not starving the sweep: a mixed group whose every partition is too small would spend one of the sweep's HOGLAKE_COMPACTION_MAX_GROUPS_PER_RUN slots and compact nothing, every sweep, because the planner packs in metadata and cannot see a layout. So the service REMEMBERS, in its own heap, every file it has probed: how its layouts DEVIATE from the declaration (the variant columns whose subtree is not the declared one), as a fingerprint, together with a fingerprint of the declaration it was judged against. The planner then packs files it knows to deviate only with files deviating the same way, drops files it knows DuckDB wrote, and packs the rest — the declared layout's, the never-probed, and any entry judged against an older declaration — together as before. A remembered remainder forms no group until enough files of its layout are known, except by a LOAN. A never-probed file is IDLE when it is in no group of the rest (declared and never-probed) that the planner would run: a main group the declared estimate's budget admission (the spill_budget / merge_budget check below) refuses is no work, this sweep or any other, so its never-probed files are as idle as those in no group, while a group it admits keeps every file it holds. Remembered populations are tried largest first, and the first is lent the shortest prefix of the idle files in candidate order, at most minInputFiles − 1, such that the planner's packing of population + loan forms a group that holds every lent file and a population file the population's own packing left out, and that passes the sorted-budget shape admission (below). So a population at or past the minimum can borrow to complete one of its size bands, and one whose layout the budgets refuse is passed over (a loan merely considered is not counted as a refusal). Only prefixes are tried, which keeps the search bounded and the same every sweep, so a completer queued behind a file that doesn't complete is skipped until the candidate order changes. The probe sorts the lent files out; at most one loan per bucket per sweep, and a lent file is probed and remembered, so never lent again. A loan is made only if the planner's packing of the rest WITHOUT it still holds every admitted main group with the same files: a file lent from a refused band of files no larger than an admitted band's would otherwise shift the smallest-first packing, close the refused remainder with the admitted band's first file and strand its other four until something arrived. And the search is bounded per bucket whatever the backlog: only the first fan-in (effectiveMaxInputFiles) of idle files in candidate order is offered, and only the eight largest remembered populations WITH a stranded file are tried (VariantLayoutGroups.LOAN_POPULATIONS_TRIED; one whose files all pack has nothing to complete and takes no slot), so a bucket of thousands of refused unknowns beside dozens of layouts costs one packing of its main population, one of each remembered population's own files, a bounded tail per population tried, and one more packing of main per loan found and checked against the admitted groups (at most eight) — not a packing of the backlog per layout every sweep. A loan that proves to be another layout leaves every file of its group where it was, the lent file now remembered where it belongs, and is charged as one layout_probe_only attempt (below): the one speculation a bucket makes a sweep, paid once per arrival, never twice for the same file. Deviations rather than whole layouts, so a file written before a variant column was added (which the rewrite null-fills) packs with later files of its layout; the declaration's fingerprint, so DDL (set_variant_shredding, a variant column added, dropped or renamed) makes every entry of the table unknown again and each file is probed once more rather than stranded — a DuckDB entry included, since whether a DuckDB file holds live variant data depends on the live columns, so a DuckDB file that no longer does compacts, null-filled, after that one re-probe. A compaction output is entered as it is registered — its layout is what was just written — so it is not probed on the next sweep to learn it. The memory is per process (empty after a restart, so each file is probed once per restart), bounded at 250k entries, and cleared of a file when it is compacted away; it is correct without it — the probe splits any group — and only the repeat depends on it. Not a column on hog_data_file: the hydrator never sees a file registered with inline stats (pyhoglake's), so the planner would need this fallback anyway.

Beside each deviating layout's fingerprint the probe also remembers its SHAPE (VariantLayoutMemory.Shape: node count, nestedness, output leaves). The planner admits a sorted group of a remembered deviating layout against the sorted budgets with THAT shape alone, in metadata, where every other group is admitted against the declared one; the declared estimate is not applied to it as well. So a narrower layout left by a since-widened declaration still compacts, and a known layout wider than the declaration is refused on its real leaf count without a re-probe. A layout the budgets refuse is probed and charged once (layout_probe_only, below), and on every later sweep refused by the planner without reading a footer: counted like the planner's other budget refusals — in the ledger as spill_budget_exceeded / merge_budget_exceeded, in Prometheus as hoglake_compaction_skipped_total{reason="spill_budget"} / {reason="merge_budget"} (the metric's labels drop the _exceeded; the budget section above maps the two) — and not charged to HOGLAKE_COMPACTION_MAX_GROUPS_PER_RUN. Admission is recomputed every plan from the current inputs and budgets, so raising HOGLAKE_COMPACTION_SORTED_HEAP_BYTES / HOGLAKE_COMPACTION_SPILL_BYTES admits the group on the next plan without a re-probe; a declaration change makes the files' entries stale, so they are probed once more. Shapes are kept one per distinct deviating layout, not per file, at most 4096 (SHAPE_CAPACITY), least recently used evicted first (the planner's lookup counts as a use, so a shape still planned every sweep stays); a group of an evicted layout is probed once more.

What a probe costs. For a variant table the probe's footer read replaces the one the rewrite's open would make: the footer is handed on (ParquetRewriter.Input.footer) while the serialized footer bytes kept so far — measured off each footer, not the registered footer_size hint — stay under 16 MiB per group, and released as each part's rewrite ends; beyond that the rewrite re-reads the tail as it always did. A parsed footer is several times its serialized length, so this is up to a few hundred MB of heap at worst, beside (not inside) HOGLAKE_COMPACTION_SORTED_HEAP_BYTES, which bounds the sorted rewrite's chunk and merge; size the pod with that headroom. A probe that finds nothing worth a rewrite (one file per layout; only DuckDB files), or whose every part is refused on re-admission (below), still read every footer, so it is charged as one attempt against HOGLAKE_COMPACTION_MAX_GROUPS_PER_RUN, counted in the ledger as layout_probe_only and in hoglake_compaction_skipped_total{reason="layout_probe_only"}. A budget-refused layout is charged this way only at its first probe; after that it recurs as a planner refusal — ledger spill_budget_exceeded / merge_budget_exceeded, Prometheus hoglake_compaction_skipped_total{reason="spill_budget"} / {reason="merge_budget"} (above) — whose levers are HOGLAKE_COMPACTION_SORTED_HEAP_BYTES / HOGLAKE_COMPACTION_SPILL_BYTES. A recurring layout_probe_only rate has one ORDINARY cause: a loan that did not pay off. A remembered remainder borrows an arrival (above), the probe finds it in another layout, nothing runs, and the attempt is charged — once per such arrival, since the arrival is then remembered and never lent again, so the rate is bounded by the arrival rate into buckets that hold a short remainder, and the remainder's own files are not counted again in files_left (below). Read a rate past what arrivals explain as the memory being lost (restarts, its 250k-entry capacity, or shape eviction). A group split into N parts spends N attempts, so a sweep can run past HOGLAKE_COMPACTION_MAX_GROUPS_PER_RUN by at most (layouts − 1) × HOGLAKE_COMPACTION_PARALLEL_GROUPS in its last wave; the first part of a group never yields (an in-flight group completes), though it can still be refused on re-admission; later parts yield to a sibling's heap exhaustion or a cancellation. After a split group commits, its claim is narrowed to the inputs that died, so the files left behind are free to be planned again at once.

Counted in hoglake_compaction_variant_layout_mismatch_total{catalog, reason}: split, one per group the probe found in more than one layout; duckdb, one per DuckDB-written file excluded (a DuckDB file holding no live variant column — scalars written before the column was added — is not excluded: it compacts, null-filled); layout, one per group refused because a variant field is no VARIANT group, or one whose subtree the copy could not carry whole (a REPEATED node outside a LIST or MAP layer). Rewrite activity per layout is hoglake_compaction_variant_layout_outputs_total{catalog, layout="declared"|"other"} — outputs per layout. It measures rewrites only: a falling other rate means less rewriting in old layouts, not that an old layout is gone — and hoglake_compaction_variant_layout_files_left_total{catalog}, files set aside for want of company in their layout: each once per time the memory LEARNS it is set aside (the entry records it), since the memory keeps it out of the next plan. A remembered file probed again — a remainder as the company of a loan that proves to be another layout, a declared file beside arrivals that prove so — and left exactly as it was is not counted again; the lent file, or the arrivals, are, once, as they are learned. Accumulated observations, not distinct live files: a file probed again after a restart or an eviction of its entry is learned anew and counted anew, so the counter's rate is "files newly set aside", and the files still waiting are the maintenance summary's debt.

A split after set_variant_shredding is EXPECTED, for as long as files written under the previous declaration remain in a partition beside files written under the new one: that is the case this mechanism exists for, and each layout keeps compacting among its own files without any operator action. Do not turn HOGLAKE_COMPACTION_VARIANT off on seeing it — that stops the very compaction that consolidates the old layout's files and lets small files pile up. Before reading a split as drift, check the table's declaration history. A change row holds only kind and object_id, and every alter records the same table_altered, so the change log narrows the candidates and the table's own reads decide: page GET /catalogs/{catalog}/snapshots for table_altered changes whose object_id is the table's hog_table.table_id, and for each such snapshot S compare the variant column's type_params.shredding in GET .../tables/{table}?snapshot=S and ?snapshot=S-1. A snapshot below the catalog's retained floor answers 410, so a change since expired cannot be found and the cause stays unknown. A split with NO declaration change behind it, on a table only pyhoglake's Table.append or prepare_append_tables or the connector write, and likewise a layout refusal of such a file, means the layout port has drifted from theirs (pyhoglake/tests/vectors/variant_layout_vectors.json pins the two) — then the flag should go off until the port is fixed.

A variant's chunk in the sorted rewrite is sized by its layout's Parquet nodes, not as one catalog node, and a part in another layout is sized by THAT layout's nodes (CompactionConfig.spillChunkRows with the part's layouts), not the declaration's: a declaration since cleared or narrowed leaves files far wider than the catalog says, and a chunk sized for the narrow rows would hold too many wide ones for the heap. A layout holding a LIST or MAP layer counts as nested, so its chunk is divided by HOGLAKE_COMPACTION_NESTED_SORT_EXPANSION like a nested column's. Each part is re-admitted against its own bounds before its rewrite; a part the wider rows push over a budget the declared estimate fit is refused, counted with the planner's budget refusals (ledger spill_budget_exceeded / merge_budget_exceeded, Prometheus hoglake_compaction_skipped_total{reason="spill_budget"} / {reason="merge_budget"}). The refusal is uncharged when another part of the group ran; when no part ran, the probe is charged as one layout_probe_only attempt (above). A part whose output leaf count cannot be computed skips the check and goes to the rewrite, which refuses it as unconvertible_schema.

Each table's candidate list is fixed before rewriting starts, so an output cannot feed another group in the same run. Input bytes only estimate the output size: encoding, schema changes and DV removal all move it. Files at or above the target are excluded. Zero-byte inputs are candidates like any other — they can never close a group on bytes, so they ride along until the fan-in cap closes one. Unsorted rewrites stream; sorted rewrites hold one chunk, then one row group per merged run (the external merge sort above).

Both debt endpoints read persisted asynchronous summaries of the files the planner would group (before the execution budget), trailing remainders included. A group under its scaled minimum contributes zero debt; raw small-file counts remain visible on the partition page. Neither endpoint scans the manifest. sampled_at exposes freshness; before the first sample, counts are unknown. MaintenanceSummarySampler checkpoints indexed keyset pages and per-bucket accumulators in Postgres, so a restart resumes progress. It scans files at a captured catalog snapshot. If expiry overtakes the snapshot it is evaluating at, it re-anchors: later pages are evaluated at the catalog head and the scan continues from its cursor, without publishing partial counts. It used to restart from scratch instead, which never finishes once a scan takes longer than retention: at ~0.36 ms/row and 10,000 rows a tick, millpond-prod-us's ~7.6M rows took 58 min against a 3,600 s retention, and neither it nor millrace-prod-us (600 s) published from 2026-10-16 to 10-21. The cursor is a keyset over (table_id, file_size_bytes, data_file_id), immutable per row, so a re-anchor neither skips nor repeats a row. What it changes is the snapshot the rows are judged at: above the cursor, files that ended are excluded and new ones counted; below it, rows paged earlier keep their old answer, and appends sorting below the cursor are not seen. A re-anchored sample's file measures and live totals are therefore an observation over the scan window, like hydration and removal counts always were; sample_reanchored on /maintenance/status says how many times it happened, and sampled_snapshot_id stays the scan's start. A change to the target or the min/max input files still restarts the scan. Defaults: 10,000 metadata rows per 1s tick, 60s between completed refreshes, controlled by HOGLAKE_MAINTENANCE_SUMMARY_BATCH, HOGLAKE_MAINTENANCE_SUMMARY_INTERVAL_MS (0 disables), and HOGLAKE_MAINTENANCE_SUMMARY_REFRESH_SECONDS.

The compaction planner picks buckets from the same published sample: a table's buckets with at least two groupable files, ordered by bytes per file ascending (files retired per byte rewritten), capped at 50,000, and probed from a rotating cursor so every bucket is reached. A sample cannot name a partition first written after its scan began, so the planner merges in the buckets of the table's live small files appended since the sample's start snapshot: one read of the (catalog_id, table_id, begin_snapshot) index, newest first, capped at HOGLAKE_COMPACTION_NEW_BUCKET_WINDOW files (default 10,000, about three minutes of prod-us appends; 0 disables), grouped by partition tuple. On a hot table that window is full on every sweep, not only when the sampler is behind, because the sample's start snapshot is always a scan and a refresh old. So the window size is a fixed per-sweep cost: one heap fetch and one partition-value lookup per file, inside the plan's statement timeout. A tuple written once and never again since can fall outside the window until the next generation names it. A bucket in both lists becomes one entry, and the merged list is sorted by the same bytes-per-file order. New buckets do not go first, because a fresh day's large files would then outrank every bucket of tiny files. Without the merge, on 2026-10-21 the planner saw the 1,794 buckets of millpond's 2026-10-16 generation while events_raw had 5,036, so no partition written in those five days was compacted. With no published generation at all, the planner still reads the table's smallest candidates directly.

Coverage is 100% of live layouts, not just the easy ones:

  • DV-bearing inputs compact. The rewrite reads each input's live deletion vector (Iceberg-v3 puffin deletion-vector-v1 blobs — roaring bitmap, magic and CRC verified; PuffinDeletionVector is the one server-side reader of DV content) and drops the deleted positions: survivors keep their original ids in _hog_row_id, deleted ids are gone forever, and the inputs AND their DVs end-snapshot together. The commit re-verifies the exact DV identity it planned against — a vector that grew or appeared since planning skips the group (dv_superseded in the result), so a post-plan delete is never dropped. A DV'd group's output needs no hydrator sweep: its stats come from the footer the rewrite wrote, which counted the survivors because the survivors are what it wrote, so the output registers stats_state='provided' like any other.
  • Heterogeneous-schema groups compact. Inputs written under different schema versions rewrite under the LIVE schema, mapped by field id: a live column absent from an input null-fills, promoted columns up-cast (int32→int64, float→double), dropped field ids drop their data. Only a live column unproducible from an input's physical type skips the group (unconvertible_schema — detected before any bytes are staged); the unproducible set is narrowings, physical mismatches, decimal-scale changes, non-micros time(stamp) units, and INT96. Nested containers are NOT in it: list/struct/map are copied through recursively, so a nested table compacts like any other, and an input whose nested SHAPE disagrees with the live column is unconvertible_schema rather than a guess.
  • Aborted uploads can't orphan objects. Before uploading, the output path pre-registers as an undrained hog_file_removal row (reason compaction_staging) — a claim ticket. A successful group commit settles it (drained_outcome='registered') in the same transaction that makes the path live; an aborted group leaves it for the normal cleanup drain to reclaim. The commit re-claims the ticket first, so a drain that won the race just aborts the group — cleanup can reclaim aborted outputs and can never reclaim committed ones.

Views

Versioned name + SQL text + dialect (hog_view), stored verbatim — the catalog never parses view SQL. Create/drop are DDL commits with their own change kinds, so views appear in snapshot history and time travel like everything else.

Self-knowledge: partition debt, consumers, identity

The catalog reports on itself instead of waiting for ops SQL:

  • POST /maintenance/verify — REMOVED (#261). It ran the catalog's twelve global-invariant checks in one read-only REPEATABLE READ transaction, every one of them an UNBOUNDED full-table aggregate. At gigahog-prod-us's shape (14M live hog_data_file rows, 371M hog_file_column_stats rows) it hit the 60 s statement_timeout every run and was disabled there, so the one deployment that needed a scrubber had none and the ones that ran it had nothing worth scrubbing. VerifyService, the loop (HOGLAKE_VERIFY_INTERVAL_MS — now Config.REMOVED_INTERVAL_ENV: a positive value is refused at boot, 0 and absence pass in silence), hoglake_verify_violations, hoglake_verify_errors_total and the console's panel went with it. What is NOT watched any more, in any environment: row-id tiling, DV uniqueness and bounds, orphaned rows on dropped tables, still-referenced removal-queue entries, snapshot density, next_row_id, the expiry floor, versioned-row visibility bounds, superseded-offset release, staging tickets, upload claims and compaction claims — though three of those twelve have another enforcer (removal_queue at drain time via CleanupService.referencedPaths, next_row_id via the commit-path allocator, orphans' retirement arm via the eligibility stamp), and four are now asserted in the test suite by testing/CatalogInvariants.kt (visibility_bounds, removal_queue at the compaction boundary, snapshot_density, staging_tickets arm (c)). ONE OF THOSE TWELVE HAD JUST BEEN SHARPENED AND IS NOW UNWATCHED TOO. #262 split expiry into a floor advance under the lock and a paged file-row purge off it, so a below-floor ended hog_data_file / hog_delete_file row became the DESIGNED intermediate state of a two-phase sweep rather than a violation. expiry_floor's file arm was gated on the ledger row reporting purge_truncated: false (and, after that PR's own review, on the drained row's floor covering the current one) precisely so it kept asserting the invariant without alerting on the backlog. That gate is gone with the check: a drained purge that still leaves rows below the floor — its predicate and the floor advance disagreeing, which is a bug no counter shows — is unwatched until #261. What still works is the BACKLOG half, which never needed verify: purge_truncated, purge_remaining and purge_failures on every ledger row, plus hoglake_expiry_purge_truncated_total and hoglake_expiry_purge_remaining (see §Retention). The replacement is a PAGED, RESUMABLE scrubber (one bounded page per transaction, a cursor, a run budget, a measured per-row cost) — issue #261. Until then, MaintenanceTask.VERIFY, the spec's VerifyReport/VerifyCheck schemas and the console's ledger renderer stay as HISTORICAL shapes so the ledger's existing verify rows still decode for their retention window.
  • POST /maintenance/rehydrate — the operator requeue for the hydrator's structural failures (above): flips failed → pending, catalog-wide or scoped to one namespace+table. Hoglite uses the token's placement and excludes ended files and dropped tables. One transaction updates all matching files, subject to the engine's write limits. Hoglite has no hydrator loop, so the requeue then runs one bounded hydration sweep over the same scope (#675): up to 1,000 live pending files of live tables, started within 10 s, read through the server's ObjectStore with the PostgreSQL hydrator's footer read, aggregate, size floor and object-prefix proof. The sweep starts after the highest file id the requeue found failed and wraps to the lowest ids, so files that fail on every call rotate through the sweep and cannot hold back newer ones. Each outcome lands in its own transaction, fenced on the file still live and pending and its table's schema_version, so a concurrent ALTER, drop or end leaves it pending; one bad file is marked failed and the sweep goes on. Stats or split offsets over the scan's 64 KiB per-file limit are not stored. The tenant registers and can rewrite each file's sizes (#668), so unlike the PostgreSQL hydrator the sweep's reads are held to them: the tail is a closed range ending at file_size_bytes, a footer_size over HOGLAKE_HOGLITE_MAX_FOOTER_BYTES (default 64 MiB) is not usable and the file takes the whole-object read under HOGLAKE_HYDRATOR_MAX_WHOLE_OBJECT_BYTES, and that read stops one byte past file_size_bytes, so an object longer than its registration is marked failed instead of landing on the heap. The sweep records its own hydrator run, with what it resolved before any failure; its failure is logged and does not fail the requeue. Call it again to drain a larger backlog (pending_files in GET /maintenance/status, which reports the Hoglite hydrator with no loop: manual only). The tenant can rewrite both files.path and meta.data_path (#668), so the sweep reads only under a prefix it cannot: HOGLAKE_HOGLITE_DATA_PATH_TEMPLATE (s3://warehouse/{catalog}, the catalog's name substituted) when set, else the catalog's own session under the broker provider, which the broker binds to the catalog (the broker must refuse a prefix outside the catalog's placement, docs/auth.md). A file outside it is marked failed without being read. With the template set, a Hoglite catalog create whose data_path is not the template with its name answers 422, so no catalog sits inside another's bound; a catalog created before the template, or whose tenant rewrote meta.data_path, is not swept. The broker session is resolved before any file is claimed, so a refusal (prefix_outside_catalog) fails the run once. For that up-front refusal, a catalog off its placement, and ambient or static with no template, the requeue runs alone: the rehydrate records a failed hydrator run saying why, so GET /maintenance/status's last_run shows it, and the server warns at boot when Hoglite backends are configured with neither. A session that cannot be had mid-sweep is different: the sweep has run, and stops with that file still pending and not counted as claimed; the failed run records what the sweep resolved before it as a partial result. Hoglite retirement is available through the backend seam for trusted placement. It has no HTTP trigger or background driver. Each retirement batch queues current vector and data paths before it deletes their rows. Candidate and victim reads use bounded keyset pages.
  • GET /stats/partitions (service/PartitionStatsService.kt) — leaf partitions ranked by compaction debt: debt_score is the small-file count under exactly the threshold the compactor plans with (so the ranking predicts what a sweep would do), plus stale-spec-group counts. The webui's compaction-debt page renders this.
  • GET .../tables/{t}/partitions — one row per (spec vintage, partition value tuple) with the file, byte, deletion-vector, row and compaction-debt measures as the maintenance sampler last measured them. It reads hog_maintenance_summary_tier, so it walks no manifest, takes no lock and adds nothing to a commit — which is also why it accepts no snapshot/at_timestamp: there is exactly one snapshot it can answer at, and the response names it as sampled_snapshot_id. A catalog with no published sample answers 200 with sampled_at: null, total: 0 and no partitions — the table exists, the measurement does not. Sorting, limit/offset and a repeatable filter of key_index:text (matched against the DECODED value, so 0:2026-09 is a month) are query parameters; a table with more sampled groups than the listing will materialise is 422, because it decodes, sorts and pages in memory. The webui's partitions tab renders this.
  • POST .../tables/{t}/partitions/lookup (read scope) — exact inspection of one complete tuple, sent as the JSON array request body (stored strings or JSON nulls), with spec_id (required), snapshot, limit (1-500, default 100) and cursor as query parameters. It requires no maintenance policy or sample. Resolves head once, pins file pages to that snapshot, and binds the opaque cursor to the table incarnation, spec, tuple, and page size. The initial file-ID ceiling bounds the scan even during concurrent appends. Historical DV metadata uses an indexed latest-version seek, so supersession history cannot turn each file probe into a full scan. Totals count physical file rows, not DV-adjusted logical rows; last file write/rewrite is not ingestion freshness. A bounded candidate scan returns exact totals or an explicit unavailable reason, while file inspection remains paged. The budget includes other tables/specs and retained files, but probes every tuple key (at most 10,001 index entries each) and chooses the smallest candidate set. Totals can still be unavailable even for a small partition. Only the first page computes aggregates; continuation pages report reason: continuation and callers retain the initial totals. Hydration state counts reflect the current request, not historical state at the requested snapshot. Continue until next_cursor is null, even if a page contains no matching files. Expired snapshots return 410; busy admission and query timeouts return 503 with Retry-After, distinct from an empty partition. A shared three-second transaction budget includes database work across statements; pool acquisition reduces the remaining budget and has its own five-second bound. Admission allows two lookups per process and one per catalog; a request that cannot start waits up to 200 ms in a FIFO bounded at four waiters per process and two per catalog, then returns 503. The existing file stats endpoint resolves namespaces at head, so it may return 404 for files reached through a historical namespace that has since been dropped/recreated. Existing Python, DuckDB, Trino, and hedgerow endpoints are unchanged; this is an additional operator inspection endpoint.
  • GET .../tables/{t}/partitions/values — the partition fields at the read snapshot, each with the distinct STORED, transformed values it takes across the live files (most-frequent first, capped at 500; truncated marks a field past the cap). This one is a live read, not a sample: it takes snapshot/at_timestamp, and the values are returned verbatim for a client to offer as a filter and echo back as partition=key_index:value on GET .../files.
  • GET .../maintenance/status and GET .../maintenance/runs, with operator-only instance-wide twins at GET /v1/maintenance/status and GET /v1/maintenance/runs — the read side of hog_maintenance_run (the ledger every background sweep and manual trigger writes) plus the persisted summaries. status is per-task: loop cadence, the task's own backlog keys (hydrator pending_files/failed_files, expiry's retention and floors, cleanup queued_removals and oldest_queued_age_seconds, compaction small_files/target_bytes, retirement nothing) and its most recent recorded run. Counts are absent until a sample exists — unknown, not zero. runs pages the ledger newest-first on an exclusive before run_id cursor, optionally filtered by task (422 on an unknown one), 50 per page and capped at 500. Neither queries the manifest. The instance-wide pair is the ops feed: same conventions, run rows carry their catalog name, and /maintenance/status pages catalogs on an exclusive after name cursor.
  • GET /consumers — every consumer in the catalog with per-table offsets, table names resolved, dropped tables flagged (offsets outlive drops by design — an offset on a dropped table is data, not garbage).
  • GET /v1/info — instance identity: the operator-configured display name (HOGLAKE_INSTANCE_NAME, e.g. "GigaHog"), shown in the webui topbar so nobody mistakes prod for dev. Set HOGLAKE_UI_THEME=nord on the server to select an instance color theme. Restart the server and reload the UI to apply it. The response includes ui_theme when set. The UI selects its light or dark palette from the current display mode. Unset, blank, or unknown values keep the default colors. See supported themes.
  • GET /export — the DR manifest (snapshot range + live-file manifest + consumer offsets, consistent at head) is specified, not yet implemented — see that section below.

Observability

Three surfaces, none of which ever writes to the catalog or rides a transaction (observability/):

  • /metrics (Prometheus; operator-only on the API port, and served with no auth on the infra listener at HOGLAKE_METRICS_PORT when that is

    0): per-catalog health gauges sampled by a background loop in GROUPS. The CORE group (one batched per-catalog query plus one consumer-offset query) runs on every pod that samples (HOGLAKE_METRICS_INTERVAL_MS > 0, since /v1/info and the catalogs listing are served from it) — head snapshot and age, expiry floor, removal-queue depth (undrained entries only), pending-stats AND failed-stats counts (hoglake_stats_failed_files), the head of the hydrator's queue (hoglake_stats_pending_head_file_id: the data_file_id of the oldest live pending file on a live table, the next one a sweep claims, read by key off the pending index, never aggregated; 0 with nothing pending. The head unchanged for three sweep intervals while hoglake_stats_pending_files > 0 is a stalled hydrator, whose pending files stay out of every per-value read; hoglake_stats_pending_files rising for six hours is a hydrator that is behind. rehydrate re-pends old failed files at their old ids, so the head moves back to them, which is correct: they are now the oldest work), live id-less-file count (hoglake_missing_field_id_files), live object-prefix-quarantined count (hoglake_object_prefix_quarantined_files, see Partitioning), live table count, per-consumer lag (cardinality-capped), and hoglake_live_files{catalog} (live data files, dropped tables excluded). The three live totals are read from the maintenance summary, which stamps them per catalog when it publishes a generation (V27), not from the manifest (#269): one row per catalog, minutes behind head on a large instance, and the sampler never scans hog_data_file — the rare counts come from partial indexes (V26, and V31 for prefix_quarantined). A catalog with no published totals yet publishes NO live series (hoglake_live_totals_sampled{catalog} = 0) and null on the wire, and is never read from its own manifest for them. The six EXTENDED groups — the gauges that replaced the DuckLake catalog-metrics cron's (millpond tools/ducklake_metrics.py) — run ONLY where HOGLAKE_MAINTENANCE_SUMMARY_INTERVAL_MS > 0, i.e. on the maintenance pod, so API replicas do not each publish the same instance-wide series (a sum by (table) would otherwise multiply by the replica count):

    • Per table, {catalog, namespace, table} (separate labels, as on hoglake_blind_partitioned_appends_total), read off the maintenance sampler's PUBLISHED generation (the generation /maintenance/status and the partitions endpoints read — never the manifest): hoglake_table_files, _small_files, _bytes, _small_bytes (small = under the compaction target), hoglake_table_rows (absent while the generation's row measure is incomplete), hoglake_table_delete_files (files carrying a DV), hoglake_table_partitions (partitions with files) and hoglake_table_largest_partition_files (the cheap stand-in for DuckLake's files-per-partition top-20). Live tables the generation covers only: dropped tables leave immediately, a renamed table publishes under its new name, a table created after the scan began appears with the next generation, a catalog with no published generation publishes none, and every value is as old as the generation (tens of minutes on prod-us). Capped at 500 tables per catalog, largest by files first; hoglake_table_series_truncated{catalog} is how many were cut.
    • hoglake_live_delete_files{catalog} / hoglake_live_delete_bytes — live deletion vectors on live tables (the head-time count of what the tier's dv_count sums).
    • hoglake_earliest_snapshot_age_seconds{catalog} — age of the earliest retained snapshot (the first at or above the floor); hoglake_dropped_tables_pending_retirement{catalog} — dropped tables still holding live file rows, a LOWER BOUND over the newest 10,000 dropped tables: an older pending drop is not counted, so it can read 0 with work pending on a catalog with more drops than that.
    • hoglake_relation_bytes{relation, kind=heap|index|toast}, hoglake_relation_live_tuples{relation}, hoglake_relation_dead_tuples{relation} — instance-wide, every hog_* relation, from the same function GET /v1/database/health calls.
    • hoglake_commit_lock_db_waiters{catalog} (sessions waiting for the catalog's commit lock) and hoglake_commit_lock_db_held_seconds{catalog} (the holder's TRANSACTION age — an upper bound on its hold, since the transaction may have begun before the lock) (#439), from the pg_locks read the health page makes (DatabaseHealthRepo.commitLocks: one statement, a hog_catalog key probe per lock row, 0.27 ms with a holder and three waiters). They see EVERY session — other pods, a psql session — but only at the tick: a convoy that forms and drains between two samples is invisible here. Absent while nobody holds or waits; hoglake_commit_lock_db_waiters > 10 for 5m is the alert candidate.
    • hoglake_maintenance_last_run_epoch{catalog, task, status=ok|failed} (finish time of the latest run with that status among the task's last 1,000 ledger rows; when a status scrolls out of that window the last value this process saw is republished, so status="ok" keeps ageing through a long failure streak — a restart forgets it) and hoglake_maintenance_last_run_duration_seconds{catalog, task}. Each group is its own statement and fails on its own: one that throws keeps its gauges at their last values, the others still publish, and the sample counts one hoglake_metrics_sample_errors_total plus one hoglake_metrics_group_failures_total{group} per failed group (catalogs, tables, delete_files, lifecycle, relations, commit_locks, maintenance_runs; all seven registered at 0, so a first failure is a visible step). hoglake_metrics_last_sample_epoch is LIVENESS: it advances whenever the core catalogs group succeeds, whatever the others did, so alert on the per-group counter for those. #261 removed hoglake_verify_violations{catalog, check} and hoglake_verify_errors_total{catalog} with the verify subsystem — a dashboard or alert still keyed on either would now have a series that never arrives rather than one that reads zero, and nothing behind it to alert on. NOTHING IS: checked on 2026-10-01 against live PostHog/grafana-dashboards at master (the default branch is master, not main) commit 1ea38c48, pushed that day — managed-warehouse/gigahog.json carries 21 distinct hoglake_* series and zero verify matches, and a repo-wide code search for hoglake_verify returns 0. charts/ has no hoglake_* reference in alerts/ either, so no alerting or dashboard change is owed. THE ONE PUSHED GAUGE LEFT is hoglake_retirement_consecutive_timeouts{catalog, table} (#263): CONSECUTIVE retirement runs that ended one dropped table on its own statement_timeout. Retirement does NOT resize its batch in response to a timeout — the per-row cost is flat in the batch size (RetirementCostIntegrationTest), so a cancelled batch is a COLD one, and the table is left for the next run at the same size — so hoglake_retirement_timeouts_total is a rate that is MEANT to tick occasionally and is deliberately NOT the alert. Alert on this gauge at >= 3, and it needs no for clause, because the streak IS the duration: 3 means three runs in a row, which no cache miss survives. A MultiGauge (the shape ExpiryGauges uses, and the one the removed verify gauge used), so a row exists ONLY between a table's first timeout and its next non-timeout outcome — a committed batch, a drain, a stuck table — and ABSENCE IS THE HEALTHY STATE: the series RETIRES on recovery rather than freezing at its last value, which a counter could not do (it would leave an unclosable alert on a table that is fine). A standing value means HOGLAKE_RETIREMENT_BATCH is too large for that table's per-row cascade; the knob is process-wide, so it is lowered on the INSTANCE that retires that catalog (the maintenance workload) and applies to everything that pod retires. The streak is per PROCESS and in memory: a restart republishes it on the first run that still times out. Plus source-side counters: commits by outcome, snapshots expired (and superseded consumer offsets released, in the sweep's result and audit event), files removed, hydrations by result (transient errors counted separately), and the hoglake_commit_lock_wait_seconds histogram on every commit/DDL/ maintenance tail (the convoy early-warning). Beside it, the commit lock's in-process trio (#439), recorded by Locks.acquireCatalogCommitLock for every taker: hoglake_commit_lock_waiting{catalog} (sessions of this pod inside the acquire — summed over pods, the fleet's queue depth), hoglake_commit_lock_held{catalog} (0/1 while a transaction of this pod holds it; a holder that never ends is a flat line) and hoglake_commit_lock_hold_seconds{catalog, path} (grant to the transaction's commit or rollback, path = commit, compaction, expiry, retirement, ddl or drop). These see queueing BETWEEN scrapes but only THIS pod's sessions; the _db_ pair above sees every session but only at the sampler tick. With FIFO admission a waiter's wait is the holds ahead of it, so a hold p99 rising on one path is the cause and the wait p99 its symptom. HTTP server metrics come with the Ktor Micrometer plugin. The webui renders a /metrics snapshot visually on its metrics page. Plus the two POOL gauge families (#218), read straight off the pools rather than sampled by a loop: hoglake_db_pool_active/_idle/_pending/_max (Hikari's request pool — pending is the one to alert on: active == max is a busy instance, pending > 0 is a caller queued inside getConnection with 5 s before it becomes a 500) and hoglake_request_pool_active/_queued/_max (the blocking request dispatcher). Read them together: handlers waiting in the dispatcher hold no catalog connection, handlers pending on Hikari do. active is an approximation and counts THREADS (a handler parsing its body runs on Dispatchers.IO and is not one); queued counts calls waiting for their FIRST thread, not the executor's queue depth, which also holds the re-dispatch of every coroutine that resumed. Their companion is the hoglake_request_queue_wait_seconds histogram — what the saturation COST, recorded once per request at handler entry. Its p99 against HOGLAKE_COMMIT_LOCK_TIMEOUT_MS is the reading that matters: a wait that reaches the bound is shed as a typed 503 (hoglake_requests_shed_total), so a rising tail is the warning that precedes visible refusals. The histogram is conditioned on survival — it records at handler entry, so a wait that ended in the caller giving up contributes nothing, and under a convoy bad enough that most callers time out first the surviving waits are the SHORT ones and the p99 can FALL while the instance gets worse. Read it with hoglake_request_queue_abandoned_total, which counts exactly those. Finally hoglake_health_probe_attempts_hung is the probe's own outstanding attempts: normally 0, and 2 (the cap) against a database that is demonstrably answering means the pod is stuck and must be restarted — both probe threads are parked on connection attempts nothing can interrupt, so /healthz will report 503 for the rest of that pod's life. The refusal is logged at ERROR.
  • Audit log: every consequential action (DDL, commits with outcome, options changes, expiry/cleanup runs, offset commits) emits one structured JSON line on the hoglake.audit logger — actor, action, object, outcome, request id — strictly after its transaction resolves. Request ids ride X-Request-Id in and out.
  • GET /v1/database/health (persistence/DatabaseHealthRepo.kt, service/DatabaseHealthService.kt): the health of the Postgres INSTANCE behind the catalog, read from the statistics views, plus findings that interpret those numbers for this schema. It reads catalog and pg_stat_* relations only — never a hog_* table — so its cost does not scale with the manifest, and it carries NO query text, because pg_stat_activity.query holds literal values (object paths, identifiers, author strings) and only durations and counts may cross the wire. Each finding is a severity (INFO, WARN or CRITICAL, sorted worst-first) plus a stable code, a detail of what was measured, a hoglake_impact saying why it matters HERE — the second half is the reason this endpoint exists rather than a link to a generic Postgres dashboard — and a resolution saying what happens next and by whom: kind is maintenance (one of hoglake's own loops closes it on its schedule, and task names it, e.g. reindex for bloated indexes while that loop has recorded a run in the last three hours), operator (nothing in hoglake will; text says what to do) or watch (no action; text says what would change that). A finding's kind can follow its severity: xid_wraparound and dead_tuples are a watch at WARN and an operator's at CRITICAL. The CRITICAL-capable codes are invalid_indexes, inactive_replication_slot, prepared_transactions, commit_lock_held, autovacuum_disabled, xid_wraparound and idle_in_transaction (which escalates from WARN to CRITICAL with the age of the oldest idle transaction, because an open transaction pins the vacuum horizon for the whole database and every expiry delete and compaction supersession stays unreclaimable until it ends). The WARN set is long_transaction, lock_wait, dead_tuples, never_analyzed, sequential_scans, unused_indexes, cache_hit_ratio, connection_saturation, index_bloat and checkpoints_requested; temp_files and toast_dominant are INFO.
  • Health: /healthz proves the catalog is reachable (SELECT 1 on the probe's OWN one-connection pool, bounded four ways by HOGLAKE_HEALTH_PROBE_TIMEOUT_MS — Hikari connectionTimeout, pgjdbc connectTimeout/socketTimeout, session statement_timeout — with a wall-clock deadline of twice it); /livez is process liveness only. The probe shares nothing with the request path, so a full pool reads 200 and only a database that does not answer reads 503 (#218). Before that it borrowed a request connection, and a commit convoy that filled the pool read as "database dead" and got both API pods liveness-killed.

Background assembly

App.kt wires services into Ktor and startBackground() runs the loops — maintenance summary, hydrator, expiry, cleanup, compaction (default off: HOGLAKE_COMPACTION_INTERVAL_MS=0 — flipping it on is an ops decision), retirement (also default off), reindex (also default off), metrics sampler — as coroutines under one supervisor scope (BackgroundLoops), each with its own interval knob (Config.kt, all env-sourced, <= 0 disables), per-catalog failure isolation (a failed iteration is logged + counted and the loop keeps running), and structured, bounded shutdown (cancel + join, 5s cap). Main.kt = migrate (under an advisory lock, so replicas don't race DDL) → assemble → start loops → start the metrics listener (when HOGLAKE_METRICS_PORT > 0) → serve.

Every route handler's blocking work runs off the Netty event loop (api/BlockingDispatch.kt, #218): one interceptor in its own phase, inserted after Plugins so it never sheds ahead of RequestId, installed once by App.module, runs the rest of the pipeline under a bounded dispatcher of HOGLAKE_REQUEST_THREADS threads (default HOGLAKE_DB_POOL_SIZE). /healthz, /livez and /metrics bypass it, matched on a path normalised for trailing slashes, so a full dispatcher is still observable and still probes green. Measured, not assumed: /healthz/ is a 404 today, because this server does not install Ktor 3's IgnoreTrailingSlash — configure the probe without the slash. Normalising makes that a fast 404 rather than a queued timeout, and removes the trap where installing that one-line plugin later would route a real probe through the saturated pool.

Excess requests QUEUE, and the queue is bounded by AGE rather than by depth. The interceptor stamps System.nanoTime() before the hand-off, records the wait as hoglake_request_queue_wait_seconds at handler entry, sheds a request whose wait already passed HOGLAKE_COMMIT_LOCK_TIMEOUT_MS with the typed 503 + Retry-After before it borrows a connection, and charges the rest of the wait against the advisory-lock bound inside Locks.acquireCatalogCommitLock — so a request cannot spend the admission budget twice (25 s queued plus a fresh 30 s lock wait was 55 s of server time for a caller that had gone). The shed is judged at ADMISSION, when a call reaches a thread: a transient convoy drains and discards its stale head, while a pod whose pool never frees a thread queues rather than refuses, which is why readiness-on-sustained-saturation is still a follow-up.

Main.kt also floors Netty's CALL group at HOGLAKE_NETTY_CALL_GROUP_SIZE (default max(4, availableProcessors)), which is defence in depth rather than the fix: Ktor sizes that group at the CPU count exactly, and the production pod has one CPU, so a probe's dispatch — or a /metrics scrape, which shares the bypass and is real CPU work on that thread — would otherwise queue behind another call. The WORKER group keeps Ktor's own default (parallelism / 2 + 1): it does socket IO, it is not where blocking work or the probe handler runs, and applying this floor there would RAISE it on every pod with more than two CPUs.

There is no verify loop any more. It ran VerifyService.runOnceAllCatalogs() — one twelve-check report per catalog, recorded in the ledger with trigger loop — behind HOGLAKE_VERIFY_INTERVAL_MS, default 0 and set to 3600000 only on the Gigahog maintenance workload. #261 removed it: every check was an unbounded full-table aggregate, and at production scale the sweep timed out instead of reporting, so the knob was "0" there. The env var is now in Config.REMOVED_INTERVAL_ENV, which splits on the VALUE: 0 and absence pass in silence, a positive value is refused at boot naming #261. 0 is what the chart renders — unconditionally, from a REQUIRED verifyIntervalMs, with no override in any environment — so a blanket REMOVED_ENV refusal would reject every pod over a value that means what is now true. The cost of that would be a stalled rollout rather than an outage (maxUnavailable: 0, so the old ReplicaSet keeps serving; the signal is a Degraded Application, in dev only, with prod behind the promotion gate) — but a refusal nobody needs is still a refusal. A POSITIVE value is refused because it asks for checks that no longer run. RemovedEnvConfigTest pins both tiers. The entry graduates to REMOVED_ENV once the chart stops rendering the key.

Specified, not yet implemented

CDC publications — the WAL tap: a catalog-managed publication tails a table's changefeed and produces rows to Kafka, its progress tracked as a first-class consumer offset (so the retention floor protects unpublished ranges automatically). Fully specified in the OpenAPI (endpoints return 501) so clients can build against the shape.

GET /catalogs/{c}/export — the DR manifest (snapshot range + live-file manifest + consumer offsets, consistent at head), likewise fully specified in the OpenAPI and answering 501 until built.

Operational endpoints and probe contracts

Served at the root (not under /v1), documented in openapi/hoglake.yaml:

Endpoint What Kubernetes probe
GET /livez Process liveness only — never touches the database liveness (a database outage must not restart pods)
GET /healthz Readiness: the catalog must answer (SELECT 1 on the probe's own connection, bounded by HOGLAKE_HEALTH_PROBE_TIMEOUT_MS; the zombie-server incident is why it touches the database at all, #218 is why it no longer touches the request pool) readiness (an unready pod leaves the Service)
GET /metrics Prometheus text exposition; operator-only on the API port, unauthenticated on the infra listener (HOGLAKE_METRICS_PORT, when > 0), which serves only this route scrape target (via the infra listener), never a probe

One more read-only operational endpoint is served under /v1, not the root:

Endpoint What Kubernetes probe
GET /v1/database/health Postgres-instance health from the statistics views, with interpreted findings (see Observability) — instance-level, never a hog_* read, and carries no query text never a probe

The webui container serves its own static GET /health (nginx return 200, independent of the SPA fallback and the API proxy) as its probe target, and proxies /healthz, /metrics and /openapi.yaml through to the server. Its upstream is resolved at request time (nginx resolver + variable proxy_pass), so the console boots and probes green whether or not the server exists yet; proxied paths return 502 until it does, then heal without a restart.

Dev environment

Toolchain via flox (JDK 25); Gradle via the checked-in wrapper (./gradlew, version pinned in gradle/wrapper/gradle-wrapper.properties — never a system gradle); recipes via just (see justfile, composed into ../justfile):

just            # list recipes
just test       # full suite (Docker required)
just unit       # no Docker
just one 'com.posthog.hoglake.commit.*'
just schema-check
(cd .. && just test-hoglite)  # the hoglite live classes, in a Linux container (see Testing)
just compose-up # Postgres 18 + MinIO (ports overridable via HOGLAKE_*_PORT)
just run        # server on :8080
just docs       # OpenAPI spec in Swagger UI on :8090 (HOGLAKE_SWAGGER_PORT)

The compose MinIO needs the server's S3 env pointed at it — the defaults are blank/ambient (AWS default chain, for IRSA in deploys), so without these the first S3-touching path (hydrator footer reads, cleanup deletes, compaction rewrites) dies with the SDK's "Unable to load credentials" chain error before any request is made:

export HOGLAKE_S3_ENDPOINT=http://localhost:9000   # MinIO from compose-up
export HOGLAKE_S3_ACCESS_KEY=hoglake               # MINIO_ROOT_USER
export HOGLAKE_S3_SECRET_KEY=hoglake123            # MINIO_ROOT_PASSWORD
just run

(HOGLAKE_S3_PATH_STYLE already defaults to true, which MinIO requires.) Both keys set selects the static storage provider; see HOGLAKE_STORAGE_PROVIDER in docs/auth.md ("Storage credentials") for ambient and broker. When the server runs in a container instead, use http://host.docker.internal:9000 — or http://minio:9000 with the container attached to the compose network — as the endpoint.

pyhoglake's test_compaction_copies_a_declared_variant_table and test_compaction_after_set_variant_shredding_compacts_each_layout_apart need HOGLAKE_COMPACTION_VARIANT=true on the server they run against; they fail, not skip, without it. ci/live-python.sh sets it; a dev server must set it by hand.

Layout

  • src/main/resources/db/migration/ — Flyway. V1__init.sql is frozen as of v1.0.0 and the chain is append-only from there; V32 is the latest. schema.sql is the canonical twin, equivalence-tested.
  • src/main/kotlin/com/posthog/hoglake/
    • model/ — domain types (mirror the OpenAPI schemas).
    • persistence/ — JDBI repositories; all SQL parameterized.
    • service/ — DDL, alter, scan, views, options, expiry, cleanup.
    • commit/ — the commit path (OCC, lock tail, row-id assignment).
    • compaction/ — small-file merging.
    • hydrator/ — deferred-stats hydration.
    • stats/ — Iceberg single-value bounds codec.
    • observability/ — metrics, audit, request ids.
    • api/ — Ktor routes implementing the spec.
    • auth/ — token verification, the route authorization table, auth modes. Tokens are ES256 or RS256 compact JWS verified against a JWKS that may mix EC P-256 and RSA keys (encryption keys and keys for other algorithms are skipped), so an off-the-shelf identity provider can issue them. Catalog grants come from the cat object or, equivalently, from hoglake:<catalog>:<scope> values in the standard OAuth scope claim; a token carrying both must have them agree.

Testing

JUnit 5 + AssertJ; property tests via kotest-property (strategy: ../fuzzing.md). Integration tests use Testcontainers (Postgres 18, MinIO), tagged integration, and need Docker (docker-java.properties in test resources pins the Docker API version for recent daemons). The schema-equivalence test and an OCC concurrency torture suite run with everything else in just test.

The hoglite live classes (com.posthog.hoglake.hoglite.*IntegrationTest, through HogliteConformanceEngine) run a real hoglited on a MinIO container. The binary comes from HOGLITE_BINARY (else hoglited on PATH); without one they SKIP, and with HOGLITE_REQUIRED=1 they fail instead. hoglite ships Linux binaries only, so on a Mac just test always skips them; CI's hoglite-live job runs them on the newest tested build. Locally, just test-hoglite [filter] (repo root) does the same in a Linux container: ../ci/hoglite-live-local.sh fetches the build for the Docker daemon's architecture (../ci/fetch-hoglited.sh, checksum and -version provenance verified), runs :test under eclipse-temurin:25 with the daemon's socket mounted and the host network (the engine reaches MinIO at 127.0.0.1:<mapped port>), keeps its Linux Gradle state in ~/.cache/hoglake/hoglite-live/ (HOGLITE_LIVE_CACHE), and closes with ../ci/check-hoglite-live.sh, the fail-closed check CI runs. That check reads the reports of the hoglite *IntegrationTest classes only, so a filter must match only those ('com.posthog.hoglake.hoglite.HoglitePinned*', say); a run of anything else ends with "no report" whatever its result. Needs docker and an authenticated gh.

Atomic CREATE / CTAS

Catalog responses advertise atomic-table-creation-v1. Prepare a definition with PUT /v1/catalogs/{catalog}/table-creations/{operation-uuid}, write Parquet using the returned field IDs and write_path, then POST the ordered file registrations to that operation's /commit. Preparation creates no visible table or snapshot and does not reserve the target name. Publication installs the definition, files, and receipt in one database transaction and one snapshot. Empty registrations create an empty table. INSERT continues to use the existing append API.

Repeat preparation with the same definition, or publication with the identical ordered file list, to recover lost responses. Different payloads under the same operation ID conflict. GET the operation to inspect its durable state. A committed receipt remains valid even after subsequent table deletion or replacement. POST /abort to atomically fence publication; if publication already won, abort returns committed and never deletes the table. HTTP 200 reports operation state, including rejected and aborted; clients must inspect the response state.

Only publication takes the catalog-wide commit lock, followed by the operation row lock. Status, abort, and expiry serialize on the operation row; preparation uses the unique operation key to resolve concurrent retries. No operation takes the catalog lock while holding an operation row lock. Both row and catalog waits honor HOGLAKE_COMMIT_LOCK_TIMEOUT_MS (default 30000; 0 disables the bound), returning 503 with Retry-After when the bound is exceeded.

Prepared operations expire after 24 hours, checked under the operation row lock on status, abort, preparation retry, or publication. Terminal receipts are retained for the lifetime of the catalog in this version. No automatic object deletion is added: failed or aborted writes can leave objects. A prepared status or an unavailable receipt is not permission to delete data. Only terminal aborted/rejected operations are eligible for operator cleanup, after their writers have stopped. Never remove files from committed operations based on operation age; normal catalog retention owns their lifecycle. There is no automatic fallback to staging-table rename.

The base API supports unpartitioned creation (partitioned and sorted creation use the /partitioned and /sorted preparation variants, advertised as atomic-partitioned-table-creation-v1 and atomic-sorted-table-creation-v1), at most 10000 columns and 10000 files per operation, and validates registration metadata using the existing append checks. It does not open Parquet objects at publication time. Field IDs are table-local, start at one, and are installed with the prepared UUID at publication. Expanding receipt retention or automated orphan cleanup is separate work.

Atomic preparation, publication, and abort emit table_creation_* audit events after their transactions finish. hoglake_table_creation_total labels attempts by catalog, action, and outcome; terminal retries are replayed. Only first-time successful publication increments hoglake_commits_total{result="committed"}. Stored definitions carry a format version and stable wire type names; existing unversioned receipts remain readable and retryable.

A supplied footer_size must be nonnegative and fit within file_size_bytes - 8 for both initial publication and INSERT. Atomic publication requires this field; ordinary INSERT retains support for omitted footer metadata.

Recovering an INSERT response

idempotent-append-v1 advertises durable commit replay and GET /v1/catalogs/{catalog}/commit/receipts/{operation}. The operation is the existing optional idempotency_key UUID on /commit. Both the append and its full canonical request receipt commit in one PostgreSQL transaction under the catalog lock. Reusing a key with another payload returns 422. Receipts have no expiry or snapshot/table foreign key, so later writes, rename, drop and snapshot expiry cannot cause publication again. Existing receipts remain replayable.

Canonical comparison orders append groups, their files and column statistics; partition value order remains significant. The read snapshot, expected table UUID, all registration fields, and remaining request metadata are included. A missing receipt does not fence an in-flight request. Retry only the identical payload with the same key; never infer permission to delete uploaded files.

Deploy this server before enabling connector recovery. Older clients (Python, DuckDB, hedgerow and the console) retain their existing behavior and need no wire changes. /commit/prepared remains supported. Manual SQL reruns, query/task retries and orphan collection are outside this guarantee.

Application authentication is optional (HOGLAKE_AUTH_MODE, default off); under enforce this lookup needs read on the catalog. Under off, protect it with the same authenticated deployment boundary and catalog authorization as /commit; catalog scoping alone is not authentication. This change does not introduce an authentication framework or authorize any deployment.

Atomic partition replacement

atomic-partition-replacement-v1 adds POST /v1/catalogs/{catalog}/commit/replacements/prepared: the commit request plus file_ends, which ends whole live data files of a table and applies appends in one snapshot with the usual durable idempotency receipt (GET /commit/receipts/{operation} serves it). It is the commit a day-at-a-time backfill needs: a reader at the old snapshot sees the old day, a reader at the new one sees only the replacement, and none sees a day missing or doubled. It is a dedicated endpoint so an older server answers 404 instead of ignoring file_ends and publishing only the appends.

Each file_ends entry names a table with its required expected_table_uuid and exactly one of partitions (non-empty tuples, as long as the live partition spec and spelled as partition_values are) or all_files: true. A year, month, day, hour or bucket value must be a base-10 integer string (20401 for a day, not 2025-11-10; null is allowed, identity values are not checked), else 422 naming the table, field and value: a tuple is matched as a literal string, so a date spelled another way would end nothing and double the day. A tuple that matches no live file ends nothing and is not an error. The request needs idempotency_key, read_snapshot, author and message, and is refused with 400 when deletes or require_unchanged_tables is present. appends may be empty. The response is the commit result plus ended_files, the data files ended; the receipt stores it, so a replay and GET /commit/receipts/{operation} return it too (a receipt written before it was stored omits it).

Under the commit lock the server checks the incarnation, then the conflict window, then that no live file of the table was written under another partition spec (409 partition_spec_mismatch; all_files is exempt; skipped without a scan when the table has only ever had one spec), then ends every matching live file and its live deletion vector, then appends. The conflict window depends on the end:

  • all_files: the table must be unchanged since read_snapshot, as a delete target is. Inserts, deletes, ends, replacements and DDL conflict.
  • partitions: only the target tuples must be unchanged. Another commit that began or ended a data file in one of them, or registered a deletion vector against such a file, is a 409 commit_conflict, and so is any DDL on the table. Appends to other partitions do not conflict, so a replacement does not livelock under continuous appends elsewhere in the table.
  • Compaction never conflicts, in either case: the files ended are those live at commit and a compaction planned against one skips it.

Files appended by the request are never ended by it. A path the catalog already records as a data file, live or ended, cannot be appended here (422 naming the path): paths are deterministic, and overwriting an ended file's bytes would break every snapshot that still reads it. Nothing is deleted: ended files follow the normal retention, expiry and cleanup, as a truncate's do.

The commit records table_deleted_from (and table_inserted_into with appends) on each table, which is what makes guarded writers that read earlier conflict. For a table whose files it really ended it also records table_replaced; a commit that ended nothing records none. The changefeed raises 409 reconciliation_required for a window that crosses a table_replaced (as for a truncate), on that row rather than on the ended files, which retention reclaims: the barrier holds at the retention floor too.

Partition tuples are matched against the table's own live files, narrowed by the first key and then compared in full. The conflict probe for a partitions end reads the files and deletion vectors recorded since read_snapshot.

Atomic DML transaction publication

atomic-dml-transactions-v1 adds POST /v1/catalogs/{catalog}/commit/transaction. The request uses the existing guarded, idempotent commit envelope. The unchanged-since-read_snapshot requirement binds the tables the transaction DELETES from — those conflict with inserts, deletes and DDL — because a delete is published against a read of the target's rows. A table the transaction only appends to keeps the ordinary DDL-only rule: appends never conflict with appends, inside a transaction as much as outside one, so an append-only transaction does not 409 on a concurrent INSERT. Every table publishes in one snapshot and one durable receipt. This is snapshot isolation with write-write conflicts; read-only tables and other catalogs are not part of the commit read set.

Because "unchanged" binds only the delete targets, a statement that read a table but produced no deletion vector for it — a MERGE or UPDATE whose predicate matched nothing — must still send a delete group for that table with an empty files list, or it keeps no read-set protection. That is the same anchor /commit/mutations/prepared already documents, and it is now load-bearing for /commit/transaction too.

Compaction is never a conflict, on any guarded path. A table_compacted change rewrites which files back a table, never which rows are visible in it, so it cannot invalidate a read set — and treating it as one livelocked every mutation on a continuously compacted table, where a group publishes every couple of minutes and any read-to-publish window longer than that retried into the next one forever. The same exclusion applies to the atomic-replacement guard in service/TableCreationService.kt, where the rejection is durable (rejected/target_changed), so a CREATE OR REPLACE whose upload outlived one compaction interval burned its receipt and the retry raced the next group.

What compaction can invalidate is a specific deletion-vector target, and that is caught per file: a DV against a data file that was live at read_snapshot and has since been retired — by compaction or another commit — is a 409 (retryable: re-read at the compaction snapshot and re-publish against the output), while one against a file that was already dead at read_snapshot stays a 422. Expiry is deliberately not on that list: for expiry to have removed a file that was live at read_snapshot, read_snapshot must be below the floor, and the floor guard returns 410 before any per-file check runs — so a connector never needs a retry path for it.

A transaction may delete rows from files it has staged privately. A DV registration can specify data_file_id: 0 and data_file_path referencing exactly one append in the same table and same commit. The server resolves that reference after allocating and inserting the new files, inside the same transaction. Ambiguous, missing and cross-table references roll everything back. Numeric IDs retain their existing snapshot checks. Other commit endpoints reject this new field; old replicas lack the transaction endpoint, so clients must never fall back. New fields are omitted from ordinary receipt fingerprints, preserving existing receipts.

Upload claims do not take the commit lock. A writer claims one upload per output file, so claim/renew/abandon/schedule-expired taking the per-catalog commit lock — unbounded, with no admission timeout — meant paying the catalog's whole write-throughput bottleneck once per file, for nothing: claim paths are server-generated random UUIDs and the claim INSERT is ON CONFLICT DO NOTHING. Row-level semantics replace it. Every transition re-checks the claim's state in the statement that takes its row lock, so under READ COMMITTED one that waited on a publication's row lock re-evaluates against the committed row and cannot clobber a settled claim, and UploadService.register — which runs inside the commit transaction — takes the claim rows FOR UPDATE. With no lock above them, renew, abandon and register take the claim rows they lock in upload_id order: concurrent renewals of one owner, one per writer of an operation, deadlocked before they did. The expired-upload sweep's fence re-checks the whole candidate predicate, not just "not registered", so a renewal that landed between candidate selection and the fence wins, as renewUploads promises; it fences each candidate in its own short transaction, because a publication registering one of those paths waits on that row lock while holding the catalog commit lock, and one transaction over a 10,000-row batch would convoy the catalog behind the sweep. It also refuses to queue a path any data or deletion-vector file row still claims, and rests an abandoned tombstone for the drained-ledger retention between offers.

Trino stages DML on its coordinator and uses this endpoint at explicit COMMIT. DDL remains autocommit-only. Failed/coordinator-lost transactions leave only leased uploads until publication; an unknown publication outcome must be resolved from the receipt, not by deleting objects or blindly resubmitting SQL. Python, DuckDB, hedgerow and the web UI retain their ordinary commit behavior. They read the usual positive file IDs, row lineage and Puffin vectors after publication; private IDs and paths add no new committed storage or scan representation. No migration is needed beyond the claimed-upload ledger required by this capability.