oink: preview and multi-version serving from a docs repository
This proposal describes a product direction that is not implemented. Do not use it as a configuration or command reference. Current behavior is defined by the architecture contract, the CLI contract and the versions guide.
Status and surface
Status and date: draft (v2 redesign after adversarial review and local benchmarking), 2026-11-28; product requirements and architecture direction, not an implementation contract.
Owner: OINK maintainer.
Baseline: OINK v1.7.0 / v1.8.0-dev (plain CSS, no Sass, no Bootstrap JS); installed Hugo v0.170.1; the local 0.1.0-dev candidate of pgsty/oink-cli (unreleased, no users).
Affected contracts: CLI contract (superseded if this proposal is accepted), Architecture · Outputs and runtime, Shell · Search, actions, and runtime, and the versions guide.
Related proposals: takes over the unimplemented version-lifecycle stage of the CLI roadmap; answers the open question of theme roadmap R2, “native version dimension or independent builds”; delivers the SQLite search backend left open by the local search proposal.
Affected implementation: a new, clean Go repository for the oink binary (pgsty/oink-server, retiring pgsty/oink-cli as archived history); six small, low-coupling OINK theme additions (C1–C6, see theme coordination).
Release intent: staged, delivering local preview (M0) and Git multi-version Hugo serving (M1) first; see milestones. This proposal commits to no release date.
Summary
Run one lean Go binary (oink, ~20 MB) directly against any OINK or Hugo Git documentation repository:
oink does not fork Hugo and does not import Hugo’s unstable internal Go packages. It orchestrates the official Hugo binary as an isolated child process (using PATH or an auto-cached, SHA-256-verified official release), stores deduplicated outputs in local SQLite (CGO_ENABLED=0) packed with standard RFC 7932 Brotli clusters, and sits behind Cloudflare’s free CDN without requiring D1 or Workers.
The core model fits in one sentence: Git is the authoritative source, a version is a pointer to a Git ref or frozen archive, rendered output is an immutable content-addressed snapshot, and the server never rewrites HTML bytes.
Four mutually consistent invariants run through the whole design:
- Plain Hugo still builds every OINK site unchanged. Ordinary consumers need only the official Hugo binary; removing
oinkbreaks nothing. - Production serves only immutable snapshots with zero cross-request tearing. Production never reads the working tree; failed, timed-out, or OOM builds never replace live pointers; fingerprinted assets stay resolvable across a
≥ 48hgrace window after snapshot switches. - Zero server-side HTML splicing. The server performs no byte-offset HTML rewriting and no fragment builds. Version menus and outdated/prerelease banners are progressively enhanced on the client from
/_oink/versions.json(with a static fallback link to/versions/when JavaScript is off), while SEO canonical and indexing rules travel in standard HTTP response headers (LinkandX-Robots-Tag). - Cost follows active unique content, with honest boundaries. Publishing a new release never rebuilds old versions; historical versions that predate breaking theme retirements are frozen via
oink freezerather than re-compiled; full-text search indexes only configured active version lines by default.
Context and evidence
Current state
- OINK treats each documentation version as an independent Hugo build with
params.versionsbaked into every page. Adding a version forces updating every maintained branch and rebuilding all of them (see the versions guide). pgsty/oink-cliis an unreleased0.1.0-devcandidate with no users; the owner confirmed the new design need not be constrained by it.- Multi-version documentation such as the Chinese PostgreSQL manual (
pgdoc-cn, 560 versions) explodes into gigabytes when deployed as per-version static trees and exceeds Cloudflare Pages file limits. - Self-hosted Go + local SQLite behind Cloudflare’s free CDN avoids per-row/storage pricing of managed edge databases such as Cloudflare D1 while keeping one binary for local preview, production serving, and offline reading.
Empirical benchmarks
Measured read-only on 2026-11-28 on the actual target repositories (darwin/arm64, Hugo v0.170.1, SQLite 3.54.0, zstd, brotli):
| Measurement | Observed result | Design consequence |
|---|---|---|
pgdoc-cn Git repository |
559 v* tags + master (560 versions; 1,118 tags total including REL_* duplicates), Git pack 78.18 MiB |
Regex matching deduplicates twin tags on the same commit |
pgdoc-cn tree scan & body dedup |
528,798 HTML entries, 527,348 unique Git blobs (5,856.9 MiB); stripping navheader/navfooter leaves 98,141 unique bodies (1,206.7 MiB) |
Reading and stripping all 527k blobs takes 48.9 s in Python (est. 12–25 s in Go), so full materialization runs asynchronously in the background |
pgdoc-cn base SQLite store (no FTS5) |
1 MiB clusters + 14.60 MiB SQLite metadata (entries WITHOUT ROWID, objects, paths, snapshots) = 44–62 MiB depending on cluster ordering and codec |
All 560 versions fit comfortably under 65 MiB without search |
pgdoc-cn contentless FTS5 (content='', detail=full, CJK bigrams) |
Latest 1 line (1,155 docs): 10.84 MiB (0.92 s); Latest 6 major lines PG 13–18 (4,250 unique docs): 32.41 MiB (5.07 s); All 29 major lines (20,177 docs): 98.46 MiB (20.81 s); All 560 versions (98,141 docs): > 473 MiB (> 100 s) |
Indexing all 560 minor releases blows past < 100 MiB by > 5× and distorts IDF. Separating search.db and indexing active major lines keeps pgdoc-cn (content + 6 active lines search) at ~75–85 MiB |
Cluster codec comparison (15 × 1 MiB pgdoc-cn clusters, 14.23 MiB raw, (path, version) order) |
zstd -3: 0.411 MiB (34.6×); zstd -9: 0.372 MiB (38.3×); zstd -15: 0.361 MiB (39.4×); brotli -q 6 (lgwin=22): 0.337 MiB (42.2×), dec p50=0.29 ms / p99=0.76 ms; brotli -q 9: 0.326 MiB (43.6×), dec p50=0.26 ms / p99=0.34 ms; brotli -q 11: 0.306 MiB (46.6×), dec p50=0.27 ms / p99=0.42 ms |
Brotli beats zstd on ratio, matches zstd decode speed (< 1 ms p99), runs pure-Go (CGO_ENABLED=0), and is natively decoded by Apple’s Compression framework (COMPRESSION_BROTLI) with zero third-party dependencies in Crib |
pigsty.io (bilingual OINK docs) |
1,547 files, Git pack 154.92 MiB; data/ holds contributors.yaml, footer/, landing/, pgext/, upstreams.yaml, star_history.json |
Confirms data/ and static/ carry version-specific content and must travel with the version commit |
pgext.cloud & pg.center |
pgext.cloud/public is 1.2 GB for 1,493 HTML files (71 MB index.xml); both pgext serve and pg.center already run as dedicated Go + PostgreSQL (pgx) apps |
Database-backed catalogs and knowledge graphs stay dedicated Go+PG apps sharing OINK’s chrome CSS bundle, rather than being forced into static sidebar trees |
| Local binary & theme sizes | hugo v0.170.1 binary = 87 MB; OINK runtime assets (layouts, assets, i18n, data, static) = 25.77 MiB; theme tests/ = 79 MB |
Decoupling official Hugo keeps oink around ~20 MB and allows independent Hugo upgrades |
Owner inputs
Confirmed premises from the 2026-11-27 and 2026-11-28 discussions:
- One Go binary named
oinkrunning directly on a Git documentation repository: local live preview while editing (oink dev) and production serving (oink serve). - Production is Git-aware: pin one branch or serve configured branches and tags as multi-version documentation without exploding storage across 500+ PostgreSQL versions.
- Self-hosted Go server + local SQLite (avoiding expensive managed edge databases like Cloudflare D1), sitting behind Cloudflare CDN; large media can remain on nginx or local media mounts.
- Full-text search and optional page views on SQLite; single-file
.oinkpackages readable directly byoink serveand the macOS reader app Crib (which has zero third-party dependencies). - ACL / access control is deferred out of v1; the unreleased
oink-clineed not constrain the design.
Goals and non-goals
Goals:
- G1 Lean single binary. Running
oinkin any OINK repo previews it locally (auto-resolving official Hugo if absent); the same binary runs production serving and static/package exports. - G2 Git-aware multi-version serving. Branches, tags, aliases (
current,latest), and frozen archives resolve deterministically; all 560 versions ofpgdoc-cnare reachable; publishing a new version never rebuilds existing versions. - G3 Bounded storage without explosion. Storage follows unique content via Brotli clusters; all 560
pgdoc-cnversions plus active-line FTS5 stay under100 MiB. - G4 Resilient atomic operations. Production serves only committed/frozen immutable snapshots; bad commits, build OOMs, timeouts, and
kill -9never degrade live traffic; rollback completes in< 1 s; fingerprinted assets never 404 across snapshot switches. - G5 Honest theme compatibility. Plain Hugo stays untouched; active lines share theme styling safely while keeping their own
data/andstatic/; versions predating breaking OINK retirements freeze cleanly without violating OINK’s no-compat-shim rule. - G6 Scoped search and offline
.oink. Active-line FTS5 handles CJK and technical identifiers accurately; one compacted, signed, Brotli-compressed.oinkarchive opens directly inoink serveand Crib with zero Crib third-party dependencies.
Non-goals for v1:
- No ACL, RBAC, OAuth accounts, login sessions, or authenticated preview hosts (deferred to a separate proposal that must isolate private content at build time rather than via HTTP path filters).
- No built-in comment or moderation platform (v1 keeps giscus and adds a version-independent
termkey so discussions stay unified across versions). - No server-side HTML slot splicing (no
<template data-td-slot>offsets or fragment builds). - No Hugo fork and no importing
github.com/gohugoio/hugo/commands. - No database-driven catalog/graph pages inside
oink(pgext serveandpg.centerremain separate Go+PG services sharing OINK’schromeCSS). - No multi-tenant hosting, multi-instance shared state, or built-in ACME TLS (run behind Cloudflare, nginx, or Caddy).
- No Hugo multihost (per-language domain) routing in v1.
Users and target sites
| Target site | Shape | How it uses oink |
|---|---|---|
oink.pgsty.com / pigsty.io |
Bilingual EN/ZH Hugo + OINK docs, tens of versions, rich data/ |
oink dev locally; oink serve with active build track + oink freeze for pre-breaking legacy versions; Cloudflare CDN in front |
pgdoc-cn / pgdoc-en (pgsql.cc) |
560 versions of DocBook/pgweb HTML | renderer: html (profile: pgweb), lines + releases + current alias, active-line FTS5 (< 100 MiB total), compacted .oink package for Crib |
| Static sites on Cloudflare Pages | Single version or small version set | oink build [--versions] -o dist/ exports static files + versions.json + _redirects |
pgext.cloud / pg.center |
Dedicated Go + PostgreSQL dynamic apps | Keep their Go+PG backends; share OINK look via css/bundle.html "chrome"; optionally mount oink serve under /docs/ via reverse proxy or embed a read-only oink/reader package later |
Product shape
Commands
| Command | Behavior |
|---|---|
oink |
Runs oink dev inside a Hugo/OINK site directory; prints help elsewhere |
oink dev [DIR] |
Previews the working tree (drafts/future included) by proxying official hugo server; --versions mounts already-built Git versions read-only |
oink serve [DIR | GIT-URL | FILE.oink] |
Production server: publishes Git refs + frozen archives, or serves one .oink file read-only |
oink freeze <VERSION> [--from DIR | REF] [-o FILE] |
Captures a complete static build into a frozen archive snapshot so future breaking theme upgrades never break it |
oink build [--versions] [-o DIR | FILE.oink] |
Exports a static directory tree (with versions.json and _redirects) or a compacted, signed .oink archive |
oink check [--versions] |
Builds in isolation, validates version config, reports warnings/broken local links, and flags active lines incompatible with an upcoming theme upgrade (0 pass / 1 findings / 2 error) |
oink versions |
Resolves Git refs and oink.yaml and prints versions, aliases, default, and archived status without building |
oink status | rebuild | rollback | backup |
Operates a running oink serve over its 0600 local Unix socket; backup runs SQLite VACUUM INTO on state.db |
oink hugo … |
Invokes the resolved official Hugo binary directly with all arguments passed through |
oink --version |
Prints versions of oink, resolved Hugo, embedded SQLite driver, and cached OINK theme |
Development mode
- Listens on
127.0.0.1by default and serves the working tree including uncommitted edits and drafts. - Spawns official
hugo serveron an ephemeral loopback port with--appendPort=false --liveReloadPort=<proxy_port> --baseURL=http://127.0.0.1:<proxy_port>/and reverse-proxies it:- forwards HTTP/1.1
Upgrade: websocket(/livereload) transparently so LiveReload works out of the box; - serves
/_oink/versions.json,/_oink/where,/_oink/search, and/_oink/hitlocally against dev state; - streams Hugo’s own diagnostics cleanly to the terminal rather than scraping unstructured stderr text to fabricate source line numbers or injecting scripts that break site CSP/gzip responses.
- forwards HTTP/1.1
Production mode
- Reads only committed Git refs and explicitly registered frozen archives; never touches the working tree.
- Serves immediately at cold start from existing snapshots in
cache.dbwithout blocking on rebuilds. - Accepts a local checkout (using
.git), a bare repository push target, a trusted remote Git URL (mirrored into--data-dir), or a single.oinkfile (read-only mode, zero background builds). - Upgrades cleanly: replacing the
oinkbinary and restarting never triggers snapshot rebuilds unless the Hugo version, skin commit, or corpus profile version actually changed.
Static export, freezing and packages
oink build -o public/produces output byte-identical to running the same official Hugo release directly.oink build --versions -o dist/writes each version under its prefix alongside a generated/_oink/versions.json, a static/versions/index page, and_redirects(for Cloudflare Pages / Netlify).oink freeze <version>snapshots a version’s built output into a self-contained immutable archive before a breaking OINK/Hugo upgrade.oink build --versions -o site.oinkwrites a compacted, single-file, Ed25519-signed.oinkarchive readable by bothoink serve site.oinkand Crib.
Core model
| Concept | Definition |
|---|---|
| Source | A Git repository plus optional frozen archive snapshots (mode: archive) |
| Version | A published label bound to a Git ref (3.7 → v3.7.2, devel → main) or a frozen snapshot (2.7 → v2.7.oink) |
| Line | A release series (17 covers 17.0–17.12; 3.7 covers 3.7.0–3.7.x) |
| Alias | A movable pointer to a version (current → 18, latest → highest-numbered line) |
| Skin | The ref supplying shared layout and styling for active Hugo builds (defaults to the newest stable release tag, not moving main) |
| Snapshot | An immutable manifest mapping paths to content-addressed objects, keyed by H(version_commit, skin_commit, hugo_version, profile_version, url_base) |
| Cache / Search / State | Three physically separate SQLite files: cache.db (rebuildable content store), search.db (rebuildable FTS5 index), and state.db (durable counters and audit log, back up via oink backup) |
Versions from Git refs
- Without
oink.yaml, the default branch HEAD is the sole version, served at/(--ref <branch>pins another branch). tagsis a regular expression with named capture groupslineandpatch. Ordering compares dotted integer components numerically. Non-matching tags (such asREL_*aliases or-rc1) are ignored; duplicate tags on the same commit collapse to one canonical label.releases: trueadditionally exposes every matched patch tag (e.g./docs/17.4/).branchesmaps explicit single-segment URL-safe labels (^[a-z0-9][a-z0-9._-]*$) to branches (preventing branch names containing/from producing ambiguous URL prefixes).line_branchoptionally tracks the head of each line’s maintenance branch instead of its newest tag (for translation repos shipping mid-release fixes).defaultnames the version served without a prefix at/. Whendefaultis omitted (as inpgdoc-cnwhere all versions live under/docs/{label}/),oink.yamlmust specifyroot_redirect(e.g./docs/current/, answered with302) or a root landing source; an omitteddefaultwithoutroot_redirectis a validation error.
Dual-track version lifecycle
OINK intentionally retires public interfaces in minor releases with zero compatibility shims (for example, v1.6.0 removed Sass hooks and v1.8.0 removed the social shortcode, causing older content to fail Hugo builds). Real sites such as pigsty.io also store versioned facts in data/ and static/. Therefore oink supports two explicit tracks for Hugo versions:
- Track A — Active build track (
mode: build, default). Used for release lines sharing the current breaking-change generation of OINK:- Content domain comes from the version commit: all resolved
contentDirand content mounts declared in effectivehugo.yaml, plusdata/,static/, and non-style/non-scriptassets/(so versioned screenshots, download manifests, checksums, anddata/docs_nav.jsonstay accurate to that version). - Skin domain overlays appearance only: from the pinned
skinref (default: newest release tag, never movingmain), takinglayouts/, theme module pin,assets/css/,assets/js/,i18n/, and appearance-only parameters (params.ui.preset*,dark_mode). - Any version that requires its own configuration/layouts can set
skin: self. - Content adapter guard:
_content.gotmplfiles found in non-skin refs are rejected by default during materialization unlessallow_content_adapters: trueis explicitly set inoink.yaml.
- Content domain comes from the version commit: all resolved
- Track B — Frozen archive track (
mode: archive). Used whenever a version crosses a breaking theme or Hugo upgrade:- Before upgrading the site across a breaking OINK release, the maintainer runs
oink freeze <version>(or imports an existing built static tree) and lists it underversions.frozeninoink.yaml. - Frozen snapshots are ingested directly into
cache.dbas immutable objects and never rebuilt from source again, yet participate seamlessly in/_oink/versions.json, archived banners,/_oink/where, and HTTP SEO headers.
- Before upgrading the site across a breaking OINK release, the maintainer runs
External HTML corpus importer
For pre-rendered HTML repositories such as pgdoc-cn and pgdoc-en, renderer: { type: html, profile: pgweb } provides a dedicated importer:
- Streams objects directly from Git via
git cat-file --batchwithout checking out a worktree. - Strips DocBook
navheader/navfooterinto location-independent body HTML and parsesindex.htmlinto a compact per-version navigation JSON. - Preserves single visual authority: the importer does not hand-generate complex OINK component markup in Go. Pages render inside a minimal theme-built shell template (theme item
C6) with one body insertion point, and a dedicated.td-corpus-pgwebCSS layer styles native DocBook classes directly.
URLs, redirects and SEO
- Layout: single-host path layout
/{version}/{lang}/...(default version drops{version}). Hugo multihost is unsupported and reported clearly byoink check/oink serve. - Default version redirect:
/v{default}/xresponds with302 FoundandCache-Control: public, max-age=300(never301, so browsers are never pinned to stale redirects whendefaultadvances). - Aliases: HTML corpus aliases (location-independent bodies) serve in place; Hugo version aliases respond with
302(max-age=300). - Orthogonal SEO via HTTP headers (compliant with Google Search Central; zero HTML rewriting):
| Version kind | HTTP X-Robots-Tag |
HTTP Link: rel="canonical" |
HTML <link rel="canonical"> & hreflang |
In sitemap.xml / RSS |
|---|---|---|---|---|
| Default version (or primary alias) | none | none (HTML self-canonical) | self-canonical + full hreflang |
yes (sole source) |
Non-default major line (e.g. /v3.6/, /docs/16/) |
none | target same-language path in default version if present, else self | omitted at build time (C3) |
no |
Exact patch release & prerelease (17.4, devel) |
noindex, follow |
none (never combine noindex with cross-version canonical) |
omitted at build time (C3) |
no |
- Error pages:
404carriesX-Robots-Tag: noindex, loads/_oink/where?path=...to suggest versions containing that path, and marksdata-td-no-history. Unbuilt versions return503 Service UnavailablewithRetry-After: 10. Error page language resolves in order: matched URL language prefix →Accept-Languageheader → site default language.
Architecture
Pipeline
- Resolve: read
oink.yamlfrom the configured ref, compute version/alias tables, and derivesnapshot_key = H(version_commit, skin_commit, hugo_version, profile_version, url_base). Matching keys are skipped immediately. - Materialize: for Track A Hugo versions, create a temporary
git worktreeat the version commit and overlay only the skin’s appearance files; for Track B archives and HTML corpora, read directly without a worktree. - Build / Import: invoke official Hugo in an isolated child process into a temporary output directory, or stream HTML corpus pages through the
pgwebprofile. - Ingest: hash every output file, pack only unseen objects into Brotli clusters in
cache.db, populateentriesandrecent_assets, and updatesearch.dbif the version is insidesearch.scope. - Publish: flip
versionsandaliasespointers in a single SQLite transaction, regenerate/_oink/versions.jsonpayload, and enqueue batched Cloudflare prefix purges if configured.
Decoupled Hugo engine and isolation
- External official Hugo binary:
oinknever importsgohugoio/hugo/commands. It resolves Hugo in order:--hugo→PATH→ auto-managed~/.cache/oink/hugo/<version>/hugo(downloaded from official GitHub Releases with pinned SHA-256 verification unless--offline). This keepsoinkaround~20 MB, avoids Go dependency bloat, and lets sites upgrade Hugo independently ofoink. - Theme provisioning:
_vendor/→ Go module cache (whengois present) → cached OINK theme release injected viaHUGO_MODULE_REPLACEMENTS,GOWORK=off, andHUGO_MODULE_WORKSPACE=off. Sites importing additional non-vendored Hugo modules requiregoorhugo mod vendor;oinkdoes not reimplement Go’s MVS resolver. - Portable child-process resource isolation:
- Never set
RLIMIT_ASon Go child processes (Go’s 64-bit virtual arenammapfails immediately withENOMEM). - Every build child runs in its own process group (
Setpgid: true), receivesGOMEMLIMITset to 80% ofbuild_memory_limit(default4 GiB), runs at lowered priority (setpriority/nice, plus Linuxionice), and is watched every 500 ms by a parent RSS monitor (Linux/proc/<pid>/status, macOSproc_pidinfo) thatSIGKILLs the entire process group on RSS breach or timeout. - On Linux hosts with delegated cgroup v2 write access (such as systemd
Delegate=yes),oinkadditionally enforces kernelmemory.max.
- Never set
- Build security: skin refs are explicitly trusted code;
oink servestill injects a configuration overlay forcingsecurity.exec.allow: []unless--allow-execis explicitly passed, and passes only a minimal environment variable allowlist to build children (never CDN tokens or host secrets).
Storage, Brotli clusters and asset retention
- SQLite Go driver (
CGO_ENABLED=0): default togithub.com/ncruces/go-sqlite3(WASM SQLite with full FTS5, compact binary, zero C toolchain for cross-compilation), benchmarked againstmattn/go-sqlite3duringM0before freezing. - Physical separation into three SQLite databases:
cache.db(WAL,PRAGMA synchronous = NORMAL, rebuildable):meta,clusters(id, codec, raw_size, data),objects(id, hash, cluster, offset, size, media_type),paths(id, path),snapshots(id, key, version, commit_sha, state, created_at),entries(snapshot, path, object) WITHOUT ROWID,recent_assets(path, object, expires_at),versions,aliases. On startup,oinkcleans up any interruptedstate='building'snapshots and unreferenced orphan clusters left by a prior crash.search.db(WAL,PRAGMA synchronous = NORMAL, rebuildable): decoupled FTS5 index so search maintenance never contends with content reads or bloats content snapshots.state.db(WAL,PRAGMA synchronous = FULLfor power-loss durability, non-rebuildable): daily page-view totals and build/audit history. Backed up safely online withoink backup(SQLiteVACUUM INTO) or Litestream.
- Single universal codec — RFC 7932 Brotli (
lgwin=22):- Empirically verified on
pgdoc-cn1 MiB clusters to achieve 42.2× at-q 6(0.76 msp99 decode) and 43.6–46.6× at-q 9..11(0.34–0.42 msp99 decode), outperformingzstd -15while decoding natively in Apple’sCompressionframework (COMPRESSION_BROTLI) with zero third-party dependencies in Crib and pure-Go (github.com/andybalholm/brotli) inoink. - Online
cache.dbappends use fast-q 6; compacted.oinkexports re-sort objects by(path, version_sort_key)and pack at-q 9(or-q 11with--max-compress). - Adaptive cluster size:
1 MiBraw target for small-page corpora (median < 64 KiB);4 MiBraw target for large Hugo pages (median ≥ 64 KiB, still inside Brotli’slgwin=224 MiB sliding window!) so tens of versions share one compression window cleanly.
- Empirically verified on
- Cross-request asset retention (eliminating switch/GC 404s):
- Garbage collection retains snapshots and objects for
max(3 latest snapshots, 48 hours)— strictly longer than CDN edge TTL (24h) plusstale-if-error(1h). - Whenever a request for a fingerprinted asset (
/css/*,/js/*,/webfonts/*, hashed media) misses the newly switched current snapshot, the server falls back torecent_assetsand returns200 OKfrom the retained object.
- Garbage collection retains snapshots and objects for
- Read-only
.oinkdistribution archive (oink.store/v1):- Exported with
oink build --versions -o site.oink: compacted clusters,journal_mode=DELETE,VACUUM, optional scoped FTS5 tables, and canonical logical Ed25519 signing (SHA-256 over sortedmetaexcludingsignatureplus sorted(snapshot, path, object_hash)records stored inmeta['manifest_sha256']and signed inmeta['signature'], avoiding circular file-byte hashing).
- Exported with
Scoped FTS5 search
- Explicit index scope (
search.scope): defaults toactive-lines(non-archived major lines), with optionsdefault-onlyandall. Onpgdoc-cn, indexing the 6 active major lines (PG 13–18, 4,250 unique docs) adds only32.4 MiBin5.1 s, keeping totalpgdoc-cnstorage (cache.db+search.db) around75–85 MiB(<100 MiB). - Version and language isolation: queries filter by
(version_line, lang)directly inside the index rather than taking global Top-K across all versions and post-filtering (preventing empty recalls on high-frequency terms and cross-language leakage). - Tokenization and section granularity:
- Hugo sites ingest section-level records directly from OINK’s
offline-search-index.<lang>.json(preserving headings,data-td-search-entryanchors, and excerpts);pgwebcorpora split sections on headings. - FTS5 uses
content=''andtokenize="unicode61 tokenchars '_-./:'"so identifiers (work_mem,--baseURL,/pg/data) stay intact; a shared Go pre-processor emits overlapping CJK bigrams and normalizes common SQL/JSON operators (->>,::,@>). - Acceptance uses a fixed curated 60-query EN + ZH + identifier/operator benchmark (targeting Top-5 recall
≥ 90%and p99 latency< 25 ms), rather than claiming byte-level ranking equivalence with the browser’s 922-line scanning engine.
- Hugo sites ingest section-level records directly from OINK’s
Serving, Cloudflare caching and updates
Request dispatch order: /_oink/* endpoints → /versions/ static directory → longest-prefix version/alias match (or default version / root_redirect) → pin current snapshot → entry lookup → recent_assets fallback (for fingerprinted assets) → language-aware 404 / 503.
| Response | Browser Cache-Control |
Cloudflare Cloudflare-CDN-Cache-Control |
Invalidation |
|---|---|---|---|
| Fingerprinted assets | public, max-age=31536000, immutable |
max-age=31536000 |
Content-addressed filename |
| Release / line HTML | public, max-age=300 + ETag |
max-age=86400, stale-while-revalidate=600, stale-if-error=3600 |
Batched prefix purge on publish |
Moving branch HTML (devel) |
public, max-age=60 + ETag |
max-age=300, stale-while-revalidate=60, stale-if-error=1800 |
Prefix purge on publish |
/_oink/versions.json |
public, max-age=60 |
max-age=60, stale-while-revalidate=300, stale-if-error=3600 |
Single-URL purge on version change |
/_oink/search, /where, /hit |
private, no-store (/where: public, max-age=60) |
no-store |
Never cached |
- Cloudflare Cache Rules contract: Cloudflare does not cache HTML by default, and
s-maxagecauses Cloudflare to ignorestale-if-error. UsingCloudflare-CDN-Cache-Controlavoids that conflict so edge nodes serve stale pages across origin restarts. Operators configure one Cache Rule matching public paths (excluding/_oink/*) withEligible for cacheandUse cache-control header if present(never “Ignore cache-control header”). The purge client batches up to 100 prefixes per API call and rate-limits cleanly under Cloudflare Free’s5 req/minceiling. - Updates and fair scheduling: triggered by periodic
git fetch(default 60 s), HMAC-verified webhooks (POST /_oink/hooks/<provider>), or local bare-repo pushes. Builds run at default concurrency1with aging priority (default version first, waiting versions gain priority over time so frequentmaincommits cannot starve low-traffic lines); newer commits coalesce queued builds for the same version.
Cookieless page views and hybrid apps
- Page views (
/_oink/hit, opt-in, off by default): pages sendnavigator.sendBeacon. The server verifies same-originOrigin/Sec-Fetch-Site, filters common bot UAs, and deduplicates repeat views in memory using a Plausible-style daily rotating random salt hashSHA256(daily_salt || host || ip || ua || path)(no cookie, no IP written to disk, salt discarded every 24 hours). Increments flush every 60 s into daily aggregates instate.db. - Comments: v1 uses OINK’s existing giscus integration enhanced with a version-independent
termkey (C4). - Hybrid integration for
pgextandpg.center: those applications retain their own Go + PostgreSQL runtime for live catalogs and knowledge graphs, share OINK’s visual identity viapartial "css/bundle.html" "chrome", and either reverse-proxy/docs/tooink serveor (in a later library phase) embed a read-onlyoink/readerGo package over.oinkarchives.
Configuration
Two files with clean ownership: hugo.yaml owns page rendering and params.ui.*; oink.yaml (schema_version: oink.serve/v1) owns publishing, versions, search scope, media mounts, and CDN purging. Secrets come strictly from environment variables.
Output, accessibility and security boundaries
- Output and progressive enhancement: static HTML stays complete without JavaScript; without JS, the version control degrades to a semantic link to
/versions/(a theme-rendered static directory of all versions); Print, Markdown, and LLMS remain per-version; RSS andsitemap.xmlcome from the default version only. - Accessibility and localization: every new user-visible string (
503,prereleasebanner,/versions/page, 404 version hints, version-scoped search) ships natively in all 32 OINK locales and passes the documentation site’s axe checks. - Management and metrics isolation: management CLI commands talk solely over
<data-dir>/oink.sockcreated with mode0600. Prometheus/metricsis served only onoink.sockor an explicit loopback-only listener (--metrics-listen 127.0.0.1:9091), never on the public reverse-proxied HTTP port. - No accidental secret exposure: child Hugo processes run with
security.exec.allow: []by default and stripped environment variables; CSP headers permit OINK’s own startup scripts without wildcard inline execution.
Theme coordination
Dropping server-side HTML slot splicing, accounts, and built-in comments trims theme work down to six small, high-leverage changes (C1–C6). All paths below are relative to the OINK theme repository root.
Theme changes (C1–C6)
| Item | Change | Files | Stage |
|---|---|---|---|
| C1 | Fix O(N²) linear scan in pager-state.html with a cached path → index map; update sidebar-nav.js to highlight the active row from window.location.pathname rather than link[rel="canonical"] |
layouts/_partials/pager-state.html, assets/js/sidebar-nav.js |
M1 |
| C2 | Emit noindex on 404.html; add a localized 503 (“building”) template across all 32 locales; add data-td-no-history to error templates and update history.js to skip any page carrying it |
layouts/404.html, layouts/_partials/head.html, assets/js/history.js, i18n/*.yaml |
M1 |
| C3 | Add a build-level oink_managed_seo switch that omits HTML <link rel="canonical"> and hreflang on non-default versions (delegated to HTTP headers); remove target="_blank" on same-site archive banner links and add a prerelease banner (32 locales); support configuring site-root storage scope for history and shortcuts without breaking subpath isolation |
layouts/_partials/seo-alternates.html, layouts/_partials/version-banner.html, layouts/_partials/scripts.html, layouts/_partials/shell/history-dialog.html |
M1 |
| C4 | Add an opt-in js/chunks/oink-versions.js runtime that hydrates the navbar/drawer/footer version menu, Command Palette switch_version options (preserving page path), and archived/prerelease banners from /_oink/versions.json, with a no-JS static link to /versions/; fetch /_oink/where on 404 pages; add a version-independent term option to giscus.html |
layouts/_partials/navbar.html, layouts/_partials/actions/context.html, layouts/_partials/giscus.html, assets/js/ |
M1 |
| C5 | Refactor command-palette.js query execution to support an opt-in async remote search backend (/_oink/search with debounce, AbortController, and version-scope toggle), preserving zero network requests when unconfigured |
assets/js/command-palette.js, layouts/_partials/shell/search-dialog.html |
M2 |
| C6 | Add a minimal corpus shell layout (one body insertion slot + navigation JSON hook) and a .td-corpus-pgweb CSS adapter layer so external HTML corpora inherit OINK styling cleanly |
layouts/, assets/css/td/ |
M2 |
(Independent theme housekeeping, non-blocking: add an empty tests/go.mod in the OINK theme repository so the 79 MB test fixtures stop inflating Go module zips for all consumers.)
Process coordination
- Independent releases: because
oinkdoes not embed Hugo or require a lockstepembed.goin the theme root, OINK theme releases andoinkbinary releases ship independently. - Contract ownership:
/_oink/versions.jsonschema,/_oink/searchresponse shape, and theC6corpus shell contract live in OINK’s bilingual Design contracts with explicit version fields. - Checkers:
oinkGo tests verify plain-Hugo parity,pgdoc-cnstorage/latency budgets,kill -9recovery, asset grace-window retention, HTTP SEO headers, andexecisolation; theme checkers (check-shell.py,check-goldens.py,check-i18n.py) andoink.pgsty.comPlaywright suites verify rendered output.
Compatibility and migration
- Plain Hugo sites are completely unaffected. The theme repository remains pure templates, CSS, JS, and i18n with no server code or
embed.gorequirement. - Existing
params.versionsstatic sites keep working unchanged. Adoptingoink serveswitches them to/_oink/versions.jsonwithout editing historical tags. - Retiring
oink-cli. If accepted, the CLI contract is marked superseded andpgsty/oink-cliis archived. Essential link/translation checks move tooink check;oink.result/v1andoink.policy/v1are retired cleanly (oink.yamluses explicitschema_version: oink.serve/v1). - Crib compatibility. Existing
.cribfiles are untouched; Crib adds.oink(oink.store/v1) reading using Apple’s built-inlibsqlite3andCOMPRESSION_BROTLIwith zero new third-party dependencies.
Implementation and checker plan
Create a clean Go repository (pgsty/oink-server, producing the oink binary) split into focused packages: hugoexec (official Hugo resolution, SHA-256 caching, isolated child runner + RSS watchdog), gitsrc (ref resolution, worktree materialization, cat-file --batch streaming), corpus/pgweb, store (cache.db + Brotli clusters + .oink compaction & Ed25519 manifest signing), search (search.db scoped FTS5 + CJK/identifier analyzer), serve (routing, HTTP SEO/CDN headers, Cloudflare batched purge, recent_assets fallback), pv (daily-salt dedup counter + state.db), and admin (0600 Unix socket + VACUUM INTO backup).
Milestones
| Milestone | Estimate | Scope | Exit evidence |
|---|---|---|---|
| M0: Lean dev & check binary | 2 weeks | oink (dev, build, check, versions, hugo); official Hugo auto-cache + SHA-256 verification; LiveReload WebSocket proxy; ncruces vs mattn SQLite benchmark |
Clean machine without preinstalled Hugo/Go previews oink.pgsty.com and pigsty.io with live reload; oink build matches plain Hugo byte-for-byte |
| M1: Multi-version Hugo serving | 3 weeks | oink serve, oink.yaml (v1), oink freeze, dual-track lifecycle, cache.db (Brotli clusters + 48h recent_assets grace window), atomic switch, status/rebuild/rollback/backup, HTTP SEO & Cloudflare headers, theme C1–C4 |
Bilingual site with 5+ tags, 1 frozen legacy version, and moving devel runs live; publishing a new tag rebuilds zero old versions; bad commits/OOM/kill -9 keep live site up; old HTML fetching old fingerprinted CSS returns 200; rollback < 1 s; EN/ZH + axe pass |
M2: pgdoc-cn 560 versions & scoped search |
2–3 weeks | pgweb importer, theme C5–C6, search.db (active-line FTS5 + CJK bigrams + identifiers/operators), 60-query benchmark |
All 560 pgdoc-cn versions reachable; cache.db + 6 active major lines search.db total < 100 MiB; cold start < 2 s; hit p99 < 5 ms, cluster miss < 15 ms; resident RAM < 512 MiB; 60-query Top-5 recall ≥ 90% |
M3: .oink packages, Crib & PV |
2 weeks | Compacted .oink export (brotli -q 9), Ed25519 manifest signing & verification, oink serve x.oink, Crib native reader (libsqlite3 + COMPRESSION_BROTLI), daily-salt /_oink/hit PV |
Signed .oink round-trip serves byte-identical output; Crib opens all 560 pgdoc-cn versions with zero third-party libraries; PV deduplicates refreshes with no IP persisted |
Acceptance criteria
- Zero-rebuild publishing: pushing a new tag
v3.8.0on an M1 test site triggers exactly one Hugo build; existing versions remain untouched;/_oink/versions.jsonupdates and client version menus showv3.8.0with working same-page links. - No cross-request asset tearing: after 4 consecutive CSS-changing publishes and a GC pass within 48 hours, an older cached HTML page’s request for its original fingerprinted CSS still returns
200 OK. - Resilience & memory containment: an intentionally low
build_memory_limittriggers watchdogSIGKILLof the Hugo child process group without degrading server availability;kill -9mid-ingest leaves live snapshots intact and auto-cleans orphan clusters on restart;oink rollbackcompletes in< 1 s. pgdoc-cnscale & latency: all 560 versions resolve;cache.db+ 6-linesearch.dbstay under100 MiB; cold start< 2 s; p99< 5 ms(LRU hit) /< 15 ms(cluster decode); 60-query EN/ZH/identifier search benchmark hits Top-5≥ 90%at< 25 msp99.- SEO & security verification: default version emits self-canonical +
hreflang; non-default lines emit HTTPLink: rel="canonical"with no conflicting HTML canonical/hreflang; patch releases anddevelemit onlyX-Robots-Tag: noindex, follow;/v{default}/xreturns302; repositories enablingsecurity.execare blocked by default;oink.sockis0600;/_oink/metricsis404on the public listener. - Package round-trip:
oink build --versions -o x.oinkfollowed byoink serve x.oinkpasses Ed25519 verification and serves byte-identical responses for every URL.
Risks
| Risk | Mitigation |
|---|---|
| Readers without JS do not see the interactive version dropdown | Every page carries a static <a href="/versions/"> link to a theme-rendered full version index; SEO relies on HTTP headers, not JS |
| Maintainer upgrades OINK across a breaking change without freezing old lines first | oink check --versions audits active lines against the new theme and lists versions needing oink freeze before cutover |
Cloudflare Cache Rule misconfiguration or Free-tier purge throttling (5 req/min) |
Ship copy-pasteable Respect-Origin Cache Rule recipes + oink verify-cdn; batch up to 100 prefixes per purge with rate backoff |
| Background builds saturate a small single-core VPS | Default concurrency 1, nice/ionice, GOMEMLIMIT, RSS watchdog, and Cloudflare edge absorption (stale-if-error=3600) |
pgweb DocBook HTML variations across 25 years of PostgreSQL releases |
Test importer across all 560 real pgdoc-cn / pgdoc-en tags (v6.0–v20devel) in M2 CI fixtures |
Alternatives
| Alternative | Conclusion |
|---|---|
Per-version static builds on Cloudflare Pages (mike / Read the Docs style) |
mike and RTD already use client-side versions.json (no full menu rebuilds), so small sites work well via oink build --versions; however 560 pgdoc-cn versions (529k files, 6.15 GB) exceed Pages’ 20k/100k file limits and blow up storage |
| Cloudflare R2 + Workers + D1 | Avoids a VPS origin, but D1 query/storage pricing for 529k manifests and full-text search is unacceptable to the owner; self-hosted oink + local SQLite + free Cloudflare CDN keeps cost flat and works identically offline |
Embedding github.com/gohugoio/hugo/commands in-process/re-exec |
Couples to an unstable internal Go API, bloats binary to ~130–145 MB, and forces releasing oink on every Hugo upgrade; orchestrating the official Hugo binary is cleaner and smaller |
| Server-side HTML byte-offset slot splicing (v1 draft Stage 2) | Breaks page-for-page version_menu_pagelinks without server-side URL rewriting, ties all old versions’ ETags to default-version page deletions, and doubles theme surface (T1–T12); client versions.json + HTTP SEO headers achieve the same goal far more simply |
Kiwix/ZIM or docs.rs S3 + PostgreSQL |
ZIM is a strong read-only archive reference (clusters + index), while SQLite + Brotli avoids writing a custom binary parser for Crib (Apple ships libsqlite3 + COMPRESSION_BROTLI); docs.rs targets multi-terabyte Rust crates with container fleets, overkill for single-repo docs |
Hugo native [versions] matrix (v0.153+) |
Builds every version together in one Hugo invocation; memory and rebuild cost scale as versions × pages (unworkable for 560 versions). Suitable only for small static sites under theme roadmap R2 |
Resolved design decisions
All architectural decisions previously left open are resolved for this v2 baseline:
- Decoupled official Hugo binary (instead of importing
gohugoio/hugo/commands): keepsoink~20 MB, decouples Hugo upgrades, and eliminates Go dependency conflicts. - Zero HTML splicing (
/_oink/versions.json+ HTTPLink/X-Robots-Tagheaders) (instead of Stage-2<template data-td-slot>splicing): removes full rebuilds on release, preserves page-for-page switching, and cuts theme coordination from 12 items to 6. - Dual-track version lifecycle (
mode: build+oink freeze): active lines keep their owndata/andstatic/while sharing a pinned release-tagskin; historical versions crossing breaking OINK retirements freeze cleanly without compatibility shims. - Universal RFC 7932 Brotli (
lgwin=22) foroink.store/v1: empirically outperformszstd -15onpgdoc-cn1 MiB clusters (42.2–46.6×,< 0.8 msp99 decode), runs pure-Go inoink, and decodes natively in Crib via Apple’sCOMPRESSION_BROTLIwith zero third-party dependencies. - Scoped
search.db(active-linesdefault): separates FTS5 fromcache.dband indexes active major lines by default (32.4 MiBfor PG 13–18), keeping all 560pgdoc-cnversions + search under100 MiB. - Clean new binary repository (
pgsty/oink-server) and explicitoink.yamlschema (oink.serve/v1): retirespgsty/oink-clicleanly without carrying deadoink.result/v1history. - Defer ACL/auth/comments and keep
pgext/pg.centerdynamic apps separate: keeps v1 focused, secure behind Cloudflare CDN, and deliverable in ~9–10 weeks acrossM0–M3.
Decision log
| Date | Record |
|---|---|
| 2026-11-27 | Owner defines online needs: multi-version docs (including 500+ PG versions), search, page views, comments, pgext/pg.center, Cloudflare preference |
| 2026-11-28 | Initial v1 draft written (embedded Hugo CLI, Stage-2 HTML slot splicing, zstd SQLite store, full-corpus FTS5, accounts/ACL/comments) |
| 2026-11-28 | Adversarial architecture review and live local benchmarks on pgdoc-cn, pigsty.io, pgext.cloud, and pg.center identify key flaws: 560-version FTS5 exceeds 473 MiB, Stage-2 splicing conflicts with version_menu_pagelinks and per-page canonical, content/-only skinning breaks data//static/ and retired shortcodes, RLIMIT_AS crashes Go children, s-maxage disables Cloudflare stale-if-error, and brotli beats zstd while matching Apple’s native COMPRESSION_BROTLI |
| 2026-11-28 | Owner confirms self-hosted SQLite behind Cloudflare CDN (no D1), defers ACL out of v1, and delegates remaining architecture decisions; proposal rewritten as v2 redesign |