Agent guidance for this repo (github.com/PostHog/hoglake — the standalone hoglake monorepo; the codebase began life as a subtree of the PostHog DuckLake fork, now PostHog/ducklake, whose history holds the pre-split commits).
Do not push until all required tests have run on the exact changes being
pushed. This includes the server suite with Docker, Kotlin and Python lint,
Python type checks, all three Python unit suites (just pyhoglake unit,
just hedgerow unit, just millrace unit), both live client suites plus
just millrace live, and the UI tests and build. Run additional component
checks for affected code, such as the DuckDB extension's live tests.
A skipped live suite, a missing service, a unit-only run, or checks from an
older revision do not satisfy this rule. Wait for every command to finish and
read its result. Any failure blocks a push, including a failure that also
occurs on main. Fix it or report the exact failure and obtain explicit user
authorization to push with that known failure. Do not exclude tests, add
xfail, or accept a failing job to get a green result.
Before every commit and push:
(And before a PR that touches a maintenance loop, the commit path or a statement over the manifest tables: the six scale questions at the end of Scale doctrine are answered in the PR body, the sixth being what ran on the local stack and what it showed.)
(And before any PR that changes server behaviour: the PR body says how
the change behaves on Hoglite, per Hoglite considerations,
and just test-hoglite ran on the exact changes.)
(cd server && flox activate -- ./gradlew :test) # Docker required
just lint-all # ktlint + ruff (check & format) across the three Python trees, mypy on pyhoglake + millrace
just pyhoglake unit
just hedgerow unit
just millrace unit
just live-python # builds this checkout, starts isolated services, fails on skips
just millrace live # the Kafka-ingestion live stack (PG + MinIO + Kafka), fails on skips
just test-hoglite # the hoglite live classes on the newest hoglited, in a Linux container, fails on skips
just webui test
just webui buildruff (and mypy) are held to ONE version by the root uv.lock, with a
floor rather than an == in each tree's dev group, and run through
uv run — never uvx ruff, which resolves a different rule set per
machine and silently ignores the projects' per-file-ignores. The
floors exist because an == repeated across the members gave Dependabot
two pins for one package as soon as it bumped one of them, which no
workspace resolution satisfies, so it skipped the tool with a "handled
error" on every run; with floors it moves the lock once.
The four Python trees (pyhoglake/, hedgerow/, bench/, millrace/)
are one uv workspace: the root pyproject.toml lists the members and
holds nothing else, and ONE root uv.lock pins all of them (Python
=3.12, the intersection of the members' floors). Dependents take pyhoglake as
{ workspace = true }. A fifth member,pyhoglake-variant-codec/, is pyhoglake's VARIANT codec in Rust (maturin): onlyuv sync --group variant-codec(or--extra variant-codec) inpyhoglake/builds it, which needs Rust, and_variant_backenduses it when it is installed and speaks itsPROTOCOL(PYHOGLAKE_VARIANT_CODEC=auto|native|python) forencode_json,verifyandstructure_fault. Its release wheels come fromvariant-codec-wheels.yml; the millrace image builds its own in a stage whoserust:image tag, maturin and zig must stay those ofrust-toolchain.tomland the workflow (millrace'stests/test_ci_gate.pychecks).uv sync/uv runinside a member directory select that member against the root lock; never add a per-directoryuv.lockback — separately locked trees went stale on every pyhoglake pin bump (#332). The members share one.venvat the root.
The server builds through the checked-in Gradle wrapper
(server/gradlew, pinned in
server/gradle/wrapper/gradle-wrapper.properties) — never a
system-installed gradle. The just server ... recipes route through it
too, so just test-all (server + pyhoglake) stays equivalent.
The hoglite live classes (com.posthog.hoglake.hoglite.*IntegrationTest,
HogliteConformanceEngine) need a hoglited, which hoglite ships for
Linux only, so just server test SKIPS them on a Mac and that green does
not cover them; CI's hoglite-live (in the required server-checks
gate) runs them against the newest tested build. just test-hoglite [filter] is the local equivalent: ci/hoglite-live-local.sh fetches
that build for the daemon's arch (ci/fetch-hoglited.sh, checksum and
provenance verified), runs the classes under a Linux JDK container on
the host's Docker daemon and network, with its own Gradle cache under
~/.cache/hoglake/hoglite-live/, and ends with ci/check-hoglite-live.sh,
the fail-closed check CI runs: classes ran, none skipped. It is not in
just test-all (a container, the GitHub API and a few minutes).
The DuckDB extension is built and tested separately (it is not in
just): cd duckdb-client && ./test/run-live-tests.sh, which needs
the dev stack and a pyhoglake checkout for its fixtures. Its
sqllogictests SKIP without HOGLAKE_URL, so a green make test
without a server up verifies nothing — see
duckdb-client/README.md for the build flags
(omitting BUILD_EXTENSION_TEST_DEPS=full makes vcpkg delete
curl/openssl/zlib from the build tree).
just live-python is the required client/server check. It builds the server
from this checkout, starts isolated PostgreSQL and MinIO services, and runs
both clients' integration tests, including qe_*.py. It fails if either
suite fails, skips a test, produces no tests, or has no readable report. It
writes logs and JUnit reports to .artifacts/live-python/ and removes its
services on exit. The default ports are 15432 (PostgreSQL), 18080 (server),
19000/19001 (MinIO). Override HOGLAKE_PG_PORT, HOGLAKE_PORT,
HOGLAKE_MINIO_PORT, and HOGLAKE_MINIO_CONSOLE_PORT if those ports are in use.
It does not replace the unit suites or the full server suite above.
For manual investigation against a shared development server: just server compose-up && just server run in another
terminal first — integration tests skip cleanly when no server is up,
so a green run without one is NOT a full verification. Say which you
ran. The server needs the compose MinIO's credentials in its env
(HOGLAKE_S3_ENDPOINT/HOGLAKE_S3_ACCESS_KEY/HOGLAKE_S3_SECRET_KEY
— see server/README.md §Dev environment) or the hydrator/cleanup/
compaction paths fail the SDK credentials chain. (just up / just down instead brings up/tears down the whole stack in containers —
server + webui images built from the working tree, webui on :5173 —
with the S3 env wired by the compose file.)
The server suite includes the schema equivalence gate
(just server schema-check): fold(migrations) must equal schema.sql.
If you touch a migration, update schema.sql in the same change or
this fails. It also includes the mapper-coverage gate
(MapperCoverageGateIntegrationTest): every hog_* table's live columns
must equal the set declared in persistence/HogSchemaColumns.kt — a
new column means updating the row mapper(s) named there AND the
declaration, or the gate fails naming the table and column.
Before the PR opens, mutation-test every load-bearing predicate
you added or changed: flip it (a conflict kind in or out, > to >=,
a NOT EXISTS guard removed, FOR UPDATE dropped, a lock put back),
run the narrowest class, and the test you wrote for it must red. Three
review rounds on one change found three, four and three uncaught
mutations in a row; each was a rule the diff claimed to enforce and
nothing pinned. A chain/depth test must not seed the intermediate state
that lets depth 1 pass.
./gradlew :test -PunitOnly runs without Docker. It excludes the JUnit
tag integration (plus *IntegrationTest* by name), so every class that
opens a container MUST carry @Tag("integration");
IntegrationTagGateTest reads the test sources and reds when one does
not. The earlier junit.jupiter.tags.exclude system property was not a
JUnit parameter and filtered nothing (#181), so twenty tagged classes
without the name ran and failed on any machine without Docker.
Prefer fixup commits over amending and force-pushing.
The catalog is a service, not a client library (see README.md — the design doc — and the defect ledger for why). Clients never see the backing Postgres. Writers write parquet to object storage themselves and register it via footer-shipping commits; readers plan from metadata. Kotlin/Ktor/JDBI server, Python client, React console, Python replication daemon:
| Component | What | Stack | Tests |
|---|---|---|---|
server/ |
The control plane: DDL, commits (OCC + admission backpressure), scans, changefeed, offsets, retention/expiry/cleanup, hydrator, compaction, retirement, metrics, audit | Kotlin 2.4 / JDK 25 (flox) / Ktor / JDBI / Flyway / parquet-java (footer reads + compaction writes) | JUnit 6 + Testcontainers (PG18, MinIO) + kotest-property |
pyhoglake/ |
Thin API client; owns the Python writer path (parquet with field IDs, footer stats, Iceberg bounds codec) | Python 3.12 (flox) / uv (workspace member; root uv.lock) / httpx / pyarrow |
pytest + pytest-httpx + hypothesis |
webui/ |
Lakekeeper-style management console: catalog browser (namespaces/tables/files/scan with time travel; the namespace listing is NAME, RECORD_COUNT, FILE_COUNT, FILE_SIZE, SNAPSHOTS, EARLIEST_SNAPSHOT, COMMENT — table_uuid stays on the wire but is shown on the table page, not as a column), newest-first snapshot timeline (before paging), consumers (grouped, names resolved, dropped badges), compaction-debt page, maintenance pages (central catalog×task matrix + per-catalog task panels over the run ledger), /metrics visualizer, instance-name badge; int64 wire fields carried as strings (lossless above 2^53) |
Vite / React / TS | vitest (mocked fetch) |
hedgerow/ |
viaduck's successor: source table → destination table replication, append-only, single-destination | Python / uv (workspace member) / pyhoglake | pytest; scripted-fake unit + live integration |
millrace/ |
Kafka → hoglake ingestion daemon with SlateDB staging; see docs/kafka-ingestion.md | Python / uv (workspace member) / pyhoglake + slatedb | pytest + hypothesis + live stack |
duckdb-client/ |
DuckDB extension: ATTACH over REST, scan (partition pruning + deletion vectors), INSERT/UPDATE/DELETE via footer-shipping commits, DDL, time travel, metadata/maintenance functions | C++ / DuckDB (pinned) / cpp-httplib + yyjson (both duckdb-vendored) / roaring via vcpkg | sqllogictests against the live dev stack + cross-client wire vectors |
The REST contract is server/src/main/resources/openapi/hoglake.yaml
— it is the single source of truth for wire shapes; server routes,
pyhoglake, webui fixtures, and hedgerow all conform to it. Change the
spec and the implementations together.
The production deployment of hoglake is Gigahog (deploy targets
gigahog-server / gigahog-webui in PostHog/charts). CI is
path-scoped per component, posthog-monorepo style:
| Workflow | Paths | Runs |
|---|---|---|
server.yml |
every PR and push to main; a changes job selects server/**, codec vectors, the live-test harness, the file itself, and the heavy jobs skip otherwise (REQUIRED CHECK server-checks, the gate over server-test and python-live; see the ruleset note below) |
server-test + ktlint (Docker/Testcontainers; schema-equivalence gate included), both live Python suites, and a server-checks gate that requires both suites before deployment, PR image boot-smoke, the gated deploy job, and trino-test — the integration harness against the fork's public image (ghcr.io/posthog/truffle, newest ordered release tag; pin via the HOGLAKE_TRINO_IMAGE repo variable). trino-test runs on an ARM runner (the image is arm64-only), is NOT in deploy's needs, and must stay non-required: a broken fork build must never wedge hoglake CD |
migration-chain.yml |
every PR and push to main, NO path filter | the append-only / no-duplicate-version / numbered-above-main gate on server/src/main/resources/db/migration, fetching main fresh at run time. Its own workflow because it is a REQUIRED CHECK, and it was the first to hit the rule below |
webui.yml |
every PR and push to main; a changes job selects webui/**, the OpenAPI spec, the shared vectors, the file itself (REQUIRED CHECK webui-test) |
npm run build (tsc gate) + vitest + PR image boot-smoke + gated deploy job |
ci-python.yml |
every PR and push to main; a changes job selects pyhoglake/**, hedgerow/**, millrace/**, bench/**, the root pyproject.toml and uv.lock, the OpenAPI spec, ci/**, the workflow files, the server files and .github/dependabot.yml the client's tests read (the filter's comment names each), and the jobs skip otherwise (REQUIRED CHECK python-checks) |
on a PR that changes the codec's source, codec-version (a changeset naming pyhoglake-variant-codec, or a hand-bumped version). pyhoglake: pyhoglake-checks.yml (ruff, mypy, pytest on 3.12–3.13, the variant suites on the pyarrow floor pyproject.toml declares and — non-blocking — on the newest pyarrow at least 7 days old, build, wheel smoke test). hedgerow and bench: uv sync, ruff (pinned; bench exempt until its format backlog lands), pytest. millrace: uv sync, ruff, mypy, pytest, and the mutmut survivors gate. When pyhoglake-variant-codec/**, uv.lock or the codec's wheel workflow or scripts changed, variant-codec-wheels.yml too, for the manylinux wheels and the sdist. Unit tests plus both live client suites through python-live.yml; a python-checks job fails if any dependency fails |
bench-image.yml |
bench/** pyhoglake/** root pyproject.toml uv.lock |
builds bench/Dockerfile (context = REPO ROOT: bench installs pyhoglake as a uv workspace member from the root uv.lock, so the root manifest, the lock, pyhoglake and every member's pyproject.toml must be in the context) and smokes it — CLI runs, non-root, no .venv, and the installed pyhoglake is this commit's and not PyPI's. A main push then publishes multi-arch ghcr.io/posthog/hoglake-bench (sha + latest), gated on the smoke and live client tests. NOT CD: no charts dispatch, no chart references it, it is pulled by hand into bench/deploy/bench-pod.yaml. Its build stage is deliberately NOT $BUILDPLATFORM-pinned — a virtualenv holds native wheels, so each arch installs its own |
millrace-image.yml |
millrace/** pyhoglake/** pyhoglake-variant-codec/** root pyproject.toml uv.lock ci/** |
builds millrace/Dockerfile (context = REPO ROOT, same reason as bench) for amd64 and, under QEMU, arm64, and smokes each — both entrypoints (millrace, python -m millrace.maintenance) refuse an empty env at config with exit 2, non-root, no .venv, pyhoglake is this commit's, and the Rust VARIANT codec (cross-built by zig in a $BUILDPLATFORM stage) is installed, off by default (PYHOGLAKE_VARIANT_CODEC=python), and with native encodes as the Python codec does. A main push publishes multi-arch ghcr.io/posthog/hoglake-millrace tagged r<UTC minute>-<sha6> (the Kargo release tag; org.opencontainers.image.revision/.source annotations on the index, verified after push), by sha, and latest, gated on the smoke and the live suites. No charts dispatch: a Kargo Warehouse in PostHog/charts subscribes to the repository |
ecr-release.yml |
runs when Server or Webui completes on main (workflow_run); PRs that change the workflow or .github/scripts/ecr-release.sh run a dry run, and workflow_dispatch runs one on any branch |
the gigahog CD entry point: it makes the images the Kargo Warehouse turns into Freight (CD paragraph below). A gate job reads server-checks and webui-test for the commit. It publishes when no gate failed and at least one passed. It does not read the deploy jobs. One publish job builds BOTH images (same contexts and platforms as the deploy jobs) and pushes BOTH to the shared-services ECR with ONE tag, r<UTC minute>-<sha6>, plus the org.opencontainers.image.revision/.source annotations on the index and each manifest. ECR gets that tag only: the repositories have immutable tags. A rerun uses the commit's existing release again and pushes only a missing image. The job reads the role ARN from the HOGLAKE_AWS_ECR_PUBLISH_IAM_ROLE secret. The Warehouse makes Freight only when both repositories have the same newest tag, so never publish one image alone. The dry run, from a PR or from a manual dispatch, pushes to a local registry and runs the same checks without AWS. A dispatch on main with dry_run false publishes, and reads the same test gates as a push to main. A dispatch on a branch other than main must set dry_run, because the role trust accepts only refs/heads/main. Not a required check |
python-live.yml |
reusable: server, Python checks, benchmark image, millrace image | builds the checked-out server, starts PostgreSQL and MinIO, runs both live client suites (live job) and the millrace Kafka-ingestion live suite (live-millrace job, which adds apache/kafka to the stack via ci/live-millrace.sh), rejects skipped or empty reports, and saves logs and JUnit reports. A failed live run blocks server deployment, PyPI publishing, and benchmark and millrace image publishing |
publish-pyhoglake.yml |
pyhoglake-v* tags (not pyhoglake-variant-codec-v*); PRs touching the workflow |
pyhoglake-checks.yml, then the built wheel with its variant-codec extra in a clean env, the pinned codec from PyPI (ci/variant_codec_smoke.py), and the variant suites through it, so a pin not on PyPI fails every run; tags also publish to PyPI (trusted publishing, pypi environment) and create a non-latest GitHub release |
variant-codec-wheels.yml |
reusable: Python checks (manylinux only), codec publishing (every platform, on a tag or a manual run) | pyhoglake-variant-codec's abi3 wheels (manylinux_2_28 and musllinux_1_2 x86_64/aarch64 through zig, macOS arm64/x86_64, Windows x86_64) and sdist, each installed into pyhoglake's locked env on its own platform (ci/variant-codec-wheel.sh: the parity smoke ci/variant_codec_smoke.py, then the variant suites except on Windows) and uploaded as an artifact |
publish-pyhoglake-variant-codec.yml |
pyhoglake-variant-codec-v* tags; PRs touching the workflow |
variant-codec-wheels.yml; tags also publish those exact files to PyPI (trusted publishing pinned to this file, pypi environment) and create a non-latest GitHub release. The tag's version must be the codec's |
release.yml |
a main push that touches .sampo/changesets/*.md; workflow_dispatch (on a branch other than main: a dry run of the bump only) |
the Sampo release flow of Versioning: the Release environment gate (plus a Slack approval request in #alerts-managed-warehouse when vars.RELEASE_SLACK_ENABLED is true), sampo release + ci/release_versions.py sync committed to main by the releaser App (its secrets live only in the Release and release-tags environments), then tag-and-release (the vX.Y.Z tag and GitHub release, the codec tag; ci/release_tags.py plans the tags and makes every step a safe re-run) and tag-pyhoglake (waits for the codec on PyPI, then the pyhoglake-vX.Y.Z tag). One run at a time (concurrency: release; the dry run has its own group). Not a check |
release-failure-notification.yml |
workflow_run of Release on main, only with vars.RELEASE_SLACK_ENABLED true |
replies in the approval's Slack thread when a Release job failed, timed out or was cancelled, when the tag job never ran, or when the released reply was skipped (.github/scripts/release-failure-notification.cjs). Survives a cancelled Release run because it is its own workflow |
changeset-hygiene.yml |
PRs from this repository (not Dependabot) | ci/changeset_hygiene.py: one sticky comment while a PR changes a package's source without a changeset naming it, names a package that did not change, or has a changeset that does not parse; deleted when fixed. Informational, NOT a required check |
fuzz.yml |
nightly cron + dispatch | ./gradlew fuzz over every Jazzer target (900s per soak target, 60s per sweep target, by default), with the generated corpus accumulated across nights through the actions cache. Not a PR check: PR CI only REPLAYS the committed seed corpus, inside :test |
semgrep.yml |
all | python / kotlin+java / general packs, pinned container |
dependency-review.yml |
PRs | vulnerability gate (license allow-list deferred until the three-ecosystem atom set settles) |
Live Python failures block deployment and publishing. The current merge
rules require migration-chain, server-checks, python-checks, and
webui-test; the live Python suites are required through those gates.
Required checks run on every PR, by construction. The main
ruleset ("Require to be up to date", repository-level) requires
migration-chain, server-checks, python-checks and webui-test,
with the up-to-date policy on. A required check has to be PRODUCED on every PR:
a workflow that path-filters itself out of a PR leaves its check
"expected" forever and the PR cannot merge — #299 (webui-only) sat
BLOCKED with every check green until #301 moved the migration gate out
of server.yml, and a Python-only PR had no test at all. So no
required workflow carries a trigger-level path filter; each has a
changes job (dorny/paths-filter, pinned) and the heavy jobs carry
if: needs.changes.outputs.<tree> == 'true'. A job skipped that way
reports skipped, which the ruleset accepts; a workflow that never
ran reports nothing. The three names are distinct on purpose: two
workflows both naming a job test produced two test check runs on
a PR touching both trees, and which one the ruleset read was not
defined. Renaming a required job means editing the ruleset in the
same breath (gh api repos/PostHog/hoglake/rulesets/24498452), or
every PR is blocked on a name nothing produces.
Require the gate, not the leaf. Where a workflow has a gate job
that fans in several suites (server-checks over server-test and
python-live; python-checks over the pyhoglake checks, the live
client suites and the hedgerow/bench/millrace checks), the ruleset requires
the GATE. Requiring a leaf let #304 wire the live Python suites into
three workflows as a deploy gate and merge while that gate was red —
the suites had been failing for days outside CI, which is what #304
set out to fix — and main was red for two hours until #306 repaired
them. Two rules fall out: a PR that adds a gate merges green on that
gate, and no suite in this repo lives outside CI (a suite that only
runs locally rots; the live suites did for four releases).
CD is Kargo: project gigahog in PostHog/charts
(argocd/gigahog/kargo/manifests/). Nothing in this repo dispatches to
charts; the charts state files state/gigahog-*.yaml and the
promote-to-prod.yml path no longer apply to gigahog. A main push
becomes Freight in three steps. (1) Server and Webui run on every
main push, and each completion starts ecr-release.yml (table above);
its gate publishes once neither server-checks nor webui-test
failed and at least one passed, so a red main push never publishes and
a push touching neither tree publishes nothing. (2) publish builds
BOTH multi-arch images (build stages are pinned to
$BUILDPLATFORM; the mw fleet runs Graviton) and pushes both to the
shared-services ECR (hoglake-server, hoglake-webui, us-east-1)
under ONE tag, r<UTC minute>-<sha6>. (3) The Warehouse
gigahog-release polls every 5m the two repositories in BOTH
us-east-1 and eu-central-1 (Lexical, discoveryLimit: 1, tags
^r[0-9]{12}-[0-9a-f]{6}$) plus the gigahog paths of charts main,
and makes Freight only when all four images have the same tag, the
same 40-hex org.opencontainers.image.revision whose first six
characters are the tag suffix, source = this repository, and the
same digest per image in both regions. This repo pushes only
us-east-1; the eu-central-1 copies arrive outside it, and until they
match there is no Freight. A charts commit to a watched path also
makes new Freight (same images, new charts commit).
There are nine Stages, gigahog-{server,webui,maintenance}-{dev,prod-us,prod-eu}.
Each promotion runs the materialize-release-v3 ClusterPromotionTask:
it renders charts/posthog-app into PostHog/k8s-rendered-manifests
(kargo/rendered/gigahog/<app>/<stage>) with the Freight digest of the
regional repository named by
shared/gigahog/kargo-image.<server|webui>.<region>.yaml; the Argo CD
Applications (argocd/gigahog/application.*) have automated sync off
and name their Stage in kargo.akuity.io/authorized-stage.
gigahog-maintenance has no image of its own: it runs the
hoglake-server image with apps/gigahog-maintenance/ values. dev and
prod-us read us-east-1, prod-eu reads eu-central-1. The three dev
Stages take Freight directly from the Warehouse and auto-promote the
newest (project-config.yaml). The six prod Stages are manual and
request only Freight that has passed the SAME app's dev Stage
(sources.stages: [gigahog-<app>-dev]; server-prod needs server-dev,
not webui-dev). Promote prod in the Kargo UI (project gigahog) or
with kargo promote --project gigahog --stage <stage> --freight <name>,
one Stage at a time: gigahog-server-prod-us, gigahog-webui-prod-us,
gigahog-maintenance-prod-us, then the same three -prod-eu. Nothing
enforces promoting the three from the same Freight;
argocd/gigahog/release-group.yaml (platformctl) lists them as one
group. The gigahog-kargo-project Application ignores drift on
autoPromotionEnabled, so the live policy can differ from git: check
the Kargo UI, not the file.
A flaky-failure rerun: rerun the failed jobs of Server or Webui;
the completed run starts ecr-release.yml again, the gate reads the
latest attempt, the release publishes, and dev auto-promotes the new
Freight. A rerun of ecr-release.yml reuses the commit's existing tag
and pushes only a missing image. A commit that first publishes late
gets a LATER minute in its tag than newer commits already published,
so the Warehouse (Lexical, newest tag only) makes Freight from the
OLDER commit and dev auto-promotes it. A manual dispatch on main
releases the head of main, not an older commit.
The deploy jobs of server.yml / webui.yml deploy nothing. Gated
on server-checks / webui-test, they push multi-arch
ghcr.io/posthog/hoglake-server|-webui (sha + latest) for test and
benchmark consumers, and their builds fill the GHA cache scopes
server / webui that ecr-release.yml reads (never writes). The ECR
gate does not read them, so a GHCR failure does not block CD. Keep the
name: fields Server and Webui and the job names changes,
server-checks and webui-test: the ECR gate reads them by name.
Images deploy per-commit by SHA+digest (above); semver is release-only,
and releases are cut by Sampo
changesets through release.yml, PostHog's SDK release flow
(posthog-python's). Two packages release from this repository:
hoglake, the release train: server, trino harness, webui, OpenAPI spec, pyhoglake and hedgerow share ONE version, carried by ten strings (server + trinobuild.gradle.kts, the spec'sinfo.version, webuipackage.jsonplus twopackage-lock.jsonentries, pyhoglake + hedgerowpyproject.toml, and their twouv.lockentries). Sampo's manifest for it is the rootpyproject.toml(a virtual uv project, never built; the comment there says why), its changelog the rootCHANGELOG.md, its tagsvX.Y.Zandpyhoglake-vX.Y.Z.pyhoglake-variant-codec, its own version, released only when the codec changes; tagpyhoglake-variant-codec-vX.Y.Z.
A PR that changes something a user of a release should hear about adds
a changeset, .sampo/changesets/<name>.md, naming the package and the
bump (CONTRIBUTING.md § Adding a changeset; changeset-hygiene.yml
comments, non-blocking, when a PR changes a package's source without
one). A PR that changes the codec's source MUST carry a codec changeset
(ci-python's codec-version, a required leaf of python-checks). The
version strings themselves are not edited by hand: between releases
main carries the LAST RELEASED version, and the pending changesets are
the delta.
Merging a changeset to main starts release.yml: a maintainer approves
the Release environment (the gate; with the repository variable
RELEASE_SLACK_ENABLED=true, and only then, notify-approval-needed
first asks in #alerts-managed-warehouse, replies there on approval,
release and rejection, and release-failure-notification.yml reports
failures; Slack is off by default and a missing Slack variable or secret
never fails a release), and the releaser GitHub App
(GH_APP_HOGLAKE_RELEASER_*) runs sampo release, which bumps the
root pyproject and/or the codec's and writes the changelog entries,
then ci/release_versions.py sync, which copies the train version into
the other nine strings and the codec's version into pyhoglake's
variant-codec pin and runs uv lock, and commits the result straight
to main (a signed API commit, no PR, no [skip ci]: the released
commit's images come off the normal CD path). ci/release_tags.py plan
decides what that commit releases: the train when its version moved,
the codec when its version moved OR has no tag yet (a hand bump, or a
run that died before tagging, both of which would otherwise leave
pyhoglake pinned to an unpublished codec), and it fails on a tag that
already exists for a version being released, consulting only the tags
of the packages that move. The tag-and-release job then tags vX.Y.Z
and creates the GitHub release from the newest CHANGELOG.md section
and tags pyhoglake-variant-codec-vX.Y.Z; tag-pyhoglake waits for
that codec release on PyPI (up to 90 minutes) and only then mints its
token and tags pyhoglake-vX.Y.Z; the two publish workflows fire on
their tags as before and still refuse a tag whose version is not the
pyproject's. The App's secrets live in two environments and nowhere
else: Release (required reviewers, main only) for version-bump, the
gate, and release-tags (main only, no reviewers) for the two tag
jobs, so a branch workflow cannot mint a token and a re-run of the tag
jobs never re-asks. Every tag step is idempotent (release_tags.py tag-state: a tag already at the release commit is kept, one elsewhere
fails) and the GitHub release is skipped when it exists, so a failed
run is fixed by re-running its failed jobs. A full re-run after the
commit landed finds the changesets consumed and stops at
check-changesets; recover by tagging the release commit by hand with
the commands in release.yml's comments. release-failure-notification.yml
replies in the approval thread when any of that fails (Slack on). A
codec-only release moves the pin on main without a
pyhoglake release, so a codec changeset normally travels with a
hoglake: patch (pyhoglake) changeset stating the new pin. The
:checkOpenapiVersion gradle task (in CI) still locks the spec's
info.version to the server version; ci/release_versions.py check
verifies all ten strings and the pin, and its tests run a sync over a
copy of the real files. The Python packages' __version__ attributes
read the installed metadata, so they are not version strings to bump.
Release notes live in the changesets, so the former "Pending note for
the X.Y.Z release body" paragraphs here are retired.
The old rule "an unreleased build never claims a released number" (a
-dev / .dev0 suffix on main, restored by a PR after each release)
is dropped with the dev suffix: Sampo rejects .dev0 outright and
would read -dev as a pre-release line, and the suffix bought little,
since the version is constant between releases either way. The build
stamp below is what tells two deploys apart; pyhoglake installed from
a main checkout reports the last release, as every changesets-managed
package does.
A release does not gate deploys. Kargo's gigahog-release Warehouse
makes Freight from every main build that passes CI (above), so a prod
Stage can be promoted to any build that ran in dev. To ship a release
to prod, promote the Freight whose image tag ends in the release
commit's first six characters (the sampo release commit on main).
Because that version is constant between releases, it cannot tell two
deploys apart. The image build therefore also carries a BUILD STAMP: the
CD job passes HOGLAKE_BUILD_STAMP (a UTC date -u +%Y%m%dT%H%MZ) as a
Docker build arg, the Dockerfile forwards it to gradle as -PbuildStamp,
generateVersionResource writes it beside the version, and GET /v1/info
reports it as build for the webui badge. It is SUPPLIED, never
generated by gradle: an ordinary local build passes nothing and reports
no stamp, so a stamp in the webui always means "this came off the
pipeline". Keep it out of project.version — that is the contract
version :checkOpenapiVersion gates against, and a per-build suffix
there would break that gate on every build.
-
Snapshot ids are dense per catalog and ordered with commit order (assigned inside the per-catalog advisory-lock commit tail:
pg_advisory_xact_lock((4740871::bigint << 32) | (catalog_id & 4294967295))— every DDL/commit tail usespersistence/Locks.kt; the key must be computed identically everywhere or serialization silently breaks). -
Row-id ranges are assigned server-side at commit, contiguous per file, tile
[0, total)per table, never reused — the lineage guarantee.table_uuidchanges on drop+recreate; consumers key on it and must SEE incarnation changes (hedgerow halts on them). Compaction preserves ids by materializing them: outputs carry an explicit physical_hog_row_idint64 column under the reserved parquet field id 2147483646 (never allocatable to a real column), flagged byhog_data_file.explicit_row_ids— when set,row_id_startis only min(input ids), not positional. Sorting on rewrite is safe only because of this; positional reassignment of merged rows is the predecessor's rowid-remap bug and must never return. The flag — never a file's own field ids — decides which source a reader uses, and a reader must refuse a file that disagrees with its registration in EITHER direction, because the server cannot detect the disagreement (registration never opens the parquet, and the removed/verifywas metadata-only). Both refusals are implemented and tested induckdb-client/, and COMPACTION enforces them server-side as well — it is the one server surface that does open the parquet, soParquetRewriter.rowIdCarrierrefuses both directions before a rewrite can launder a file that disagrees with its registration. The server also enforces the reserved_hogprefix that protects the carrier now (Identifiers.RESERVED_COLUMN_PREFIX, at every nesting level), so duckdb-client/DESIGN.md finding 9 is closed for names created through the DDL; files registered before the reservation, or written by a foreign writer, are still what the refusals above are for. -
One live deletion vector per data file (unique partial index); supersessions only grow (
delete_countmonotone); a DV newer than yourread_snapshotis a 409, never a lost update. -
Physical deletion is never authorized by the queue: cleanup liveness-checks every path against live references at drain time;
still_referenced > 0is an invariant violation, alerted, not deleted. Draining soft-deletes: settledhog_file_removalrows keepdrained_at/drained_outcome(the queryable forensics ledger, purged pastHOGLAKE_REMOVAL_LEDGER_RETENTION_SECONDS, default 30d); undrained rows accumulateattempts/last_attempt_at. The ledger is also commit-integrated both ways: commits 409 any registered path with an undrained row (path-reuse guard) and compaction pre-registers its output path as acompaction_stagingclaim settled'registered'on group commit — and only if cleanup has not TOUCHED that ticket. THE DRAIN IS A CLAIMED WORK QUEUE AND TAKES NO CATALOG LOCK ANYWHERE (V21): CLAIM in its own transaction committed before any object-store call, WORK with nothing open, SETTLE fenced onclaimed_by. A claim is a LEASE (HOGLAKE_CLEANUP_CLAIM_LEASE_SECONDS, 900), not a lock, and theclaimed_byfence is what stops a lapsed worker writing the ledger over the worker that took its row. THE LEASE IS CLEANUP'S ALONE:commitGroupre-reads its staging ticketFOR UPDATEand takes it only if NOBODY HAS TOUCHED IT, because an expired claim does not mean the object survived — it means nobody knows. The proof — the four-inserters-three-serializers argument, thehog_uploadrow-lock arm, the staging carve-out, theDeleteObjectsceiling, the ledger-purge shape and the production measurements — is in server/README.md §Retention, expiry, and safe file removal, which is the single home for it. -
Expiry never passes head or (when
consumer_floor) the min consumer offset, and names the pinning consumer. Ranges belowearliest_snapshot_idare 410 Gone — consumers reconcile, never silently skip; the floor advance captureshog_catalog.earliest_snapshot_timeso 410s can say WHEN the floor was reached. A fifth sweep step deletes versioned DDL rows (hog_table_version/hog_column/hog_sort_spec/hog_view/hog_table_layout) whoseend_snapshot <= earliest_snapshot_id— invisible at every retained snapshot, so DDL churn cannot grow them unbounded.hog_partition_specis deliberately kept (ExpiryService.VERSIONED_TABLES_NEVER_CLEARED): file rows name their spec byspec_idat every snapshot and spec ids areMAX(spec_id) + 1, so deleting a retired spec would break the live files written under it, and relabel them when it held the table's highest id. The FILE rows below the floor are the exception, and deliberately: a sweep advances the floor under the commit lock and then purgeshog_data_file/hog_delete_filein bounded pages OUTSIDE it, so an ended row below the floor is legitimate state for a few sweeps. It is unreadable (410) and immutable while it sits there, and each page queues its paths in the same statement that deletes its rows. NOTHING ASSERTS THE INVARIANT HALF OF THIS ANY MORE: #262 gated/verify'sexpiry_floorfile arm on the ledger row reporting the purge drained, precisely so it kept catching a drained purge that still left rows below the floor (its predicate and the floor advance disagreeing) without alerting on the designed lag — and #261 removed the check. UNWATCHED UNTIL #261 ships the paged scrubber. The BACKLOG half still works and never needed verify:purge_truncated,purge_remainingandpurge_failureson the ledger row,hoglake_expiry_purge_truncated_totalandhoglake_expiry_purge_remaining. server/README.md §Retention has the rate arithmetic and the 2026-10-01 incident it comes from. -
Versioned-row visibility: a row is visible at S iff
begin_snapshot <= S AND (end_snapshot IS NULL OR S < end_snapshot). Every read path uses exactly this predicate. -
TableInfo aggregates never come from
hog_table_stats(that row is the gross append counter / row-id allocator anchor — head-scoped by nature). Where they DO come from is now the request's own shape (#232), and the response says which:snapshot/at_timestampgiven: the files visible AT THAT SNAPSHOT, aggregated from the manifest (FileRepo.aggregateAt). Exact, and the only correct answer for a past snapshot. Same for a createTable/alterTable receipt, whose snapshot its own transaction just made.- neither: the MAINTENANCE SAMPLER's published generation, summed per
table (
TierTotalsRepo), because the maintenance section's rule below — persisted summaries, never the manifest — applies to this endpoint too: the writer fleet calls it three times per flush and the aggregate it replaced was ~10M manifest rows per call. The response carriestotals_snapshot_id(the snapshot the numbers are exact at — or, for a generation whose scan expiry overtook and re-anchored, the start of the window they were observed over; seeMaintenanceSummarySampler) andtotals_as_of; all three totals are ABSENT, never 0, when the published generation does not cover the table. totals=false: absent, and no file read of any kind. The identity read.read_snapshot_idis present on every one of these paths — it describes the read, not the totals, and a writer sends it back as a commit'sread_snapshot.
THE NAMESPACE LISTING (
TableSummary) IS NOT ON THIS RULE YET: it still aggregates the manifest per table throughLIVE_SUMMARIES_SQL's LATERAL, and its three totals stay required and exact at head. So the table GET and the listing can disagree by the sample's age for the same table; the OpenAPITableschema states the asymmetry, and moving the listing ontoTierTotalsRepo.PER_TABLE_SQLis its own change. -
Audit/observability never rides a transaction and never writes to any database. Audit emits after commit/rollback; metrics are passive. Maintenance run history and asynchronous summaries are durable operational state; run-history writes are best-effort after task transactions resolve. The removal ledger remains transactionally integrated with commits and cleanup, as invariant 4 requires.
-
All SQL is parameterized. No string-built values, anywhere.
-
Rows-then-offset everywhere (server offset API is monotonic; hedgerow commits offsets only after destination durability).
-
The table is the authority: no code path may treat a dropped table's file rows as reachable data. Table state is established BEFORE file rows are read, written or counted.
DROP TABLEis O(columns) —TableRepo.markDroppedsetshog_table.dropped_snapshotand end-snapshots the one live version row and the column rows, and touches NOhog_data_fileorhog_delete_filerow. It used to end-snapshot all of them in the same transaction, under the per-catalog commit lock: 3,008,849 rows measured at 44.6 s and 3.9 GB of WAL warm and uncontended, which on gigahog-prod-us was a drop that could not complete at all (#193). The rows leave later, paced, throughRetirementService, and only oncedropped_snapshot <= hog_catalog.earliest_snapshot_id— above the floor a read at S < drop is still legal and still needs them. One predicate expresses the rule (t.dropped_snapshot IS NULL, or:snapshot < t.dropped_snapshotfor a time-travel read) and every resolver, loop, gauge and check below uses it:TableRepo.findLive/findAt, the commit read'sresolvedCTE (CommitTail.READ_SQL),CompactionService's planner AND its commit re-verification,Hydrator.claimPending/rehydrateFailed,CatalogMetrics's sample,MaintenanceSummarySampler's scan. THREE CARVE-OUTS, and they are the whole list:- path-keyed liveness (
CleanupService.referencedPaths,UploadService's reclaim/register probes) asks "does ANY row name this path", live or not, and MUST keep seeing dropped tables' rows: that is what fences their objects against physical deletion until retirement queues them; - the retirement loop itself, whose entire job is those rows;
- maintenance surfaces that count rows at NO snapshot (the
hydrator, the gauges, the debt sampler) filter on
hog_tablerather than resolving visibility at a snapshot, because there is no snapshot to resolve at. TRUNCATE IS NOT COVERED.CatalogService.truncateTableis the one remaining caller ofFileRepo.endLiveFiles/endLiveDeleteFilesand keeps the O(rows) pass under the commit lock;POST .../truncateon a multi-million-row table has today's hazard, and redesigning it is its own change.
- path-keyed liveness (
-
A file's partition values are valid only under the spec they were computed with, and the server cannot check them: it never opens the parquet (footer-shipping), so it can neither verify nor recompute a transform, and
CommitService.validateFiles' arity check cannot tell two same-arity specs apart.read_snapshotis therefore the whole guard, and an append whose files carrypartition_valuesNEEDS one — a blind append has no conflict window at all, so a spec change between the writer's read and its commit would register the old transform's values under the newspec_idwith nothing afterwards able to detect it. With one, the change ischeckConflicts' DDL arm. The REFUSAL is staged, not immediate:HOGLAKE_REFUSE_BLIND_PARTITIONED_APPENDS(default false) makes it the 422 the contract describes, and until then the shape is accepted and logged at WARN once per RESOLVED table per pod, naming the client and quoting the refusal it will get. (Once per resolved table, not per requested name: the dedupe key is the server'stableId, because a key holding anything a client supplies — a User-Agent, anamespace.tablestring — lets one client fill the cap and silence the signal for the whole fleet.) The flag exists because every production flush is that shape today. millpond is the primary blind writer:prepare_append_filesputs aread_snapshoton the payload and millpond deletes it (millpond/hoglake.py,payload.pop("read_snapshot", None)), because a prepared payload's basis is frozen and the 409 it earned when another pod added a column was permanent.duckdb-clientis the second — append-only commits carry noread_snapshot(storage/hoglake_transaction.cpp) and partition values ride whenever the table has a live spec (storage/hoglake_insert.cpp) — so enforcing this in the same change as the server would break both millpond's flush andINSERT INTO <partitioned table>through the extension. THE FLIP PRECONDITION is therefore two-part: millpond keeps the field (safe now, and not before —ddl_since_read_snapshotsubclassesCommitConflictError, which millpond'sis_retryableladder already recovers from byreset_caches+ dropping the refused payload, so the re-upload it was avoiding costs one flush rather than wedging), and duckdb-client starts sending one. The rule is not optional; the rollout order is. WHEN to flip is read offhoglake_blind_partitioned_appends_total{catalog,namespace,table}, which counts every occurrence and is deliberately outside the WARN's dedupe: a line that fires once per pod cannot distinguish a fixed client from a pod that already logged it, and the counter keeps counting after the flip.checkConflictsalso runs BEFOREvalidateFiles, deliberately: a DDL change and the file-level symptom it produces (stats naming a dropped field, the wrong arity, values on a now-unpartitioned table) arrive together, and the CAUSE has to answer before the SYMPTOM — a 422 tells a caching writer nothing about its stale basis, so it rebuilds the same doomed payload until the cache ages out. That arm is TYPED: when every conflicted row is DDL it isHoglakeException.DdlSinceReadSnapshot-> 409ddl_since_read_snapshotcarryingtables,read_snapshotandretry: re-prepare, never the retryablecommit_conflict. The distinction is the point: a prepared request'sread_snapshotis part of a durable payload that must be replayed byte-identically, so the refusal is permanent for that payload and a retry loop on it is a livelock. Row-content conflicts keepcommit_conflict, and so does a mixed refusal (all { ddl }, notany) — a plain retry clears those. Theexpected_table_uuidguard joins the same family:HoglakeException.TableRecreated-> 409table_recreated, because the incarnation the caller named is gone and its history does not carry over (it was aCommitConflict, and pyhoglake could only tell it apart by grepping the detail string for "the table was recreated"). So does the below-floorExpired410. Three codes, one recovery: re-read the table and prepare a new request. Andtable_recreatedis the ONLY guard against a drop+recreate —checkConflictskeys on the RESOLVED table id and countstable_createdonly for a guarded request's delete targets, so a recreate is outside an append's window however fresh itsread_snapshotis.DdlSinceReadSnapshotis a SUBCLASS ofCommitConflict, and that is load-bearing rather than tidy: clients discriminate withisinstanceladders (millpond's retry budget does, and it already recovers correctly by resetting its caches on aCommitConflict), so un-subclassing would turn a working recovery into a hard re-raise. The wire CODE is what changed. Everywhenover the hierarchy must therefore put the subclass arm FIRST —ErrorMapping,Metrics.commitFailureResultandAudit.failureOutcomeall do, and each says so.
Three outages in one week came from the same mistake, and none of them was a wrong query. Each was a correct query, a correct loop or a correct lock written for a catalog of thousands of files and run against ten million:
- 2026-09-28, expiry. One sweep deleted every ended file row below the new floor in one statement, under the per-catalog commit lock, in compaction-commit order (random heap reads). ~50k files per sweep at 700-870 µs each; the 60 s statement timeout fired 195 times in 200 sweeps, each failure holding the lock the full 60 s. Mean commit wait 13.5 s, API pods liveness-killed all day.
- 2026-09-29, cleanup. The drain re-checked every path's liveness under the commit lock: ~19 s per 1,000 paths on a table whose hot set does not fit the cache, every commit queued behind it. The lock protected nothing (V21). Cleanup was off in production until it came out, and is ON in prod-us since 2026-09-29 at 60 s / batch 10,000 / 1 worker.
- 2026-09-30, compaction (#247, shipped in 1.3.6; the other two
shipped as #220, #225). The planner loaded every small file of a
table (9.9M rows, a correlated
array_aggper row, anORDER BY) into a Kotlin list inside one transaction, then bin-packed in memory for minutes.idle_in_transaction_session_timeoutkilled the connection at 30 s; every sweep failed for eleven hours. The groups it planned were then refused anyway: packed by bytes, checked by rows, 2.9M rows against a ceiling of 552k. - 2026-09-30 again, 55 minutes after #247 rolled (#255). The fix
raised fan-in from 64 to 2,048 files per group and measured one
thing in the per-group path: the commit-lock hold, on a cache-hot
fixture. The same path read the inputs'
hog_file_column_statsrows to build the output's stats: 2,048 index descents, ~53k heap rows on a 66 GiB table, and it crossed the 60 sstatement_timeoutonce the rotation cursor reached colder buckets. Athrowinside a catch arm then bypassed the sibling arm that counts a failed group, so one group's timeout aborted the whole sweep with an empty ledger row, seven runs in a row. The full suite was green at 2,149 tests. Both defects showed in under a minute on the compose stack with four tables and a trigger that failed one output insert:maindied with zero outputs, the branch recorded one failed group and committed the rest.
The numbers to design against are production's, not the fixture's.
gigahog-prod-us on 2026-09-30: one catalog, ~500k snapshots, retention
3,600 s, ~14M live hog_data_file rows, 10M of them on one table
across ~2,800 partitions, 96% of them under 60 KiB; ~50 commits/min of
~270 files × 25 columns each, rising 4-5× with pyhoglake's concurrent
uploads; ~3,600 files added per minute; compaction retiring 64 files
per 4-minute run. The pod it all runs on: one maintenance replica with
dbPoolSize raised to 16, which is what makes 6 compaction groups plus
a cleanup worker legal against the reserve of 4. (That was 2026-09-30.
By 2026-10-21 gigahog-maintenance-compaction ran 8 replicas, nine
compaction loops in all, and the planners herded on one catalog — see
the compaction bullet under Known deferrals. A per-pod in-memory loop
is per-pod times N once the Deployment scales; ask what N of it do
together.) Any code path that is
O(files of a table), O(snapshots) or O(commits) is O(ten million) here,
and the growth rates are as important as the counts. Note also that
these are PROD-US numbers and prod-us settings: dev and prod-eu carry no
maintenance: block at all, so they run the chart defaults, and every
tuning figure in this section and in server/README §Retention is
prod-us-only.
The rules. Every one of them was violated by the code above.
- Bound every fetch. No statement on a maintenance or request path
may read an unbounded row set into memory. Every candidate, victim or
work-queue read must carry a
LIMITsized from the work the run can actually do (compaction:maxGroupsPerRun × maxInputFiles; cleanup: the sub-batch; expiry: a file-count batch), and the ledger must record when the limit truncated. Compaction's candidate read does not yet — it is the 2026-09-30 shape above, and the branch named there is where it gets one. Selecting from a per-partition summary (the sampler tier) and then fetching rows for the chosen buckets is the shape; "select everything and filter in Kotlin" is not. - Bound every unit of work under a lock or inside a transaction.
A statement under the per-catalog commit lock, or inside any
transaction, has a row bound and a
SET LOCAL statement_timeoutsmaller than the lock's fair share. Loops of bounded steps, each its own transaction, with a run budget and a pause (the retirement shape), never one statement that is "done when it is done". A read that takes several statements to answer one request (partition lookup) takes one deadline before it borrows a connection and sets each statement's timeout to the time remaining, so the bound is per request, not per statement. - Never hold a transaction across non-database work. Parquet I/O,
object-store calls, in-memory sorting and packing, HTTP calls: all
of it happens between transactions, never inside one. Read what you
need, commit, compute, open a new transaction for the write, and
re-check under it what could have changed (liveness, claims). The
test suite enforces this with
PgTestSupport's default 2 sidle_in_transaction_session_timeoutguard. Tests that need production's statement bound opt intoproductionSession = true: a 60 sstatement_timeout, with the default 2 s idle guard still applied. The production statement bound is opt-in because bulk fixtures may take longer on a slow machine. Cleanup's object-store calls happen after its claim commits and before its settle transaction opens, so the idle guard does not constrain them. Do not raise the value to make a test pass; split the transaction. - Measure per-row cost, not per-statement cost. A statement's plan says which index it uses; the per-row cost on production's access pattern (random heap reads on a 10M-row table versus PK-order reads) is what decides whether a 50k-row batch takes 1 s or 50 s. Expiry's 700 µs/file versus retirement's 20 µs/row for the same CTE was the whole 2026-09-28 incident. State the per-row figure and the batch that fits the budget in the KDoc.
- Prove the plan on a production-shaped fixture. "An index proves itself against the query it serves" (below) is necessary, not sufficient: a fixture of a few thousand rows proves nothing about a skip scan, a generic-plan flip after pgjdbc's fifth execution, or a correlated subquery. Plan tests for a hot statement seed at least 100k rows in the shape production has (the events table's partition skew, mostly-live files, retained history) and assert rows examined and buffers, not only the index name. Record the measured figure in the test and the KDoc, with the fixture size.
- Run it on the local stack before it ships. The suite proves
statements and functions; it does not prove the path. A change to a
migration, a maintenance loop, the commit path, or any statement
over the manifest tables is run end to end on the compose stack
(
just upbuilds the server image from the working tree; the harness in #255's PR body is the shape) before the PR is opened: the migration applied to a database that already holds data, the loop driven through its API trigger with the knobs the PR changes set to their production values, a fault injected where production will inject one (a trigger that raises on an insert, astatement_timeoutof 1 ms, an object missing from the store), and the ledger, the file rows and the output footers read back. When the change fixes an incident, runmainthrough the same harness first so the PR shows the before and the after. The compose stack's data is small, so it will not reproduce a cost that only exists at ten million rows; that is what the plan test above is for. What it does reproduce is everything a unit fixture mocks away: boot, Flyway, the pool and its session bounds, the real object store, a sweep's accounting when one unit of work fails, and what the console shows for it. The PR body says what ran and what it showed; "the suite is green" is not an answer to this question. - Do the growth arithmetic for anything written per commit or per
file. Rows per file per commit × files per commit × commits per
minute × retention, in bytes on disk, before the change ships.
hog_commit_receiptstored 566 KB per 270-file commit and nothing purged it — ~40 GB/day, 58.2 GiB standing when #240 found it. It now stores a 33-byte digest instead of the body and expires atHOGLAKE_RECEIPT_RETENTION_SECONDS(7 days), purged in bounded pages by the cleanup sweep (V24). Column stats are 25 rows per file and are still unbounded. Every such table needs a retention and a bounded purge from the day it is created — bounded, not necessarily PK-walking: the removal-ledger purge walks its primary key because its predicate (drained_at) is uncorrelated with that key, so pages can purge nothing and the walk needs a cursor and a skip cap. The receipt purge walks(catalog_id, created_at)instead, because the predicate IS the indexed column and the eligible rows are therefore a dense prefix — no cursor, no skip, andpurged < pagemeans the end. Pick whichever makes the eligible set an index range; what is not negotiable is that a page bounds the rows EXAMINED and that the statement carries its ownstatement_timeout, because a page's cost is not always its row count (a legacy receipt's ~160 KiB body is ~80 synchronous TOAST-chunk deletes on top of its heap delete). - Size groups by every dimension a downstream bound checks. If a later stage refuses on rows, pack by rows and bytes; if it refuses on heap, pack by the estimate it will apply. A planner that packs by one dimension and refuses on another does nothing forever and says so in a WARN nobody reads.
- Stage every refusal that a live client could hit. A new 4xx on a
path a deployed writer uses ships behind a flag (default off) with a
counter that shows the fleet has stopped sending the shape, and only
then flips.
HOGLAKE_REFUSE_BLIND_PARTITIONED_APPENDSis the model; millpond strippingread_snapshotfrom every payload was found by a review, not by the flag. - Fanout is the multiplier. Files per commit is set by partitions
touched, not rows per flush, so a faster writer produces more files,
more stats rows, more change rows and smaller files, not bigger
ones. When a change raises the write rate, re-run the arithmetic
for expiry (
HOGLAKE_EXPIRY_BATCH × 60 / intervalmust exceed the commit rate), compaction throughput, receipt growth and lock duty cycle (hold time per commit × commits per minute).
Before opening a PR that touches a maintenance loop, the commit path,
or any statement over hog_data_file, hog_snapshot_change,
hog_file_partition_value or a stats table, the PR body answers:
what bounds this per run, what bounds it per transaction, what the
per-row cost is on production's access pattern, what the plan test's
fixture size is, what grows per commit and how it is purged, and what
ran on the local stack and what it showed.
hoglake has two catalog stores behind one REST contract. PostgreSQL holds
a few large catalogs in one shared database. Hoglite holds each catalog in
its own SQLite tenant on hoglite,
for very many small ones (README "Backends: PostgreSQL and Hoglite"). A
feature that works on PostgreSQL is not done until it works on Hoglite,
or until the PR says, in its body and in the docs, that it is
PostgreSQL-only and why. Hoglite is not a port to catch up on later: the
parity review of 2026-11-19 found 28 gaps (issues #666 to #693, label
hoglite), every one of them a PostgreSQL feature that shipped without
its Hoglite half.
Rules.
- Design for both stores. Every change to the catalog model, the commit path, a read, a maintenance task, auth, routing or an error code states its Hoglite behaviour in the PR body: implemented the same way, implemented differently (how, and what differs for a caller), or PostgreSQL-only (why, and what a Hoglite caller sees instead). "Not applicable" needs a reason.
- Test parity. A behaviour tested on PostgreSQL is tested on Hoglite
in the same PR. Prefer one test parameterized over both backends (the
pattern of
HogliteCommitParityIntegrationTest,HogliteScanStatsParityIntegrationTestand the other*Parity*classes) to two tests that drift apart. A Hoglite live class is namedcom.posthog.hoglake.hoglite.*IntegrationTest, sohoglite-liveruns it. Assert the same status, error code and body on both, not "not a conflict". - Schema changes reach the tenant. A PostgreSQL migration that adds a
table, column, constraint, index, vocabulary value (maintenance task,
change kind, removal reason) or foreign key has a Hoglite counterpart in
HogliteSchema.ktin the same PR. Tenants have no migrations yet (HogliteSchema.ktKDoc), so any change to a released tenant shape also needs the tenant-upgrade path the KDoc demands. - Run it.
just test-hoglite(a Linux container with the newest testedhoglited) is part of the pre-push checklist for any server change. On macOSjust testskips the hoglite live classes, and a skipped class is not a passing one.
What review looks for. Each of these shipped once without its Hoglite half. Look for the same shape in new code:
| Missed on Hoglite | Example |
|---|---|
| A guard PostgreSQL enforces in SQL, a constraint or a lock | No data_path overlap check at catalog create (#666); no foreign keys or cascades in the tenant schema, and 5 CHECKs against PostgreSQL's ~75 |
| A check that assumes one database sees every catalog | PostgreSQL's overlap and name checks cannot see Hoglite tenants; names are not unique across backends (#689) |
| Authority that comes from a row the tenant can write | meta.data_path and removals rows steer hoglake's S3 deletes and writes (#668); meta.name never compared with the requested catalog (#670) |
| Auth rules that differ between hoglake and hoglite | A catalog-bound operator token was fleet-wide in hoglake until #667 bound it as hoglite does; tokens hoglake accepts and hoglite refuses (#681); the token re-verified on every hop, so long operations fail midway (#680) |
| A background loop with no Hoglite driver | Retirement unreachable, so a catalog with a dropped table can never be dropped (#674); no hydration, so pending files never get stats (#675) |
| Audit, metrics or status emitted only on the PostgreSQL path | Most Hoglite mutations unaudited (#676); Hoglite catalogs absent from per-catalog gauges, fleet status and hoglake_commits_total (#677); configured loop intervals reported for loops that never run (#690) |
| Retries and idempotency | A 503 commit_outcome_unknown that may be durable, retried blindly by a client (#669); non-commit writes with a fresh txid per call (#682); a drop that fences and then fails half-way (#683) |
| Clocks and precision | Snapshot time from the JVM clock at transaction build (#672); millisecond timestamps against PostgreSQL's microseconds (#673); upload expiry on each replica's clock |
| SQL semantics that differ between SQLite and PostgreSQL | BINARY text ordering and NULLs first (#671); rowid reuse where PostgreSQL has sequences; UTF-16 lengths; no REGEXP in CHECKs; IN passing NULL |
| Limits PostgreSQL does not have | hoglited's 64 MiB /tx body (#684), 100k rows / 64 MiB / 5 s per query (#686), scan refusals PostgreSQL serves (#685) |
| A guard scoped to the catalog where PostgreSQL scopes it to the table | A width-changing promote fenced on meta.next_file_id fails on any busy catalog (#687) |
| Error codes and check order | 404/409 on Hoglite where PostgreSQL answers 422, and the read-snapshot check before table resolution (#688) |
| Shared resources | One unhealthy Hoglite backend failing /healthz on every pod (#678); Hoglite calls sharing the request threads and breaker with PostgreSQL (#679) |
| A test that exists for one backend only | Time travel by timestamp, changefeed semantics, sort order, object-prefix commits, uploads, views and the contract-shape *SpecParityTest classes are PostgreSQL-only (#693) |
- Dependency versions are looked up, never recalled. When adding or
pinning a dependency, verify the latest stable version against its
registry (Maven Central, npm, PyPI) at that moment — a version
written from memory is stale by your knowledge horizon, silently
(the original dependency set arrived up to 17 months old this way,
and security scanning never notices staleness without a CVE).
Dependabot version updates (.github/dependabot.yml) backstop this
weekly; grouped minor/patch PRs get a normal review, majors get
their own. Python is ONE uv entry at
/(the workspace root and its one lock), so a bump lands in every member's lock at once. - Migrations: plain SQL in
server/src/main/resources/db/migration/. The chain is append-only as of v1.0.0 (2026-09-11, the Gigahog deploy):V1__init.sqlis FROZEN — never edit it; schema changes are newV<n>__migrations, andschema.sqlmust equal the fold of the whole chain (the equivalence test enforces it). There is noV5__— the number is skipped, which Flyway allows and which nothing in the repo explains; it is not a missing file. FKs with CASCADE, partial indexes for hot predicates, CHECK-constrained vocabularies (deliberate choice over PG enums while the vocabulary churns). No migration ledger hacks — Flyway owns it.- Every heavy-lock statement runs inside the
lock_timeoutwindow.ALTER TABLE(ADD COLUMN included — it is ACCESS EXCLUSIVE even when metadata-only),ADD/DROP CONSTRAINT,DROP INDEXand any backfillUPDATEsit after the V9 save+SET lock_timeout = '5s'and before the restore; onlyCREATE INDEX CONCURRENTLYandDROP INDEX CONCURRENTLYsit outside it, because both wait out older transactions by design (a wait a 5 slock_timeoutwould abort while a hydrator sweep holds the index) and neither blocks a write while they wait. A migration session has nolock_timeoutof its own, so an unguarded ALTER queues behind one in-flight commit for up to the statement timeout and every reader queues behind IT, while every other booting pod waits on the Flyway advisory lock. V10 put its ADD COLUMN after the restore, V11 and V12 had no guard at all, and V14's first draft repeated it. A CHECK over a table that is not known-tiny isNOT VALIDthenVALIDATE CONSTRAINT.MigrationLockWindowTestnow READS the files (V14 and up; V9-V13 are grandfathered, V10-V12 being the recorded violations) and reds on a heavy statement outside the window, on a missing window, and onSET LOCALin a file Flyway runs outside a transaction — where it applies to nothing. Deleting the save/restore pair from a migration used to leave the whole suite green, which is why the rule was broken four times and caught by review four times. CREATE INDEX CONCURRENTLYis not the safe default; it is a trade, and it is measured PER MIGRATION. The exemption above says CIC MAY sit outside the window, not that it should be preferred. Both halves are table-size questions and neither answer transfers: on a small table a plain build can be no slower than CIC and one pass instead of two (V16 blocks), while on the manifest a plain build blocks every commit in the fleet past the admission bound (V17 does not). State the measurement in the file, from a run rather than from the neighbouring migration; each migration carries its own figures. A blocking build's cost is seconds of blocked writes inside the 5 s window (V13's/V16's transactional shape, where a failure rolls back and writes no history row). A CIC's cost is that its phases WAIT OUT every transaction older than themselves, and a parked build is a pod that never binds:Main.ktmigrates before the listener opens, and the chart's startup probe SIGKILLs at 30 x 5 s. Hoglake's own parker is gone —Database.awaitMigrationLockpollspg_try_advisory_lockinstead of blocking inside it, because a blocked lock wait is an open statement with a live xmin and CIC parked behind a replica waiting on the very migration CIC belongs to (a CHAIN, not a cycle, so the deadlock detector never fires). What remains are FOREIGN snapshots — an operator's psql in a transaction,pg_dump, an RDS export, a logical-decoding reader — none of which carry hoglake's idle bound. So a CIC on a big table is announced in its file as an OUT-OF-BAND step (CREATE INDEX CONCURRENTLY IF NOT EXISTS, run before promoting, after checkingpg_stat_activityfor old transactions), which makes the migration a no-op; V17's header carries the statements. Every cancelled build leaves an INVALID index, so a file that builds concurrently clears one first —CREATE INDEX CONCURRENTLY IF NOT EXISTSmatches on NAME and would skip it forever.- An index proves itself against the query it serves. The
migration test runs the migration FILE (
Database.migrate()afterPgTestSupport.freshDatabaseAt(<previous version>), or after deleting the history row) against rows inserted BEFORE it, thenANALYZEs andEXPLAINs the production statement — the repo function's own SQL, exposedinternal— asserting the index name appears andSeq Scanon the table does not. V14's first index was on the wrong column of a recursive join, and its test was green because it EXPLAINed a predicate no code path issues. A partial predicate is asserted throughpg_index.indpred, not by counting table rows, and the KEY throughpg_index.indkeyresolved to attribute names — acontains("catalog_id", "path")overpg_get_indexdefis satisfied by the index's own NAME. The index name and the absence ofSeq Scanare the weakest assertions available, and V16 has the proof: rewriting its guard topath LIKE ANY(...)— which no btree under a non-C collation can drive — still producedIndex Only Scan using hog_file_removal_undrained_path, because the leadingcatalog_idwas enough, withpathdemoted to a Filter. What separates the two is what the scan DID:Index Searches(one descent per probe key, not one for the whole statement) and the ABSENCE ofRows Removed by Filter. Take buffers from the SCAN NODE, not the plan's maximum — EXPLAIN'sPlanning:section carries aBuffers:line that dwarfed a well-indexed scan's — and derive the budget from the probe rather than writing a constant: the constant V16 started with sat 1.27x below the degraded plan it had to exclude. The probe set itself must be SCATTERED, as a commit's output paths are; sixty-four keys sharing a prefix let the btree descend twice and walk, which made the measurement four times kinder than the real statement. hog_file_removalis indexed BOTH ways —..._drain (catalog_id, removal_id)for the cleanup drain's ordered LIMIT and..._undrained_path (catalog_id, path)for the commit path's path-reuse guard andUploadService's reclaim probe (V16, #199: without it every commit read the catalog's whole queue). Both are partial ondrained_at IS NULL, and the path one is deliberately NOT unique: nothing makes a file path unique, so expiry can queue one path twice from oneDELETE ... RETURNING, and with no writer carryingON CONFLICTa unique violation would abort the sweep that advances the retention floor. The OTHER half of that statement pair ishog_data_file_path/hog_delete_file_path(catalog_id, path) (V17): the drain's liveness check asks those two tables the same question once per sub-batch, and until V17 both legs were a full scan of the manifest (the V17 file carries the buffer counts). NOT partial, because the check covers "any file row, live or not".hog_upload's leg needs nothing:UNIQUE (catalog_id, path)(V12) is already that key, and its fallback is bounded by the catalog's ACTIVE claims rather than by an append-only history. The index is paid on the hottest write in the system, and it is builtCONCURRENTLYbecause at that size a plain build blocks every commit past the admission bound — which reverses V16's trade on measurement rather than on analogy. What makes a concurrent build safe to deploy, and what still cannot make it safe on its own, is the CIC rule above.hog_data_file_ended (catalog_id, end_snapshot) WHERE end_snapshot IS NOT NULL(V19, #193) is the third entry, and the one that INVERTS V17's partial-index decision for a reason rather than a preference. It servesExpiryService.DATA_FILE_EXPIRY_SQL— the sweep's data-file DELETE, which carriesend_snapshot IS NOT NULL AND end_snapshot <= floorand, before V19, matched NO index's leading columns at all:hog_data_file_liveis partial on the COMPLEMENT of those rows, and everything else leads on ids or paths. So the statement was a sequential scan of the whole manifest, inside the sweep transaction, under the per-catalog commit lock. Measured on a fixture with production's mostly-live ratio (200,000 rows / 4,445 heap pages, 4,000 of them ended — one row in every hundred, the fraction the test'sENDED_EVERYfixes;V19DataFileEndedIndexMigrationIntegrationTestruns the migration against rows seeded BEFORE it and EXPLAINs the repo's owninternalconstant) with the ended rows SCATTERED through the manifest, scan node only: 4,445 buffers as aSeq ScanwithRows Removed by Filter: 198,000-> 2,003 buffers as anIndex Scan using hog_data_file_endedwithIndex Searches: 1and nothing filtered — 2.2x at a 1.0% ended fraction. THE SCATTER IS THE MEASUREMENT. An earlier draft clustered the ended rows and read 91x, which was an artifact of insert order: contiguous rows share heap pages. Production's ended rows are wherever expiry and compaction left them, so the index path costs roughly ONE HEAP BUFFER PER ENDED ROW and the win isseq pages / ended rows— 2-6x at prod-us's standing 30-90k of ~5.0M, and a WASH right after a large batch of rows ends (measured at 300k scattered ended rows: 300,003 buffers with the index against 112,655 without, i.e. marginally slower). It is still the right index, because the steady state is the low fraction and because a sequential scan grows with the CATALOG while this grows with the WORK. It also does NOT bound the row work: the RI triggers for the three cascading children (~4 s per 300k rows against an EMPTY child table) and the CTE's tuplestore spilling atwork_mem4 MB are the dominant costs of that DELETE, and neither moves. (#419 measured the alternatives: an explicit dependent delete beside the cascade costs MORE — 112,564 against 83,436 buffers per 1,000-file page — because the trigger still fires and re-reads the dead tuples; with the three FKsNOT ENFORCEDit saves 12% of the buffers and no reads. The page's cost is ~3.9 cold reads per file on the stats primary key, which no delete shape changes; neither shipped — server/README.md §Retention has the table.) PARTIAL here where V17's is not, because V17's statement covers "any file row, live or not" while this one carriesend_snapshot IS NOT NULLin its own text — and the rows the predicate excludes are the overwhelming majority (4.94M of gigahog-prod-us's ~5.0M are live), so the index holds only the ~30-90k ended rows at a measured 12 bytes each and AN APPENDED ROW NEVER ENTERS IT. The hottest write in the system pays nothing, which is the whole argument. BuiltCONCURRENTLYin V17's shape: the build is a full heap scan whatever the index holds, so at production size it is V17's 26-35 s and a plain build's SHARE lock would block every commit for it — and the cold estimate is a FLOOR: two heap passes over 1,491 MiB is ~24 s at an idle volume's 125 MB/s and 30-60 s on a busy one, against a 60 s session statement bound. NO MATCHING INDEX ONhog_delete_file— expiry's DV arm is anORwhose second arm is a correlatedEXISTSand the planner never chooses one for it, so an index there would be paid on every write and used by nothing; splitting that statement into two arms is the fix, and it is ticketed. V19 and V20 are both applied in all three environments; the general rule their split recorded stands. AnALTER TABLEmigration againsthog_tableMUST be timed, because an EXPIRY SWEEP HOLDS ACCESS SHARE ONhog_tablefor its whole transaction (step 5 deletes fromhog_table_version, whose FK references it), so a long sweep makes theSET LOCAL lock_timeout = '5s'fire, which rolls the migration back cleanly and crash-loops the pod until the sweep finishes — the designed behaviour, and a deploy that looks hung. Checkpg_stat_activityfor an in-flight sweep before promoting one, and do NOT raise retention to make the sweep easier: that makes it zero-work and the floor stops moving at all. A TRANSACTIONAL migration that fails rolls back and writes no history row and the next pod retries; a non-transactional one half-applied needsflyway repairbefore any replica can validate again.
- Every heavy-lock statement runs inside the
- Change kinds (
hog_snapshot_change.kind) are the typed OCC vocabulary; adding one = migration + schema.sql +ChangeKindenum + conflict-rule review inCommitService.object_idis ONE column over three disjoint id spaces — table, namespace, view — and only the kind says which, so any read that goes BY object id filters on kind or silently counts a namespace's history against a table that shares its id.ChangeKind.TABLE_SCOPEDis that filter, and it is an EXPLICIT list, notstartsWith("TABLE_"): a derived set cannot be checked, because any test would have to apply the same rule and agree with itself (the first version did, and a hypotheticalTABLE_NAMESPACE_MOVEDwould have joined the set and passed). Adding a kind therefore means classifying it inTABLE_SCOPEDorNON_TABLE_SCOPED;TableSummaryVocabularyTestasserts the two PARTITION schema.sql's vocabulary, so an unclassified kind reds and the author has to answer the question rather than inherit an answer. - A table's snapshots are defined through the change log, because
snapshots are CATALOG-wide.
TableSummary.snapshot_countis the number of distincthog_snapshot_change.snapshot_idvalues at or above the catalog'searliest_snapshot_idwhose row isTABLE_SCOPEDand names the table;earliest_snapshot_idis the smallest of them, null when none. Both are RETAINED-only by construction, so they shrink as expiry advances the floor — they answer "how far back can this table still be read", never "how many commits has it taken". One commit can write several change rows for one table in one snapshot (truncate writes two, an atomic replacement three), so the count isDISTINCTon the snapshot id and nothing else. The floor bound is DEFENCE rather than arithmetic: today'sExpiryServiceadvances the floor and deletes the snapshots below it in one transaction, andhog_snapshot_changecascades, so after a sweep there is nothing below the floor left to exclude and the bound is provably redundant. It stays because the alternative is a query whose correctness depends on that cascade with nothing saying so, and it is tested against the state it defends against (a floor moved ahead of its reclamation), not against a state the server produces. GET .../tablesis the one unpaged listing that scales with data. One row per live table, one statement, per-table work index-driven — linear in the namespace. Measured on a 54k-table namespace (270k files / 270k change rows, PG18, warm, serial): 389-402 ms, 595,488 shared buffers, 9.16 MiB of JSON, with the finalORDER BYspilling 595 temp blocks. The FILE rollup is 73% of the buffer traffic and the change-log lateral 27% — so the tempting optimisation is the wrong one: the change-log lateral's per-loop Sort (count(DISTINCT)cannot usehog_snapshot_change_conflict's snapshot_id ordering with the kind filter betweenobject_idandsnapshot_id) would cost a second index on the table every commit's OCC check writes, to save a quarter of a read path's buffers. The 9 MiB unpaged body is the real limit, and it is a shape problem, not a plan problem: PAGING is the follow-up. Numbers re-measured for this entry rather than carried over from the review that raised it — the review's differed (444 ms / 813k / 5.4 MiB), which is what happens to a number nobody re-runs.- Compaction is never a conflict, and only a race gets a retryable
status. Any guard that compares a writer's read set against
hog_snapshot_changeexcludestable_compacted(both the commit path and the guarded replacement publish): compaction changes no visible row, and a deletion vector whose target compaction retired is caught per file by the liveness check. On a table under continuous compaction (one group every ~2.6 min in production) anything that treats it as a conflict livelocks every statement longer than one interval — and did, for UPDATE/MERGE, from #161 until the post-merge review of #156–#162 caught it. A plan-to-commit race answers 409; 422 is for a request that was already wrong at its ownread_snapshot, andend_snapshot == read_snapshotis the 422 side of that line. A conflict test drives the real service between read and publish (CompactionService.compactPlannedGroup,ExpiryService.runOnce); seeding change rows by SQL asserts the rule you wrote, not the system, and passed a livelock. - Whatever mints a new identity releases the old one's consumers.
Consumer offsets pin expiry on purpose and survive drops on purpose;
atomic replacement mints a new
table_uuid, so a consumer's row on the retired uuid pinned the whole catalog forever with no delete API. Lineage between incarnations is RECORDED (hog_table.replaced_table_id, written by the replacement path) and walked from that column; it is never derived at run time from a convention such as "dropped in the snapshot the successor was created in", because a convention nothing enforces has a failure mode of deleting a consumer's position on a table it is still draining. The commit path walks backward from the table just committed (primary-key hops, zero in the normal case); the expiry sweep walks forward for every consumer as the catch-all for rows committed before the rule existed. - Stored payloads outlive the code that wrote them. JSON the server
writes and later reads back — commit receipts, table-creation
definitions, the maintenance ledger — is decoded with the lenient
stored-payload mapper (
WireJson.storedPayloadObjectMapper), never the strict API mapper, and every new defaulted field on a stored model is@JsonInclude(NON_DEFAULT). A rolling deploy has both versions replaying each other's rows; a receipt carrying"require_unchanged_tables": falsemade the older replica throw under the catalog lock and 500. The mixed-fleet case is a test with an unknown property at the top level AND nested inside a file entry. The API mapper stays strict: an unknown request field is a 400. - The per-catalog commit lock is for commits. Nothing acquires it
unless it allocates a snapshot or settles state inside a commit
transaction, and every acquirer passes
commitLockTimeoutMs— the default argument is an unbounded wait. Upload claims took it once per output file with no bound. Row-level state re-checks replace it: under READ COMMITTED anUPDATE ... WHERE state = 'active're-evaluates its predicate after waiting on the row lock, so a settle that landed first wins without any global lock; the predicate that selects candidates is the predicate that fences them, verbatim, or a renewal in the window is clobbered. Sweeps settle one row per transaction so a commit never queues behind a sweep while holding the commit lock. With no lock above them, claim rows need an order of their own: a statement that locks more than one takes them inupload_idorder, and updates them in a second statement (UploadService's class comment). Concurrent renewals of one owner deadlocked before they did. EVERY ACQUIRER IS OBSERVED AND SAYS WHAT IT IS (#439): it passes the catalog's name and aCommitLockPath(commit,compaction,expiry,retirement,ddl,drop), the lock statement itself is private toLocks, and the hold is settled on the JDBI handle's commit/rollback/close hooks rather than by the caller, so there is no release to forget.CommitLockCallSitesTestpins the path of every call site by file and function; a new acquirer edits that table, and adds aCommitLockPathonly when none of the six fits. What the series can see: the in-processhoglake_commit_lock_waiting/_held/_hold_seconds{path}see queueing between scrapes but only their own pod; the sampledhoglake_commit_lock_db_waiters/_db_held_secondssee every session (other pods, psql) but only at the metrics tick. server/README.md §Observability has the rest. - A new guard never edits an existing test out of its way. When a
new refusal reds a test, that test either asserts the refusal or has
its fixture changed to satisfy the guard legitimately, with the reason
in the test. Swapping
add_columnforset_sort_orderin two tests to keep them green (#159) hid that the guard fires on any table with hydration in flight. - PR-body claims are not evidence. Test counts, "adversarial review found no blocking issues" and "verified against Trino" are read as claims to verify from the code and the tests; a review that trusts them reviews nothing. Eight PRs each carried the clean-review line; three of them held the livelock, the 500 and the expiry pin above.
- Errors: services throw
HoglakeException.*; the API maps them (401/403/404/409/410/422; commit admission timeout 503 + Retry-After; parse failures 400). New failure modes get a typed exception, not a status code sprinkled in a route. - The request path never blocks the event loop, and the probe never
borrows a request connection (#218).
App.moduleinstalls ONE interceptor (api/BlockingDispatch.kt) that runs the rest of the pipeline — routing, the handler, serialization — under a bounded dispatcher ofHOGLAKE_REQUEST_THREADSthreads, defaultHOGLAKE_DB_POOL_SIZE. One seam, not ~90withContextcalls, because the failure mode of the per-handler form is a new route that looks like its neighbours and reintroduces the incident with nothing redding. The seam lives in its OWN PHASE inserted afterPlugins, not inPlugins: same-phase interceptors run in registration order, so atPluginsit shed AHEAD ofRequestIdand the 503 went out with noX-Request-Id— the response class most likely to be investigated being the one that could not be./healthz,/livezand/metricsBYPASS the dispatcher (PROBE_PATHS, matched on a path normalised for trailing slashes): they are the surfaces an operator reaches for exactly when the queue is longest. Excess requests QUEUE, and THE QUEUE IS BOUNDED BY AGE, NOT DEPTH. The wait is FROZEN at admission (RequestAdmission.admit), not read live, and the difference is not cosmetic: elapsed-since-dispatch grows with THE HANDLER'S OWN EXECUTION, soPOST .../maintenance/compact— a synchronous sweep on the handler thread — would take the lock with the 1 s floor for every group after the first 30 s of the run and 503 blaming a queue wait that never happened. One budget, charged once: the shed happens before a connection is borrowed, and the remainder is charged against the advisory-lock bound (RequestAdmission.remainingLockTimeoutMs, floored so a request never arrives with a useless remainder and never raised above a bound an operator set lower). TWO BOOT REFUSALS.HOGLAKE_REQUEST_THREADS > HOGLAKE_DB_POOL_SIZEis refused naming both knobs — handler threads above the pool queue insidegetConnectionand 500 after Hikari's 5 s bound instead of queueing in the dispatcher, which is the same argumentHOGLAKE_COMPACTION_PARALLEL_GROUPS' boot check makes — as are a dispatcher of zero threads, a probe timeout under Hikari's own 250 ms floor, and a call group of zero. The default reserves NOTHING for the background loops: on the API workload the chart turns them all off, but a pod that runs loops and serves traffic should setHOGLAKE_REQUEST_THREADSbelow the pool by the number of loops it runs. SHUTDOWN ORDER IS PART OF THE FIX:Main.ktstops the ENGINE first, then the metrics listener, and only then closes the loops and the pools, and both new pools close withshutdown()+ a bounded wait, falling back toshutdownNow()only when the wait expires — interrupting an in-flight commit to save a second of shutdown is the behaviour #218 complains about. The incident narrative, the Netty call-group floor, the probe's own pool and threads, and the full pool/dispatcher metric roster are in server/README.md §Background assembly and §Observability, which is the single home for them. The Ktor TEST ENGINE cannot see any of this: it has no call group and no event loop, so a blocked handler starves nothing and/healthzanswers whether or not the fix exists. The property is pinned against the REAL Netty engine on a real port (api/RequestDispatchIntegrationTest), and any future change to request dispatch belongs there too. - Background loops are coroutines: every periodic job (hydrator,
expiry, cleanup, compaction, retirement, reindex, metrics sampler,
maintenance_summary)
registers with
BackgroundLoops(one supervisor scope owned byApp.startBackground()) — never a raw daemon thread. Contracts:intervalMs <= 0= disabled; a failed iteration is logged + counted (hoglake_background_loop_failures_total{loop}) and the loop (and its siblings) keeps running; shutdown is structured and bounded (cancel + join, 5s hard cap). Tests drive the services'runOnce/sampleOnceentry points directly, not the scheduler. Every maintenance-task run — loop sweep or manual/maintenance/trigger — is recorded inhog_maintenance_runviaMaintenanceRunStore.recorded(the per-catalogrunOnceis the one funnel; the hydrator's instance-wide sweep fans out one row per claimed catalog). Recording is post-run and best-effort (never fails the task); the cleanup sweep purges rows pastHOGLAKE_MAINTENANCE_LEDGER_RETENTION_SECONDS(7d default), and commit receipts pastHOGLAKE_RECEIPT_RETENTION_SECONDS(7d, #240/V24 — floored per catalog at twice its snapshot retention and capped at 30 days, because a receipt purged inside a client's replay window turns that replay into a duplicate publication with nothing reporting it). Read side: per-catalogGET .../maintenance/status+/runsand the instance-wideGET /v1/maintenance/status+/runstwins (MaintenanceStatusService; batched reads independent of catalog count). Dashboard and partition-debt requests read persisted asynchronous summaries, NEVER the manifest — and since #232 that includes the TABLE GET's three totals, which sum the published generation's tier rows (TierTotalsRepo.PER_TABLE_SQL, the one per-table sum; the two per-partition-group readers share only its published-generation predicate,TierTotalsRepo.PUBLISHED_GENERATION_JOIN). Invariant 7 has the full contract, including what the response says about freshness and which endpoint is still exempt.MaintenanceSummarySamplercheckpoints keyset pages in(catalog, table, file_size_bytes, file_id)order — the order compaction bin-packs in (V10 indexes it) — carrying each bucket's partial group across pages inpending_max_bytes. Default row budget 10,000/tick, interval 1s, refresh delay 60s after a completed scan (HOGLAKE_MAINTENANCE_SUMMARY_*). Incomplete generations are never published; old samples remain visible with freshness timestamps. Expiry overtaking a scan RE-ANCHORS it (it used to restart it): the scan moves its visibility snapshot to head, counts it inscan_state/the sample'sreanchors(surfaced assample_reanchoredon/maintenance/status) and continues from its cursor. The restart never finished once a scan outlasted retention — millpond-prod-us (58 min scan, 3,600 s retention) and millrace-prod-us (600 s) published nothing from 2026-10-16 to 10-21. The cursor is over immutable keys, so no row is skipped or paged twice; a re-anchored generation's file measures and V27 totals are an observation over the scan window, and the sample'ssnapshotId/published_snapshotstay the scan's START (coverage, dropped-table subtraction and the planner's new-bucket bound read it). A policy change still restarts. The class KDoc has the argument and the error bound. The central status endpoint pages catalogs (50 default, max 100). The COMPACTION PLANNER's bucket list is the published generation's buckets MERGED with the buckets of live small files appended since that sample's start snapshot (CompactionService.newBuckets, one bounded read of the(catalog_id, table_id, begin_snapshot)range, newest first, capped atHOGLAKE_COMPACTION_NEW_BUCKET_WINDOW, 10,000 files, which on a hot table is a per-sweep cost because the window is full on every sweep): a generation cannot name a partition first written after its scan began, and on 2026-10-21 that was every partition millpond'sevents_rawhad gained in five days (5,036 live against the 1,794 the planner saw). One value order for the merged list, not new-first;mergeBuckets' KDoc says why.- Retirement (
MaintenanceTask.RETIREMENT, loopretirement, invariant 11) is the loop that deletes a dropped table's file rows and queues their objects.HOGLAKE_RETIREMENT_INTERVAL_MSis 0 = off by default, the position compaction takes and for a sharper reason: a batch TAKES THE PER-CATALOG COMMIT LOCK, hundreds of times per run, so on an API replica it would tax the commit tail it serves. The chart turns it on for the maintenance Deployment alone. There is no manual trigger and noPOST /maintenance/retire: the loop is the only driver, deliberately, because a trigger reaches every replica. The knobs, and every one of them is a TIME knob:HOGLAKE_RETIREMENT_BATCH(8,000 rows per transaction, a ~160 ms lock hold at the measured 19.6 us/row and 2,902 B of WAL per row —RetirementCostIntegrationTest, on a fixture with the production 9:1 stats ratio; the time moves with the machine and the WAL does not, so what CI asserts is that shared buffers per row (50.4) and WAL per row are FLAT in the batch size, and the microseconds are held to the same flatness only underHOGLAKE_MEASURE=1),HOGLAKE_RETIREMENT_PAUSE_MS(750, so an 18-25% duty cycle on the lock — a foreground commit's p99 tax is about one hold),HOGLAKE_RETIREMENT_RUN_BUDGET_MS(60,000 of wall clock per run per catalog, so a 50M-row table is paced by the interval rather than by one continuously-held run — there is no cursor to lose, the victim select is just "what is still live on this dropped table"), andHOGLAKE_RETIREMENT_QUEUE_CEILING(500,000 undrainedhog_file_removalrows, above which a run declines to start; ~125 hours of drain at the STANDING cleanup defaults, which makes it a circuit breaker there, and ~50 minutes at the runbook's event settings of 10,000 per 60 s, which makes it a throttle). IT IS CHECKED ONCE PER RUN, so the EFFECTIVE CAP IS ABOUT TWICE IT: a run that starts just under the ceiling commits ~528,000 more rows before the next one can stop it, so 500,000 admits a peak of ~1,030,000 undrained rows — about 631 MB ofhog_file_removalat 631 bytes per undrained row, not the ~315 MB the number alone suggests. Size storage against the doubled figure. A run the ceiling stops STILL STAMPSretirement_eligible_atfirst, so a wedged retirement is dateable rather than silent — the reader was/verify's orphans arm and #261 removed it, so the column is write-only until a scrubber replaces that check; andHOGLAKE_RETIREMENT_QUEUE_CEILING=0with the loop ON is REFUSED AT BOOT, because every run would skip forever with nothing saying so. THE ELAPSED TIME OF A LARGE RETIREMENT IS SET BY THE CLEANUP DRAIN, not by this loop's knobs, and the arithmetic is worth doing before touching either. One 60 s run is ~66 batches (a ~160 ms hold plus a 750 ms pause each, and the pause is charged against the budget because the budget is wall clock), so atHOGLAKE_RETIREMENT_BATCH8,000 a run retires ~528,000 rows and, at a 60 s interval plus a 60 s budget, lands every ~120 s — ~15.8M rows/hour of CAPACITY. The drain is 600,000 paths/hour at the event settings and 4,000/h at the standing ones, so retirement outruns it by more than an order of magnitude andHOGLAKE_RETIREMENT_QUEUE_CEILINGis what actually paces it: bursts of ~60 s of holds, once per ~50 minutes of drain. Elapsed time for a 3M-row table isqueued paths / cleanup rate— ~5 hours at the event settings — and shortening the interval or lengthening the budget does not move it. The only lever isHOGLAKE_CLEANUP_BATCH/HOGLAKE_CLEANUP_INTERVAL_MS. The candidate read and the eligibility stamp are bounded atRetirementService.MAX_TABLES_PER_RUN(1,000) tables per run, ordered bytable_idso the bound is a stable PREFIX: a mass drop on a 54,000-table catalog must not make a run that the budget stops after a handful of tables read and stamp all of them first. SINGLE FLIGHT per catalog through a SESSION advisory lock on its own lock class (Locks.tryAcquireCatalogRetirementLock): a second maintainer SKIPS rather than queues, because Postgres's lock queue is FIFO so W maintainers tax every foreground commit by(W - 0.5) x holdand the work is idempotent. A batch sets its own transaction-localstatement_timeout—min(session statement_timeout / 4, admission / 2). A batch it CANCELS IS COUNTED AND NOT RESIZED (#263): every batch of every table of every run runs atHOGLAKE_RETIREMENT_BATCH, the cancelled one rolls back whole, the table is left for the next run, and that run asks for the same rows at the same size. THE PER-ROW COST IS FLAT IN THE BATCH SIZE (RetirementCostIntegrationTest: 19.5 µs/row at 2,000 and 19.6 at 8,000), so a batch that crossed the bound crossed it COLD rather than big — and the cancelled statement warmed exactly the pages it touched, which makes the retry the cheap case. This loop used to halve instead, and that locked in a size chosen by the worst page of the night: on millpond-prod-us a 13.9M-row retirement walked from 8,000-row batches to 62 in its first cold hour and stayed there for a day (~4,700 rows per 60 s run, ~280k rows/hour against the ~15.8M/hour the defaults size for, the commit lock idle between ~0.1 s holds), and when the pod was restarted at 18:04 UTC on 2026-10-02 at a configured 1,000 it retired 36,000 rows in its first run and was back at 62 by 18:19. THE ONE CASE THAT NEEDS A HUMAN is a table that times out run after run — its per-row cascade does not fit the bound at this batch, and no retry will change that — so alert onhoglake_retirement_consecutive_timeouts{catalog,table}(RetirementGauges, a MultiGauge whose row exists only between a table's first timeout and its next NON-TIMEOUT outcome, so the series RETIRES on recovery and>= 3needs noforclause) and lowerHOGLAKE_RETIREMENT_BATCHon the instance that retires that catalog — the knob is process-wide.hoglake_retirement_timeouts_totalis the per-run rate and is deliberately NOT the alert: an occasional tick is a cache miss. The cost of not retrying in-run is stated rather than hidden: an intermittently cold table forfeits the rest of ONE run's budget per timeout, which on a one-table catalog is the whole run, and that is accepted — re-attempting on a busy RDS to exploit a maybe-warm page needs its own backoff and attempt cap for a hope rather than a plan. CleanupService's hold-budget arithmetic does not apply and no longer exists at all: a retirement connection makes no object-store calls, so it is never idle in transaction, and the drain those bounds were written for holds no lock any more (invariant 4). A batch deletes DELETION VECTORS FIRST, bydata_file_id, with NOend_snapshotclause — the data-file delete cascadeshog_delete_file, so any DV left when it runs is taken away UN-QUEUED and its puffin leaks forever (bug hunt #16's exact failure, carried forward). - Retirement feeds cleanup, and the two are coupled by the queue
ceiling. Every row a retirement batch deletes queues one path, and
the drain is much the slower of the two (
HOGLAKE_CLEANUP_BATCHperHOGLAKE_CLEANUP_INTERVAL_MS, against a sub-batch that has to pay oneDeleteObjectsround trip — timesHOGLAKE_CLEANUP_WORKERS, since the batch is a PER-WORKER budget and a worker's rate no longer costs anyone the commit lock). Unpaced, a 3M-row table converts a bounded metadata problem into a 3M-row queue — ~1.9 GB of ledger at the measured 631 bytes per undrained row — so a run whose catalog is already overHOGLAKE_RETIREMENT_QUEUE_CEILINGdeclines to start. That count is ONE count per RUN, never one per batch: at 3M queued rows it is ~100k buffers, and per batch it would be that times 376. The other direction of the coupling is expiry's: retirement DELETES rows rather than end-snapshotting them, so it adds nothing to expiry's below-floor sweep — but a dropped table's rows sit inhog_data_fileuntil it runs, which is what V19's partial index and the gauges'hog_tablejoin both exist to survive. - Reindex (
MaintenanceTask.REINDEX, loopreindex,ReindexService, #268) is the hourly index-bloat check: autovacuum never shrinks an index, and on this schema bloat arrives in steps, at any hour (the 13.9M-row prod-us retirement lefthog_data_filewith 14.8 GB of indexes over 1.48M rows). Hourly, not daily, because a run rebuilds one index: a backlog of N bloated indexes drains in N hours, where once a day left a bloated 30 GB index waiting up to a day. It estimates every valid btree index on a hog_* table frompg_stats(the check_postgres / ioguix arithmetic,ReindexService.ESTIMATE_SQL: catalog reads only) and rebuilds at most ONE — the largest estimated excess over threshold — withREINDEX INDEX CONCURRENTLY, on its own connection, under NO commit lock, with that session'sstatement_timeoutraised to an hour and restored after. Threshold: ratio >= 3.0 on an index of at least 8 MiB, or >= 1 GiB of excess at a ratio of at least 1.5 (a random-key btree sits at ~1.35 on its own). Constraint-backing indexes are eligible (PG >= 12 rebuilds them in place); on equal excess a non-constraint one goes first. EXCLUDED, with the next candidate going instead: an index expected to rebuild past 16 GiB (MAX_REBUILD_EXPECTED_BYTES;too_large— a concurrent rebuild writes ~0.9x its size in WAL and ~1x in temp files while the old copy still exists, so ~3x its size in transient disk:hog_file_column_stats_pkeyat ~15 GB expected is admitted and needs ~45 GB of headroom whenever it runs; anything larger is an operator's off-peak job) and one whose newest attempt failed (last_attempt_failed). With every candidate excluded the row names the first, withexpected_bytes. TWO CONSEQUENCES, stated so nobody infers them: a failed attempt is RETRIED once its row leaves the 7-day ledger, so an index that reliably times out costs its rebuild — ~3x its expected size in transient disk (~45 GB for the stats pkey) and up to an hour of I/O — every week until a human looks; and an over-cap index is NOT NAMED in the ledger while a smaller candidate is over threshold — rows that rebuilt something carryexcluded(how many candidates were passed over), and the health page'sindex_bloatfinding names them. A rebuild that succeeded but whose read-back failed stays anokrow withpost_step_errorand noafter_bytes. Every number above is a constant, not a knob, and so is the schedule: due once an hour, at the top of each UTC hour (RUN_EVERY, epoch-aligned windows; configurable later).HOGLAKE_REINDEX_INTERVAL_MS(0 = off) is only the POLL; the chart turns it on for the maintenance Deployment alone, and its one rebuild connection is priced in the pool budget. The gate reads the LEDGER (newestreindexrow'sstarted_at), so a restart does not repeat the hour's run, a pod down at the top of the hour runs on its first poll in that hour, and a pod down for several hours runs ONCE on return, not once per missed hour; amigration_pending/reindex_in_progressrow does not close the hour, so it is retried on every poll until the hour ends (the next hour is a fresh run anyway, so there is no separate retry cut-off). GUARDS, each askipped_reason:reindex_in_progress(ANY index build in this database inpg_stat_progress_create_index— not filtered oncommand, which is NULL to a non-superuser for another role's backend),reindex_lock_held(the instance-wide single-flight lockLocks.REINDEX_LOCK_CLASSheld by another session — this task's own rebuild, so it closes the hour rather than retrying),migration_pending(the migration advisory lock held, or a failed Flyway history row) — both checked BEFORE invalid*_ccnew/*_ccoldleftovers of a failed rebuild are dropped, because an in-flight build's copy is exactly such an index — thenretirement_pending(RetirementService.ELIGIBLE_PREDICATEanywhere) andpurge_pending(any catalog's latest expiry row haspurge_remainingatExpiryService.PURGE_REMAINING_CAP, or is truncated with the count unknown — routine lag is not a mass delete), which would re-bloat the index within hours and are asked only when something IS over threshold, so a quiet hour stays a quiet row through a week-long retirement.purge_pendingis a WASTED-WORK guard, not a correctness or lock one (REINDEX CONCURRENTLY tolerates the purge's DML), and its wait is BOUNDED (#429): once every pending catalog's purge has stayed at the cap, never once draining below it, forHOGLAKE_REINDEX_PURGE_WAIT_WINDOWShours (default 3, at least 1), the run rebuilds anyway and the row carriespurge_pending_overridden: true— a purge that cannot drain (prod-us 2026-10-22, the #419 cascade cost) deletes at its budgeted rate whether the rebuild waits or not, so waiting only lets the excess grow. The ratio arm skips a PARTIAL index underMIN_RATIO_PARTIAL_LIVE_ENTRIES(10,000) live entries — a drained queue's index (hog_file_removal_undrained_pathread "69372x") is its high-water mark over a page — so it is rebuilt, and reported byindex_bloat, on the 1 GiB excess arm only. A failed REINDEX is afailedrow carrying the attempt, never retried in-run, and drops its own_ccnewat once (one cancelled in validation is ready for writes). READING THE LEDGER ROW: the run is instance-wide and the ledger per-catalog, so one run is the SAME row on every catalog (MaintenanceRunStore.recordedAllCatalogs, V25 adds the task to the CHECK).checked/over_threshold/invalid_droppedare always there;index,table,before_bytes,after_bytes,duration_msappear when a rebuild was attempted,skipped_reasonwhen a guard fired; a row with only the three counters and zeros is the quiet steady state.GET /v1/database/healthcarries the same estimate (indexes[].estimated_bloat_bytes/_ratio, findingindex_bloat), andhoglake_index_bloat_bytes{table,index}is the gauge — published only by the pod running the loop (hourly run plus every metrics tick there), never by an API pod serving the health page, so the series does not flap between pods. The estimate is as fresh as the table's last VACUUM/ANALYZE and under-reports deduplicated indexes —hog_data_file_changefeed/_liveread ~0.17 fresh, so their bloat shows ~6x low and the ratio rule needs ~18x real bloat there; it never over-reports for a missingpg_statsrow or a never-vacuumed index (no estimate instead). What a rebuild costs: two heap passes of its table, its size in WAL, one pooled connection for the duration, a held snapshot per phase (the health page'slong_transactionfinding will name it while it runs), and no autovacuum on that table until it ends (it cancels a running one) — paid at whatever hour the index crosses threshold, peak included, which is the price of not waiting a day. A pod killed mid-rebuild leaves the backend running it with the session lock; the killed run writes no row and the next poll recordsreindex_lock_held, which closes the hour (the orphan IS this hour's rebuild). A rebuild that runs its full hour ends past the next window's start, so that window's run starts right after it; intended. DEPLOY NOTE: do not promote a release with a migration while a rebuild runs; a rebuild can start at the top of any hour and run up to an hour, so check every time. AnALTER TABLEon the table being rebuilt hits its 5 slock_timeoutand the pod crash-loops until the rebuild ends; aCREATE INDEX CONCURRENTLYwaits out the rebuild's snapshot and dies on the 120 sMIGRATION_LOCK_WAIT. Check first:SELECT pid, command, phase, relid::regclass FROM pg_stat_progress_create_index WHERE datid = (SELECT oid FROM pg_database WHERE datname = current_database());—Database.migratelogs the same rows at WARN before Flyway runs.
- Retirement (
- Multi-agent work: partition by package/file ownership; frozen
shared files (build files, Model.kt, migrations, spec) change only
through the integrating session; agents report needed changes rather
than making them. Concurrent gradle runs contend on the build dir —
EOFException in
:testresults is contention, rerun. - Every feature and its tests consider ALL consumers. The wire
contract has more implementations than the server suite runs, and the
ones that drift are the ones nothing reds. A type-system,
wire, or file-format change states its effect on each consumer —
implemented, refused with a named error, or an issue filed — and never
leaves one silent.
- pyhoglake is the reference client. It shares the Iceberg
single-value codec through
pyhoglake/tests/vectors/bounds_vectors.json(109 vectors, count pinned on both sides —qe_vectors.test_vector_file_header_contractandBoundsVectorFile.EXPECTED_COUNT— so a silently shrunken file cannot pass), and the VARIANTtype_params.shreddinggrammar throughpyhoglake/tests/vectors/variant_shredding_vectors.json(declarations with the exact refusal each gets, pinned the same way intest_variant_ddl.pyandVariantShreddingVectorFile.EXPECTED_COUNT), and each declaration's Parquet layout throughpyhoglake/tests/vectors/variant_layout_vectors.json(49 vectors, pinned intest_variant_layout_vectors.pyandVariantLayoutVectorFile.EXPECTED_COUNT): a change toPlan.expected_elementsor toVariantLayout.ktregenerates it (regen_variant_layout_vectors.py) and moves the other side with it. It mirrors the server's type mapping and validation gates, which therefore move with the server: a change toVariantShredding.kt's rules or messages updates that file andpyhoglake/variant.pytogether, and one to the column-level refusals pyhoglake raises locally (VariantShredding.kt's nested and not-a-variant messages,ColumnTrees.kt's type_params-on-a-container message) updatespyhoglake/variant.pyandpyhoglake/ops.py, whichtest_variant_ddl.pychecks against both sources. The object-prefix layout (ObjectPrefix.kt: prefix grammar, containment, the stats proof and the reader role's IAM Resource pattern) is shared throughpyhoglake/tests/vectors/object_prefix_vectors.json(69 vectors, pinned intest_object_prefix_vectors.pyandObjectPrefixVectorFile.EXPECTED_COUNT, regenerated byregen_object_prefix_vectors.py);pyhoglake.object_prefix, which writers build those paths with, is held to the same file. A parity test must PARSE the other side's artifact or share a fixture:test_transforms.pyregexesColTypeout ofModel.ktandBUCKETABLE_TYPESout ofAlterService.kt, andScalarTypeParityTestreads the migration,schema.sql, and the OpenAPI enum off disk, for exactly this reason. A test that restates the constant it claims to mirror asserts only that the file compiles, and one that reconstructs its own expectation cannot fail at all — both shapes are in the tree today. - duckdb-client is NOT in server CI, so nothing reds when the
server outgrows it: the ten scalar types of #66 shipped with the
extension unable to read them (
Unknown hoglake column typeat bind — a clean refusal, tracked separately, but nobody chose it), and the same is true ofvariant(#77). Its DESIGN.md carries invariants the server has contradicted when nobody looked — the reserved row-id field id, the twoexplicit_row_idsdisagreement refusals — as well as the numbered findings listed under Known deferrals. - The Trino connector lives in the PostHog/trino fork; the in-repo
harness (
server/trino/) resolves the newest fork image at run time and is the cross-repo drift alarm. A server feature that changes what files or scans look like adds a harness case where feasible — "to the extent possible" is the standard, since the connector code is not here. Harness assertions must never pin fork prose; discriminate on object paths hoglake registered and on values only a correct implementation can know. Replay every new predicate offline against inputs it MUST reject before believing a green container run: five successive generations of one fail-open matcher were each invisible in a green suite and visible in seconds of replay (#75). - hedgerow and the webui consume the same wire and restate the same vocabularies, and neither is exercised by the server suite either.
- Worked example,
TableSummarygrowing five fields +comment(#189): pyhoglake and the webui implemented them; the DuckDB extension'sHoglakeApiClient::ListTables(duckdb-client/src/rest/hoglake_api_client.cpp:689) reads onlynameandtable_uuidoff each array member and ignores the rest, so an additive change is safe there and it was left alone; hedgerow never calls the endpoint at all. Saying which of the four it is — implemented, safe-by-construction, or not a consumer — is the point; "additive, so fine" without naming them is the shape that lets one drift.
- pyhoglake is the reference client. It shares the Iceberg
single-value codec through
- Look the invariant up before you write it down. Before
implementing a rule about row ids, field ids, or column binding, READ
the ones already stated: this file, the
duckdb-client design doc,
iceberg-federation.md, and the comments in
server/schema.sql. Follow the document over an instruction or an intuition, and say that you are doing so. Two regressions shipped because a rule was invented while the correct one was already on disk. - API changes get the fuzzing treatment. The Jazzer targets under
server/src/test/kotlin/com/posthog/hoglake/fuzz/have reached defects nothing else did, so they are part of the change, not a follow-up (see fuzzing.md). New or changed wire surface — DTOs, OpenAPI shapes, validation — extends the wire corpus; new parse or validation logic gets a target or joins an existing one. Cross-surface machinery (a reader/rewriter pair, a codec's encode/decode) gets an agreement- or round-trip-style fuzzer whose oracle checks GROUND TRUTH, never mutual agreement: an agreement oracle went blind to a real bug for more than a million executions because unifying the two surfaces had correlated their errors. Every campaign finding becomes a deterministic regression test in:test— a corpus seed is NOT regression cover, becausefuzzand:testare different Gradle tasks and PR CI replays only:test. Verify the red before the green by reading the<testcase name=...>entries inserver/build/test-results/test/TEST-*.xml, never an exit code: a--testsfilter that matches nothing FAILS the build, and that failure has been misread as a failing assertion. AndColTypeordinals are baked into the corpora — the decode target reads its first byte as a type index modulo the vocabulary size — so the enum is append-only, and any membership change means rerunning./gradlew generateFuzzSeedsand recommitting the seeds — otherwise the seeds silently start exercising different types than their names claim.- A target whose coverage is flat from
INITEDtoDONEis saturated: its budget is a regression sweep, and it belongs in the sweep class (fuzzSweepTargets). A target under ~1,000 exec/s is starved and finds nothing at any budget: profile it with JFR before giving it minutes — the nightly ran NestedAgreement at 11 exec/s (7k executions a night) for a week and ParquetFooter at 580/s, both dominated by HadoopConfigurationconstruction (#165), while five saturated targets burned 600 s each. Read the nightly'sINITED/DONElines when a run is suspiciously green.
- A target whose coverage is flat from
- QE culture: substantive changes get an adversarial review or QE agent pass before merge; bugs found by tests/fuzzing become pinned regression tests + (design-class ones) defect-ledger entries.
-
Compaction (M4) — 100% implemented, so what belongs here is only what is still deferred. The design — one-pass bin packing, the scaling minimum, the two knobs, the claim, the sorted rewrite's external merge sort and its budgets, the typed skips and their measurements — is in server/README.md §Sort orders and compaction, the single home for it. Three rules of the sorted rewrite (hoglake#134) that code elsewhere must not break: (1) a TRUSTED run is
explicit_row_ids AND begin_snapshot >= live sort spec's begin_snapshotand is never verified — socommitGrouprefuses a group whose livesort_idmoved during its rewrite (null <-> non-null included), and anything else that registersexplicit_row_ids = truewould be trusted as sorted; only compaction may. (2) The ORDER GUARANTEE, stated precisely: key order is exact whenever every trusted run is key-nondecreasing; ties are (key, row_id) when every trusted input was itself written that way — true of every output since #134 — and otherwise deterministic but unspecified (pre-#134 outputs broke ties in input order). Nothing may depend on more. (3) The spill directory (HOGLAKE_COMPACTION_SPILL_DIR) is private to one hoglake process: startup removes everyhoglake-compaction-spill-*directory in it, and only those (the prefix is hoglake's own because the default is the sharedjava.io.tmpdir; never shorten it to something another tool could also create). The planner'sspill_budget_exceeded/merge_budget_exceededcallExternalMergeSort.admitrather than restating its arithmetic; keep it that way.heap_budget_exceededis historical (reads 0) and stays on the wire.Metadata admission predicts ordinary allocations. Arbitrary payloads can exceed that prediction. Runtime guards can refuse an admitted group. The worker caches deterministic memory and spill-budget refusals by immutable identity.
Schema, sort, layout, DV, input, or effective-budget changes invalidate that identity. Planning, remembered-layout parts, borrowing, and execution use the shared metadata estimate. Execution also checks actual allocations and spill bytes.
(4) Every other input of at least
HOGLAKE_COMPACTION_VERIFY_MIN_BYTES(16 MiB) is VERIFIED by the sortedness pre-pass (SortednessCheck: a projected read of its key columns, plus the carrier for an explicit-row-id file, every physical row, stop at the first violation) and, if sorted, is a run candidate like a trusted output; smaller files go straight to the chunk phase (files_unchecked). The verdict is used once and never recorded — under one-pass compaction a file is compacted once. The planner's refusals stay worst case (assume nothing verifies); keep them that way, since the planner cannot read files. Key comparison in the file's own domain is only valid while every conversion the rewrite makes preserves order: a new promotion that does not (any unit or scale change) must make the pre-pass refuse that pairing. (5) A prior output whose schema EQUALS the output schema, with no live DV and row groups of at least 32 MiB, is APPENDED byte for byte (ParquetRewriter.appendRefusal; on a sorted table only with a first-key range strictly disjoint from every other run's). An appended row never passes the column plan, so a change that makes the decode path alter a value of an IDENTICAL schema (a normalization, a new conversion on an identity column) must add a disqualifier there, and a change tooutputSchemasilently stops existing outputs from appending (slower, not wrong). An unsorted output's row order is not its inputs' order: encoded rows land after the appended row groups. Rows are written by theirRowPlanstraight from the decoded source row; there is no output-shaped copy to hang per-row logic on. (6) N maintenance pods share a catalog through CLAIMS, and the claims are rows in ONE table (hog_compaction_claim, V15): group claims (64-hexgroup_key, the input ids ininput_file_ids) make execution disjoint, and BUCKET claims (bucket:+ a hash of spec id and partition values, emptyinput_file_ids) make planning disjoint — a plan that claimed every free group of a fully probed bucket marks it, the next plan skips it before probing (buckets_skipped_claimed), and the last of its groups to settle releases it. Its lease is short (HOGLAKE_COMPACTION_BUCKET_CLAIM_TTL_SECONDS, 600 s) and renewed by the per-group refresh, because a killed pod releases nothing and a leaked bucket claim hides the whole bucket; never give it the group claims' hour. Anything that reads the table must keep the two kinds apart (starts_with(group_key, 'bucket:')), and nothing may treat either as authorization. PLANNING TAKES NO LOCK (#418): the catalog planning lock covers only the claim transaction, which re-reads the live claims under it and drops every planned group that overlaps one before inserting — that re-read, not serialized probes, is what keeps two runs off the same files, and it is exact only because every claimant releases the lock AFTER its claim transaction commits. A plan path that claims without the lock or without the re-read can hold overlapping groups under different keys, and a failed claim transaction plans nothing (never the unclaimed plan). Holding the lock across the probes (1.4.1) made one slow probe every sibling's 15 s lock wait: 38 of 40 millpond-prod-us sweeps failed on 2026-10-22. The probe's statement bound isHOGLAKE_COMPACTION_PLAN_STATEMENT_TIMEOUT_MS(default 60 s, the session's), no longer the 15 s fail-fast that shape needed; the claim transaction keeps a fixed 15 s equal to the lock wait. Each pod's bucket cursor starts at a hash of its identity (POD_NAME/HOSTNAME), and the compaction loop — and only it — sleeps with ±25% jitter (BackgroundLoops.Jitter); server/README.md has the incident and the arithmetic. Not done, by decision: writer-declared sortedness (a client's declared order is never believed, only its rows), a multi-pass merge. Remaining rewrite deferrals (all surface asunconvertible_schemaskips, never wrong bytes): INT96, decimal-scale changes, and non-native time(stamp) units — each timestamp type accepts only the unit its own files carry (millis fortimestamp_s/timestamp_ms, micros fortimestamp/timestamptz, nanos fortimestamp_ns), andtimestays micros-only. No unit CONVERSION exists, because no legal promotion produces a unit mismatch:PROMOTIONSfollows DuckLake's documented table, which has no timestamp rungs. -
Field ids are a contract, audited after the fact: the hydrator's footer read flags files whose parquet schema has any leaf without
PARQUET:field_id(hog_data_file.missing_field_ids; gaugehoglake_missing_field_id_files{catalog}; the reserved_hog_row_idid 2147483646 is fine). While a FLAGGED file is LIVE,add_columnandrename_columnare refused with 409idless_files_present(id-less files bind columns by name; renaming would silently NULL their history in readers). Apendingorfailedfile is trusted (#445): the clause that refused over those verified only the deferred-stats path, and on a busy deferred-stats table it never cleared, so the writer crash-looped on schema drift. The flag's lag is the sweep's, and the sweep is a queue: each catalog's pending files indata_file_idorder,Hydrator.DEFAULT_SWEEP_LIMITper replica perHOGLAKE_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, unbounded while the backlog grows — and DDL can land before the flag; what the flag buys is that no further DDL does, and that the gauge says why.rename_tableis unaffected. Files registered with inline stats never pass through the hydrator, so only deferred-stats files get audited — still a known gap, and nothing else covers it: the verify endpoint was metadata-only by design and could not do the S3 footer reads this check needs, and #261 removed it anyway.AlterGuardPlanIntegrationTestpins the guard's count to thehog_data_file_missing_field_idspartial index. -
An added column must be nullable at every node (#446,
AlterService.requireAddedSubtreeNullable): hoglake has no column defaults (no Iceberg v3initial-default), so every file written before anadd_columnreads NULL for it, andnullable: falseanywhere in the added subtree — top-level, under a structparent, or nested inside an added container — is a 422 naming the path. A map'skeyis the one exception (the type model requires it non-null). Unconditional, files or not, matching Iceberg v2's "added columns must be optional";create_tablestill takes a required column.pyhoglake.ops.add_columnrefusesnullable=Falsebefore the round trip. -
The hydrator's size floor gates stats ROWS, never the footer read (#432,
HOGLAKE_HYDRATOR_MIN_FILE_BYTES, default 1 MiB, 0 = rows for every file). Every pending file is claimed and footer-checked as before; one under the floor flips toprovidedwithmissing_field_idsandsplit_offsetsset and nohog_file_column_statsrows, counted as the sweep result'sstats_skipped_below_floor(a subset ofhydrated). The under-floor read buys the field-id audit flag,split_offsetsand, on a table with the object-prefix layout, the prefix proof (2.1c: the quarantine check runs before the floor, so the GET cannot be skipped there): since #445 the DDL guard refuses over FLAGGED files only, so a file leftpendingholds nothing up, and the first-draft argument for keeping the GET (a pending tiny file blocking DDL forever on a bucket compaction never rewrites) died with the pending clause. Whether the GET is worth keeping at millrace's file rate on tables WITHOUT the option is the floor's own question. The rows are the cost the floor removes: ~26 per tiny file, inserted only for the expiry purge to cascade-delete (~642M of them on millrace-prod-us's 24.7M pending files on 2026-10-22). server/README.md §File registration has the reasoning. -
Maintenance verify — REMOVED (#279, 2026-10-02; tracked by #261):
POST /v1/catalogs/{c}/maintenance/verify, its background loop (HOGLAKE_VERIFY_INTERVAL_MS), itshoglake_verify_violations/hoglake_verify_errors_totalmetrics, its console panel and its twelve checks are gone, along withVerifyService,VerifyQueryPlanIntegrationTestandVerifySpecParityTest. WHY, and it is the Scale doctrine's own argument: a run was twelve UNBOUNDED full-table checks in ONE REPEATABLE READ transaction. On gigahog-prod-us (14M livehog_data_filerows, 371Mhog_file_column_statsrows) it crossed the 60 sstatement_timeoutevery run, so it was disabled there (verifyIntervalMs: "0") and proved nothing at the only scale that mattered — a checker that is green because it never finished is worse than no checker. Every rule in Scale doctrine applied to it: no bound per run, no bound per transaction, no per-row figure, a fixture of thousands against a manifest of millions. WHAT CAME WITH IT.MaintenanceTask.VERIFYSTAYS in the enum (hasLoop = false) and in the spec'sMaintenanceTask, becausehog_maintenance_run.task's CHECK (V2, frozen chain) still admits'verify'andMaintenanceRunStore.runMappererrors on an unknown task — deleting the value would 500 every unfilteredGET /maintenance/runsfor as long as one historical row survivesHOGLAKE_MAINTENANCE_LEDGER_RETENTION_SECONDS. The spec'sVerifyReport/VerifyCheckschemas and the console's renderer for averifyledger row stay for the same reason, marked HISTORICAL; they go once the retention window has passed everywhere.HOGLAKE_VERIFY_INTERVAL_MSis inConfig.REMOVED_INTERVAL_ENV, a middle tier betweenREMOVED_ENV(any value refused) and ignoring a knob: a POSITIVE value is refused at boot naming #261, while0and absence are accepted in silence.0is what the gigahog chart renders — unconditionally, from a REQUIREDverifyIntervalMs, with no override anywhere underargocd/gigahog/values/— so aREMOVED_ENV-style refusal would reject every pod over a value that means exactly what is now true. (It would not take production down: the chart setsmaxUnavailable: 0, so the old ReplicaSet keeps serving and the failure is a STALLED ROLLOUT plus a Degraded Application paging#alerts-managed-warehouse, in dev only — the prod Kargo Stages are manual promotions of Freight that has passed dev.) A positive value is refused because it is an operator asking for invariant checks that no longer exist, and silence there would leave them believing a catalog is being scrubbed.RemovedEnvConfigTestpins both tiers; neither had a test before. The entry graduates intoREMOVED_ENVonce the chart stops rendering the key at all. WHAT IS NOW UNWATCHED. All twelve checks are gone, and the list is exhaustive rather than a sample:row_id_tiling,delete_vectors,orphans,removal_queue,snapshot_density,next_row_id,expiry_floor,visibility_bounds,offset_release,staging_tickets,upload_claims,compaction_claims. THREE of those twelve have another enforcer and their absence here is defensible:removal_queueis enforced at drain time byCleanupService.referencedPathsand itsstill_referencedcounter;next_row_idby the commit-path allocator that owns the column; andorphans' retirement arm by the stamp + ledger counters in the retirement bullet above. The other nine have no at-rest enforcer in any environment. Four are now asserted in the TEST suite only, bytesting/CatalogInvariants.kt:visibility_bounds,removal_queueat the compaction boundary,snapshot_density(all 10 concurrent-commit sites inCompactionParallelIntegrationTest), andstaging_ticketsarm (c) — rebuilt because they were the oracle's only falsifiable arms at those call sites and nothing else covers them. The versioned-table schema-drift guard that rode in the deleted verify test moved toExpiryServiceIntegrationTest(VERSIONED_RETENTION_TABLES is every versioned table the schema has), where it never needed a verify symbol. Three artefacts are now written and read only by tests, kept because none can be reconstructed after the fact:hog_table.retirement_eligible_at(no reader at all), andhog_file_removal's'absent'outcome plus the HEAD-before-DELETE carve-out that produces it — read only byCatalogInvariants. FOLLOW-UP TO DECIDE, not a standing property: that carve-out costs two round trips per staging path, which is what forcesCleanupService.STAGING_SUB_BATCH = 25instead of the full sub-batch, and at the ~9.4k orphaned tickets / 50 per hour that file records it is an eight-day drain. Keep it for the scrubber or drop it and lose the outcome forever — somebody has to choose.HOGLAKE_CLEANUP_STAGING_GRACE _SECONDSalso lost its only ceiling (verify's 6 h ticket age) and has none today; arequirebounding it against the cleanup interval would restore it as code rather than prose. The replacement is a PAGED, RESUMABLE SCRUBBER — one bounded page per transaction, a cursor, a run budget, a per-row figure measured on a production-shaped fixture — tracked as issue #261. -
DuckDB client (
duckdb-client/): complete through time travel and maintenance functions, verified against the live dev stack, but NOT yet in CI and not yet released as of 2026-09-30 (four server releases into that state) — no path-scoped workflow, and itsduckdb/extension-ci-toolstrees are gitignored pinned clones rather than submodules (the repo root was out of the branch's write scope; they become submodules on extraction to a standalone community-extension repo). Its DESIGN.md ends with numbered findings for the server; four are still open: two documented divergences (no transactional DDL, append-only/changes) and noexplicit_row_idsonFileRegistration(#30) and head-only listings (#28), each capping a parity item. -
CDC publications to Kafka (the WAL tap): fully specified in the OpenAPI (501s) + README; not implemented.
-
DR/export:
GET /v1/catalogs/{c}/exportspecified in the OpenAPI (snapshot range + live-file manifest + consumer offsets, consistent at head); 501 stub until built. -
Iceberg REST facade + Trino: design obligations in docs/iceberg-federation.md / docs/trino-integration.md; v1 schema already conforms (typed bounds, Iceberg transforms, DV-only deletes).
-
Auth: the ENFORCEMENT layer has landed — JWT verification, the route-to-scope table (server/src/main/kotlin/com/posthog/hoglake/auth/AuthPolicy.kt), per-catalog scopes, the
HOGLAKE_AUTH_MODE=off|warn|enforce|localflag (local: the server is its own issuer, key inHOGLAKE_AUTH_SIGNING_KEY, tokens fromhoglake token mint; docs/auth.md "Local issuer"). It isoffby default, i.e. today's behaviour.enforcerefuses every caller that has no token from the configured issuer, so deploywarnfirst and watchhoglake_auth_requests_total{outcome="missing"}until it is zero for everyclientclass.warnPERMITS EVERYTHINGenforceWOULD REFUSE, includingDELETE /v1/catalogs/{catalog}and the maintenance routes: it is a measurement mode, not a partial enforcement, and aread-only tenant writes freely while it is on. Deploy it where that is acceptable, which is anywhere the current behaviour is already "no auth at all"./metricson the main port is operator-only; setHOGLAKE_METRICS_PORTbeforeenforceand scrape that infra listener, which serves the same registry with no auth and needs no token. hoglake is a resource server: it issues nothing on the request path and calls nothing to decide a request. SetHOGLAKE_AUTH_ISSUERandHOGLAKE_AUTH_JWKS_URL(or_FILE) to whichever issuer the deployment runs — any identity provider that emits the token contract in docs/auth.md; PostHog's is hogtower — then flip the mode. hoglake owns the contract and its test vectors; issuers conform to them. Never add code that names hogtower or PostHog teams: the PostHog behaviour is configuration. -
pyhoglake implements
truncate[W]partition transforms; the server's Transform vocabulary doesn't include truncate yet (client-ready, server gap). -
Catalog drop (#412) is server + pyhoglake only: no console action and no DuckDB-client vocabulary yet, and no offset-delete API, so a catalog any consumer ever read is undroppable without hand-deleting its offsets.
-
bench/is outsidejust lint-all: it passesruff checkbut 13 files failruff format --check(ruff 0.17.1). Format it and wire it in (add thelintrecipe) as its own change, so the reformat lands as a reviewable diff rather than noise inside another.
hoglake is issuer-neutral and docs/auth.md stays that way. The specs for
how PostHog deploys it — the shared hoglake catalog on its Trino pools,
Remote Schemas to its internal gigahog deployment, the session token with
embedded storage credentials, and the cross-repo burndown lists — live in
PostHog/hogtower under docs/ (indexed in that repo's AGENTS.md):
docs/remote_schema.md, docs/truffle-hoglake-catalog-routing.md,
docs/gigahog-imports-and-partitioning.md, docs/jwt-aws-session-design.md,
docs/hoglake-auth-posthog-profile.md. Read the relevant one before changing
a cross-service contract; a design change goes into that spec first, and the
contract itself into docs/auth.md here (hoglake owns the token contract;
issuers conform to it).
Reference docs live in docs/; README.md is the front door. The predecessor-analysis set (the DuckLake and pyducklake API maps, the C++ source inventory, the Paimon comparison, the schema review and the language retrospective) was retired in the 2026-09-17 docs pass: each had done its job informing the as-built system, and git history holds them.
Design — server/schema.sql (the schema, table by table, with each index's rationale beside it) · docs/iceberg-federation.md / docs/trino-integration.md (engine surfaces).
Rehearsing a Postgres major-version move: the integration harness pins
the version production runs, overridable for a dry run of the whole
suite — ./gradlew :test -PpgImage=postgres:19 (or
HOGLAKE_TEST_PG_IMAGE). A version move rarely breaks application code;
it breaks statistics views that moved columns, which only an integration
run can see. The suite, the dev compose stack and the CI image-smoke
service all run Postgres 18 as of 2026-09-18 (moved from 16); the
override runs backwards too, down to Postgres 17
(-PpgImage=postgres:17), which is how a failure gets attributed to the
version rather than to the environment. 17 is the floor: partition
lookup sets transaction_timeout, which 16 does not have.
Two things the test suite cannot see, and a future move must check by
hand: the docker-library image's PGDATA path (18 moved it to
/var/lib/postgresql/18/docker and the VOLUME to the parent, so a
compose mount of the old /var/lib/postgresql/data silently stops
persisting), and Flyway's supported-version table — a Flyway that
predates the server warns "support has not been tested" on every
migration and is the thing to bump first.
Operating — docs/operational-notes.md (what changes, and what honestly doesn't, at 2PB/1T) · docs/fuzzing.md (property testing and fuzzing).
Why this architecture — docs/ducklake-defect-ledger.md (the predecessor's production bugs, and where hoglake answers each).
Per-component — server · duckdb-client (design · parity) · trino connector · pyhoglake · webui · hedgerow · bench.
Bug-hunt writeups and in-flight worklists stay local-only (they are
snapshots of a moving tree, not documentation). Name one
<whatever>-not-for-commit.md and .gitignore will refuse to stage it
— no edit to .gitignore, and the filename never lands in a tracked
file, which matters when the name itself would disclose something.