docs(production): standardiserad produktionsberedskap och gap-analys

Lägger docs/production-readiness.md och siax/production-gaps.json enligt SIAX Master Definition of Done. Underlag: git-, kod- och live-evidens 2026-11-11. Nivån är evidensbaserad, inte ett leveransgodkännande.
This commit is contained in:
2026-11-10 03:07:36 +01:00
parent fb072d47c7
commit a4189333af
959 changed files with 5 additions and 115771 deletions
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
-159
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
-244
View File
@@ -1,244 +0,0 @@
# 06 · Data engine
The engine turns sources into delivered, provenance-tagged data. It is the legal motor — the whole product positioning depends on it. The real code lives in `services/api/` (FastAPI orchestrator + workers), **not** at the `src/workers/` path this doc used to point to — the "Pipeline stages" section below states plainly, stage by stage, what's built vs. still spec.
> ### Known issue — two diverged git remotes for this repo (unresolved, Simon's call)
> This doc describes the compliant-only sourcing chain as *the law*. That law was briefly violated on one
> of this repo's two remotes, so anyone reading this doc needs to know both exist:
> - `github.com/sax3l/0pt` (this session's `origin`) — the remote this documentation pass was verified against.
> - `git.siax.io/sax3l/0pt` (Gitea) — a **separate, diverged** remote that shares origin history with GitHub for
> at least part of the codebase (`services/api/workers/adaptive_router.py` is byte-for-byte identical between
> GitHub's current `main` and Gitea's post-fix PR branch, so they were once the same commit lineage).
>
> Gitea's `main` independently accumulated three commits on 2026-07-13 that added a real WAF-bypass /
> proxy-rotation / fake-identity scraper stack (`services/scrapers/*`) — exactly the category of code
> §"Prohibited" below and CLAUDE.md §1 forbid. Those commits never touched GitHub's `main`. The stack was
> since removed on Gitea via PR #1, but:
> - **Which remote is authoritative / deployed to `0pt.app` is unknown** — not resolved this session.
> - **Whether the two remotes are supposed to be kept in sync is unknown** — not resolved this session.
>
> This pass does not resolve either question. Simon: decide which remote is canonical, confirm the other has
> no lingering bypass code, and either merge or retire the loser before treating "the 0pt repo" as singular
> in any future doc pass.
## Sourcing chain (strict priority — this is the law)
For each field × market, acquire in this order; stop at the first that works:
1. **Official API / bulk** — registries with programmatic/bulk access (highest confidence).
2. **Authorized public web** — clearly public pages, **respecting `robots.txt` and rate limits**, no auth walls.
3. **Licensed partner data** — contractually obtained.
4. **Otherwise → "not available / licensed only"** — delivered honestly as level 0. **Never guessed.**
**Current implementation covers tier 1 only.** All five working connectors in `services/api/sources/connectors.py`
(`gleif_by_lei`, `brreg_by_orgnr`, `companies_house_by_number`, `prh_by_businessid`, `cvr_by_number`) call
official JSON APIs over `httpx`, nothing else. There is no HTML-scraping/parsing library anywhere in
`services/api` (no `bs4`/`lxml`/`selectolax`, no `playwright`, no `scrapy`/`crawlee` — checked against
`requirements.txt` and the source tree), so tier 2 (authorized public web) has no code path yet. Tier 3
(licensed partner) also has no connector — `sources.yaml`'s `bolagsverket` entry is `access: licensed` with
no matching function in `connectors.py`; it correctly falls through to level 0 today. Both tiers remain
target design, not built.
### Prohibited (do not build, keep, or extend)
- WAF/bot-detection bypass — **including FlareSolverr**, "stealth"/patched browsers, undetected-* used to defeat detection.
- Proxy/fingerprint rotation to evade bans; scraping behind login walls; automated fake-account creation (Apollo etc.).
- **Reconciliation note (stale — kept for history):** this section used to say "if `browser_worker.py` has an
`HTTP → FlareSolverr → Playwright` chain, drop the FlareSolverr stage." **`browser_worker.py` does not exist
anywhere in this repository** (verified this pass — no file of that name on GitHub's `main`). There is
nothing to reconcile in the current Python engine. The bypass code that *did* exist, briefly, lived in
`services/scrapers/*` on the Gitea remote only (see the Known Issue callout above) and has since been
removed there via PR #1. `adaptive_router.py` (below) has never contained a bypass tier on either remote —
it chooses among **compliant** methods only (API > bulk > authorized fetch > licensed), by design.
## Pipeline stages (per job)
```
sourcing → extraction/OCR → structuring → enrichment/fusion → QA
```
The stage names below are the target architecture. `services/api/workers/pipeline.py::run_job` is the one
function that actually runs today, and it implements a much smaller slice of this than the stage list
implies — see the "built vs. not built" status called out under each stage below.
1. **Sourcing** — `adaptive_router.plan_for_market(market)` returns a hardcoded, ordered list of compliant
`source_id`s per market (see table below); `pipeline.py` tries each in order for a given key and **stops at
the first one that returns a result** (`break` after first hit). This is sequential fallback, not
concurrent racing — the phrase "source-racing = query several authorized sources and take the
fastest/freshest" describes a target behavior that isn't implemented; today only one source is ever queried
per key unless the first fails. Writes raw payload fields directly into the record dict (no separate
raw-payload store).
2. **Extraction / OCR — not built.** There is no `ocr_worker`, no `unstructured`, no `paddleocr`/`pytesseract`
anywhere in this repo (checked `services/api/requirements.txt` and the full source tree — none present).
"Extraction" today is just each connector in `connectors.py` parsing the JSON response of its own API call
into a `CompanyResult`. Document/PDF/image ingestion and the OCR cascade described here are spec only.
3. **Structuring — partially built.** `services/api/workers/resolve.py::resolve()` does real, deterministic
entity resolution: block by `(market, name[:1].upper())`, then `rapidfuzz.fuzz.token_sort_ratio(...) >= 92`
to merge duplicates, bumping `confidence` by +0.1 per corroborating match (capped 0.99) and incrementing
`agreed_sources`. That part is real and unit-testable. What's **not** built: no spaCy/transformers, no NER,
no multilingual normalization (`sv/no/da/fi/de/fr` from the original text), and no explicit LEI-based
cross-market entity linking — matching is name-string-similarity only, within the same market. `spacy` and
`transformers` are not in `requirements.txt`.
4. **Enrichment / fusion — partially built, not fully wired into the job.** The confidence/agreement bump
described above happens inside `resolve()`. Separately, `opensanctions_screen()` (sanctions/PEP) and
`rdw_vehicle()` (NL vehicle data) are real, working connectors in `connectors.py` — but `pipeline.py` never
imports or calls either one. They're only reachable as their own standalone endpoints
(`GET /screen`, `GET /vehicles/{plate}` in `orchestrator/main.py`), not as an automatic enrichment step on
an order's records. NACE/SNI classification and "website/tech" enrichment have no code anywhere.
5. **QA — not built beyond a single threshold filter.** The entire QA stage in `pipeline.py` is:
`delivered = [r for r in deduped if r["confidence"] >= threshold]`. That's real and does drop
below-threshold rows (deliver fewer, never fabricate — that principle holds). But there is no
Great Expectations (not in `requirements.txt`, not imported anywhere), no separate validity/format,
completeness, freshness, or post-dedup-uniqueness checks beyond the confidence number already computed in
structuring, and no quality-report object emitted or stored anywhere — `deliveries` (the SQL table defined
in `sql/001_init.sql`) is never written to by this service. This mirrors a confirmed, broader finding this
session: 0pt's data-quality/QA layer was at one point documented elsewhere (TypeScript side,
`src/services/quality-check-service.ts` etc.) as if built and tested, but those files **do not exist** in
this repo's history at all (zero commits, any branch — see `docs/07-dependencies.md` note). `docs/ICEBERG_WRITE_BOUNDARY.md`,
`docs/11-lakehouse-write-plan.md`, and `docs/P0_QUERY_SOURCE_FLOW.md` have all since been corrected — each
now carries its own explicit "fabricated, not built" callout rather than asserting those files as real —
and `docs/P0_DATASET_QUALITY_FLOW.md` documents this gap as target-spec-only. The Python engine
independently confirms the same gap: **no real quality-check enforcement exists in this codebase today**,
in either language.
**"Each stage updates `jobs` ... so the production tracker / SSE can render it live" is not what happens.**
`run_job` runs synchronously start-to-finish and returns one final dict (`stage: "qa", pct: 100, state: "done",
metrics, records`). `orchestrator/main.py`'s `POST /orders/{oid}/run` awaits the whole thing and stores that one
result in an in-memory `_JOBS` dict; `GET /orders/{oid}/status` just returns whatever's there, or a static
`{"stage": "queued", "pct": 0, "state": "queued"}` placeholder before it's run. There is no per-stage
incremental progress, no `pct` that climbs, and **no SSE endpoint exists anywhere in `orchestrator/main.py`**
(grepped — none). Live progress rendering is target design, not current behavior.
### `adaptive_router` — actual market coverage (verified against `services/api/workers/adaptive_router.py`)
`MARKET_SOURCES` currently has real entries for exactly five markets, each a short compliant list — not the
"elaborate multi-source lists" an earlier version of this router may have implied:
| Market | Ordered plan | Note |
|---|---|---|
| NO | `brreg`, `gleif` | |
| GB | `companies_house`, `gleif` | |
| FI | `prh`, `gleif` | |
| DK | `cvr`, `gleif` | |
| SE | `gleif` only | Bolagsverket bulk is licensed (see above); SE company core relies on GLEIF + a not-yet-built licensed/partner route |
| anything else | `["gleif"]` | fallback in `plan_for_market()` |
`ACCESS_RANK` (`api=0, bulk=1, authorized_web=2, licensed=3`) is defined in the same file but is **not
actually used** by `plan_for_market()` to sort anything — the lists above are hand-ordered constants already
in the desired priority, and the rank dict is currently dead code (documentation-as-code, not logic).
## Confidence & provenance scoring
- Per field, `connectors.py`'s `Provenance` dataclass carries: `field_name`, `source_id`, `confidence` (0–1),
`level` (0–3), `freshness`. **`agreed_sources` is not a field on `Provenance`** — it's tracked separately, at
the merged-record level, by `resolve()` (`match["agreed_sources"] = ... + 1`). If a doc or downstream
consumer expects `agreed_sources` inside each `bridge_provenance` row, that's a mismatch to reconcile against
the actual dataclass shape, not a fact to assume.
- Level: 0 = unavailable/licensed; 1 = single source; 2 = partial corroboration; 3 = ≥2 independent sources agree.
- `est_confidence` on the order = aggregate target (computed in `orchestrator/main.py::compute_estimate`);
delivered `avg_confidence` = actual, computed in `pipeline.py` as the mean confidence of delivered rows.
- **None of this is persisted to Postgres by the current service.** `sql/001_init.sql` defines the
`bridge_provenance` table (plus `dim_company`, `dim_source`, `fact_financials`, `deliveries`, etc.), and
`asyncpg` is a listed dependency — but nothing in `services/api` actually calls `asyncpg` or issues a query.
`DATABASE_URL` is read exactly once, in `orchestrator/main.py`'s `/health` handler, purely to report a
boolean (`"db": bool(os.getenv("DATABASE_URL"))`). `orchestrator/main.py` stores orders and jobs in
in-memory dicts (`_ORDERS`, `_JOBS`) that reset on every restart. The schema exists; the wiring from
pipeline output → Postgres rows does not yet.
### Network-layer provenance: `1p` (not yet in use)
`bridge_provenance` answers *which source a field came from*. It does not answer *what
actually happened on the wire* — which policy authorized the fetch, whether `robots.txt` was
read and what it said, or whether the bytes we parsed were the page or a bot wall served with
HTTP 200. **[`1p`](https://git.siax.io/sax3l/1p)**, the SIAX egress measurement point, closes
that gap and extends the provenance chain all the way down to the network layer.
1p owns four things: a per-destination policy as code (default DENY; rate, robots/ToS stance,
allowed methods), a single egress choke point, block detection, and one provenance record per
fetch written to AUD0. Everything else is composed (AUD0, ST0RE, CL0UD).
Why this matters for 0pt specifically — three facts that are hard to assert without it:
| Claim 0pt makes | What 1p adds |
|---|---|
| "acquired from an authorized public page, respecting `robots.txt`" | The record carries the robots decision **plus a sha256 of the `robots.txt` it was taken from**. A policy that says `respect` and cannot read robots denies the fetch — silence is not permission. |
| "these are the bytes we parsed" | `body_sha256` per fetch, so a delivered field can be tied back to the exact response at the exact time. |
| "level 1/2/3 corroboration from independent sources" | Responses are classified `ok` / `rate_limited` / `forbidden` / `captcha` / `blocked_soft` / `error`. `blocked_soft` is the expensive one: **HTTP 200 whose body is a block page**. Without it, a bot wall gets parsed and scored as corroborating data. |
**It is a measurement point, not a bypass.** This is consistent with, not an exception to,
the prohibitions above and in `CLAUDE.md` §1: 1p exists to *detect* blocking and *prove*
provenance, never to evade. Its purchased-residential egress pool is an interface with a stub
that throws — wiring it up would be a separate, explicit decision. Block detection also
alarms on a rising *trend*, never on single events, and deliberately excludes `error`
(their 5xx, our timeouts) from the blocking measure.
**Status: not in use.** 1p is Phase 0 — code, contracts, tests; not deployed, no credentials
set. No 0pt worker routes through it today, and `bridge_provenance` remains the only
provenance 0pt writes. Adopting it is a later, separate step.
## `sources.yaml` (machine-readable registry)
Single registry that drives the router, the `/sources` API, and the (still-to-be-built) public sourcing-map
page. `services/api/sources/sources.yaml` currently has **8 entries**: `gleif`, `brreg`, `companies_house`,
`prh`, `cvr`, `bolagsverket`, `rdw`, `opensanctions`. Schema per entry (as actually used, confirmed against the
file — no `entities`/`fields` mismatch found):
```yaml
- source_id: gleif
name: GLEIF (LEI)
market: global
access: api # api | bulk | authorized_web | licensed
cadence: daily
licence: "open (CC0) — VERIFY current terms"
entities: [company]
fields: [lei, legal_name, address, status]
base_url: https://api.gleif.org
robots_ok: true # for authorized_web only; must be honored
notes: "cross-border key"
```
`orchestrator/main.py` loads this file once at import time (`yaml.safe_load(...)`) and serves it through
`GET /sources` (id/name/market/access/licence/cadence only) and `GET /sources/{market}`. It is genuinely the
live registry behind those two endpoints — that part of the doc's original claim holds.
### Starter set (VERIFY current access/licence per source before relying — terms change)
- **GLEIF / LEI** — typically open; cross-border key. Connector: `gleif_by_lei` — real, working.
- **Brønnøysund (Brreg, NO)** — typically open API. Connector: `brreg_by_orgnr` — real, working.
- **Companies House (UK)** — free API (key required, `COMPANIES_HOUSE_API_KEY`). Connector:
`companies_house_by_number` — real; degrades honestly to level-0 unavailable if the key is unset (does not
fabricate).
- **PRH (FI)** — Connector: `prh_by_businessid` — real, working.
- **CVR / Virk (DK)** — connector actually calls `cvrapi.dk` (a third-party aggregator), **not** Virk's own API
directly, despite the registry entry's `base_url: https://datacvr.virk.dk`. `sources.yaml`'s `base_url` for
`cvr` does not match what `connectors.py::cvr_by_number` actually calls — flag for reconciliation (either
update `base_url` to `cvrapi.dk` or switch the connector to call Virk directly; not resolved this pass).
- **Bolagsverket (SE)** — restricted for bulk; `sources.yaml` marks it `access: licensed`; **no connector
exists** for it in `connectors.py`. Consistent with the doc's own "plan licensed/partner route" framing —
not a false claim, just confirming it's still unbuilt.
- **RDW (NL)** vehicle data — open, Socrata-backed. Connector: `rdw_vehicle` — real, working, but **not called
by the job pipeline** (only reachable via `GET /vehicles/{plate}`).
- **OpenSanctions** — global sanctions/PEP screening. Connector: `opensanctions_screen` — real, working, same
caveat: reachable only via `GET /screen`, not part of `run_job`.
- Vehicle beyond RDW (**Traficom FI**, **Transportstyrelsen SE**, **DVLA UK**) — no connectors exist yet;
*(verify each before building; vehicle/PII rules differ)*.
> Do not hardcode access terms as fact. When building each connector, confirm the current API/licence/robots
> status and record it in `sources.yaml`. If unclear or disallowed for bulk, route to licensed/partner or mark
> fields level 0.
## Structured financials (XBRL) — real but unwired
`services/api/sources/financials.py::companies_house_filings()` is a real, working function: given a
Companies House number and `COMPANIES_HOUSE_API_KEY`, it fetches the accounts filing history and returns up to
10 filings. It is **not imported or called anywhere else in the codebase** (grepped `services/api` — only
`financials.py` itself references the function name). The file's closing comment describes a further XBRL
extraction step ("with `arelle` installed, download each accounts filing's iXBRL document and pull tagged
facts...") that has no code at all — `arelle` is not in `requirements.txt`. Treat the whole file as a real but
disconnected building block, not a wired pipeline stage.
## Libraries used here
Target list only — see `docs/07-dependencies.md` for what's actually installed today vs. still to be added,
with an explicit install-status callout per package. As of this pass, the *only* Python packages installed for
this engine are `fastapi`, `uvicorn`, `pydantic`, `httpx`, `asyncpg` (unused), `python-dotenv`, `pyyaml`,
`rapidfuzz`, `tenacity` — i.e. the API-only tier 1 sourcing + structuring-by-fuzzy-match slice described above,
nothing from the extraction/OCR/NER/quality layers this section used to list as if already in place.
File diff suppressed because one or more lines are too long
-279
View File
@@ -1,279 +0,0 @@
# 08 · Infrastructure
> Verified against actual repo state 2026-07-19 (branch `main`, plus `.env.example` read from
> `feature/0pt-env-example`). Where this doc previously described a target that doesn't match
> what's committed, that's called out explicitly rather than silently corrected — see the repo's
> honesty convention in `docs/ICEBERG_WRITE_BOUNDARY.md`.
## Repo structure (actual, not the original `apps/web` sketch)
The monorepo did **not** converge on the `apps/web/` + `packages/shared/` layout this doc originally
sketched. What's actually on `main` today:
```
0pt/
├─ CLAUDE.md
├─ README.md · SECURITY.md
├─ docs/ # this documentation set
├─ app/ # Next.js App Router (Vercel) — the "edge" plane, AT THE REPO ROOT
│ ├─ api/ # route handlers: orders, auth, admin, catalog, connections,
│ │ # vehicles, subscriptions, sources, estimates, health, uploads,
│ │ # payments, 0pt/*, screen, webhooks, ai
│ ├─ bestall/ katalog/ kallor/ order/ portal/ admin/ tjanster/ # pages
├─ lib/ # edge-side helpers: db.ts, engine.ts, auth.ts, stripe.ts,
│ │ # orders-store.ts, subscriptions-store.ts, data.ts, services.ts
├─ src/ # SIAX-platform-facing TS layer (NOT under app/ or lib/)
│ ├─ clients/ # cl0ud-, n0d-, aud0-, st0re-, st0re-lakehouse-client.ts
│ ├─ services/ # dataset-, source-, source-query-, iceberg-write-,
│ │ # document-capture-, document-extraction-, external-writeback-,
│ │ # source-rate-policy-, dataset-iceberg-mapping-service.ts
│ ├─ adapters/ # local-blob-store.ts, odoo-bills-adapter.ts, graph-mailbox-adapter, ...
│ └─ types/
├─ components/ hooks/ styles/ # design system in code (docs/05) — data-artifact.tsx,
│ │ # provenance-badge.tsx, embed.tsx, use-reveal.ts, globals.css
├─ packages/schemas/ # JSON Schemas for 0pt.* event/entity contracts (not a pnpm workspace
│ │ # package today — pnpm-workspace.yaml has no `packages:` list)
├─ services/api/ # FastAPI orchestrator + workers (the "engine" plane, on a VPS)
│ ├─ orchestrator/main.py
│ ├─ workers/ # adaptive_router.py, pipeline.py, resolve.py, queue.py, run.py
│ ├─ sources/ # sources.yaml + connectors.py (docs/06)
│ └─ Dockerfile · requirements.txt
├─ sql/ # migrations — see "Schema state" below
├─ infra/
│ ├─ docker-compose.yml # real, committed (not a sketch — see below)
│ └─ Caddyfile # real, committed
├─ tests/p0/ # vitest, TS-side (services/clients/adapters)
└─ (no .github/workflows/ directory exists — see "CI/CD" below)
```
**Known open question (not resolved this pass, Simon's call):** `CLAUDE.md` and `README.md` both
now note that `github.com/sax3l/0pt` (this checkout's `origin`) and `git.siax.io/sax3l/0pt` (Gitea)
are two remotes that share part of the same history but have independently diverged — Gitea's `main`
picked up a WAF-bypass/proxy-rotation scraper stack (since removed via a Gitea PR) that never touched
GitHub's `main`. Which remote is authoritative/deployed, and whether they should be kept in sync, is
undecided. This doc describes what's on **this** checkout's `main` only.
### Schema state (sql/)
Only two migration files exist in the repo's history, on any branch: `sql/001_init.sql` (the core
schema — `dim_company`, `dim_contact`, `fact_financials`, `orders`, etc., per `docs/03-data-model.md`)
and `sql/004_iceberg_write_boundary.sql` (`opt_dataset_iceberg_mappings` + source-rate-policy tables,
per `docs/ICEBERG_WRITE_BOUNDARY.md`). **There is no `sql/002_*` or `sql/003_*` anywhere in this
repo's git history** (`git log --all` for those paths returns zero commits) — despite
`docs/ICEBERG_WRITE_BOUNDARY.md`, `docs/11-lakehouse-write-plan.md`, and `docs/P0_QUERY_SOURCE_FLOW.md`
citing `sql/002_p0_dataset_quality.sql` and a `sql/003_*` as if they were already-applied migrations.
They are not real. See "Security & compliance" below for what this means for QA/quality-check claims.
## Hosting topology
- **Vercel** — `app/` (this repo's root, not a separate `apps/web`) → `0pt.app`. **Verified this pass**
(network check performed): `https://0pt.app` returns HTTP 200, serves a Next.js/Turbopack app titled
"0pt — your data" with SIAX branding, and `GET https://0pt.app/api/health` returns
`{"ok":true,"service":"0pt-web","db":"not_configured","queue":"not_configured",...}` — an exact shape
match for this repo's own `app/api/health/route.ts`. So README's "Live: https://0pt.app" is confirmed
accurate, and the live deployment confirms `DATABASE_URL`/`REDIS_URL` are **not** set in production —
i.e. the live site is running on the in-memory order/subscription stores described throughout this
doc, not against a real Postgres. This does not confirm which git remote/commit is deployed, or that
every route behaves as documented — only that the deployment exists and matches this repo's shape.
- **One VPS** (Hetzner, per `docs/02`) — `infra/docker-compose.yml` (see below) runs FastAPI, worker,
NocoDB, Metabase, Postgres, Redis, Caddy. This compose file and its `Caddyfile` are real, committed
files — not a sketch — but this pass found no evidence (no CI/CD, no deploy log, no accessible host)
that they have ever actually been run against a live VPS. Treat as "written, unexecuted."
- **Cloudflare R2** — documented target for file storage. `app/api/uploads/route.ts` checks for
`R2_ACCESS_KEY_ID`/`R2_BUCKET`/`R2_ENDPOINT` and returns `501 storage_not_configured` when absent;
when "present" it still returns a **hardcoded `put_url: null`** — there is no actual presigned-URL
generation implemented yet. R2 upload is an env-guarded stub, not a working integration.
- **Postgres** — `lib/db.ts` resolves `DATABASE_URL || POSTGRES_URL || POSTGRES_PRISMA_URL` (Vercel
Postgres integration sets the latter two automatically) and falls back to `null` (in-memory stores)
when none is set. This part is real and wired.
## docker-compose (`infra/docker-compose.yml` — real file, reproduced here for reference)
```yaml
services:
postgres:
image: pgvector/pgvector:pg16
environment: { POSTGRES_USER: opt, POSTGRES_PASSWORD: ${PG_PASSWORD}, POSTGRES_DB: opt }
volumes: ["pgdata:/var/lib/postgresql/data", "../sql:/docker-entrypoint-initdb.d:ro"]
redis:
image: redis:7
api:
build: ../services/api
command: uvicorn orchestrator.main:app --host 0.0.0.0 --port 8000
environment: { DATABASE_URL: "postgres://opt:${PG_PASSWORD}@postgres:5432/opt", COMPANIES_HOUSE_API_KEY: "${COMPANIES_HOUSE_API_KEY:-}", INTERNAL_TOKEN: "${INTERNAL_TOKEN}" }
depends_on: [postgres, redis]
worker:
build: ../services/api
command: python -m workers.run
environment: { DATABASE_URL: "postgres://opt:${PG_PASSWORD}@postgres:5432/opt", COMPANIES_HOUSE_API_KEY: "${COMPANIES_HOUSE_API_KEY:-}" }
depends_on: [postgres, redis]
nocodb:
image: nocodb/nocodb:latest
environment: { NC_DB: "pg://postgres:5432?u=opt&p=${PG_PASSWORD}&d=opt", NC_PUBLIC_URL: "https://data.0pt.app" }
depends_on: [postgres]
metabase:
image: metabase/metabase:latest
environment: { MB_DB_TYPE: postgres, MB_DB_HOST: postgres, MB_DB_PORT: "5432", MB_DB_USER: opt, MB_DB_PASS: "${PG_PASSWORD}", MB_DB_DBNAME: opt }
depends_on: [postgres]
caddy:
image: caddy:2
ports: ["80:80", "443:443"]
volumes: ["./Caddyfile:/etc/caddy/Caddyfile", "caddydata:/data"]
depends_on: [api, nocodb, metabase]
volumes: { pgdata: {}, caddydata: {} }
```
Note vs. an earlier draft of this doc: the `api`/`worker` containers here only receive
`DATABASE_URL`, `COMPANIES_HOUSE_API_KEY`, and `INTERNAL_TOKEN` — **not** `STRIPE_*`, `RESEND_API_KEY`,
or `R2_*`. That's correct as written: Stripe, R2, and (a documented but unbuilt) Resend integration
are all called from `app/api/*` route handlers, which run on Vercel, not inside this compose stack.
**`Caddyfile` (real, committed):**
```
api.0pt.app { reverse_proxy api:8000 }
data.0pt.app { reverse_proxy nocodb:8080 }
dash.0pt.app { reverse_proxy metabase:3000 }
```
## Environment variables
**`.env.example` now exists and is merged to `main`** (BACKLOG P3-5: the stale
link to the unmerged `github.com/sax3l/0pt/pull/3` that used to sit here has
been removed — that PR landed a while ago). It was previously impossible to
commit: `.gitignore`'s blanket `.env*` rule silently matched `.env.example`
too, so it was never added despite `docs/09-build-plan.md` Phase 0 requiring
it since day one; `.gitignore` now has `!.env.example` to fix that. README's
"Env inventory: `.env.example`" link is a real, current reference.
The table below is grep-verified against `main` this pass, not transcribed from `.env.example`'s own
comments — in one case (`ST0RE_URL`, see note) that turned up a discrepancy worth flagging.
| Var | Status on `main` | Where |
|---|---|---|
| `DATABASE_URL` / `POSTGRES_URL` / `POSTGRES_PRISMA_URL` | **Wired** — priority-ordered fallback | `lib/db.ts` |
| `ENGINE_URL` | **Wired** — edge defers to FastAPI engine when set, else computes locally | `lib/engine.ts` |
| `INTERNAL_TOKEN` | **Wired** — sent as `X-Internal-Token` on every `engineFetch()` call | `lib/engine.ts` |
| `AUTH_SECRET` | **Wired**, but only for a lightweight HMAC session scaffold — **not Auth.js**. `lib/auth.ts`'s own comment: "Production auth = Auth.js + Postgres adapter... wired once the database is provisioned" | `lib/auth.ts`, `app/api/auth/login/route.ts` |
| `DEV_LOGIN_KEY` | **Wired** — gates the dev-only login route (403 without a match); not a real auth system | `app/api/auth/login/route.ts` |
| `AUTH_URL` | Documented target — no read found | — |
| `STRIPE_SECRET_KEY` | **Wired** — real Stripe Checkout session creation (test or live key both work; not test-mode-locked in code) | `app/api/payments/[order_id]/deposit/route.ts` |
| `STRIPE_WEBHOOK_SECRET` | **Wired** — real signature verification, advances order status | `app/api/webhooks/stripe/route.ts` |
| `NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY` | Documented target — no read found | — |
| `R2_ACCESS_KEY_ID`, `R2_BUCKET`, `R2_ENDPOINT` | **Presence-checked only** — gates a `501` vs stub `200`; no actual R2 client/presign call exists yet | `app/api/uploads/route.ts` |
| `R2_ACCOUNT_ID`, `R2_SECRET_ACCESS_KEY` | Documented target — no read found (even the stub above doesn't check these) | — |
| `OPT_LOCAL_BLOB_DIR` | **Wired** — local-disk fallback artifact store, used when no object storage is configured | `src/adapters/local-blob-store.ts` |
| `RESEND_API_KEY` | Documented target — **no Resend call site anywhere in this repo**; not "unconfigured", genuinely not implemented | — |
| `METABASE_SITE_URL`, `METABASE_SECRET_KEY`, `NOCODB_BASE_URL`, `NOCODB_API_TOKEN` | Documented target — no read found. `components/embed.tsx` renders an iframe from a `src` prop the *caller* must supply; no server-side signed-URL generator exists to produce that `src` | — |
| `DOC_INTELLIGENCE_ENDPOINT`, `DOC_INTELLIGENCE_KEY`, `DOC_INTELLIGENCE_API_VERSION` | **Wired** | `src/services/document-extraction-service.ts` |
| `GRANT_ENC_KEY` | **Presence-checked only** — gates `501` vs a stub `201` that returns `{ grant_id, status: "pending" }`. No AES-GCM encryption, no read-only validation, no actual storage happens yet despite the route's own comment describing that flow | `app/api/connections/db-grant/route.ts` |
| `NEXT_PUBLIC_APP_URL` | **Wired** — used as a fallback origin for building Stripe redirect URLs | `app/api/payments/[order_id]/deposit/route.ts` |
| `NEXT_PUBLIC_API_URL` | Documented target — no read found | — |
| `REDIS_URL` | **Presence-checked only**, in `/api/health` — no queue code in this repo reads it (Celery/queue usage, if any, is `services/api`'s own concern, out of this repo's TS surface) | `app/api/health/route.ts` |
| `COMPANIES_HOUSE_API_KEY` | Real key referenced by `services/api` (Python engine, `sources.yaml`/`connectors.py`) and passed through by `infra/docker-compose.yml` — not part of the Next.js edge app's own env surface | `services/api/` |
### Platform-client URLs — corrected from a stronger claim
`CL0UD_URL`, `N0D_URL`, `AUD0_URL`, and **`ST0RE_URL`** are all **documented targets only — none of
the four is read via `process.env.*` anywhere in this repo's committed code**, grep-verified this
pass (`grep -rn "process\.env\.\(ST0RE_URL\|CL0UD_URL\|N0D_URL\|AUD0_URL\)"` returns zero matches
outside comments and one `it.todo(...)` placeholder in `tests/p0/iceberg-write-service.test.ts`).
This corrects a claim that appears in `.env.example` itself (on `feature/0pt-env-example`) and was
carried into an earlier version of this doc: that comment states "`ST0RE_URL` **IS** read
(`src/clients/st0re-client.ts`, `src/clients/st0re-lakehouse-client.ts`)". That is not accurate as of
this verification. Both of those client files — like `cl0ud-client.ts`, `n0d-client.ts`, and
`aud0-client.ts` — only export a `create*Client(baseUrl?: string)` factory that falls back to an
in-memory mock when no `baseUrl` argument is passed. Every call site in this repo (`app/api/0pt/**`
routes, `src/services/*.ts`) either passes no `baseUrl` at all or forwards an `opts?.st0reBaseUrl`-style
constructor option that nothing upstream ever populates from `process.env.ST0RE_URL`. This matches
`docs/ICEBERG_WRITE_BOUNDARY.md`'s own "Verification status" section, which lists wiring
`ST0RE_URL` → `IcebergWriteService({ st0reBaseUrl: process.env.ST0RE_URL })` as **future work**, not
something already done.
**Net effect:** setting any of `CL0UD_URL`/`N0D_URL`/`AUD0_URL`/`ST0RE_URL` in a deployed environment
today does nothing by itself. A future pass has to wire each route/service to actually read its
corresponding env var before the value has any effect. Until then, every 0pt→platform call in this
repo runs against the deterministic in-memory mock built into each client file — real, tested TS, but
never exercised against a live CL0UD/N0D/AUD0/ST0RE instance from this codebase.
## Security & compliance — corrected against actual code, not the target design
The items below were previously described as already-built behavior. Grep/read-verified this pass,
several are **env-guarded stubs that return a plausible-shaped response without doing the described
work**. Stating this plainly, per this repo's own honesty convention:
- **Customer DB grants** — `app/api/connections/db-grant/route.ts` returns `501` when `GRANT_ENC_KEY`
is unset, and a stub `201 { grant_id, status: "pending" }` when it is set. **There is no AES-GCM
encryption, no read-only-role validation, and no persistence implemented yet** — the route's own
comment describes the target behavior ("validate read-only, AES-GCM encrypt conn_string, store,
audit") but the code doesn't do it. This is a real gap, not a doc typo.
- **File delivery / presigned R2 URLs** — same pattern: `app/api/uploads/route.ts` is a `501` stub
with a hardcoded `put_url: null`. No presigned URL is ever actually generated in this repo today.
- **Tenant/org isolation — OPEN SECURITY GAP, not a deliberate two-tier design.** Several `app/api/0pt/*`
routes read `tenant_id`/`project_id` directly from the request body instead of from a server-bound
session:
- `app/api/0pt/lakehouse/mappings/route.ts`
- `app/api/0pt/lakehouse/mappings/[mappingId]/writes/route.ts`
- `app/api/0pt/sources/rate-policies/route.ts`
- `app/api/0pt/sources/[sourceId]/query/route.ts`
- `src/services/document-capture-service.ts`
This is not a defensible internal-vs-external boundary — **it's because no auth/session system
exists anywhere in this repo yet.** `app/api/orders/route.ts`'s own `GET` handler carries the
literal comment `// org scoping added with auth` — i.e., not yet. `lib/auth.ts` is a lightweight
HMAC session scaffold gated by a dev-only login key, unconnected to any of the `0pt/*` routes above.
Any caller can currently claim any `tenant_id` for these endpoints. Fixing this is Phase 3 of
`docs/09-build-plan.md` (Auth & portal shell) — it is Simon's call how that auth design binds
`tenant_id` server-side; it is not built anywhere in this repo today.
- **PII (contacts/UBO) / DPA** — no code found in this pass implementing lawful-basis recording,
deletion-on-request, or a published DPA. Treat as target design, per `CLAUDE.md` §5, not shipped.
- **Secrets rotation / least privilege** — no rotation tooling found in this repo (expected — that's
an operational practice, not application code — but noting it's unverified either way).
- **Quality/QA gate on delivered data** — `src/services/quality-check-service.ts`,
`src/services/quality-report-service.ts`, `src/types/quality-check.ts`, `src/types/quality-report.ts`,
`src/data-platform/services/catalog-service.ts`, and `sql/002_p0_dataset_quality.sql`/`sql/003_*.sql`
were at one point referenced in `docs/ICEBERG_WRITE_BOUNDARY.md`, `docs/11-lakehouse-write-plan.md`,
and `docs/P0_QUERY_SOURCE_FLOW.md` as if built and tested. **None of these files has ever existed in
this repo's git history, on any branch** (`git log --all` confirms zero commits for every one of
those paths). **All three of those docs have since been corrected** (verified this pass) — each now
carries its own "fabricated, not built" callout and none currently asserts those files as real; this
section restates the underlying fact because it directly bears on the "Security & compliance" claims
below: **there is no lakehouse-side data-quality/QA enforcement built in this repo today**. (The
Python engine's `services/api/workers/pipeline.py` does have a real, working confidence-threshold
drop — `delivered = [r for r in deduped if r["confidence"] >= threshold]` — but that's a separate,
narrower mechanism inside the FastAPI pipeline, not the TS/lakehouse quality-check layer those three
docs describe.)
## Embedding NocoDB / Metabase
`components/embed.tsx` (`EmbeddedView`) is real, committed code — a sandboxed `<iframe>` that renders
whatever `src` URL its caller passes, with a placeholder state when `src` is `null`. **What's missing:
the server-side code that generates a signed Metabase/NocoDB embed URL from `METABASE_SECRET_KEY` /
`NOCODB_API_TOKEN`.** No such generator was found in this pass. So the embed *shell* exists; the
signed-URL *plumbing* that would make it show real customer data does not yet.
## CI/CD
**There is no `.github/workflows/` directory anywhere in this repo.** No lint/typecheck/build/test
pipeline runs in CI today. On the TS side, `pnpm lint`, `pnpm typecheck`, and `pnpm test` (vitest,
`tests/p0/*.test.ts`) exist as local scripts in `package.json`, but nothing invokes them automatically
on push/PR. **On the Python side there is no lint/test tooling at all** — grep-verified this pass:
`ruff` and `pytest` appear nowhere in `services/api/requirements.txt` or anywhere else in this repo
(no `pyproject.toml`, no `pytest.ini`, no test files). `services/api/README.md`'s own "Run locally"
section only lists `pip install -r requirements.txt` + `uvicorn`/`python -m workers.run` — no lint or
test step. An earlier version of this doc claimed `ruff`/`pytest` "exist as local scripts" for
`services/api`; that was unverified and is corrected here. This is a real gap against
`docs/09-build-plan.md` Phase 0's "CI skeleton" deliverable — not yet built, not a doc omission.
## Monitoring
- **Vercel Analytics** — genuinely wired: `app/layout.tsx` imports and renders `<Analytics />` from
`@vercel/analytics/next` (`package.json` dependency `@vercel/[email protected]`).
- **Sentry** — not found. No `sentry` package in `package.json`, no Sentry init/config file anywhere
in the repo. This is a documented target only, not shipped.
- **Uptime ping on `/health`** — `app/api/health/route.ts` exists and returns `{ ok, db, queue, ts }`
based on env presence checks; no external uptime monitor wired to it was found in this repo (that
would live outside this codebase regardless, e.g. an external pinger — unverified either way).
- **Worker/job health in admin** — `app/admin/jobs/page.tsx` exists as a page; this pass did not trace
whether it reads real job state or placeholder data (out of this doc's grounding scope — flagged for
whoever owns `docs/01-product.md`/admin-portal docs to verify).
-245
View File
@@ -1,245 +0,0 @@
# 09 · Build plan
Phased, in dependency order. **Finish a phase to its acceptance criteria before the next.** Each phase = small, reviewable commits. Reconcile with existing code rather than rewriting wholesale.
> **Status callouts added 2026-07-19.** Each phase below now carries a `Status:` line, grep/read-verified
> against `main` this pass. These are conservative on purpose: a phase is only called **Done** when this
> pass found real, working code satisfying its Accept criteria; anything else is **Partial** (with the
> specific evidence and gap named) or **Not started**. No phase is upgraded to Done without a code
> citation. Where a referenced doc (e.g. `docs/design/...`) doesn't exist, that's flagged rather than
> silently worked around. See `docs/08-infrastructure.md` for the full env/security grounding these
> statuses draw on.
## Phase 0 — Foundation & repo
- Monorepo structure (`docs/08`). Migrate existing `src/orchestrator` + `src/workers` into `services/api`.
- Postgres schema + migrations (`docs/03`); `pgvector` enabled. `.env.example`.
- `docker-compose` up (postgres, redis, api, worker, nocodb, metabase, caddy). `/health` green.
- CI skeleton (lint/typecheck/build).
- **Accept:** `docker compose up` runs the whole stack locally; migrations apply; `/health` returns ok for db + queue.
- **Status: Partial.**
- Repo structure exists but diverged from the `apps/web`/`packages/shared` layout `docs/08` originally
sketched — it settled on `app/` (Next.js, repo root), `lib/`, `src/` (platform clients/services), and
`services/api/` (FastAPI). `docs/08-infrastructure.md` now documents the structure as-built.
- Migration to `services/api/orchestrator` + `services/api/workers` is **done** (verified: those
directories exist and contain `main.py`/`adaptive_router.py`/`pipeline.py`/etc.; no `src/orchestrator`
or `src/workers` remain at the old paths).
- Postgres schema is real: `sql/001_init.sql` (`CREATE EXTENSION vector`, `CREATE EXTENSION pgcrypto`,
17 tables incl. `orgs`, `users`, `orders`, `jobs`, `audit_log`, `bridge_provenance`, `db_grants`,
`payments`) + `sql/004_iceberg_write_boundary.sql`.
**No `sql/002_*` or `sql/003_*` exists anywhere in this repo's history** — some other docs
(`docs/ICEBERG_WRITE_BOUNDARY.md` etc.) cite a `sql/002_p0_dataset_quality.sql` that was never built;
see `docs/08-infrastructure.md`'s "Schema state" section.
- `.env.example` — **now exists and is merged to `main`** (BACKLOG P3-5: the
stale link to the unmerged `github.com/sax3l/0pt/pull/3` that used to sit
here has been removed — that PR has long since landed, `.env.example` is
a real, current, gitignore-exempted file at the repo root today).
- `infra/docker-compose.yml` and `infra/Caddyfile` are real, committed files (not sketches) covering
exactly the services listed. **This pass found no evidence they've ever actually been run** — no
CI, no deploy log, no reachable host checked. "File exists and looks correct" ≠ "verified to run";
treat the Accept criterion ("docker compose up runs... /health returns ok") as unverified.
- CI skeleton — **not built.** There is no `.github/workflows/` directory in this repo at all. `pnpm
lint`/`typecheck`/`test` exist as local scripts only.
## Phase 1 — Design system in code
- Tailwind + shadcn; `globals.css` (grain + reveal keyframes) and `useReveal` verbatim (`docs/05`).
- Build **DataArtifact** primitive (table/map/schema/chart/grid) and **ProvenanceBadge** (`docs/design` prompts 5.1, 2.11).
- **Accept:** a sample page renders mono tokens, a DataArtifact animates on scroll, reduced-motion respected, focus rings visible.
- **Status: Partial — real components exist; scroll-motion/reduced-motion/focus-ring behavior not
independently exercised this pass.**
- Tailwind + shadcn/radix stack: confirmed real in `package.json` (`tailwindcss`, `@radix-ui/*`,
`class-variance-authority`, `tailwind-merge`, `tailwindcss-animate`).
- `hooks/use-reveal.ts`, `components/data-artifact.tsx`, `components/provenance-badge.tsx` all exist
and are used across `app/katalog`, `app/kallor`, `app/bestall`, `app/order/[id]`, and most
`components/sections/*` files (grep-confirmed).
- `docs/design/0pt-v0-build-brief.md` and `docs/design/0pt-design-coverage-and-visuals.md` (the
"prompts 5.1, 2.11" this bullet references) **do not exist anywhere in this repo** — confirmed via
full-repo search; there is no `docs/design/` directory at all. `CLAUDE.md`'s own doc index has
already been corrected to flag this as a gap rather than list them as real. Treat any reference to
specific numbered "build-brief prompts" in this build plan as pointing at a doc that was never
written — not this file's scope to author that content.
- Reduced-motion handling, focus-ring visibility, and actual scroll-triggered animation behavior were
not executed/verified in this pass (no browser run performed) — code presence is confirmed, runtime
behavior is not.
## Phase 2 — Marketing + catalog (placeholder data)
- Landing components top-to-bottom (build-brief 2.1–2.10): Header, Hero, Philosophy, Catalog teaser, Engine, Visualisation gallery, Coverage, Editorial, Proof, Footer.
- Full **Catalog** page + **Dataset detail** + **Sourcing-map** page (coverage doc 5.4). Postgres full-text search.
- All with loading/empty/error states + mobile.
- **Accept:** marketing site + catalog browse work end-to-end on placeholder catalog rows; one continuous scroll reads well; DoD met per screen.
- **Status: Partial.**
- Landing section components are real: `components/sections/{hero,philosophy,gallery,editorial,
pricing,technology,testimonials,footer,featured-products,collection}-section.tsx` all exist.
- `app/katalog/page.tsx`, `app/katalog/[id]/page.tsx`, `app/kallor/page.tsx` all exist.
- **Postgres full-text search was not found** — grepped for `to_tsvector`/`websearch_to_tsquery`
across the whole repo, zero matches. Catalog browsing today reads from `lib/data.ts` placeholder
data, not a full-text query against Postgres. This Accept criterion's "catalog browse... on
placeholder catalog rows" half is plausible; the Postgres full-text search half is not built.
- Loading/empty/error states + mobile + DoD-per-screen were not independently audited screen-by-screen
this pass — `components/states.tsx` (`LoadingSkeleton`, `ErrorState`) exists and is imported widely,
which is evidence toward this but not a full verification.
## Phase 3 — Auth & portal shell
- Auth.js + Postgres adapter; sign in/up/verify/forgot. `orgs`/`users`.
- Portal shell + Dashboard ("Mina beställningar") with empty state.
- **Accept:** a user can sign up, land in an empty dashboard, sign out; routes protected.
- **Status: Not done — this is the most consequential gap in the whole repo, not a minor loose end.**
- **There is no Auth.js integration.** `lib/auth.ts` is a from-scratch, ~40-line HMAC-SHA256 session
scaffold (Web Crypto, no dependency) whose own comment states: "Production auth = Auth.js + Postgres
adapter + OAuth (docs/02) — wired once the database is provisioned." `app/api/auth/login/route.ts`
is a **dev-only** login gated by a shared `DEV_LOGIN_KEY`, not sign-up/verify/forgot.
- `orgs` and `users` tables exist in `sql/001_init.sql` (schema is ready), but nothing in the app
reads/writes them for real session-bound identity today.
- `app/portal/page.tsx` and sibling portal pages exist (shell is real), but routes are **not**
protected by any real session check tied to that schema.
- **Concretely, this means the tenant/org isolation several `0pt.*` API routes assume does not exist
yet.** `app/api/0pt/lakehouse/mappings/route.ts`, `.../writes/route.ts`,
`app/api/0pt/sources/rate-policies/route.ts`, `app/api/0pt/sources/[sourceId]/query/route.ts`, and
`src/services/document-capture-service.ts` all read `tenant_id`/`project_id` straight from the
request body — anyone can claim any tenant. `app/api/orders/route.ts`'s own `GET` handler carries
the literal comment `// org scoping added with auth`. This is an open security gap, not a
two-tier design choice — see `docs/08-infrastructure.md`'s "Security & compliance" section for the
full list. **Do not build any doc or feature that assumes tenant-scoped auth already exists.**
## Phase 4 — Order lifecycle end-to-end (test mode)
- **Configurator** (2.12) wired to `POST /estimates` (real estimate math in FastAPI).
- **Deposit checkout** (2.13) → Stripe **test** Checkout → webhook → order `IN_PRODUCTION`.
- **Production tracker** (2.14) reading `GET /orders/{id}/events` (SSE) — pipeline may be **simulated** at this phase.
- **Validation & delivery** (2.15): tabs render from a sample delivery; **accept** → `POST /payments/release` (test) → `DELIVERED`; **revise** leaves escrow untouched.
- AI-assist (`POST /ai/parse`) prefilling the configurator.
- **Accept:** a full custom order can be configured, deposit paid (test), watched, validated, accepted, and "delivered" — state machine in `docs/01` traversed; escrow split correct.
- **Status: Partial — the payment/escrow spine is genuinely real; the SSE tracker is not.**
- `app/api/estimates/route.ts` exists.
- Deposit checkout is **real, working code**: `app/api/payments/[order_id]/deposit/route.ts` calls
Stripe's Checkout Sessions API directly (not a stub) and `app/api/webhooks/stripe/route.ts` verifies
the webhook signature and advances order status via `setStatus`.
- `app/api/payments/[order_id]/release/route.ts` is also real: it enforces the escrow rule in code —
balance release is rejected with `409 not_accepted` unless `order.status === "accepted"` — matching
the "escrow split correct" accept criterion's intent.
- **`GET /api/orders/{id}/events` (SSE) does not exist.** Only `GET`/`PATCH /api/orders/{id}` were
found (`app/api/orders/[id]/route.ts`); no `/events` sub-route, and no `EventSource`/
`text/event-stream`/`ReadableStream` usage anywhere in `app/` (grep-verified). If a production
tracker is live today, it's polling `GET /api/orders/{id}`, not the SSE stream this bullet describes
— or it hasn't been built. Either way, the SSE contract as written is not implemented.
- `app/api/ai/parse/route.ts` is real: a genuine (non-fabricated) keyword/regex heuristic that
prefills a config object, with a documented fallback to `engineFetch("/ai/parse", ...)` when
`ENGINE_URL` is set. This one holds up as described.
## Phase 5 — Real data engine (Nordic slice)
- Compliant connectors first: **GLEIF + Brreg + Companies House** (verify access terms; record in `sources.yaml`). Remove any FlareSolverr/bypass path (`docs/06`).
- Pipeline stages produce real `dim_company` + `fact_financials` with `bridge_provenance`; QA threshold drops low-confidence rows.
- Production tracker now reflects **real** job metrics.
- **Accept:** a Nordic company dataset is produced for a real order, every field has provenance, quality report generated, level-0 fields shown honestly (not fabricated).
- **Status: Partial.**
- `services/api/sources/sources.yaml` and `connectors.py` are real: GLEIF, Brreg, Companies House,
PRH, and CVR are all registered, each with an explicit `licence: "... — VERIFY"` tag rather than an
assumed-clean claim — matches the "verify access terms" instruction.
- `services/api/workers/adaptive_router.py`'s own comment confirms: "There are NO bypass/stealth/
proxy-rotation tiers here, by design (CLAUDE.md §1)" — the FlareSolverr/bypass removal is done, at
least on this repo's `main` (see `docs/08-infrastructure.md`'s "Known open question" about the
diverged Gitea remote, which independently added such a stack on its own `main` — unresolved which
remote is canonical).
- `services/api/workers/pipeline.py` has a real, working confidence-threshold QA drop: `delivered =
[r for r in deduped if r["confidence"] >= threshold]`, plus an `avg_confidence` figure in its output.
This is a genuine, narrow QA mechanism inside the Python engine.
- **This is not the same thing as the "quality report" / quality-check layer once described in
`docs/ICEBERG_WRITE_BOUNDARY.md`, `docs/11-lakehouse-write-plan.md`, and
`docs/P0_QUERY_SOURCE_FLOW.md`.** Those three docs used to cite `src/services/quality-check-service.ts`,
`src/services/quality-report-service.ts`, `src/types/quality-{check,report}.ts`, and
`src/data-platform/services/catalog-service.ts` as already-built and tested. **None of those files
has ever existed in this repo's git history, on any branch** — and all three docs have since been
corrected to say so explicitly (verified this pass), rather than repeating the original claim. So:
the narrow Python-side confidence filter is real; the broader TS/lakehouse "quality report" this
Accept criterion likely also intends is not built (see `docs/P0_DATASET_QUALITY_FLOW.md` for the
honest target spec). Whether `pipeline.py`'s `avg_confidence` output satisfies "quality report
generated" is a judgment call for whoever runs this phase — flagging rather than deciding it here.
- Whether an actual Nordic dataset has been produced end-to-end for a real order was not verified
this pass (would require running the stack).
## Phase 6 — Delivery surfaces & integrations
- Exports: CSV / Parquet / JSON via R2 presigned URLs.
- Embedded **NocoDB** ("Min data") and **Metabase** dashboards via signed URLs in mono chrome.
- Integrations: **FiveCRM push**, webhooks, Google Sheets.
- File **uploads** (Uppy → R2) for matching/enrichment.
- **Accept:** a delivered dataset is downloadable, viewable in embedded NocoDB + Metabase (no separate login), and pushable to FiveCRM; uploads work.
- **Status: Not done — this phase is UI-shell-only today.**
- CSV/Parquet/JSON exports via R2 presigned URLs: not found. `app/api/uploads/route.ts` (the closest
R2-touching code) is a `501` stub with a hardcoded `put_url: null` — no presign logic exists yet,
for uploads or exports.
- `components/embed.tsx` (`EmbeddedView`) is real — a sandboxed iframe shell — but the server-side
signed-URL generator for Metabase/NocoDB (`METABASE_SECRET_KEY`/`NOCODB_API_TOKEN`) that would feed
it a real `src` was not found anywhere in this pass.
- "FiveCRM" appears only as a **destination label string** in `lib/data.ts`, `lib/services.ts`,
`app/portal/integrationer/page.tsx` (explicitly described in that file's own comment as
"presentationella toggles" — i.e. presentational, not wired), and as one of several regex-matched
destination names in `app/api/ai/parse/route.ts`'s heuristic. **No actual FiveCRM API push exists.**
- `uppy` is not a dependency in `package.json` (checked directly) — the Uppy → R2 upload flow this
bullet describes has no corresponding package installed, let alone implemented.
## Phase 7 — Subscriptions / feeds
- `subscriptions`; recurring jobs (weekly/daily) delivering **deltas**; webhooks on change.
- Freshness monitoring; Resend emails (confirmation, "din data är klar", feedback).
- **Accept:** an order converts to a feed; a scheduled run produces a delta + fires a webhook + email.
- **Status: Partial — data layer real, scheduling and email are not.**
- `lib/subscriptions-store.ts` is real CRUD against the `subscriptions` table (with an in-memory
fallback when no DB is configured) — `createSubscription`/`listSubscriptions` genuinely insert/read.
- No recurring-job scheduler (cron, queue consumer producing deltas, etc.) was found on the TS side of
this repo. `services/api/workers/queue.py` exists on the Python side but this pass did not trace
whether it implements actual delta-producing scheduled runs — flagged as unverified rather than
assumed either way.
- **Resend is not wired at all** — grepped for `resend`/`Resend` across the whole repo, zero matches
outside `RESEND_API_KEY` being listed as an env var. No confirmation/"din data är klar"/feedback
email has been implemented.
## Phase 8 — Admin, hardening, compliance
- Admin: order queue + scope/quote + escrow release; **source registry & freshness** monitoring; worker/job monitoring; customer + catalog management.
- Customer **DB-access grant** flow (encrypted, read-only, time-boxed) + revoke.
- Security pass: RLS, presigned-only files, signed embeds, secret rotation, `audit_log` everywhere; **DPA** published; legal pages.
- Finalize all loading/empty/error states + mobile across the app.
- **Accept:** admin can run the business; DB-grant flow works and self-revokes; security checklist passes; DoD met app-wide.
- **Status: Partial — UI shell real, the security substance is not.**
- Admin pages exist: `app/admin/{page,jobs/page,sources/page,customers/page,verktyg/page}.tsx`. This
pass did not verify whether they read real backend data or placeholders.
- `sql/001_init.sql` defines `audit_log`, `db_grants`, and `payments` tables — schema is ready.
- **The DB-access grant flow is a stub, not a working feature.**
`app/api/connections/db-grant/route.ts` returns `501` without `GRANT_ENC_KEY`, and with it set
returns a hardcoded `201 { grant_id, status: "pending" }` — **no AES-GCM encryption, no read-only
validation, and no self-revoke logic exist in code today**, despite the route's own comment
describing that target behavior. See `docs/08-infrastructure.md`'s "Security & compliance" section.
- RLS enforcement, presigned-only files (blocked on the Phase 6 R2 gap above), signed embeds (blocked
on the Phase 6 NocoDB/Metabase gap above), and a published DPA were not found as implemented in this
pass. Treat the "security checklist passes" accept criterion as not met.
## Phase 9 — Launch
- Domain `0pt.app` (Vercel) + subdomains (api/data/dash via Caddy). Sentry + uptime live.
- Soft launch: Protosell internally + a handful of existing dealer relationships.
- **Accept:** a real external customer completes an order start→delivery in production; feedback loop running.
- **Status: Domain is live; soft-launch/customer criterion not verified.**
- **Verified this pass** (network check performed): `https://0pt.app` returns HTTP 200 and serves this
repo's own Next.js app (title "0pt — your data", SIAX branding); `GET /api/health` returns
`{"ok":true,"service":"0pt-web","db":"not_configured","queue":"not_configured",...}`, an exact shape
match for `app/api/health/route.ts`. README's "Live: https://0pt.app" is confirmed, and the response
confirms the live deployment has no `DATABASE_URL`/`REDIS_URL` set — see `docs/08-infrastructure.md`'s
"Hosting topology" section. This does not confirm which git remote/commit is deployed (see the
diverged-remotes note elsewhere in this doc), or that api/data/dash subdomains or Caddy are live —
only the root Vercel deployment was checked.
- **Sentry is not wired** — no `sentry` package in `package.json`, no Sentry config file anywhere in
the repo (grep-confirmed). `@vercel/analytics` **is** genuinely wired (`app/layout.tsx` renders
`<Analytics />`), which is a real but much smaller piece of the "Sentry + uptime live" bullet.
- No evidence either way on the soft-launch/external-customer criterion — out of this doc's ability to
verify from code alone.
---
## Working conventions (for Claude Code)
- Tech docs + identifiers **English**; UI copy **Swedish**.
- Conventional Commits; one concern per PR; keep diffs reviewable.
- No secrets in code; update `.env.example` when adding env. (`.env.example` itself currently lives on
`feature/0pt-env-example` / PR #3 — merge that first, or this instruction has nothing to update yet.)
- Add/extend tests for engine logic (estimate math, fusion/confidence, dedup) and API contract.
- When a source's access/licence is unclear, **verify and record in `sources.yaml`** before relying; if disallowed for bulk, route to licensed/partner or mark level 0 — never bypass, never fabricate.
- Touch the design tokens/motion only via `docs/05`; keep red ≤ once per screen; no photography.
- If anything here conflicts with existing code, **flag it** in the PR description and propose the reconciliation rather than guessing.
- **Two git remotes claim to be this repo** (`github.com/sax3l/0pt` and `git.siax.io/sax3l/0pt`), and
they have independently diverged (see `CLAUDE.md`, `README.md`). Don't assume the checkout you're in
is the only copy, and don't silently pick one as canonical — that's Simon's decision, flag it if it
becomes relevant to the phase you're working on.
-104
View File
@@ -1,104 +0,0 @@
# 10 · Lakehouse decision (pointer)
This doc is a **pointer**, not a new architecture. It records an ecosystem-wide decision made
outside this repo and states what it means for 0pt specifically. It does not change anything in
`docs/02-architecture.md` or `docs/03-data-model.md` today — Postgres remains the backbone for
0pt's platform tables and current data entities (`docs/03`). Read this alongside those docs, not
instead of them.
> **Status update.** Since this pointer doc was first written, a follow-up implementation pass
> turned most of 0pt's side of this plan into real TypeScript — see
> `docs/11-lakehouse-write-plan.md`'s "what the implementation pass closed" section and
> `docs/ICEBERG_WRITE_BOUNDARY.md` for the current, corrected status. Two things to know before
> reading the rest of this doc: (1) that write-path code is **real and unit-tested against a mock
> ST0RE client, not verified against a running ST0RE deployment**; (2) an earlier version of
> `docs/11` and `docs/ICEBERG_WRITE_BOUNDARY.md` also claimed 0pt's data-quality/QA stage had a
> dedicated, tested `quality-check-service.ts`/`quality-report-service.ts` implementation — that
> claim was **fabricated**. `git log --all` for those paths (and `sql/002_p0_dataset_quality.sql`,
> `sql/003_*.sql`) returns zero commits, on any branch, ever. Both docs have been corrected; see
> them for the full account. This doc's own references to "QA" below point only to the *spec* in
> `docs/06-data-engine.md`, not to any implemented service.
## The decision (made elsewhere — do not re-litigate here)
**Apache Iceberg is the canonical SIAX lakehouse table format**, per **ADR-0030**, authored in the
`n0d` (Compute OS) repo (a dated copy also lives in `cl0ud`'s `docs/architecture/`, since the
boundary audit that motivated it originated in n0d but the ADR itself is recorded as SIAX-wide;
both copies describe the same accepted decision — verified by reading both this pass). Delta Lake
is explicitly rejected as the canonical P0/P1 format across SIAX Technology; it may only ever be
used later as an import/export bridge, never as the format 0pt writes natively.
Rationale (from the ecosystem ADR, summarized): SIAX needs one vendor-neutral, multi-engine,
catalog-first open table format for the MinIO/ST0RE lakehouse, because several products need to
share the same tables — ST0RE owns catalog/metadata, 0pt owns dataset writes, N0D owns
query/compaction execution, AUD0 owns lineage, API0 owns docs — and because future reads must
work from many engines (Trino/Spark/Flink/DuckDB/etc.), not one.
## Cross-product ownership split (context, not 0pt's to change)
| Product | Owns |
|---|---|
| ST0RE | Table/catalog/artifact metadata (the Iceberg catalog + table registry) |
| **0pt** | **Dataset production and writes into Iceberg tables**, through ST0RE's table registry |
| N0D | Query/compaction/maintenance execution only |
| AUD0 | Lineage |
| CL0UD | Policy |
This table condenses ADR-0030 §2.1/§2.4's ownership split for 0pt's purposes — it is a paraphrase,
not a verbatim quote (corrected this verification pass; re-checked against `cl0ud`'s copy of the
ADR). The ADR's §2.4 table also names **INF0** (model registry/experiment tracking, MLflow as an
adapter) and its §2.1 also names **API0** (schema/docs exposure); both rows are omitted here
because neither changes anything for 0pt specifically. One paraphrase is deliberate, not
accidental: the ADR's own 0pt row reads "Dataset production, **quality**, data contracts, writes"
— the word "quality" is intentionally dropped from this table's 0pt row above, because 0pt's
quality/QA stage is not yet built (see the status callout at the top of this doc). See ADR-0030
§2.4 directly (`cl0ud`'s or `n0d`'s copy) for its own exact wording of every row.
## What this means for 0pt
0pt is the **write-path owner** for the datasets it produces: 0pt runs sourcing → extraction →
structuring → enrichment → QA (`docs/06-data-engine.md` — a design spec, not yet a built service;
see the status callout above) as it does today, and writes the resulting datasets as **Iceberg
tables through ST0RE's table registry**. 0pt does **not** talk to N0D's catalog or any lakehouse
storage directly; it goes through ST0RE.
ST0RE's table registry is real, committed code (`sax3l/st0re`, `/v1/st0re/lakehouse/*`), and 0pt
has a real client and services that target it — `src/clients/st0re-lakehouse-client.ts`,
`src/services/iceberg-write-service.ts`, `src/services/dataset-iceberg-mapping-service.ts`. None of
this has been exercised against a *running* ST0RE instance from this repo: every test to date runs
against that client's deterministic in-memory mock (no `ST0RE_URL` was reachable from this
environment). Treat "0pt writes Iceberg tables through ST0RE" as **real code, mock-tested, not
live-verified** — see `docs/ICEBERG_WRITE_BOUNDARY.md`'s "Verification status" section for the full
detail, including what is and isn't wired end-to-end.
This does not replace Postgres as the platform backbone (orders, users, jobs, billing — `docs/03`
— stay exactly as they are). It is additive: dataset **output** (the delivered data product, today
exported as CSV/Parquet/JSON per `docs/04-api.md`) gains an additional, canonical Iceberg
write-path. Concrete to-dos, current build status, and required schema/event names are in
`docs/11-lakehouse-write-plan.md`.
## Also relevant: the `sourceRatePolicy` deprecation in N0D
The same ecosystem audit that produced ADR-0030 found N0D's `ComputePolicy` type carrying a
`sourceRatePolicy` field (per-source-domain crawl rate limits, e.g.
`{'allabolag.se': 1, 'ratsit.se': 1}`) hardcoded into N0D's policy defaults. That is 0pt's own
crawl-domain knowledge — it has been deprecated in N0D (the field is still present on the type for
backward compatibility, but N0D's own boundary-repair tests assert it now has **zero effect** on
any allow/deny decision; verified by reading `n0d`'s `src/policy.ts` and
`src/__tests__/boundary-repair.test.ts` this pass). 0pt does not rely on N0D for source-rate/
crawl-compliance policy; 0pt already owns the sourcing chain and its rate limits today
(`sources.yaml`, `docs/06-data-engine.md` §`rate_limit`), and has since formalized its own model —
`src/services/source-rate-policy-service.ts`, real and tested, see `docs/11-lakehouse-write-plan.md`
and `docs/ICEBERG_WRITE_BOUNDARY.md`.
## Non-goals of this doc
- Does not itself implement Iceberg writes — see `docs/11-lakehouse-write-plan.md` /
`docs/ICEBERG_WRITE_BOUNDARY.md` for what a later pass actually built (real, mock-tested code;
not live-verified; data-quality/QA enforcement specifically is **not built** — see the status
callout above).
- Does not modify `docs/03-data-model.md`'s Postgres schema.
- Does not require ST0RE's table registry to exist — as of this pass it does exist as real,
committed code in `sax3l/st0re`, though this repo has not confirmed it live/reachable. This doc
remains the pointer; `docs/11` lists what's still blocked on a *live, reachable* ST0RE vs. what
0pt has already built against the mock.
-215
View File
@@ -1,215 +0,0 @@
# 11 · Lakehouse write plan (0pt's to-do list)
Concrete follow-up to `docs/10-lakehouse-decision.md`. This is a planning doc for a **future**
implementation session — it names the schemas/events precisely so that session doesn't have to
guess, but it does not build the full pipeline today.
> **Correction (documentation-accuracy pass).** This doc previously stated that item 4 (quality
> rules staying in 0pt) was "already true today" and, in the update section below, that
> `src/services/quality-check-service.ts` and `src/services/quality-report-service.ts` were real,
> tested files that a later pass left "untouched." **That was fabricated.** `git log --all` for
> `src/services/quality-check-service.ts`, `src/services/quality-report-service.ts`,
> `src/types/quality-check.ts`, `src/types/quality-report.ts`, `sql/002_p0_dataset_quality.sql`,
> and `sql/003_*.sql` returns zero commits, on any branch (`main`, `feature/0pt-env-example`,
> `ci/add-quality-gate`), ever — these files have never existed in this repository. 0pt's
> data-quality/QA stage is a **design spec only** (`docs/06-data-engine.md` §QA — Great
> Expectations-style checks, intended to run inside the Python worker pipeline in `services/api`)
> and is **not yet implemented** as any dedicated service in this repo, TypeScript or otherwise.
> This is a real, currently open build gap, not a doc typo — see item 4's corrected entry below
> and `docs/ICEBERG_WRITE_BOUNDARY.md`'s "Data quality: not yet built" section for the full
> account. Everything else on this page (items 1, 2, 3, 5, 6, 7, 8) was independently re-verified
> against the actual service/client/test files this pass and remains accurate.
## 2026-07-13 update: live verification + field-level gap closure
A later pass live-verified the write path against `api.st0re.siax.io` (real namespace/table/snapshot
rows created), added the `namespace_id`/`mapped_at` fields the task spec names literally, and fixed
three real ST0RE contract bugs the code below had (missing tenant/actor headers, an invalid
`datasetId` FK reference, and a missing lookup-or-create for namespaces). Full detail in
`docs/ICEBERG_WRITE_BOUNDARY.md`'s "2026-07-13 update" section -- read that before this section
below, which is the original (2026-07-12) status record and is otherwise unchanged.
## 2026-07-12 update: what the 0pt write-boundary implementation pass closed
This pass turned most items below into real, tested code. Full detail in
`docs/ICEBERG_WRITE_BOUNDARY.md`; short version (re-verified this documentation-accuracy pass
against the actual files):
- Item 2 (`0pt.dataset_iceberg_mapping`): CLOSED as real code -- `src/types/dataset-iceberg-mapping.ts`,
`src/services/dataset-iceberg-mapping-service.ts`, `packages/schemas/0pt.dataset_iceberg_mapping.schema.json`,
`sql/004_iceberg_write_boundary.sql` (`opt_dataset_iceberg_mappings`), tested in
`tests/p0/dataset-iceberg-mapping.test.ts`. Field names differ slightly from the "suggested shape"
above (`dataset_iceberg_mapping_id` as PK, `iceberg_table_id` instead of `iceberg_table_ref`,
`mapping_status` instead of bare `entity_type`/`market`) -- reconciled against ST0RE's REAL
shipped `IcebergTable.tableId` shape (sax3l/st0re, not the "future" registry this doc assumed) and
against this session's own task spec; see the boundary doc for the full reconciliation note.
- Item 3 (first test dataset write): CLOSED against ST0RE's now-real (but not live-verified from
this environment) `/v1/st0re/lakehouse/*` API -- `src/clients/st0re-lakehouse-client.ts`,
`src/services/iceberg-write-service.ts`, proven in `tests/p0/iceberg-write-service.test.ts`
against that client's mock implementation (same mock/HTTP convention as `cl0ud-client.ts` etc).
NOT verified against a running ST0RE deployment in this pass -- see the boundary doc's
"Verification status" section and the `it.todo` in that test file.
- Item 4 (quality rules stay in 0pt): **NOT BUILT.** `src/services/quality-check-service.ts` and
`src/services/quality-report-service.ts` do not exist and never have (see the correction callout
above) -- there was nothing for this pass to leave "untouched." The *intent* (0pt owns QA logic,
N0D never does) is still the correct target and nothing since has contradicted it, but it is not
yet backed by any code. This is an open gap for a future implementation session, not a closed
item.
- Item 5 (`0pt.source_rate_policy`): CLOSED as real code -- `src/types/source-rate-policy.ts`,
`src/services/source-rate-policy-service.ts`, `packages/schemas/0pt.source_rate_policy.schema.json`,
`sql/004_iceberg_write_boundary.sql` (`opt_source_rate_policies`), tested in
`tests/p0/source-rate-policy.test.ts`. Kept `requests_per_second`-style fields (as `domain`/
`robots_ok`/`access`) as OPTIONAL alongside the task-spec's primary `rate_limit_per_minute`/
`crawl_budget`/`compliance_notes` fields -- both specs for this same contract are satisfied on one
row, not two competing shapes.
- Item 6 (four AUD0 events): CLOSED for all four names -- `0pt.dataset_iceberg_table_mapped` and
`0pt.iceberg_write_requested`/`0pt.iceberg_snapshot_created` emit from
`src/services/iceberg-write-service.ts` and `dataset-iceberg-mapping-service.ts`;
`0pt.source_rate_policy_created` emits from `src/services/source-rate-policy-service.ts`. All via
the existing `Aud0Client` (mock/no-op by default, same as every other AUD0 emission in this repo --
AUD0 itself still has no live ingestion endpoint).
- Item 7 (N0D heavy-write requests): CLOSED as real code -- `IcebergWriteService.requestIcebergWrite`
requests an N0D job (`0pt.iceberg_write_job`) only when `heavy: true`, never executes in-process;
tested in `tests/p0/iceberg-write-service.test.ts`.
- Item 8 (no lakehouse state outside ST0RE): CLOSED as a design property, not just a statement --
`IcebergWriteService` and `DatasetIcebergMappingService` hold zero table/snapshot fields; the only
thing 0pt persists is the mapping's `iceberg_table_id` reference. See the boundary doc.
- Item 1 (Iceberg canonical, Delta rejected): CONFIRMED, unchanged from `docs/10` --
`IcebergWriteService.mapDatasetToIcebergTable` defaults `table_format` to `"iceberg"`.
## To-do list
1. **Use Apache Iceberg as the canonical write format** for datasets 0pt produces, per
`docs/10-lakehouse-decision.md` / ADR-0030 (`n0d` repo). Do not adopt Delta Lake as a native
write target; Delta is import/export-bridge-only, ecosystem-wide.
2. **Add a `dataset_to_iceberg_table` mapping.** Every 0pt dataset (today: rows keyed by
`entity_type` + market in `dim_company` / `fact_financials` / `dim_contact` / `dim_ubo` /
`dim_vehicle`, per `docs/03-data-model.md`, or a catalog product / order delivery) needs a
stable mapping to the Iceberg table(s) it is written to. Schema name:
**`0pt.dataset_iceberg_mapping.schema.v1`**. Suggested shape (to be finalized by the
implementation session, following the `snake_case` / `uuid` PK / `created_at`+`updated_at`
conventions in `docs/03-data-model.md`):
- `dataset_id` — 0pt-side identifier (catalog product id, or `order_id`+`item_id` for custom
orders).
- `iceberg_table_ref` — fully-qualified table identifier as registered in ST0RE's table
registry (catalog.namespace.table).
- `entity_type`, `market` — for routing/filtering.
- `mapped_at`, `mapped_by`.
3. **Write a first test dataset to Iceberg** through ST0RE's table registry. *(Status: CLOSED per
the update above — `tests/p0/iceberg-write-service.test.ts` exercises exactly this pilot flow,
but only against `St0reLakehouseClient`'s mock; not yet run against a live ST0RE. Treat this
item as "code exists," not "validated end-to-end against a real deployment.")* Original plan:
pick a small, low-risk dataset (e.g. a single-market `dim_company` slice) as the pilot, to
validate the write path end-to-end before any production order relies on it — that live-ST0RE
validation still has not happened.
4. **Keep data quality rules in 0pt.** This is the correct *target* per the `n0d` audit, and
remains a spec-level design in `docs/06-data-engine.md` §QA (Great Expectations-style checks
for validity, completeness, freshness, uniqueness, corroboration), but **it is not built** —
there is no dedicated quality-check/quality-report service in this repo as of this writing (see
the correction callout at the top of this doc). Once it is built, the design intent stands:
quality logic must be caller-supplied logic that 0pt owns and hands to whichever engine executes
a job; it must not become logic owned or embedded by N0D, even after N0D executes heavy
writes/compactions on 0pt's behalf (see item 7). This item stays open until that service exists
and is tested.
5. **Keep source-rate/crawl-compliance policy logic in 0pt** — build a real model here, do not
rely on N0D for this. *(Status: CLOSED per the update above — `SourceRatePolicyService` is real
and tested.)* Context: N0D's `ComputePolicy.sourceRatePolicy` (per-domain crawl rate limits) has
been deprecated in N0D as part of the same audit (the field is still present on N0D's type for
backward compatibility, but N0D's own boundary-repair tests assert it now has zero effect on any
allow/deny decision — verified by reading `n0d`'s `src/policy.ts` and
`src/__tests__/boundary-repair.test.ts`) — that field never belonged to N0D. 0pt already has the
raw material for this in `sources.yaml`
(`docs/06-data-engine.md`, the `rate_limit` / `robots_ok` fields per source), but that's
currently free-text/per-entry, not a first-class policy object. Formalize it as
**`0pt.source_rate_policy.schema.v1`**. Suggested shape, following the same conventions:
- `source_id` — references `dim_source(source_id)` (`docs/03-data-model.md`).
- `domain` — the crawl-target domain (e.g. `allabolag.se`).
- `requests_per_second` / `requests_per_minute` — the compliance-derived rate limit.
- `robots_ok` — whether `robots.txt` permits the access pattern.
- `access` — mirrors `dim_source.access` (`api`|`bulk`|`authorized_web`|`licensed`).
- `created_at`, `updated_at`, `created_by`.
This model belongs entirely to 0pt's sourcing/compliance domain (`docs/06`) — it must not be
reintroduced into N0D, CL0UD, or any other product's policy defaults.
6. **Emit lineage for dataset → Iceberg table → snapshot**, to AUD0. *(Status: CLOSED per the
update above — all four events below are wired and fire through the existing `Aud0Client`,
which is mock/no-op by default because AUD0 still has no live ingestion endpoint. This did not
mean standing up a bespoke lineage sink prematurely — it means calling the same shared,
already-mocked AUD0 client interface every other 0pt event in this repo already calls.)* Plan
for three events, emitted by 0pt at the corresponding step:
- **`0pt.dataset_iceberg_table_mapped`** — fired when step 2's mapping is created/updated.
- **`0pt.iceberg_write_requested`** — fired when 0pt requests a write of a produced dataset
into its mapped Iceberg table (whether executed by 0pt directly or via an N0D job, per
item 7).
- **`0pt.iceberg_snapshot_created`** — fired once the write lands and a new Iceberg snapshot
exists for the table, carrying enough detail (table ref, snapshot id, row count, dataset id,
order id if applicable) for AUD0 to build lineage from source → dataset → Iceberg
snapshot.
- **`0pt.source_rate_policy_created`** — fired when a new `0pt.source_rate_policy.schema.v1`
record is created (or materially updated), so AUD0/CL0UD have an evented trail of 0pt's
crawl-compliance posture without needing to poll 0pt's DB.
7. **Request N0D jobs for heavy writes/compactions if/when needed, rather than 0pt executing
them itself.** *(Status: CLOSED per the update above — `IcebergWriteService.requestIcebergWrite`
requests an N0D job only when `heavy: true`, tested.)* 0pt produces and owns the dataset; if a
write or compaction is heavy enough to warrant dedicated compute (large backfills, table
maintenance), 0pt should submit that as a job request to N0D's execution layer rather than
running it in-process in `services/api` workers. N0D executes; it does not own the data, the
schema, or the decision of *what* to write.
8. **Do not persist lakehouse table state outside ST0RE.** *(Status: CLOSED as a design property
per the update above — `IcebergWriteService`/`DatasetIcebergMappingService` hold zero table or
snapshot state; the only thing 0pt persists is a reference `iceberg_table_id`.)* ST0RE's table
registry now exists as real code (not yet confirmed live/reachable from this repo). 0pt must not
stand up a parallel catalog/metadata store of its own (that would repeat the exact mistake this
plan is repairing: N0D building its own Iceberg catalog because nothing else had one yet).
## Required schema names (for the future implementation session)
- `0pt.dataset_iceberg_mapping.schema.v1`
- `0pt.source_rate_policy.schema.v1`
## Required future event names (for the future implementation session)
- `0pt.dataset_iceberg_table_mapped`
- `0pt.iceberg_write_requested`
- `0pt.iceberg_snapshot_created`
- `0pt.source_rate_policy_created`
## Sequencing / dependencies
*(Status note: this section described the original plan's dependencies. As of the 2026-07-12
update above, items 1, 2, 3, 5, 6, 7, 8 are built — mock-tested, not live-verified. Item 4
(data-quality/QA service) is the one item that remains genuinely not-started; see the correction
callout at the top of this doc. The dependency shape below is kept for the record and because
"mock-tested" is not the same as "the dependency is resolved" — see each item's status note above
for what's still actually pending.)*
- Items 2, 4, 5 have no hard dependency on another product and can be defined/built inside 0pt —
2 and 5 now are; 4 (the QA service) still is not.
- Items 1, 3, 8 depended on **ST0RE's table registry** existing. It now exists as real code in
`sax3l/st0re`; what remains outstanding is a *live, reachable* `ST0RE_URL` to verify against —
no code path in this repo reads `ST0RE_URL` from the environment automatically (same as
`CL0UD_URL`/`N0D_URL`/`AUD0_URL` — none of the platform clients have an env fallback wired; a
base URL must be passed in explicitly via each service's constructor options). Wiring `ST0RE_URL`
alone would not be enough, either: `sax3l/st0re`'s current `main` enforces `X-Tenant-Id`/
`X-Actor-Id` headers on the `getTable`/`createSnapshot` routes this write path calls, and this
repo's `St0reLakehouseClient` does not send them yet — see `docs/ICEBERG_WRITE_BOUNDARY.md`'s
"Real code, not live-verified" section for the full account (found during this verification pass).
- Item 6 depended on **AUD0** existing as a real evented product; it still does not have a live
ingestion endpoint, so the four events fire through `Aud0Client`'s mock/no-op path, same as every
other AUD0 emission in this repo.
- Item 7 assumes N0D's job-request surface (see `n0d` repo) is reachable from 0pt's orchestrator;
`IcebergWriteService` calls `N0dClient.createJob`, which — like the other platform clients — has
no live `N0D_URL` wired from this repo's environment either.
## Explicitly out of scope for 0pt (do not build here)
- An Iceberg catalog implementation, or any direct MinIO/Iceberg client code, ahead of ST0RE's
registry existing — that repeats the `n0d` mistake this plan is repairing.
- Query, compaction, or table-maintenance execution — that is N0D's job.
- A lineage UI or lineage storage — that is AUD0's job; 0pt only emits the events above.
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
-189
View File
@@ -1,189 +0,0 @@
# 0pt ingestion plane (P060–P068)
> Written 2026-09-04. Every claim here is backed by a test path or a
> recorded command; anything not verified says so. Read `STATUS.md`'s
> "P060-P068 ingestion plane" section for the classification table and the
> honest-gaps list — this document is the mechanism, that one is the status.
## The shape
```
Source Registry Connector Ingestion Runner
(P060: who, what, (P061: nine (P062: one envelope,
under what rights, operations, one one durable checkpoint)
on what schedule) conformance suite)
│ │ │
│ classification gate │ discover / validate │ read ─┐
│ blocks activation │ connect / read │ │
▼ ▼ resume / backfill ▼ ▼
opt_sources records ───────────────▶ IngestionEnvelope
opt_source_rights │
opt_source_authorization ├─▶ P063 schema gate
opt_source_schedule ├─▶ P064 quality gate
opt_source_schemas ├─▶ P068 ledger (peek)
opt_ingestion_checkpoints ├─▶ SINK (caller-supplied)
├─▶ P068 ledger (commit)
├─▶ checkpoint (commit)
└─▶ P067 lineage edge
```
## P060 — the registry, and the gate
A source now carries: `source_id`, `tenant_id`, `project_id`, `source_type`,
`owner_id`, an **authorization** record, a **license/purpose rights** record,
**provenance** (how the data is obtained), a **schedule**, a versioned
**schema**, a durable **checkpoint**, and a `status`.
`status` starts at **`pending`**. It was `active` before — both repository
implementations wrote `input.status ?? "active"` — which meant an
unclassified source went live the moment it was registered. `activateSource`
is now the only path to `active`, and it refuses unless ALL of these are on
record:
- an `owner_id` (distinct from `created_by`: who is accountable, not who typed it),
- an **unexpired** authorization granted by an accountable actor
(`svc_*`/`system`/`automation` are rejected — a source may not authorize itself),
- rights with a `license_id` **and** at least one `allowed_purpose`,
- provenance with a sourcing `method`.
Schedule, schema and checkpoint describe HOW a source runs, not WHETHER it
may, so they are deliberately not part of the gate.
The default is enforced in two places on purpose: in the repositories, and as
`ALTER TABLE opt_sources ALTER COLUMN status SET DEFAULT 'pending'`, so a raw
`INSERT` from psql cannot produce an unclassified-but-active source either
(proved in the realinfra suite).
Routes: `GET/POST /api/0pt/sources/{id}/activate` (GET returns the
classification without changing anything), `GET/PUT …/authorization`,
`GET/PUT …/schedule`.
## P061 — the connector contract
Nine operations on one interface: `validate` (pure, no IO, fail-closed),
`connect` (idempotent), `discover`, `health` (reports, never throws), `read`
(honours `limit` exactly), `checkpoint`, `resume`, `backfill` (bounded — an
open-ended range is refused), `disconnect` (idempotent, safe after an error).
`src/connectors/conformance.ts` is a plain async function, not a test file,
so the same suite runs from tests, from an operator script against a real
configured source, and (later) from a pre-activation check. There is no
"skip" verdict: a connector that cannot honestly serve a check FAILS it.
Two heterogeneous connectors pass it:
| | `HttpJsonConnector` | `JsonlFileConnector` |
|---|---|---|
| transport | network, real HTTP | local filesystem |
| cursor | opaque server token, with a `cursor_field` fallback | line offset it computes itself |
| exhaustion | server-reported | exact (the file is finite) |
| health | HTTP round trip | `stat` |
| backfill bounds | server-defined (sequence/timestamp) | line numbers |
| CDC deletes | no — it does not claim `cdc` | yes, via `_op` |
The `cursor_field` fallback exists because the conformance suite caught a
real defect: an API that stops returning `next_cursor` at the end of a page
left the connector with nothing to resume from, so `resume()` silently
restarted at the beginning.
## P062 — one envelope, one durable checkpoint
`IngestionEnvelope` is the single shape everything downstream sees:
`mode` (batch/stream/cdc), `operation` (upsert/insert/update/delete),
`partition_key`, `record_key`, `schema_version`, a monotonic `sequence`,
`occurred_at`/`ingested_at`, `payload` (null only for a delete) and
`provenance` (connector id + version + run id + cursor).
**Ordering is the contract.** Per page:
```
read/resume → normalize → schema conformance → quality gate
→ ledger PEEK → SINK → ledger COMMIT → checkpoint COMMIT
```
Both commits happen after the sink resolves. The two tempting shortcuts are
both data-loss bugs, and one of them was written here first — see STATUS.md's
"A real bug this pass wrote and then caught".
The resulting guarantee is **at-least-once**, not exactly-once.
`envelope_id` is a deterministic hash of
`(source, partition, record_key, content)` so a dedup-capable sink survives a
re-delivery.
## P063 — schema evolution
`RecordSchema` is a small structural shape (field → type + required) plus a
`CompatibilityPolicy` (`backward` / `forward` / `full` / `none`).
`checkCompatibility` answers what breaks, in which direction, and why. It is
deliberately not a second JSON-Schema dialect: the question is "is version
N+1 of an UPSTREAM shape safe for consumers of version N?", which needs a
comparable structure, not a validator.
Two enforcement points, both upstream of any consumer write:
1. the runner's **discovery gate** — a shape change that breaks the previous
version's declared policy fails the whole run before the first `read()`;
2. **per-record conformance** — a source that drifted without redeclaring its
schema is caught on the offending record, before the page reaches the sink.
A producer cannot widen its own policy: the PREVIOUS version's policy governs
whether a change is allowed.
## P064 — quality with consequences
`QualityGate` composes the existing `ExpectationEngine` (the Great
Expectations core subset already in this repo) and adds the missing half: a
declared `on_violation` action.
- `block` — the page fails, and the checkpoint does **not** advance, so the
bad page stays unconsumed rather than being stepped over.
- `quarantine` — failing envelopes are persisted whole to
`opt_quality_quarantine` (recoverable, not merely counted); clean ones
continue and the checkpoint advances.
- `warn` — everything continues, violations are counted and reported.
There is no default. With no policy the run report says
`quality_policy: "none_declared"` — an undeclared policy must never read as a
passed one. An expectation the local engine cannot execute counts as a
VIOLATION, never a silent pass.
## P067 — queryable lineage
`LineageEmitter` keeps emitting OpenLineage to AUD0, and **AUD0 remains the
system of record**. `LineageStore` adds 0pt's own flattened projection — one
row per (run, input, output) with a deterministic `edge_id` — because
"emitted to AUD0" was never the same thing as "answerable from 0pt".
```
GET /api/0pt/lineage?tenant_id=…&output_name=0pt:dataset:ds_x # what fed it
GET /api/0pt/lineage?tenant_id=…&input_name=source/src_x # what it produced
```
An unfiltered dump is refused (400): that is an export, not a query.
## P068 — bounded, idempotent backfill
`opt_ingestion_ledger` holds one row per `(source_id, record_key)` with the
last accepted content hash. A backfill runs through the same envelope,
schema, quality and ledger path as a normal run, and:
- **never touches the live checkpoint** — a backfill must not rewind or
advance streaming ingestion;
- **re-emits nothing** on a repeat — every record comes back `duplicate`;
- **still re-emits a genuine content change** — idempotency is not amnesia;
- **refuses an unbounded range** at the connector contract level.
## Running the real-infrastructure proof
```bash
docker run -d --name opt-ingestion-pgtest \
-e POSTGRES_USER=opt -e POSTGRES_PASSWORD=opt_test_pw -e POSTGRES_DB=opt_test \
-p 15434:5432 postgres:16-alpine
INGESTION_TEST_DATABASE_URL=postgres://opt:opt_test_pw@localhost:15434/opt_test \
pnpm vitest run tests/p0/ingestion-plane-postgres.realinfra.test.ts
```
The suite applies `sql/002_source_registry.sql` and
`sql/007_ingestion_plane.sql` itself (both are idempotent). It skips
honestly, never fabricating success, when the env var is unset.
File diff suppressed because one or more lines are too long
-180
View File
@@ -1,180 +0,0 @@
# 0pt Dataset Quality / QA Flow — TARGET SPEC ONLY, NOT YET BUILT
> **This document describes what does not exist yet.** Every file, service,
> type, and schema named below is a proposal, not a fact. Read this doc with
> "should"/"would need to"/"is intended to" — never "does" or "is." If any
> other doc in this repo states or implies that dataset-level quality
> enforcement is already built, real, and tested, that statement is wrong;
> see "Why this doc exists" below.
## Why this doc exists
Several docs in this repo — `docs/P0_QUERY_SOURCE_FLOW.md` (before this
pass's correction), `docs/ICEBERG_WRITE_BOUNDARY.md`, and
`docs/11-lakehouse-write-plan.md` — reference the following as if they are
real, already-built, already-tested files in this repo:
- `src/services/quality-check-service.ts`
- `src/services/quality-report-service.ts`
- `src/types/quality-check.ts`
- `src/types/quality-report.ts`
- `src/data-platform/services/catalog-service.ts`
- `sql/002_p0_dataset_quality.sql`
- `sql/003_*.sql` (unspecified third migration)
**Verified this pass:** `git log --all` for every one of those paths returns
**zero commits, ever, on any branch** (`main`, `feature/0pt-env-example`,
`ci/add-quality-gate` all checked). A full-repo `find` for each filename
also returns nothing. These files have never existed in this repository's
history. `docs/ICEBERG_WRITE_BOUNDARY.md` even states outright that "0pt's
QA stage... remains entirely 0pt-owned" and cites `quality-check-service.ts`
as the thing that wasn't touched by that pass — implying it exists to not
touch. It doesn't exist to begin with.
This means: **0pt's dataset-level data-quality/QA enforcement stage does
not exist in code at all**, despite being described elsewhere as complete.
This is a real, currently-open gap — not a doc typo. This document replaces
those false claims with an honest target specification: what this stage
*should* look like if/when it gets built, grounded in the parts of this
repo's design that *are* real today.
`docs/P0_QUERY_SOURCE_FLOW.md`'s "Known gaps" section has the fuller list of
exactly which files make the false claim and where; this doc does not
repeat that inventory, only the target design.
## What already exists that this would build on (real, verified)
- **The provenance/confidence model** — `docs/06-data-engine.md`'s pipeline
stage 5 ("QA") already specifies the *rules* this stage should enforce,
even though no code implements them yet:
- Per-field `bridge_provenance`: `source_id`, `freshness`, `confidence`
(0–1), `level` (0–3), `agreed_sources`.
- Level semantics: 0 = unavailable/licensed, 1 = single source, 2 =
partial corroboration, 3 = ≥2 independent sources agree.
- The QA rule: **drop rows below the order's `confidence_target`** —
deliver fewer rows, never fabricate a value to hit a target.
- `est_confidence` (order-level target) vs. `avg_confidence` (delivered,
actual) as the two numbers this stage would need to reconcile.
- **The Dataset registry** — `src/services/dataset-service.ts` /
`src/types/dataset.ts` are real, in-memory, tested code. `Dataset` already
has `dataset_type: "raw" | "structured" | "enriched" | "curated"` and
`status: "active" | "archived" | "deprecated"` — a quality stage would
need to decide whether a failed QA pass changes `status`, or whether
quality state lives entirely in a separate table/type instead (see
"Open questions" below).
- **The N0D job pattern** — `src/services/iceberg-write-service.ts` is real,
tested code showing the actual "sync path vs. N0D job" split this
codebase already uses elsewhere: an `input.heavy` flag routes to
`this.n0d.createJob(...)` instead of running inline. A quality-check
service would plausibly reuse this same shape (small samples checked
inline; a real run against a full dataset dispatched as an N0D job) —
but nothing today wires that up for quality checks specifically.
- **The CL0UD-policy-before-execution pattern** — `src/services/external-writeback-service.ts`
(`0pt.write_external_record`, real, tested) calls
`Cl0udClient.evaluatePolicy()` before performing its write. If a quality
service is meant to policy-gate before running (as
`docs/ICEBERG_WRITE_BOUNDARY.md` implies with its "CL0UD is always
re-consulted" framing), this is the real precedent to follow, not
something already done by the nonexistent `quality-check-service.ts`.
- **The AUD0 event pattern** — every real service in this repo
(`source-service.ts`, `dataset-service.ts`, `source-query-service.ts`,
`external-writeback-service.ts`, `iceberg-write-service.ts`) emits AUD0
events via `createAud0Client()` against an in-memory mock (no live AUD0
endpoint reachable from this repo). A quality service would follow the
same convention.
## What this stage should do (target design — none of this is built)
1. **Trigger.** A quality check would need to run after the enrichment/
fusion stage (`docs/06-data-engine.md` stage 4) and before a dataset is
marked ready for delivery or written to Iceberg via
`IcebergWriteService`. Whether this is a synchronous call, an
automatically-triggered N0D job, or an explicit caller action is
undecided.
2. **Checks to run**, per `docs/06-data-engine.md`'s stage 5 language
(originally scoped as "Great Expectations or equivalent, run inside the
worker"):
- **Validity** — field format/range checks against the schema for that
`dataset_type`.
- **Completeness** — required-field coverage.
- **Freshness** — age of each `bridge_provenance.freshness` against a
staleness threshold.
- **Uniqueness** — post-dedup uniqueness (RapidFuzz dedup already
happens upstream per `docs/06-data-engine.md` stage 3; this would be a
verification pass, not the dedup itself).
- **Corroboration** — cross-check `bridge_provenance.level`/`agreed_sources`
against the order's declared `confidence_target`; rows below target
get dropped, never backfilled with a guess.
3. **Output: a quality report.** Would need a `QualityReport` shape
(proposed home: `src/types/quality-report.ts`, not yet created) capturing
at minimum: `dataset_id`, `check_run_id`, per-check pass/fail counts,
`rows_dropped_below_confidence_target`, `avg_confidence` (delivered,
actual — per `docs/06-data-engine.md`), and a timestamp. This is the
thing `docs/06-data-engine.md` calls "the quality report stored on
`deliveries`" — that storage location (a `deliveries` table) does not
exist in this repo's `sql/` directory either; `sql/001_init.sql` would
need to be checked/extended for it, or a new migration written.
4. **Gate, not silent pass-through.** Per CLAUDE.md's non-negotiable
constraint #1 ("we never invent values") and #3 ("provenance per field"),
a dataset that fails its quality gate should not silently ship — the
order's delivery flow (`docs/01-product.md`'s order lifecycle) would need
to surface a failed/partial QA result to the customer, not swallow it.
## What would need to be created (none of this exists)
| Proposed file | Would contain |
|---|---|
| `src/types/quality-check.ts` | `QualityCheckRequest`/`QualityCheckResult` shapes: which checks to run, thresholds, dataset/source refs |
| `src/types/quality-report.ts` | `QualityReport` shape described above |
| `src/services/quality-check-service.ts` | Orchestrates the checks (validity/completeness/freshness/uniqueness/corroboration), CL0UD policy check, N0D job dispatch for heavy runs (same `input.heavy` shape as `iceberg-write-service.ts`), AUD0 emission |
| `src/services/quality-report-service.ts` | Persists/retrieves `QualityReport`s; registry pattern matching `DatasetService`/`SourceService` (in-memory today, same known "not shared across route modules" limitation until real persistence lands) |
| A new SQL migration | Schema for quality-check runs and reports. **Numbering note:** this repo's `sql/` directory today contains only `001_init.sql` and `004_iceberg_write_boundary.sql` — `002` and `003` were referenced in other docs but never created, so there is a numbering gap. Whether a new migration should fill `002`/`003` or continue from `005` is an open question — do not assume `002_p0_dataset_quality.sql` is the correct filename just because other docs guessed it. |
`src/data-platform/services/catalog-service.ts` is referenced elsewhere in
this repo's docs (as the source of an "`L4` = restricted sensitivity"
precedent) but was also confirmed this pass to not exist anywhere in this
repo — it is a separate fabrication from the quality-check one, not
something this quality stage specifically depends on. If a dataset-level
catalog/listing capability is needed as part of this work, the registered
`0pt.catalog_list` and `0pt.source_registry_list` capabilities
(`cl0ud`'s `packages/capability-registry/src/registry.ts`, both real
registry entries, `surfaces: ['api']`) are the closest existing hooks — but
whether either is meant to serve this purpose, or a new capability is
needed, is undecided.
## No capability registered for this yet
`cl0ud`'s `packages/capability-registry/src/registry.ts` was checked this
pass for anything quality-related: no `0pt.quality_check`,
`0pt.run_quality_checks`, or similarly-named capability exists. The
registry does have a `qualityGateRequired` boolean flag used by *other*
capabilities (e.g. one INF0 capability sets it `true`), but nothing wires
`0pt`'s own dataset QA into that flag or into any capability of its own.
Building this stage would need a new capability entry, decided surfaces
(`api` at minimum, per the six-surface model; `job` likely for a
full-dataset run), a `riskLevel`, and a `piiLevel`.
## Open questions for Simon
- Does quality-check execution belong entirely in 0pt (as
`docs/ICEBERG_WRITE_BOUNDARY.md` asserts should be true, even though the
code backing that assertion doesn't exist), or should the actual
check-running compute move to N0D as a job type, with 0pt only owning the
*rules*?
- Where does a `QualityReport` get persisted — a new `sql/00X_*.sql` table
in 0pt's own Postgres, or through ST0RE (matching the "ST0RE owns
metadata, 0pt owns production" boundary `docs/ICEBERG_WRITE_BOUNDARY.md`
draws for Iceberg tables)?
- Does a dataset that fails QA change `Dataset.status`
(`src/types/dataset.ts`), or does quality state live entirely outside the
`Dataset` record?
- What migration number should the new schema use, given the `002`/`003`
gap described above?
- Should this become its own registered `0pt.*` capability, and if so what
`riskLevel`/`piiLevel` — quality checks read dataset content, which per
the reasoning already used for `0pt.query_source` (`piiLevel: 'high'`
because "can return any column, including PII") would plausibly need the
same `piiLevel`.
None of the above is decided by this document. It exists to give a future
build pass an honest starting point instead of a fabricated one.
-277
View File
@@ -1,277 +0,0 @@
# 0pt.query_source — Bounded Source Query Flow
> **Companion-doc note (corrected):** this doc originally called itself an
> "additive companion to `docs/P0_DATASET_QUALITY_FLOW.md`." That file did
> not exist anywhere in this repository at the time — `git log --all` for it
> returns zero commits, on any branch, ever. This pass adds
> `docs/P0_DATASET_QUALITY_FLOW.md` as a clearly-labeled **target spec, not
> yet built** (see that file). Treat the two docs as siblings: this one
> covers the real, working `0pt.query_source` read path; the other covers
> the *intended, unbuilt* dataset-quality/QA path that several other docs in
> this repo (wrongly) describe as already implemented. See "Known gaps"
> below for the details of that wider mixup.
Adds the capability to actually **read data** from a registered Source, not
just register its metadata.
## What this is
`0pt.query_source`: given a Source already registered via `0pt.create_source`
(`source_type = "database"`, `adapter_id = "fabric_onelake_sql"`), run a
caller-supplied SQL query against the customer's own Azure Fabric / OneLake
SQL analytics endpoint and return rows — synchronously, bounded by a max-row
and max-time ceiling.
> Note: `0pt.create_source` (the capability id `source-service.ts` emits in
> its AUD0 events) is **not** one of the 14 `0pt.*` capabilities currently
> registered in `cl0ud`'s `packages/capability-registry/src/registry.ts` —
> only `0pt.source_registry_list` (a read/list capability) is registered for
> the Source domain. `0pt.query_source` itself *is* registered (see
> "Capability registration" below). Whether `0pt.create_source` needs its own
> registry entry, or was meant to be folded into an existing one, is unresolved
> — flagging for Simon rather than guessing.
**Tenant-agnostic by construction.** Any SIAX customer registers their own
Fabric/OneLake warehouse (their own Entra tenant, their own service
principal, their own SQL endpoint). Nothing in the adapter or service layer
is hardcoded to one customer — every credential and endpoint is a parameter
supplied per call, never an env var fallback. (This is orthogonal to the
`tenant_id`/`project_id` handling gap described below — the *warehouse*
credentials are correctly never defaulted from env; the *platform* tenant_id
used for scoping/audit is a separate, unresolved problem.)
## Why bounded + synchronous, not just "run any query"
This path is for small, interactive/preview-style reads (validate a Source
is reachable, sample a table, preview a query before scheduling it). It is
*not* a general query engine:
- `max_rows`: default 1,000, hard ceiling 10,000 (`SOURCE_QUERY_DEFAULT_MAX_ROWS` /
`SOURCE_QUERY_HARD_MAX_ROWS` in `source-query-service.ts`). Excess rows are
truncated and the response is flagged `truncated: true`.
- `timeout_ms`: default 10s, hard ceiling 30s (`SOURCE_QUERY_DEFAULT_TIMEOUT_MS` /
`SOURCE_QUERY_HARD_MAX_TIMEOUT_MS`). A caller-requested value above the
ceiling is clamped down, not rejected.
- Anything heavier — large exports, long scans, scheduled/recurring pulls —
is meant to go through **N0D as a job** instead. The real, working
precedent for that "synchronous path vs. N0D job" split in this codebase
is `src/services/iceberg-write-service.ts`: it takes an `input.heavy`
flag and, when set, calls `this.n0d.createJob(...)` instead of doing the
work inline. (An earlier version of this doc cited `quality-check-service.ts`
for this same pattern — that file does not exist; see "Known gaps.")
`SourceQueryService` does not itself request an N0D job for anything today
— there is no "heavy" variant of `0pt.query_source` yet, only the bounded
synchronous path described here.
## Architecture
```
Adapter: src/adapters/fabric-onelake-adapter.ts
- acquireFabricAccessToken(): Entra service-principal OAuth2
client-credentials flow (POST login.microsoftonline.com/{tenantId}
/oauth2/v2.0/token) — generalized from v0-datahub's
scripts/ops/cloud-bootstrap.mjs `aadToken()`.
- FabricOneLakeAdapter.query(): opens a TDS pool to the Fabric SQL
analytics endpoint using that token (azure-active-directory-access-token
auth), same shape as v0-datahub's lib/warehouse/fabric-sql.ts
`buildConfig()`/`runFabricQuery()`, generalized to caller-supplied
tenant/client/secret/endpoint/database instead of one customer's env vars.
Service: src/services/source-query-service.ts
- SourceQueryService.querySource(): looks up the Source via the existing
SourceService.getSource() (read-only — does not modify source-service.ts),
validates source_type/adapter_id, clamps max_rows/timeout_ms, races the
adapter query against a timeout, truncates rows, emits an AUD0 event,
always releases the adapter's connection.
Route: app/api/0pt/sources/[sourceId]/query/route.ts
- POST { query, params?, tenant_id, project_id, actor_id?, correlation_id?,
max_rows?, timeout_ms?, connection_config } -> QuerySourceResult
- 400 on missing query/tenant_id/project_id/connection_config
- 404 when the source does not exist
- 422 (SourceQueryUnsupportedError) when source_type != "database" or
adapter_id != "fabric_onelake_sql"
- 504 (SourceQueryTimeoutError) on timeout
```
## Capability registration (CL0UD registry — verified this pass)
`0pt.query_source` is registered in `cl0ud`'s
`packages/capability-registry/src/registry.ts`:
| Field | Value |
|---|---|
| `surfaces` | `['api']` only — no `cli`/`mcp`/`job` surface is enabled |
| `sync` | `true` |
| `requiresJob` | `false` |
| `piiLevel` | `'high'` — "ad-hoc SQL against an arbitrary registered source can return any column, including PII" (registry's own comment) |
| `riskLevel` | `'L2'` |
| `mcpEnabled` / `cliEnabled` | both `false` |
| `auditRequired` | `true` (comment: "emits `0pt.source_queried`") |
| `approvalRequired` | `false` |
This matches the platform-wide six-surface capability model: every `0pt.*`
capability registered today exposes `api` only (plus `job` for a couple of
the heaviest write paths) — none has a live CLI or MCP tool yet. Any claim
of a working `siax 0pt query-source ...` CLI command or an MCP tool for this
capability would be describing a target, not current reality.
**Discrepancy found this pass:** the registry declares `riskLevel: 'L2'` for
`0pt.query_source`, but `source-query-service.ts`'s own AUD0 emission (see
AUD0 section below) uses `risk_level: "L4"` on every `0pt.source_queried`
event — a two-level gap between what the capability is registered as and
what it actually reports. Unresolved; needs a decision on which is correct
(or whether the registry entry should simply be updated to `L4` to match
the live code, given "external read with a tenant's own credentials" is
arguably closer to `L4` than `L2`).
## AUD0 event
`event_type: "0pt.source_queried"`, `capability_id: "0pt.query_source"`,
`resource_type: "source"`, `risk_level: "L4"` in the code as written today
(see the registry discrepancy noted above). For comparison, other real,
verified `risk_level` usages elsewhere in this repo's services: `source-service.ts`
and `dataset-service.ts` use `"L2"` for their own metadata-write events;
`document-capture-service.ts` and `document-extraction-service.ts` use
`"L3"`; `external-writeback-service.ts` (`0pt.write_external_record`, a real,
tested service) uses `"L4"` for live writes to an external system with a
tenant's credentials — that is the closest real precedent for this
capability's choice of `"L4"`, not the `src/data-platform/services/catalog-service.ts`
citation an earlier version of this doc made up (that path does not exist
anywhere in this repo — confirmed via `find`).
Emitted on both success (`ok:true, row_count, truncated, duration_ms`) and
failure (`ok:false, error`) via the same `Aud0Client` pattern as
`source-service.ts` / `external-writeback-service.ts`. Like every other
`Aud0Client` use in this repo, this runs against the in-memory mock client —
no live AUD0 ingestion endpoint is reachable from this codebase today (no
`AUD0_URL` is read via `process.env` anywhere in the code). Treat this as
"real code, mock-only, not live-verified," not as "integrated."
## Known gaps / deliberately left out
- **`tenant_id`/`project_id` are read straight from the request body, not
bound to an authenticated session.** `app/api/0pt/sources/[sourceId]/query/route.ts`
requires `body.tenant_id` and `body.project_id` as plain JSON fields (see
the route's own 400-check) and passes them straight through to
`SourceQueryService.querySource()`, which uses them unchecked for AUD0
scoping. This is **not** a deliberate two-tier trust design — it is
because **no auth/session system exists anywhere in this repo yet**
(`app/api/orders/route.ts`'s own `GET` handler has the literal comment
"org scoping added with auth" — i.e., not yet). Any caller can currently
claim to be any tenant simply by putting a different `tenant_id` in the
request body. This is one of several routes in this repo with the same
gap: `lakehouse/mappings/route.ts` and `sources/rate-policies/route.ts`
read `tenant_id`/`project_id` directly off the request body exactly like
this route does (verified by reading both files); `document-capture-service.ts`'s
own route (`app/api/0pt/documents/capture/route.ts`) does the same
(`body.tenant_id`/`body.project_id`). `lakehouse/mappings/[mappingId]/writes/route.ts`
is one hop removed — it takes no `tenant_id` field on its own POST body at
all; `IcebergWriteService.requestIcebergWrite()` instead pulls `tenant_id`/
`project_id` off the previously-stored mapping record (looked up by
`mappingId`), whose `tenant_id` was itself set, unauthenticated, via
`lakehouse/mappings/route.ts`'s POST body. Same underlying trust-chain
problem, one indirection further away — worth keeping the distinction
precise rather than implying all five routes share identical code shape.
The fix is an auth/session layer that server-binds `tenant_id` — that is
Simon's call, tracked as Phase 3 of `docs/09-build-plan.md`, not built
anywhere in this repo yet. Do not treat this route as tenant-isolated
until that lands.
- **`mssql` is not a declared dependency yet.** package.json and
pnpm-lock.yaml already have unrelated uncommitted changes from a separate
in-flight session at the time this capability was built, so adding a new
dependency there was avoided to prevent a collision. The adapter loads
`mssql` lazily via a non-literal dynamic import (works with any bundler/
typecheck without the package installed) and throws a clear, actionable
error if it's missing. Once package.json is settled, `pnpm add mssql` is
the only change needed to make `query()` hit a real Fabric endpoint — no
code changes required. As of this pass, this means `0pt.query_source`
cannot actually execute a live query against Fabric/OneLake yet — the
whole path up to the driver load is real and typechecks, but `query()`
will throw the "mssql package is not installed/resolvable" error on any
real invocation until the dependency is added.
- **In-memory `SourceService` is not shared across API route modules.**
Same pre-existing limitation as `sources/route.ts` /
`sources/[sourceId]/route.ts` (each Next.js route module instantiates its
own `SourceService`, so a Source created via `POST /api/0pt/sources` is not
yet visible to `POST /api/0pt/sources/[sourceId]/query` in the same running
process). `document-capture-service.ts` hit the same issue and added a
shared singleton for its own two routes; doing the same for Source would
mean editing `source-service.ts` and/or the two existing `sources/route.ts`
files, which was out of scope here to avoid touching that flagged area.
**Correction:** an earlier version of this doc, and the route file's own
header comment, said the real fix is "already pointed at by
`sql/002_p0_dataset_quality.sql` (`opt_sources` table)." That file does
not exist and never has — `git log --all` returns zero commits for it, on
any branch. The `sql/` directory in this repo today contains only
`001_init.sql` and `004_iceberg_write_boundary.sql`; no `002` or `003`
migration has ever been created. The real fix is still "back
`SourceService` with real persistence" — just not via a file that exists.
(`app/api/0pt/sources/[sourceId]/query/route.ts`'s own header comment
still makes this same broken reference; that is a code comment, not a doc,
so it's out of scope for this pass to edit, but it should be fixed
alongside whichever pass builds real persistence.)
- **No CL0UD policy check before executing a query.** Unlike
`external-writeback-service.ts` (`0pt.write_external_record`), which calls
`Cl0udClient.evaluatePolicy()` before executing a write, `source-query-service.ts`
has no `cl0ud` import and performs no policy check at all — confirmed by
reading the file in full. This synchronous read path is scoped as a
bounded preview read, not a governed job, but that's a design choice that
has not been written down or reviewed, not an enforced policy. Worth
revisiting once policy-gating on `0pt.query_source` is defined — and note
the CL0UD registry already declares `piiLevel: 'high'` for this
capability, which makes the absence of any policy check more notable, not
less.
- **No SQL rewriting/injection of `TOP`/`LIMIT`.** Row bounding is applied to
whatever the adapter returns, not pushed into the query itself (arbitrary
caller SQL can't be safely rewritten). A query that itself returns far more
rows than `max_rows` still executes in full on the warehouse before being
truncated client-side — only the *response* is bounded, not warehouse-side
compute. Documented, not silently hidden.
- **Cross-file fabrication this pass found and corrected here, but could not
fix everywhere it appears.** Several files in this repo (some in this
doc's own former text, some in code comments this pass does not own)
reference `src/services/quality-check-service.ts`,
`src/services/quality-report-service.ts`, `src/types/quality-check.ts`,
`src/types/quality-report.ts`, `src/data-platform/services/catalog-service.ts`,
`sql/002_p0_dataset_quality.sql`, and `sql/003_*.sql` as if they are real,
already-built, already-tested files. `git log --all` for every one of
those paths returns **zero commits, ever, on any branch** (`main`,
`feature/0pt-env-example`, `ci/add-quality-gate` all checked). These files
have never existed in this repository. This doc's own text used to make
this same false claim in three places; all are corrected above.
**Re-checked this pass:** `docs/11-lakehouse-write-plan.md` has since been
corrected by a parallel pass — it now carries its own "Correction
(documentation-accuracy pass)" callout and its item 4 explicitly reads
"**NOT BUILT** ... there is no dedicated quality-check/quality-report
service in this repo as of this writing," so it no longer needs the same
fix. **`docs/ICEBERG_WRITE_BOUNDARY.md` has *also* since been fully
corrected** (re-verified this pass, reading the current file end to end):
its former internal contradiction — a top-of-file correction callout next
to a body that still asserted the fabricated files as real two sections
down — has been resolved. Its "Verification status" section now reads
"this section previously pointed at `src/services/quality-check-service.ts`
as a peer example ... that file does not exist," and its data-quality
section (retitled "Data quality: not yet built (corrected)") now quotes
its own old wording only inside a "this section previously read..."
framing before stating plainly that those files don't exist and were
never built. Neither section currently asserts the fabricated files as
fact. Code comments in `app/api/0pt/sources/[sourceId]/query/route.ts`
(line 14: "`sql/002_p0_dataset_quality.sql` already defines `opt_sources`")
and `src/services/external-writeback-service.ts` (line 21: "...
`quality-check-service.ts`/`document-extraction-service.ts` already
follow") still carry the same false reference — confirmed still present
as of this pass — and remain outside any of these docs' scope to fix
(code, not docs; flagging for whoever next touches those two files). See
`docs/P0_DATASET_QUALITY_FLOW.md` (added this pass) for the honest,
target-spec-only replacement for what those files were supposed to do.
## Known issue: which 0pt repo is authoritative
This repo has two remotes with diverged history — `github.com/sax3l/0pt` and
`git.siax.io/sax3l/0pt` (Gitea) — that share origin lineage for at least
part of the codebase but have each accumulated commits the other doesn't
have. Which one is deployed to `0pt.app`, and whether they're meant to stay
in sync, is unresolved and is Simon's call, not something this pass
attempted to resolve. Noting it here since this doc describes code that
lives in "the 0pt repo" as if there's exactly one.
@@ -1,177 +0,0 @@
# 0pt — SIAX Digital Ecosystem Data Acquisition & Entity Plan
Status: TARGET / IMPLEMENTATION CONTRACT
Date: 2026-09-07
0pt remains the generic external-data acquisition/enrichment/provenance capability. Product domains own their business entities and decisions. 0pt supplies sourced observations/enrichment/entity-resolution inputs and must not become a second Work/Press/Fund/CRM SSOT.
## 1. Ecosystem uses
### Work / j0b
- company/employer/end-client enrichment;
- registry/company facts;
- source acquisition where generic 0pt infrastructure is appropriate;
- buyer/supplier enrichment for procurement;
- entity-resolution inputs;
- public technology/company signals for account intelligence.
j0b owns opportunities, roles, requirements, consultants, matches and submissions.
### PRESS0
- public source monitoring/acquisition;
- official releases/datasets;
- source snapshots/enrichment;
- factual dataset/source metadata.
PRESS0 owns articles/citations/claims/editorial decisions.
### FUND0
- issuer/company/public market facts used in project materials;
- public registry/company enrichment.
FUND0 owns project/disclosure/investor/data-room state.
### FIT0/CRM
- account enrichment and market/buying signals;
- company identity resolution.
## 2. Provenance-first invariant
Retain the existing source hierarchy/principles and ensure each field/observation can carry source, observed/fetched time, freshness/confidence and transformation/version metadata.
No enrichment should silently overwrite a higher-authority canonical fact without provenance/precedence rules.
## 3. Lossless acquisition contract
Where a product needs raw upstream retention, 0pt should return/store an immutable acquisition/artifact reference plus metadata rather than only a lossy normalized subset. ST0RE custody is preferred for large raw payloads when integrated.
Target acquisition receipt fields include:
- source/provider;
- external ID/URL;
- fetched/observed times;
- payload/artifact hash/ref;
- parser/version;
- rights/reuse/retention classification;
- data classification;
- extracted observations/provenance.
## 4. Entity resolution
Add/use Splink or equivalent approved probabilistic entity-resolution capability where it materially improves cross-source linking.
Primary use cases:
- Brainville company = LinkedIn-export/company = JobTech employer = registry company = TED buyer = Twenty account;
- duplicate/similar organizations across countries/registries;
- person/consultant references when legally/purpose appropriate.
Entity resolution returns candidates/scores/evidence. Product/canonical identity merge remains policy/domain controlled; do not auto-merge high-risk records solely on fuzzy score.
## 5. Company identity keys
Prefer strong keys where available:
- country + official registration number;
- LEI;
- VAT ID;
- official registry IDs;
- verified domains.
Use probabilistic attributes only when strong IDs are missing/inconsistent.
## 6. Public procurement enrichment
Support acquisition/normalization references for buyer/supplier/award/contract datasets such as TED/OCDS/official sources. j0b procurement domain owns the commercial opportunity/access graph; 0pt supplies sourced external facts.
## 7. Source-policy metadata
Products may pass/receive policy metadata for:
- access method;
- reuse/redistribution;
- retention;
- polling/rate limits;
- terms/license review date;
- purpose/data classification.
0pt must not globally assume all publicly reachable web content is reusable for every commercial/public purpose.
## 8. PRESS0 rights boundary
Source acquisition/extraction is not publication permission. PRESS0 editorial/source-rights policy decides what may be quoted/reproduced/published. 0pt must preserve enough source metadata to support this decision.
## 9. Company verification boundary
0pt may fetch/enrich official company facts; ID0 owns verification decisions/KYB status. j0b/CRM consume verification refs/status from ID0, not infer `verified` merely because 0pt found a matching registry row.
## 10. Market/account signals
Target observations useful to FIT0/CRM/j0b:
- hiring activity;
- public procurement notices/awards;
- public technology/platform signals;
- company growth/change events;
- leadership/public contact changes where lawful;
- relevant product/market announcements.
Signals are dated observations with provenance, not permanent assertions.
## 11. API contract
Fit into actual 0pt architecture. Product consumers should be able to request/receive:
- company/entity enrichment;
- source acquisition receipt;
- structured observations with provenance;
- entity-resolution candidates;
- provider/source health/freshness where applicable.
Avoid bespoke endpoint copies for each product if generic typed capabilities suffice.
## 12. Security/privacy
- tenant/purpose scoping;
- PII minimisation;
- egress/allowed-host controls;
- SSRF prevention for user-supplied URLs;
- secrets in canonical secret store;
- no raw sensitive payloads in logs;
- retention/deletion support;
- provider/license/data-rights documentation.
## 13. Current deployment gate
Before j0b/PRESS0/FUND0 depend on 0pt as a mission-critical production service, reconcile the repo's current deployment/live endpoint status and close any documented routing/auth/hosting gap. Do not treat architecture/code as deployed merely because it exists.
## 14. Implementation order
1. Reconcile current live deployment, auth and data/provenance APIs.
2. Stabilise generic acquisition receipt/provenance contract.
3. Add Splink/entity-resolution capability with strong-key-first strategy and reviewable candidates.
4. Wire j0b company/end-client/buyer enrichment.
5. Wire FIT0/CRM account signals.
6. Add PRESS0 source/dataset acquisition when press0 exists.
7. Add FUND0 public issuer facts when fund0 exists.
8. Load/performance/backup/restore/live verify.
## 15. Definition of Done per data capability
- source/provider documented;
- legal/license/data-use classification recorded;
- provenance/freshness/confidence available;
- deterministic/idempotent normalization where expected;
- entity resolution tested against labelled truth set;
- tenant/purpose/security tests pass;
- provider outage/schema drift handled;
- raw artifact retention/deletion contract works where required;
- actual production endpoint/dependency is live verified;
- product consumes API/contract, not DB;
- status docs reflect reality.
Target ecosystem uses in this document do not claim they are already wired.
-277
View File
File diff suppressed because one or more lines are too long
@@ -1,60 +0,0 @@
# ADR-0001 — Server-renderad authz-resolution för orderåtgärder
**Status:** Accepted
**Date:** 2026-09-29
**Owners:** 0pt (simon@siax.io)
**Related requirements:** DoD §21 (backend enforcement), §78 (error/why-UX), våg 3.6–3.7 (authz-ux/entitlement)
**Related capabilities:** `@siax/contracts/authz-ux` 0.10.0, `@siax/ui` ActionGate 0.11.1
## Context
Admin-ordkön behöver gate:a advance-aktionen. 0pt saknar klientsides-policy;
`requireOrderOwner` är server-side. Att resolvé:a i klienten vore påhittad
policy (DoD §15).
## Existing implementations
- PATCH `/api/orders/{id}` enforcar ägarskap server-side (sanningsvärdet).
- Admin-sidan hämtar ordrar via GET `/api/orders` (owner-scopad).
## Decision
**Server-renderad resolution:** GET `/api/orders` returnerar per order ett
frozen `advance_action` (ResolvedAction från `resolveAction`), derivat i
`lib/order-flow.ts` ur kanoniskt flöde + sessionens ägarskap. Klienten
renderar via `ActionGate` — ingen policylogik i UI-lagret. Ingen extra
fetch: resolutionen rids med ordningssvaret.
## Ownership
0pt äger flödet och resolutionen; DES1GN äger kontraktet (`authz-ux`) och
renderingen (ActionGate). Product Firewall: 0pt importerar @siax/*, aldrig
tvärtom.
## Contract
`ResolvedAction {state, reason?}` — stängda uppsättningar enligt authz-ux.
## Provider boundary
Framtida pay0-entitlement projiceras via `deriveEntitlement` in i samma
resolve — ingen ny endpoint behövs.
## Dependency rules
`@siax/ui`/`@siax/contracts` → 0pt. Aldrig reverse.
## Migration
Enda konsument: admin-sidan (denna PR). Övriga ytor migreras per aktion.
## Alternatives considered
- **Klientsides-resolution mot ny endpoint:** extra roundtrip, policy-läckage­
risk, mer kod — avvisad.
- **Hårdkodad disabled i UI:** duplicerar serverns sanningsvärde — avvisad
(DoD §21: backend är enforcement, UI är presentation).
## Risks
Flödesändringar måste skriva i `lib/order-flow.ts` (enda källan) —
lint-/test-täckning finns (tests/order-flow.test.ts).
## Testing / Evidence
- `tests/order-flow.test.ts`: available för aktiva steg, read_only för
terminala (incl. okända statusar i fri-text-DB) — 3/3.
- Full svit 1138+3 godkända; typecheck grön.
## Rollback
Ta bort `advance_action`-fältet + ActionGate-wrappen — klienten faller
tillbaka till tidigare rendering (flödet oförändrat).
-61
View File
@@ -1,61 +0,0 @@
# ADR-0002 — Kanonisk orderstatus: kodnivå-union + guardad DB-constraint
**Status:** Accepted
**Date:** 2026-09-29
**Owners:** 0pt (simon@siax.io)
**Related requirements:** C3 (kanonisera orderstatus), DoD §17 (backup-städ), §33 (migreringsordning), §35 (restore-drill)
**Related artifacts:** `lib/order-flow.ts` (`ORDER_STATUSES`, `OrderStatus`, `isKnownOrderStatus`, `nextOrderStatus`), `sql/015_order_status_check.sql`
## Context
`orders.status` är fri text (`sql/001_init.sql` line ~92: `status text NOT NULL DEFAULT 'draft'`).
Flödet draft→quoted→in_production→review→accepted→delivered är känt i kod, men
DB:n nekar inga andra värden — fri text har redan orsakat minst en missvisande
"klar"-visning i ordkön (okänd status renderades som "done/klar" utan att
ordern faktiskt levererats).
**Prod-harvest ej körbar i session** (2026-09-29): ingen `DATABASE_URL`/`POSTGRES_URL`
för 0pt finns i Infisical (varken default-env eller `/0pt`-sökvägar — körningen
injicerade 246 secrets utan order-DB-URL). Statusfördelningen i prod är därför
okänd här; migreringen är guardad och manuell.
## Existing implementations
- `lib/order-flow.ts` — NEXT_STATUS-flödet, `resolveAdvanceAction`, `buildOrderInboxItem`.
- `app/admin/page.tsx` + `app/api/orders/route.ts` konsumerar flödet.
- `tests/order-flow.test.ts` behandlar `cancelled` som terminal read_only-status.
## Decision
1. **Kodnivå-union är SSOT:** `type OrderStatus` = de sex flödesstatusarna +
`cancelled` (används i tests som terminal status — därmed med, trots utebliven
harvest). `ORDER_STATUSES` är den utömmande listan; `isKnownOrderStatus()`
klassar fri text fail-closed. NEXT_STATUS/resolveAdvanceAction/
buildOrderInboxItem konsumerar unionen via `nextOrderStatus()` — okänd
status ger alltid read_only / ingen inbox-post, aldrig påhittat nästa steg.
2. **DB guardas — inte typ-migreras:** `sql/015_order_status_check.sql` lägger
`CHECK (status IN (...)) NOT VALID` (fas A, kort lås, nekar vid dirt-data via
DO-preflight) och `VALIDATE CONSTRAINT` i separat session (fas B, SHARE UPDATE
EXCLUSIVE + `lock_timeout='5s'`). KÖRS EJ mot prod i sessionen — Simon kör
efter harvest-rapport och backup (`pg_dump -t orders` före fas A).
## Alternativ avvisade
- **Fortsatt fri text** — redan orsakat missvisande "klar"; ingen möjlighet att
fela tidigt vid skrivning.
- **Omedelbar NOT VALID utan harvest** — risk för prod-block: NOT VALID validerar
inte befintliga rader, men VALIDATE-fasen (och varje ny UPDATE) krockar med
okända statusar; utan känd statusfördelning är fas B en lotteri.
- **Postgres `enum`-typ** — kräver typmigrering av kolumnen (ALTER TYPE-lås,
ADD VALUE kan ej ske i transaktion i äldre PG), tyngre drift än en CHECK som
kan utökas med en rad kod + en rullande migrering.
## Consequences
- Ny status = en rad i `ORDER_STATUSES`/`NEXT_STATUS` + en uppföljningsmigrering
som lägger till värdet i CHECK:en (drop+add NOT VALID, validate igen).
- Rader med okänd status (om harvest hittar sådana) mappas i en EGEN, granskad
migrering före fas A — preflighten nekar annars körning (fail-closed).
- SQL-listan och kodlistan är dubbelbokning; testen i
`tests/order-flow.test.ts` låser att alla `ORDER_STATUSES` har definierat
beteende (nästa steg eller read_only).
-271
View File
@@ -1,271 +0,0 @@
# 0pt Analytics Core — BI-P002 … BI-P012
Status of this document: it describes what **is in this repository and has been
run**, and states separately what has **not** been deployed. Nothing here is a
plan written in the present tense.
---
## 0. The ownership boundary (normative, not negotiable)
```
SIAX / 0pt owns the analytics engine, the query compiler, the tenant forcing,
the resource governance and the semantic/contract layer.
Product repos (VehIQ and the rest) own DOMAIN MEANING — what a row means,
which metric a dealer cares about, how a screen reads.
```
Concretely, and enforced rather than asserted:
* `BIApplicationBinding` (BI-P002 entity 19) has **no credential field**, in
TypeScript or in `sql/008_analytics_domain_model.sql`. A bound BI
application authenticates to the 0pt Analytics API with a CL0UD identity and
receives compiled, tenant-forced results. It never learns a ClickHouse DSN,
user, or password. Two tests assert the absence of such a column — one over
the migration text, one over `information_schema.columns` on a live
Postgres — so adding one later is a test failure.
* `AnalyticsIdentity` (BI-P009) is a **separate parameter** from the request,
never a field on it. This estate has already shipped a live cross-tenant
hole by reading a tenant out of a request body (INF0 Wave 2); the type
shape is what stops that recurring here.
---
## 1. What each prompt produced
| Prompt | Deliverable | Where |
|---|---|---|
| BI-P002 | 19 canonical entities + migrations + tenant-scoped persistence + restore drill | `src/analytics/domain/entities.ts`, `sql/008_analytics_domain_model.sql`, `src/analytics/repositories/analytics-domain-repository.ts` |
| BI-P003 | RAW / NORMALIZED / CURATED / SERVING, with the BI-surface read rule enforced | `src/analytics/domain/tiers.ts` |
| BI-P004 | `DatasetContract` + a fail-closed compatibility gate | `src/analytics/domain/contract.ts` |
| BI-P005 | Arrow IPC encode/decode + ClickHouse pass-through | `src/analytics/arrow/ipc.ts`, `src/analytics/arrow/flatbuffer-builder.ts` |
| BI-P009 | `SiaxAnalyticsEngine` interface + ClickHouse provider, existing implementation **preserved** | `src/analytics/engine/siax-analytics-engine.ts`, `src/analytics/engine/clickhouse-engine.ts` |
| BI-P010 | Four purpose-built ClickHouse tables + rollup MV, benchmarked | `src/analytics/engine/schema.ts`, `scripts/bi-p010-benchmark.mjs` |
| BI-P011 | Layered tenant isolation: verified identity, forced compiler predicate, restricted users, row policies | `src/analytics/engine/query-compiler.ts` |
| BI-P012 | Every named ClickHouse limit + CL0UD quota + per-tenant admission control | `src/analytics/engine/resource-governance.ts` |
---
## 2. BI-P009 — what "preserve" means here
`src/analytics/clickhouse-analytics.ts` is **byte-identical to main**. The new
engine composes it:
* `health()` delegates to it;
* the pre-existing `opt_metric_events` path is reachable through
`executeLegacyMetric()`, still using its own compiler;
* everything else uses the new compiler for the BI-P010 tables.
"Do not regress the existing forced tenant predicate" is enforced by
`tests/analytics/tenant-predicate-regression.test.ts`, which asserts the exact
string `tenant_id = {tenant:String}` on the URL the adapter builds. It has been
run with the forcing deliberately deleted from both compilers and goes RED
(2 of 6 tests fail); the transcript is
`evidence/bi-p002-p012/test-transcript.txt` §1–§2.
The eight capabilities are all implemented, with one **deliberate refusal**:
`executeQuery` (analyst SQL) throws `CAPABILITY_UNAVAILABLE` until BI-P017
(SQL dialect contract) and BI-P033 (analytics authorization) exist. Shipping a
raw-SQL surface first would create exactly the "raw SQL attempt" hole BI-P011
enumerates. It is declared and refused, not silently missing.
---
## 3. BI-P010 — why four tables, measured
BI-P010 warns against "one giant unbounded table for every analytics use
case". `scripts/bi-p010-benchmark.mjs` builds both fixtures and the
counterfactual, and times them. Measured on a disposable
`clickhouse/clickhouse-server:24.8` (full transcript:
`evidence/bi-p002-p012/bi-p010-benchmark.json`):
| Question | Purpose-built | One giant table |
|---|---|---|
| 90-day metric total, one tenant | **48.8 ms p50**, 40 960 rows read | 174.4 ms p50, **5 400 000** rows read |
| Vehicle point lookup by key, one tenant | **49.3 ms p50**, 8 192 rows read | 236.6 ms p50, **7 401 152** rows read |
| Avg asking price by make over 2M vehicles | **389.6 ms p50** | 680.8 ms p50 |
| Granules read for the metric total | **5 / 660** | 660 / 1 149 |
Fixtures: 5 400 000 SaaS events (200 tenants × 12 metrics × 90 days) and
4 000 000 vehicle projections (2M for the tenant under test + 2M decoys owned
by 50 other tenants).
**Honest finding that does not flatter the design:** at this scale the
`AggregatingMergeTree` rollup (37.98 ms p50, 21 416 rows read) was *not* faster
in wall time than scanning raw events (32.55 ms p50, 40 960 rows read). It
reads about half the rows, and its value is the long TTL — raw events expire
in 30 days, the rollup keeps three years — so the rollup earns its keep on
retention and on scale beyond this fixture, not on latency at 5.4M rows. Do
not quote it as a speed win.
---
## 4. BI-P011 — the isolation proof
Four layers, and each one is tested with the layer above it *removed*:
1. **Verified CL0UD identity.** `AnalyticsIdentity` is not part of the
request; a blank tenant or principal is `UNAUTHENTICATED`, never a wildcard.
2. **The 0pt query compiler forces the tenant.** Every compiled statement
contains `tenant_id = {tenant:String}` as its first WHERE condition, with
the value bound as an HTTP parameter — the tenant string never appears in
the SQL text.
3. **Restricted database users + row policies.**
`restrictedTenantUserDdl()` renders a per-tenant ClickHouse user with
`readonly = 1` and a `CREATE ROW POLICY ... USING tenant_id = '<tenant>'`
on every analytics table.
4. **Separate database/cluster tier** for very-high-isolation customers:
supported by construction — the engine takes a `database` and a `baseUrl`
per instance — but **not yet operated**, because there is no deployed
ClickHouse for 0pt analytics at all (see §7).
The proof, run against a disposable ClickHouse with 50 rows for `t_alpha`
(value 1 each) and 50 for `t_beta` (value 1000 each):
* **hole, layer 2 removed:** the same statement minus the forced predicate
returns **50 050** — both tenants in one number;
* **closed, layer 2 present:** `t_alpha` gets **50**, `t_beta` gets **50 000**;
* **hole, layer 3 absent:** an unrestricted user issuing a predicate-free
`uniqExact(tenant_id)` sees **2** tenants;
* **closed, layer 3 present:** the restricted user issuing the *identical*
statement sees **1**, and `sum(value)` returns 50 rather than 50 050.
Adversarial cases from BI-P011's list — tenant A querying B's dataset, forged
dataset IDs, raw SQL, SQL injection, dimension identifier injection, filter
injection — are covered in
`tests/analytics/query-compiler-injection.test.ts` (compiler layer) and
`tests/integration/analytics-tenant-isolation.integration.test.ts` (live).
Dimension names are **resolved through a per-tenant allow-list**
(`DimensionDefinition`), never escaped and never spliced. A tenant that has
declared no dimensions may reference none — fail closed.
---
## 5. BI-P012 — governance, and the partial-result trap
Every setting BI-P012 names is applied. Five ride on the statement itself
(`max_execution_time`, `max_result_rows`, `max_rows_to_read`,
`max_bytes_to_read`, `max_memory_usage`) under `readonly = 1`, so the query
text cannot re-raise them; `max_concurrent_queries` is a per-user quota plus a
local admission gate.
Overflow modes are **`throw`, never `break`**. That is not a style preference.
Measured on ClickHouse 24.8: with `result_overflow_mode = break` and
`max_result_rows = 10`, a 100 000-row query returns **HTTP 200 with 65 409
rows** and nothing in the payload says it is short. A truncated answer that
looks complete is the analytics form of a false green.
Query-bomb outcomes, each fired individually and identified by ClickHouse
error code: 158 `TOO_MANY_ROWS`, 307 `TOO_MANY_BYTES`, 159 `TIMEOUT_EXCEEDED`,
396 `TOO_MANY_ROWS_OR_BYTES`, 241 `MEMORY_LIMIT_EXCEEDED`.
The second half of the DoD — "without degrading unrelated tenant beyond
declared SLO" — is timed, not assumed: an unrelated tenant's interactive query
is run five times *while* an 8-second CPU bomb is in flight, must still return
the **correct** answer, and must stay under a declared 5000 ms ceiling (measured ~30 ms on an idle
server; the ceiling is set wide for a shared CI runner, and a genuinely
starved tenant would take seconds or fail).
Two measured details worth keeping:
* `EXPLAIN ESTIMATE` must **not** run under the caller's own
`max_rows_to_read`. It fails with code 158 exactly when the estimate would
be over budget — i.e. in the only case the estimate matters. Planner calls
use `planningSettings()`, a narrower envelope, instead.
* `SELECT count() FROM numbers(2e10)` is *not* a query bomb — ClickHouse
answers it in about 5 seconds because it can skip the values. The bomb in
the test hashes every row, which cannot be short-circuited.
---
## 6. BI-P005 — Arrow, and why it is not self-certified
Two paths:
* **pass-through** — ClickHouse emits Arrow IPC itself (`FORMAT ArrowStream`);
0pt streams those bytes unchanged. `output_format_arrow_string_as_string=1`
is required, or String columns arrive as Arrow **Binary** and both pyarrow
and DuckDB read them as bytes: silent semantic loss.
* **encoded** — for results 0pt assembles itself, `encodeArrowStream()` writes
the IPC stream, including a small hand-written FlatBuffers writer (no new
npm dependency, no new supply-chain surface).
A hand-rolled encoder is only worth having if somebody else's parser agrees
with it, so conformance is established by three independent implementations:
* **pyarrow 25.0.1** and **DuckDB 1.5.5** decode both ClickHouse's bytes and
0pt's bytes to *identical* values and types
(`evidence/bi-p002-p012/bi-p005-arrow-roundtrip.json`, verdict `PASS`);
* **ClickHouse's own Arrow C++** ingests 0pt-encoded Arrow — including a
20 000-row batch whose aggregates come back exact — in
`tests/integration/analytics-arrow-clickhouse.integration.test.ts`, which
runs on every push.
Supported types and their caveats are the table in `ARROW_TYPE_SUPPORT`;
`DateTime64(6|9)` and `UInt64` above 2^63 are deliberately **outside** the
supported set rather than silently lossy.
Arrow is also not an escape hatch from BI-P012:
`assertArrowWithinResultBudget()` decodes the row count and refuses a payload
over the caller's `max_result_rows`.
---
## 7. What is NOT done — verified, not assumed
* **There is no deployed ClickHouse for 0pt analytics.** Probed 2026-09-06 on
server7, the only ClickHouse in the estate: databases are
`opt_scraped`, `default`, `system`, `INFORMATION_SCHEMA`,
`information_schema`. There is no `opt_analytics` database, so
`ClickHouseAnalytics` — the "existing working" provider — has never been
run against a production instance. Everything in this document was proven
against disposable containers.
* **server7's ClickHouse must not be used for this.** It holds
`opt_scraped` — 51 tables, 407 793 471 rows, including `persons` and
`cz_owners`. That is the b0ts scraping plane, which
`src/analytics/clickhouse-analytics.ts`'s own header already prohibits this
module from touching (Ratsit/person-PII legal case, written DPIA
prohibition on quarantined market data). It also has **zero** columns named
`tenant_id` or `project_id` anywhere on the server and **zero** row
policies, so it could not satisfy BI-P011 even if it were legally
available. Nothing on that server was modified by this work.
* **BI-P011 layer 5** (separate database/cluster tier per high-isolation
customer) is supported by construction but not operated.
* **`executeQuery`** is refused pending BI-P017/BI-P033 (§2).
* The domain repository covers `AnalyticsDataset`, `DatasetVersion`,
`MetricDefinition`, `MetricVersion` and `DimensionDefinition`. The other
fourteen entities have tables, constraints and types but no repository
methods yet; their consumers (dashboards, reports, quality runs, lineage)
arrive with BI-P025 … BI-P035.
---
## 8. Running the proofs yourself
```bash
# unit suites (no infrastructure)
pnpm vitest run tests/analytics
# live ClickHouse suites
docker run -d --name opt-bi-ch -p 18123:8123 \
-e CLICKHOUSE_USER=opt_admin -e CLICKHOUSE_PASSWORD=<throwaway> \
-e CLICKHOUSE_DEFAULT_ACCESS_MANAGEMENT=1 clickhouse/clickhouse-server:24.8
CLICKHOUSE_URL=http://localhost:18123 CLICKHOUSE_AUTH=opt_admin:<throwaway> \
pnpm vitest run tests/integration
# BI-P002 restore drill
docker run -d --name opt-bi-pg -p 15455:5432 \
-e POSTGRES_USER=opt -e POSTGRES_PASSWORD=<throwaway> -e POSTGRES_DB=opt_bi_test \
postgres:16-alpine
ANALYTICS_TEST_DATABASE_URL=postgres://opt:<throwaway>@localhost:15455/opt_bi_test \
pnpm vitest run tests/analytics/analytics-domain-postgres.realinfra.test.ts
# BI-P010 benchmark and BI-P005 external roundtrip (rewrite the evidence files)
CLICKHOUSE_URL=... CLICKHOUSE_AUTH=... node scripts/bi-p010-benchmark.mjs
CLICKHOUSE_URL=... CLICKHOUSE_AUTH=... node scripts/bi-p005-arrow-roundtrip.mjs
```
Both scripts CREATE and DROP a database. Never point either at server7 or at
any ClickHouse holding b0ts or quarantined market data.
@@ -1,257 +0,0 @@
# BI-P060, P061, P103, P104, P105 — dashboards, SLOs, benchmarks, pre-aggregation
Extends the analytics core (`0pt#34`, BI-P002..P012) and the query/metric/quality
layer (`0pt#35`). Nothing there is rebuilt: `DashboardDefinition` and
`DashboardVersion` were already canonical entities with tables in `sql/008`, and
these prompts give them behaviour.
Organised, like its predecessor, around what is **proven** and what is **not**.
---
## Where things live
| prompt | module | live proof |
| ---------------------------- | ---------------------------------------------------------- | ----------------------------------------------------------------------------------------------- |
| BI-P060 dashboard model | `src/analytics/dashboards/dashboard-document.ts` | unit (pure model + planner) |
| BI-P061 dashboard versioning | `src/analytics/dashboards/dashboard-release.ts`, `sql/010` | `tests/analytics/dashboard-release-postgres.realinfra.test.ts`, Postgres 16.15 |
| BI-P103 BI SLO | `src/analytics/slo/bi-slo.ts`, `slo/usage-events.ts` | unit; measurement path is `aud0#34`'s seven event types |
| BI-P104 benchmark harness | `src/analytics/bench/benchmark-harness.ts` | `tests/integration/bi-p104-benchmark.integration.test.ts`, ClickHouse 26.3.10.60 + DuckDB 1.5.5 |
| BI-P105 materialization | `src/analytics/materialization/` | `tests/integration/materialization-drift-clickhouse.integration.test.ts` |
Evidence: `evidence/bi-p061/dashboard-release-race.json`,
`evidence/bi-p104/benchmark.json`, `evidence/bi-p105/materialization-drift.json`.
---
## BI-P060 — the dashboard is a document, not a Superset export
`layout_json` was a string, and a string holds anything. The canonical document
carries `layout / filters / widgets / parameters / refresh / permissions /
version`, and a widget references **a metric, a contract query and a
visualization spec** — never a vendor's internal id.
The DoD is a function. `planDashboard(document, { parameters })` returns, per
widget, a runnable `AnalyticsQueryRequest` (BI-P016) plus a render spec. If it
returns a plan, the dashboard can be drawn by anything that executes the
contract and draws the twelve canonical visualization types.
Rules that are enforced rather than documented:
- a widget whose only content is a vendor id is **refused** — that is exactly
the document that cannot be reconstructed;
- `vendor_ref` may carry a Superset/Metabase id for round-tripping, but it is
excluded from the canonical hash, so re-exporting into a new Superset instance
does not fabricate a new dashboard version;
- vendor-native keys (`viz_type`, `form_data`, `position_json`, `slice_id`, …)
are refused with a message that names the rule;
- query widgets go through `parseAnalyticsQueryRequest`, so a dashboard cannot
become an SQL surface and cannot name a tenant;
- a locked filter cannot be switched off by a viewer — locked filters are how a
saved dashboard pins its scope, and removing one silently widens the result.
---
## BI-P061 — releases are a ledger
`DRAFT → PUBLISHED → SUPERSEDED`, stored in `opt_analytics_dashboard_release`
(`sql/010`) rather than as a column on the version row: `sql/008` already makes
`DashboardVersion` immutable at the database, and a lifecycle column there would
have meant weakening that. The **document** is frozen; the **release** moves.
The database enforces the state machine, not the application:
| attempted | result |
| ------------------------------------------- | -------------------------------------------------- |
| `published → draft` (un-publishing) | refused — it is how a rollback gets faked |
| `superseded → published` | refused |
| repointing a release at another version | refused (every content column is frozen on UPDATE) |
| rewriting `document_hash` or `published_at` | refused |
| `DELETE` on a release | refused — the ledger has no eraser |
| a `published` row with no `published_at` | refused by CHECK |
| a second open draft for one dashboard | refused by a partial unique index |
**Rollback mints a new version.** It does not resurrect the old release row.
"We went back to v3" becomes a timestamped fact (v5 carries
`rollback_of_version = 3`) instead of a hole in the history where v4 used to be.
The restore is verified by BI-P060 canonical hash, and `documentOf()` refuses to
serve a stored document whose hash no longer matches its release.
### The concurrency claim, measured both ways
`DashboardReleaseService.publish()` checks for a live release before writing.
That check is a read-then-write race and is **not** the guarantee.
`evidence/bi-p061/dashboard-release-race.json`, Postgres 16.15:
| run | partial unique index | transactions committed | published releases after |
| --------------- | -------------------- | ---------------------- | --------------------------- |
| `guard_absent` | dropped | 2 | **2 — two live dashboards** |
| `guard_present` | in place | 1 (loser `23505`) | 1 |
Reproduce with `node scripts/bi-p061-release-race.mjs`.
---
## BI-P103 — SLOs measured from AUD0, or declared unmeasured
The measurement path is `aud0#34`'s seven BI usage event types (BI-P076). aud0's
own doc records that zero producers emit them; `src/analytics/slo/usage-events.ts`
makes 0pt the producer. There is deliberately no second telemetry path — two
measurement systems disagree, and the disagreement surfaces during an incident.
| workload | objectives |
| --------------------- | ---------------------------------------------------------------- |
| interactive dashboard | availability, p95 first query, p95 cached, error rate, freshness |
| exploration | p95, p99, max result, timeout |
| report | completion SLA, delivery SLA |
Three verdicts that are not "met":
- **`insufficient_data`** — an availability objective over an empty window is
silence, not 100%. A started query with no terminal event is _unresolved_, not
a success.
- **`not_measurable_here`** — dashboard **freshness** is a property of the
dataset (BI-P026 / BI-P105 watermark) and report **delivery** is N0TIFY's
receipt. Neither exists in the seven event types, so both are declared
unmeasured rather than proxied by completion.
- **`low_confidence`** — a p99 over 12 samples is the 12th-slowest request
wearing a percentile's clothes. Reported with its sample size, not judged.
The producer is an allowlist built field by named field. `compiled_sql`,
`error_message`, `tenant_id`, filter **values** and result samples exist on the
0pt-side telemetry type and are never mapped; a `query_hash` that is not a
64-hex digest is dropped rather than reshaped.
### Honest status
`BI_SLO_CATALOGUE`'s targets are **starting thresholds, not derived baselines**.
No production BI traffic exists yet, so the first real baselines will come from
the first weeks of emitted events. The evaluator is built so that absence shows
up as `insufficient_data` until then, rather than as a green dashboard.
---
## BI-P104 — the harness refuses to quote one number
Six dataset profiles × two engines, 2 warmups discarded, 9 timed repetitions,
statistics from the shipped module. `evidence/bi-p104/benchmark.json`.
- **Overlapping ranges are `indistinguishable`**, whatever the medians say.
Three of the six real comparisons came out that way, one with a 1.6x median
gap — the headline a noisy host manufactures for you.
- **Every sentence carries the range, the sample size and the stability**, so it
cannot be trimmed to "4.4x faster" without visibly deleting the caveats.
- **Under 5 samples nothing is comparable.** A three-run benchmark is an anecdote.
- **Every engine BI-P104 names appears**, and the five nothing measured carry a
reason each.
Measured (warm cache, one idle host, these query shapes only):
| dataset | verdict, DuckDB 1.5.5 vs ClickHouse 26.3.10.60 |
| --------------- | ------------------------------------------------- |
| small_saas | faster, 1.6x–8.2x (median 4.4x) |
| medium_business | indistinguishable (medians 1.6x apart) |
| vehiq_market | faster, 2.4x–13.3x (median 5.8x) |
| large_event | **slower**, 0.2x–0.9x (`count DISTINCT`, 5M rows) |
| wide_table | indistinguishable |
| geospatial | indistinguishable |
Not exercised, with reasons in the evidence: **trino** (the running instance
belongs to another lane; benchmarking through it would measure their
configuration), **semantic_query** (MetricFlow has never executed in 0pt),
**superset**, **native_charts** (DES1GN owns rendering), **perspective**.
---
## BI-P105 — freshness semantics, and why freshness is not correctness
### The vocabulary
| term | definition |
| ------------------------------ | ------------------------------------------------------------------------------- |
| `data_watermark` | the newest **source** timestamp the aggregate represents. Absent = **UNKNOWN**. |
| staleness | `now − data_watermark`, in seconds. `undefined` when the watermark is unknown. |
| `max_staleness_seconds` | the freshness contract. Older than this and the aggregate stops serving. |
| `drift_check_interval_seconds` | how often the aggregate must be re-proved against its source to keep serving. |
| `last_drift_verdict` | `match` / `drifted` / `insufficient_data` from the last comparison. |
**UNKNOWN is never treated as current.** This is the same doctrine BI-P026
applies to result freshness: a missing watermark is a refusal, not a zero.
### The routing rule
A materialization serves **only** while it is provably current _and_ provably
undrifted. Eight named refusals, each a real way an aggregate becomes a
confident liar:
`coverage_miss` (metric/dimension/grain not carried — including a filter on a
dimension the aggregate already summed across) · `watermark_unknown` ·
`staleness_exceeded` · `window_beyond_watermark` (the question reaches past the
newest data; answering would silently shorten the period) ·
`drift_never_verified` · `drift_verification_stale` · `drift_detected` ·
`state_not_serving`.
`drift_never_verified` is the one people leave out and the one that matters on
launch day: a brand-new aggregate is exactly as unproven as a drifted one.
Grain rollup is restricted, not assumed: a `day` aggregate answers `day` and
coarser, never `hour`; a `week` aggregate answers only `week`, because weekly
buckets do not compose into calendar months.
### Drift detection
- **A missing bucket is drift** even when every value present is correct — late
arrivals and a materialized view created after the backfill both look like
this, and a value-only comparison passes while the total is wrong.
- **An extra bucket is drift** — the source rows are gone and the aggregate is not.
- **An empty comparison is `insufficient_data`, never `match`** (the BI-P025
false green, restated for pre-aggregates), and it takes the aggregate out of
service rather than annotating it.
- **Both tolerances must hold.** 0.1% of a 40M bucket is 40 000 kr of invisible
error; an absolute-only bound flags every rounding difference on a large bucket.
### The proof, on a live ClickHouse
`evidence/bi-p105/materialization-drift.json`, ClickHouse 26.3.10.60, 2M rows,
a real materialized view:
| step | result |
| ------------------------ | ----------------------------------------------------------------------------------- |
| after backfill | `match`, 48 buckets, 801 571 002 on both sides |
| GDPR erasure | `ALTER TABLE sales DELETE …`. An MV is an INSERT trigger and never sees a mutation. |
| what would be served | 801 571 002 against a true 761 580 554 — **39 990 448 overstated, 5.251%** |
| staleness at that moment | **1 second.** Every freshness check passed. |
| guarded router | `base_table` (`state_not_serving`) |
| counterfactual | a staleness-only router **serves it** — measured, not assumed |
| after rebuild | `match`, and routing returns to the materialization |
That last row of the counterfactual is the whole point of the prompt: staleness
is not correctness. The aggregate was one second old and wrong by 5%.
### Measured improvement, honestly
Same drill, base table vs pre-aggregate, 9 repetitions interleaved: p50 3.4x,
but the run-to-run range spans **0.6x–7.5x** on an otherwise idle host — one
sample had the pre-aggregate slower than the base table's best run. Quoting
"3.4x" as a property of the system would be misleading, which is why BI-P104's
harness exists.
---
## What is NOT proven here
- **No dashboard has been rendered.** BI-P060 produces a plan; drawing it is
DES1GN (`DES1GN#9`) and `siax-portal#5`. Nothing in this PR proves a pixel.
- **The release service has no Postgres adapter yet.** The lifecycle is proven
in-memory and the _schema_ is proven against live Postgres; wiring
`DashboardReleaseStore` to `postgres.js` is the next step and is the only
place where the two could drift apart.
- **Zero real SLO events have been emitted in production.** The producer and the
evaluator are tested; no BI surface calls the producer yet, so every objective
would today report `insufficient_data`. That is the honest empty state, and it
is deliberately visible rather than hidden behind a default.
- **No materialization is deployed.** The router and detector are proven against
a live ClickHouse in a throwaway database. Nothing schedules a refresh or a
periodic drift check yet — that belongs with ACT0/N0D scheduling.
- **Trino, Superset, MetricFlow and Perspective are unmeasured**, for the
reasons recorded in the benchmark evidence.
-160
View File
@@ -1,160 +0,0 @@
# BI-P014, P016–P022, P025–P026, P028–P031 — query, metric, quality
Extends the analytics core merged in `0pt#34` (BI-P002..P012). Nothing there is
rebuilt.
This document is organised around what is **proven** and what is **not**,
because the second list is the one that gets dropped.
---
## Where things live
| prompt | module | live proof |
| -------------------------------------- | ----------------------------------------------------------------------------------------- | ----------------------------------------------------------------- |
| BI-P014 DuckDB provider | `src/analytics/providers/duckdb-provider.ts` | `tests/duckdb/duckdb-provider.live.test.ts` |
| BI-P016 query request contract | `src/analytics/contract/query-request.ts`, `compile-clickhouse.ts`, `compile-semantic.ts` | unit only (pure compilation) |
| BI-P017 analyst SQL contract | `src/analytics/sql/` | `tests/integration/analyst-sql-clickhouse.integration.test.ts` |
| BI-P018 execution model | `src/analytics/execution/query-execution-record.ts` | `sql/009` + Postgres realinfra |
| BI-P019 cancellation | `src/analytics/execution/cancellation.ts` | `tests/integration/query-cancellation-budget.integration.test.ts` |
| BI-P020 query cache | `src/analytics/cache/query-cache.ts` | unit only (no engine involved) |
| BI-P021 cost / budget | `src/analytics/cost/query-budget.ts` | same live suite as BI-P019 |
| BI-P022 dbt contract | `src/analytics/transform/dbt-contract.ts`, `analytics/dbt/` | contract only — execution is `n0d#38` |
| BI-P025 quality provider | `src/analytics/quality/` | `tests/integration/data-quality-clickhouse.integration.test.ts` |
| BI-P026 freshness | `src/analytics/quality/freshness.ts` | unit + `sql/009` defaults |
| BI-P028/P031 metric model + governance | `src/analytics/metrics/metric-model.ts` | Postgres trigger, realinfra |
| BI-P029 semantic provider | `src/analytics/metrics/semantic-provider.ts` | **partially — see below** |
| BI-P030 semantic registry | `src/analytics/metrics/semantic-registry.ts` | unit + Postgres constraints |
---
## Five findings that changed the implementation
Each was found by writing a test that could fail, and each is pinned so it
cannot quietly stop being true.
### 1. ClickHouse `readonly = 1` on a user profile forbids **every** request setting
Measured on 24.8.14.39. A user whose profile carries `readonly = 1` answers
`Code: 164. Cannot modify 'max_rows_to_read' setting in readonly mode` to any
setting sent with the statement. So BI-P012's ceilings **cannot travel with an
analyst statement** — they are baked into the user's `SETTINGS PROFILE` at
provisioning. Proven both ways: an over-budget scan fails with code 158 from
the profile with no setting sent, and an attempt to raise it from the request
fails with 164.
### 2. `CREATE ROW POLICY IF NOT EXISTS` is a silent no-op on re-provisioning
Dropping a user empties the policy's apply-to list. The next provisioning run
sees the policy exists and does nothing, so it survives with
`apply_to_list = []` — applying to **nobody** — while `system.row_policies`
still shows the correct `select_filter`. The restricted user read 100 of 100
rows, **both tenants**, from the base table.
Fixed with `OR REPLACE`, plus `rowPolicyVerificationSql()` which turns "the
policy is applied" from an assumption into a query, and a test asserting
`applied_to_user = 1` per object. `CREATE SETTINGS PROFILE IF NOT EXISTS` has
the identical shape and is fixed the same way.
### 3. DuckDB's `allowed_directories` **alone** is a no-op
Measured on 1.5.5. With `allowed_directories` set to one mount directory and
nothing else, `read_csv('/etc/passwd')` **returned the file** and an `https://`
URL was fetched over the network. Only `enable_external_access = false`
alongside it makes the allow-list bind.
The obvious spelling of this control appears in `duckdb_settings()`, looks like
a sandbox, and permits everything. The measurement is pinned by a test that
never skips, so simplifying the bootstrap breaks the build rather than the
guarantee.
### 4. `pg_constraint.conname` is not schema-scoped
`SELECT 1 FROM pg_constraint WHERE conname = '...'` matches a same-named
constraint in **any** schema, so `sql/009` applied into a second schema
silently skipped every guarded `CHECK`. Every guard now scopes via
`conrelid = '<table>'::regclass`.
### 5. `describe.skipIf(flagSetInBeforeAll)` skips **always**
Vitest evaluates `skipIf` at collection time. Ten tests reported green while
skipping against a live, reachable ClickHouse. Replaced with the repo's
env-var gate, which **fails** when the variable is set and the server is down.
---
## What is NOT proven
- **BI-P029 / MetricFlow was never executed.** No Python runtime is
provisioned for this repo's CI, and BI-P029's "pin a currently verified
version" needs a licence and supply-chain review that has not happened.
`MetricFlowProvider.providerReadiness()` returns `verified: false` and names
all four open items. What _is_ proven is that the engine-neutral spec
compiles to a MetricFlow-shaped query and that canonical SIAX metric ids
survive a provider swap — tested against a second, deliberately
different-named provider so the equality is not trivially true.
- **The Superset integration path and the AI Analyst comparison** (BI-P029's
other two DoD surfaces) are not implemented.
- **dbt is not run here.** `DBT_RUNTIME_PIN` has both review flags `false`, and
`assertDbtRuntimeCertified` refuses a production run until they are true.
- **DuckDB Arrow IPC** is unproven: the `arrow` extension is a network install
the offline environment could not download. `readiness()` says so.
- **BI-P021's budget is a bound, not a hard cap.** In-flight enforcement is
granular to the poll interval, so the query overshoots between polls — and on
a columnar engine the overshoot is large. In the committed run
(`evidence/bi-p019-p021/`) a 1,000,000-row window cancelled the query at
**153,318,696 rows**, 55 ms in: a **153×** overshoot. The figure is
machine-dependent and moves between runs (an earlier run on the same box
recorded 131 M / 130×), which is itself the point — the bound is "roughly one
poll interval of engine throughput", not a number. It is still a bound: the
same query, unwatched, read **4,227,318,261 rows** before cancellation in the
BI-P019 case. Anyone quoting it as a hard cap is wrong.
- **The per-process window store does not bind across replicas.**
`describeEnforcement()` reports `"with N replicas a tenant can spend up to N
times this budget"`. A shared store (Valkey, or the CL0UD quota service)
behind `SharedWindowStore` is required for it to bind.
---
## Running the live suites
```bash
docker run -d --name ch -p 28123:8123 -e CLICKHOUSE_SKIP_USER_SETUP=1 \
clickhouse/clickhouse-server:24.8
docker run -d --name pg -p 25433:5432 -e POSTGRES_PASSWORD=test \
-e POSTGRES_DB=opt postgres:16-alpine
CLICKHOUSE_URL=http://127.0.0.1:28123 pnpm vitest run tests/integration
ANALYTICS_TEST_DATABASE_URL=postgres://postgres:[email protected]:25433/opt \
pnpm vitest run tests/analytics/analytics-governance-postgres.realinfra.test.ts
python -m venv .venv && .venv/bin/pip install duckdb pyarrow 'pyiceberg[sql-sqlite]'
DUCKDB_PYTHON=.venv/bin/python pnpm vitest run tests/duckdb
```
Every one of these **fails** rather than skipping when its variable is set and
the backend is unreachable.
---
## One note for whoever maintains `.gitea/workflows/ci.yml`
Not changed here — it is a protected file, and this branch touched none.
The integration job's guard is:
```sh
if grep -qE "skipped" /tmp/itest.log && ! grep -qE "Tests [0-9]+ passed" /tmp/itest.log
```
Vitest writes that summary with ANSI colour codes, so the literal text is
`Tests [22m [1m[32m81 passed[39m…`. The second pattern therefore **never
matches**, and the guard is effectively "any skip fails the job" rather than
the "skipped _and_ nothing passed" it reads as. That is stricter than intended,
not looser, so nothing is currently unguarded — but the escape hatch does not
work, and someone will eventually be puzzled by it. Piping through
`sed 's/\x1b\[[0-9;]*m//g'` before the grep would restore the intended
behaviour.
This is how the DuckDB suite's placement was caught, so the guard earned its
keep either way.
-41
View File
@@ -1,41 +0,0 @@
# API deprecation policy — 0pt
BACKLOG P6 (API-24). There is exactly one prior breaking-ish change in this
repo's history to learn from: `services/api/orchestrator/main.py` moved from
`src/orchestrator` (docs/09-build-plan.md Phase 0) — internal, pre-contract,
no external consumers yet. This policy is written before it's needed for a
real consumer, on purpose (BACKLOG's own framing: "cheaper to write the
policy than to clean up after breaking someone").
## What counts as breaking
- Removing a path, operation, or required request/response field from
`contracts/openapi.yaml`.
- Narrowing an accepted value (enum shrink, type tightening) on a request field.
- Changing a response field's meaning without changing its name/type.
- Changing default auth/tenant behavior on an existing route (e.g. what
BACKLOG P0-4 fixed — the reverse of a break, but the same class of change).
Not breaking: adding an optional field, adding a new path, widening an
accepted value, adding a new enum member a client can ignore.
## Process
1. Mark the field/path `deprecated: true` in `contracts/openapi.yaml` with an
`x-siax-deprecated-since` date and a one-line replacement pointer.
2. Keep the deprecated shape working for **at least one release cycle**
after the replacement ships (see `CHANGELOG.md` once real releases/tags
exist — BACKLOG P1-3).
3. Announce in `CHANGELOG.md`'s `[Unreleased]` section before merge, not
after.
4. Only remove once nothing in this repo's own consumers (Protosell/FiveCRM,
VehIQ per `CLAUDE.md`) is verified to depend on the old shape — "verified"
means checked against those repos, not assumed silent.
## What this repo does NOT have yet
No consumers are known to be live against this contract yet
(`docs/architecture/ARCHITECTURE.md` §2 "Beroenden nedåt": "Inga sådana
anrop finns i det här repot" — unverified downstream). This policy exists
so the first real breaking change has a process to follow, not because one
has happened.
-26
View File
@@ -1,26 +0,0 @@
# API docs — 0pt
BACKLOG P1-20 (DOC-07/08). This directory did not exist before this pass.
**Source of truth:** [`contracts/openapi.yaml`](../../contracts/openapi.yaml)
(OpenAPI 3.1, `0pt Data OS API`). Route handlers in `app/api/*` realize
these contracts; `x-siax-status` on each path says whether it's `live` or
contract-first (target).
This directory does **not** duplicate the contract as hand-written prose —
that would drift the moment one of them is edited and not the other (exactly
the kind of stale-doc problem this whole compliance pass exists to fix).
Instead:
| Question | Where to look |
|---|---|
| What routes exist, request/response shapes | [`contracts/openapi.yaml`](../../contracts/openapi.yaml) directly, or render it with any OpenAPI viewer |
| Which routes are live vs. target-only | `x-siax-status` field per path in the same file |
| Risk level + auth requirement per route | `docs/architecture/ARCHITECTURE.md` §3 "API-yta" |
| Capability → surface (API/CLI/MCP/UI) coverage | `docs/architecture/ARCHITECTURE.md` §5 "Ytor och paritet" |
| The separate FastAPI engine contract (`services/api`) | `docs/04-api.md` |
| The edge-native P0 capability contract (`app/api/0pt/*`) | `docs/12-edge-capability-api.md` |
There are genuinely **two** API surfaces documented separately (edge Next.js
routes vs. the FastAPI engine) — see `docs/02-architecture.md` "Two API
surfaces" for why, before assuming a route lives in the file you expected.
@@ -1,64 +0,0 @@
# ADR-001: Verified tenant ownership for payment orders
**Status:** Proposed
**Date:** 2026-09-15
**Deciders:** SIAX 0pt product and platform owners
## Context
The existing order configurator creates anonymous drafts, stores no verified
buyer or tenant on them, and later refers to an order by its ID. A valid
Zitadel principal proves who is calling but does not prove that this caller
owns that particular order. An order ID is an identifier, not an authorization
secret. The nullable `orders.org_id` UUID cannot directly hold the verified
tenant ID, which is a string. The repository has no automated SQL migration
runner, and legacy rows may remain unowned.
The payment flow must remain API-first and work consistently in UI, CLI and
MCP. It must not make anonymous drafts payable by treating a guessed or leaked
ID as ownership.
## Decision
Require a verified Zitadel principal before creating a payable order. Persist
`tenant_id` and buyer subject on each new order in a database migration.
Every read, status mutation and Checkout creation must use a tenant-scoped
query predicate; a cross-tenant order returns 404. The Stripe webhook uses
its verified signature plus recorded order ID and payment facts to advance
status, never a browser-supplied tenant claim. Legacy null-owned orders remain
unpayable until an audited, explicit migration or support workflow binds
them to a verified buyer. Keep the anonymous configurator as an estimate
without creating a payable order until sign-in.
## Options considered
| Option | Complexity | Scale | Consequence |
|---|---|---|---|
| Authenticate only, lookup by order ID | Low | High | Rejected: any signed-in user can access another order. |
| Bearer claim token for anonymous drafts | Medium | High | Requires capability issuance, hashing, secure browser storage and recovery. Not selected for initial production. |
| Verified tenant + buyer subject at order creation | Medium | High | Chosen: explicit ownership at source, shared API boundary. |
## Consequences
- UI must obtain a Zitadel session before order creation and send credentials
to the order and payment APIs; estimates stay anonymous.
- SQL migration must be applied and verified before the scoped code is deployed.
- Existing unowned rows are not silently assigned to a tenant.
- Idempotency keys must be scoped to the verified tenant.
- Admin operations require an explicit, audited role-bound path rather than
bypassing the buyer predicate.
## Action items
1. [x] Build and smoke-verify `sql/011_orders_tenant_ownership.sql` on
throwaway pgvector/Postgres 16, including a second idempotent application.
A deploy migration runner and production application remain open.
2. [x] Bind create-order to verified tenant and buyer subject; scope idempotency.
3. [x] Scope buyer GET/PATCH/deposit/release to tenant at the SQL boundary.
4. [ ] Wire UI Zitadel login/session and CLI/MCP bearer auth; keep anonymous estimates.
5. [ ] Test cross-tenant 404, legacy unowned rejection, webhook, and staging
purchase/refund end-to-end before enabling live Stripe.
Implementation is pending PR review and merge. It is not evidence that the
production database has been migrated or that the browser purchase path is
ready: the current UI does not send a verified Zitadel credential.
File diff suppressed because one or more lines are too long
@@ -1,43 +0,0 @@
# 0pt order-ownership cutover
Status: source implementation in PR #66; **not applied to production**.
Canonical design: [ADR-001](./ADR-001-order-ownership.md).
## Dependency order
1. Confirm the target Postgres is the canonical 0pt order store. Capture a
recoverable database snapshot and identify current migration state.
`sql/001_init.sql` and `sql/006_orders_idempotency.sql` must already be
present; this repository has no general automated migration runner yet.
2. Apply `sql/011_orders_tenant_ownership.sql` transactionally to staging,
then production only after staging verification. The file is idempotent
and leaves legacy NULL-owned rows untouched. For an environment where
`DATABASE_URL` is securely injected, a manual controlled step is:
```bash
psql "$DATABASE_URL" -v ON_ERROR_STOP=1 --single-transaction -f sql/011_orders_tenant_ownership.sql
```
3. Verify `orders.tenant_id`, `orders.buyer_subject`, the ownership-pair
check constraint and `orders_tenant_created_idx`. Record migration
output and deployment SHA in the rollout evidence. Do not deploy the
tenant-scoped source before the schema is verified; an undefined column
will fail requests.
4. Wire a real Zitadel customer UI session and send the verified credential
to every order/payment API call. Existing dev HMAC login is not a payment
identity. Keep anonymous composition as an estimate only.
5. In staging, prove: no token -> 401; spoofed tenant header -> 401/403;
another tenant's order -> 404; legacy unowned order -> 404/unpayable;
matching signed paid Stripe event -> correct status; unpaid/mismatched
event -> no status change; repeat delivery -> idempotent. Test purchase,
cancellation and refund with real sandbox endpoints. Only then review
SIAX Technology AB live credentials and enable live Stripe.
## Rollback and legacy handling
Do not drop ownership columns to roll back the application. Roll back the
application deployment to its prior SHA if needed, retaining the additive
columns and snapshot. A paid Stripe event for a legacy unowned order receives
503 and requires an explicit, audited support decision; the webhook does not
guess a tenant or acknowledge it as fulfilled. Do not silently backfill
ownership from order config, browser storage, or a known order ID.
File diff suppressed because one or more lines are too long

Some files were not shown because too many files have changed in this diff Show More