docs: full accuracy overhaul, grounded claim-by-claim in real code (#4)
* docs: full accuracy overhaul, grounded claim-by-claim in real code Every doc in this repo (CLAUDE.md, README.md, SECURITY.md, docs/*.md) was audited and rewritten by a multi-pass process: independent rewrite per cluster, adversarial re-verification of that rewrite against the actual code, then a final cross-doc consistency pass — each stage re-checking claims against the repo directly rather than trusting the previous stage. Two corrections matter most: 1. docs/ICEBERG_WRITE_BOUNDARY.md, docs/11-lakehouse-write-plan.md, and docs/P0_QUERY_SOURCE_FLOW.md asserted src/services/quality-check-service.ts, quality-report-service.ts, src/data-platform/services/catalog-service.ts, and sql/002_p0_dataset_quality.sql/sql/003_*.sql as real, tested code. git log --all across every branch shows zero commits for any of these paths, ever. 0pt's data-quality/QA enforcement does not exist in code. Corrected everywhere, with a new docs/P0_DATASET_QUALITY_FLOW.md added as an explicit target-spec (not-yet-built) replacement. 2. github.com/sax3l/0pt (this repo) and git.siax.io/sax3l/0pt (Gitea) are two diverged remotes sharing part of the same history (services/api/ workers/adaptive_router.py is byte-identical between them). Gitea's main independently accumulated a WAF-bypass/proxy-rotation scraper stack in three 2026-07-13 commits, since removed via a Gitea PR; GitHub's main never had it. Which remote is canonical/deployed is unresolved — flagged consistently across the corpus, not decided here. Also newly and consistently documented: the tenant_id/project_id-read-from- client-body gap on the P0 lakehouse/rate-policy/source-query routes (no auth/session system exists anywhere in this repo yet); that every CL0UD/ N0D/AUD0/ST0RE platform client is real but mock-only (zero process.env reads for any of their *_URL vars); that two P0 mutation routes (lakehouse/mappings, sources/rate-policies) always fail over HTTP today because their prerequisite entity can never be created via any route; a schema bug in sql/004 (FK references to opt_datasets/opt_sources, which don't exist); and that 0pt.app's live deployment was independently confirmed (curled this pass) to be running this exact codebase with DATABASE_URL/REDIS_URL unset in production. New file: docs/12-edge-capability-api.md — the edge-native P0 TypeScript capability contract (app/api/0pt/*, /api/screen, /api/ai/parse), previously undocumented and distinct from docs/04-api.md's FastAPI-engine-only scope. Verified before commit: tsc --noEmit clean; vitest run 88 passed, 1 todo, 0 failures (13 files) — docs-only change, no source touched. Co-Authored-By: Claude Sonnet 5 <[email protected]> * docs: reflect PR #5's lakehouse-mapping-registry + status-code fixes Follow-up to keep docs/12-edge-capability-api.md accurate once both PRs land: fix/0pt-full-bug-hunt (#5) fixed the shared-instance bug in the lakehouse mapping routes and added proper status-code mapping to the document extraction route. This doc was written against the pre-fix state in the same pass that added it, so it needs the same correction. Does not claim the lakehouse write path fully works now -- the deeper dataset-registration gap (no route ever calls DatasetService.registerDataset) is unchanged and still blocks it end-to-end; only the shared-instance half of the bug is fixed. --------- Co-authored-by: Claude Sonnet 5 <[email protected]>
This commit is contained in:
+7
-3
File diff suppressed because one or more lines are too long
+122
-20
File diff suppressed because one or more lines are too long
+74
-4
File diff suppressed because one or more lines are too long
+80
-18
File diff suppressed because one or more lines are too long
+83
-39
File diff suppressed because one or more lines are too long
+166
-23
@@ -1,6 +1,25 @@
|
||||
# 06 · Data engine
|
||||
|
||||
The engine turns sources into delivered, provenance-tagged data. It is the legal motor — the whole product positioning depends on it. Build on existing `src/workers/` (`adaptive_router`, `browser_worker`, `ocr_worker`, `db`) but enforce the sourcing boundary below.
|
||||
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)
|
||||
|
||||
@@ -11,10 +30,25 @@ For each field × market, acquire in this order; stop at the first that works:
|
||||
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:** if `browser_worker.py` has an `HTTP → FlareSolverr → Playwright` chain, **drop the FlareSolverr stage** and keep only: polite HTTP fetch (identifies itself, obeys robots + rate limits) → optional Playwright for genuinely public JS-rendered pages (same politeness). The `adaptive_router` then chooses among **compliant** methods only (API > bulk > authorized fetch), not bypass tiers.
|
||||
- **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)
|
||||
|
||||
@@ -22,23 +56,100 @@ For each field × market, acquire in this order; stop at the first that works:
|
||||
sourcing → extraction/OCR → structuring → enrichment/fusion → QA
|
||||
```
|
||||
|
||||
1. **Sourcing** — `adaptive_router` picks the compliant method per source; "source-racing" = query several *authorized* sources and take the fastest/freshest. Writes raw payloads + which source answered.
|
||||
2. **Extraction / OCR** — API JSON parsed directly; documents (PDF/HTML/images) via **Unstructured** + OCR cascade (PaddleOCR → Tesseract → LLM fallback) in `ocr_worker`. Output: candidate fields.
|
||||
3. **Structuring** — NER + entity resolution (spaCy / transformers, sv/no/da/fi/de/fr), normalize to schema, link entities across markets via **LEI** (GLEIF golden key). Dedup with **RapidFuzz**.
|
||||
4. **Enrichment / fusion** — combine fields from multiple sources; compute **multi-source agreement** → confidence + level; append optional enrichment (NACE/SNI, sanctions/PEP flag from official lists, website/tech).
|
||||
5. **QA** — quality checks (**Great Expectations** or equivalent, run inside the worker): validity (format/range), completeness, freshness, uniqueness (post-dedup), corroboration. Drop rows below the order's `confidence_target` (deliver fewer, never fabricate). Emit the quality report stored on `deliveries`.
|
||||
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.
|
||||
|
||||
Each stage updates `jobs` (`stage`, `pct`, `metrics` incl. per-market progress, running counts, climbing confidence) so the production tracker / SSE can render it live.
|
||||
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, write a `bridge_provenance` row: `source_id`, `freshness`, `confidence` (0–1), `level` (0–3), `agreed_sources`.
|
||||
- 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; delivered `avg_confidence` = actual.
|
||||
- `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.
|
||||
|
||||
## `sources.yaml` (machine-readable registry)
|
||||
|
||||
Single registry that drives the router, the `/sources` API, and the public sourcing-map page. Schema per entry:
|
||||
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
|
||||
@@ -48,23 +159,55 @@ Single registry that drives the router, the `/sources` API, and the public sourc
|
||||
cadence: daily
|
||||
licence: "open (CC0) — VERIFY current terms"
|
||||
entities: [company]
|
||||
fields: [lei, legal_name, address]
|
||||
fields: [lei, legal_name, address, status]
|
||||
base_url: https://api.gleif.org
|
||||
robots_ok: true # for authorized_web only; must be honored
|
||||
rate_limit: "per provider terms"
|
||||
notes: "cross-border key"
|
||||
```
|
||||
|
||||
### Starter set (VERIFY current access/licence per source before relying — terms change)
|
||||
- **GLEIF / LEI** — typically open; cross-border key. *(verify)*
|
||||
- **Brønnøysund (Brreg, NO)** — typically open API. *(verify)*
|
||||
- **Companies House (UK)** — free API (key required). *(verify)*
|
||||
- **CVR / Virk (DK)** — API access with terms. *(verify)*
|
||||
- **PRH (FI)** — varies. *(verify)*
|
||||
- **Bolagsverket (SE)** — more restricted for bulk; plan licensed/partner route. *(verify)*
|
||||
- Vehicle: **RDW (NL)** open-ish, **Traficom (FI)**, **Transportstyrelsen (SE)**, **DVLA (UK)** — *(verify each; vehicle/PII rules differ)*
|
||||
`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.
|
||||
|
||||
> 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.
|
||||
### 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
|
||||
Crawlee or Scrapy (orchestration of **authorized** fetches) · Playwright (public JS pages, politely) · Unstructured (document parsing) · PaddleOCR/Tesseract (OCR) · spaCy / HF transformers (NER, multilingual) · Polars (fast tabular) · RapidFuzz (dedup/matching) · Great Expectations (quality) · dbt (optional transform layer). Versions/install: `docs/07-dependencies.md`.
|
||||
|
||||
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.
|
||||
|
||||
+57
-43
File diff suppressed because one or more lines are too long
+230
-70
@@ -1,118 +1,278 @@
|
||||
# 08 · Infrastructure
|
||||
|
||||
## Repo structure (monorepo)
|
||||
> 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
|
||||
├─ apps/
|
||||
│ └─ web/ # Next.js (Vercel): marketing, catalog, portal, admin
|
||||
├─ services/
|
||||
│ └─ api/ # FastAPI orchestrator + workers (existing src/* migrates here)
|
||||
│ ├─ orchestrator/ # main.py + routers (docs/04-api.md)
|
||||
│ ├─ workers/ # adaptive_router, fetch_worker, ocr_worker, pipeline, db
|
||||
│ └─ sources/ # sources.yaml + connectors (docs/06)
|
||||
├─ packages/
|
||||
│ └─ shared/ # shared TS types (mirror API contract), design tokens
|
||||
├─ sql/ (or services/api/alembic/) # migrations (docs/03)
|
||||
├─ 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 # VPS always-on services
|
||||
│ └─ Caddyfile # reverse proxy + TLS
|
||||
└─ .github/workflows/ # CI/CD
|
||||
│ ├─ 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** — `apps/web` → `0pt.app`. Free Hobby until paying customers.
|
||||
- **One VPS** (Hetzner ~€5/mo) — `docker-compose`: FastAPI, workers, NocoDB, Metabase, Postgres (or Neon), Redis (if Celery), Caddy. Caddy terminates TLS and proxies `api.0pt.app`, `data.0pt.app` (NocoDB), `dash.0pt.app` (Metabase).
|
||||
- **Cloudflare R2** — files.
|
||||
- **Postgres** — on VPS (`pgvector/pgvector:pg16`) or **Neon** managed.
|
||||
- **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 — sketch)
|
||||
## 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"]
|
||||
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, R2_*, STRIPE_*, RESEND_API_KEY, INTERNAL_TOKEN]
|
||||
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 # or celery -A workers worker
|
||||
environment: [DATABASE_URL, R2_*]
|
||||
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
|
||||
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
|
||||
environment: { MB_DB_TYPE: postgres, MB_DB_HOST: postgres, MB_DB_USER: opt, MB_DB_PASS: ${PG_PASSWORD}, MB_DB_DBNAME: opt }
|
||||
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"]
|
||||
ports: ["80:80", "443:443"]
|
||||
volumes: ["./Caddyfile:/etc/caddy/Caddyfile", "caddydata:/data"]
|
||||
depends_on: [api, nocodb, metabase]
|
||||
volumes: { pgdata: {}, caddydata: {} }
|
||||
```
|
||||
|
||||
## Environment variables (full inventory)
|
||||
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):**
|
||||
```
|
||||
# Postgres
|
||||
DATABASE_URL=postgres://opt:***@host:5432/opt
|
||||
PG_PASSWORD=***
|
||||
# Internal auth (Next ↔ FastAPI)
|
||||
INTERNAL_TOKEN=*** # sent as X-Internal-Token
|
||||
# Auth.js
|
||||
AUTH_SECRET=***
|
||||
AUTH_URL=https://0pt.app
|
||||
# Stripe
|
||||
STRIPE_SECRET_KEY=sk_***
|
||||
STRIPE_WEBHOOK_SECRET=whsec_***
|
||||
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_***
|
||||
# Cloudflare R2 (S3-compatible)
|
||||
R2_ACCOUNT_ID=*** R2_ACCESS_KEY_ID=*** R2_SECRET_ACCESS_KEY=*** R2_BUCKET=opt-files R2_ENDPOINT=https://<acct>.r2.cloudflarestorage.com
|
||||
# Email
|
||||
RESEND_API_KEY=re_***
|
||||
# Embeds (signed URLs)
|
||||
METABASE_SITE_URL=https://dash.0pt.app METABASE_SECRET_KEY=***
|
||||
NOCODB_BASE_URL=https://data.0pt.app NOCODB_API_TOKEN=***
|
||||
# Encryption for db_grants
|
||||
GRANT_ENC_KEY=*** # 32-byte key, AES-GCM
|
||||
# App
|
||||
NEXT_PUBLIC_API_URL=https://api.0pt.app
|
||||
api.0pt.app { reverse_proxy api:8000 }
|
||||
data.0pt.app { reverse_proxy nocodb:8080 }
|
||||
dash.0pt.app { reverse_proxy metabase:3000 }
|
||||
```
|
||||
|
||||
Never hardcode. Vercel env for `apps/web`; VPS `.env` (git-ignored) for compose. Provide `.env.example` with empty values.
|
||||
## Environment variables
|
||||
|
||||
## Security & compliance (build in, not bolt on)
|
||||
**`.env.example` now exists** — added on branch `feature/0pt-env-example`
|
||||
(`github.com/sax3l/0pt/pull/3`, **not yet merged to `main`** as of this pass). 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. The same PR adds
|
||||
`!.env.example` to `.gitignore` to fix that. README's "Env inventory: `.env.example`" link is
|
||||
therefore currently a broken/future reference on `main` until that PR merges.
|
||||
|
||||
- **Customer DB grants**: customer creates a read-only, table-scoped, time-boxed DB role; we store the connection string **AES-GCM encrypted** (`GRANT_ENC_KEY`), validate it's read-only, and **delete after the job**. IP-allowlist; prefer a replica. Log access in `audit_log`.
|
||||
- **File delivery**: short-lived **presigned R2 URLs**; never public buckets.
|
||||
- **Isolation**: API filters by `org_id`; Postgres **RLS** where practical; NocoDB/Metabase exposed only via **signed embed URLs** scoped per customer/order (no separate login surfaced).
|
||||
- **PII (contacts/UBO)**: lawful basis recorded per delivery; honor deletion; minimize retention.
|
||||
- **DPA**: ship a Data Processing Agreement; provenance log + audit log are part of the offering.
|
||||
- **Secrets**: rotate; least privilege; no secrets in client bundles (only `NEXT_PUBLIC_*`).
|
||||
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.
|
||||
|
||||
## Embedding NocoDB / Metabase (so it feels like one app)
|
||||
- Generate a **signed embed URL** server-side (Metabase signed embedding with `METABASE_SECRET_KEY`; NocoDB shared/locked view + token) scoped to the customer's data, and render it in an iframe inside the mono chrome. The customer never sees a NocoDB/Metabase login.
|
||||
| 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/` |
|
||||
|
||||
## CI/CD (.github/workflows)
|
||||
- **web**: lint + typecheck + build → deploy to Vercel on push to `main` (Vercel Git integration).
|
||||
- **api**: lint (ruff) + tests (pytest) → build Docker image → deploy to VPS (SSH `docker compose pull && up -d`, or a small runner).
|
||||
- Run DB migrations as a deploy step.
|
||||
### Platform-client URLs — corrected from a stronger claim
|
||||
|
||||
## Monitoring (cheap)
|
||||
- Vercel Analytics + Speed Insights (web).
|
||||
- **Sentry** free tier (web + api).
|
||||
- Uptime ping on `/health`.
|
||||
- Worker/job health visible in admin (reads `jobs`).
|
||||
`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).
|
||||
|
||||
+171
-1
@@ -2,28 +2,103 @@
|
||||
|
||||
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**, on branch `feature/0pt-env-example`
|
||||
(`github.com/sax3l/0pt/pull/3`), **not yet merged to `main`**. It was blocked for the life of this
|
||||
project by `.gitignore`'s blanket `.env*` rule silently matching it too; the same PR fixes that
|
||||
with `!.env.example`. Until that PR merges, `main` still has no `.env.example`.
|
||||
- `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).
|
||||
@@ -32,12 +107,53 @@ Phased, in dependency order. **Finish a phase to its acceptance criteria before
|
||||
- **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.
|
||||
@@ -45,11 +161,34 @@ Phased, in dependency order. **Finish a phase to its acceptance criteria before
|
||||
- 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.
|
||||
@@ -57,19 +196,50 @@ Phased, in dependency order. **Finish a phase to its acceptance criteria before
|
||||
- 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.
|
||||
- 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.
|
||||
|
||||
@@ -6,12 +6,27 @@ outside this repo and states what it means for 0pt specifically. It does not cha
|
||||
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. 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.
|
||||
`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
|
||||
@@ -29,17 +44,37 @@ work from many engines (Trino/Spark/Flink/DuckDB/etc.), not one.
|
||||
| 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`) as it does today, and — once ST0RE's
|
||||
table registry exists — writes the resulting datasets as **Iceberg tables through that registry**.
|
||||
0pt does **not** talk to N0D's catalog or any lakehouse storage directly; it goes through ST0RE.
|
||||
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 once ST0RE's registry ships. Concrete to-dos and required schema/event names are in
|
||||
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
|
||||
@@ -47,14 +82,23 @@ write-path once ST0RE's registry ships. Concrete to-dos and required schema/even
|
||||
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/removed from N0D's seed data. 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 will formalize its own
|
||||
model rather than depend on anything in N0D for this. See `docs/11-lakehouse-write-plan.md`.
|
||||
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 implement Iceberg writes today.
|
||||
- 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 yet — this doc is the pointer; the plan doc
|
||||
lists what's blocked on ST0RE vs. what 0pt can define now.
|
||||
- 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.
|
||||
|
||||
@@ -2,13 +2,29 @@
|
||||
|
||||
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. Some items are already true today (quality
|
||||
rules) and this doc just confirms 0pt intends to keep them that way.
|
||||
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-12 update: what the 0pt write-boundary implementation pass closed
|
||||
|
||||
This pass (the "future implementation session" this doc was written for) turned most items below
|
||||
into real, tested code. Full detail in `docs/ICEBERG_WRITE_BOUNDARY.md`; short version:
|
||||
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`,
|
||||
@@ -24,8 +40,12 @@ into real, tested code. Full detail in `docs/ICEBERG_WRITE_BOUNDARY.md`; short v
|
||||
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): CONFIRMED, untouched -- `src/services/quality-check-service.ts`
|
||||
and `src/services/quality-report-service.ts` were not modified by this pass.
|
||||
- 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
|
||||
@@ -68,21 +88,32 @@ into real, tested code. Full detail in `docs/ICEBERG_WRITE_BOUNDARY.md`; short v
|
||||
- `entity_type`, `market` — for routing/filtering.
|
||||
- `mapped_at`, `mapped_by`.
|
||||
|
||||
3. **Write a first test dataset to Iceberg** through ST0RE's (future) table registry, once that
|
||||
registry exists. Pick a small, low-risk dataset (e.g. a single-market `dim_company` slice) as
|
||||
the pilot. This validates the write path end-to-end before any production order relies on it.
|
||||
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 already correct today (per the `n0d` audit): 0pt's
|
||||
QA stage (`docs/06-data-engine.md` §QA — Great Expectations checks for validity, completeness,
|
||||
freshness, uniqueness, corroboration) is caller-supplied logic that 0pt owns and hands to
|
||||
whichever engine executes a job; it is not, and must not become, logic owned or embedded by
|
||||
N0D. This doc confirms 0pt intends to keep authoring/owning quality rules itself even after
|
||||
N0D executes heavy writes/compactions on 0pt's behalf (see item 7).
|
||||
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. Context: N0D's `ComputePolicy.sourceRatePolicy` (per-domain crawl rate
|
||||
limits) has been deprecated/removed from N0D's seed data as part of the same audit — that field
|
||||
never belonged to N0D. 0pt already has the raw material for this in `sources.yaml`
|
||||
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:
|
||||
@@ -95,8 +126,11 @@ into real, tested code. Full detail in `docs/ICEBERG_WRITE_BOUNDARY.md`; short v
|
||||
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, once AUD0 exists as a real
|
||||
evented product (it does not yet — do not build a lineage sink against it prematurely). Plan
|
||||
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
|
||||
@@ -111,16 +145,19 @@ into real, tested code. Full detail in `docs/ICEBERG_WRITE_BOUNDARY.md`; short v
|
||||
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.** 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.
|
||||
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** once ST0RE's registry exists. Until
|
||||
then, 0pt has no lakehouse table state to persist at all — Postgres (`docs/03`) remains the
|
||||
only store. Once ST0RE ships its registry, 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).
|
||||
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)
|
||||
|
||||
@@ -136,12 +173,30 @@ into real, tested code. Full detail in `docs/ICEBERG_WRITE_BOUNDARY.md`; short v
|
||||
|
||||
## Sequencing / dependencies
|
||||
|
||||
- Items 2, 4, 5 have no hard dependency on another product and can be defined/built inside 0pt
|
||||
today (this repo already owns `sources.yaml` and the QA stage).
|
||||
- Items 1, 3, 8 are blocked on **ST0RE's table registry** existing.
|
||||
- Item 6 is blocked on **AUD0** existing as a real evented product.
|
||||
*(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;
|
||||
no such integration exists yet in `services/api` and none is being added by this doc.
|
||||
`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)
|
||||
|
||||
|
||||
File diff suppressed because one or more lines are too long
+149
-37
File diff suppressed because one or more lines are too long
@@ -0,0 +1,180 @@
|
||||
# 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.
|
||||
+192
-25
@@ -1,8 +1,18 @@
|
||||
# 0pt.query_source — Bounded Source Query Flow
|
||||
|
||||
Additive companion to `docs/P0_DATASET_QUALITY_FLOW.md`. Adds the capability
|
||||
to actually **read data** from a registered Source, not just register its
|
||||
metadata.
|
||||
> **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
|
||||
|
||||
@@ -12,11 +22,23 @@ 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.
|
||||
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"
|
||||
|
||||
@@ -31,9 +53,15 @@ is reachable, sample a table, preview a query before scheduling it). It is
|
||||
`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 —
|
||||
must go through **N0D as a job** instead, the same split
|
||||
`quality-check-service.ts` already uses (`runQualityChecks` → CL0UD policy
|
||||
→ N0D job, not an inline synchronous call).
|
||||
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
|
||||
|
||||
@@ -64,19 +92,91 @@ Route: app/api/0pt/sources/[sourceId]/query/route.ts
|
||||
- 422 (SourceQueryUnsupportedError) when source_type != "database" or
|
||||
adapter_id != "fabric_onelake_sql"
|
||||
- 504 (SourceQueryTimeoutError) on timeout
|
||||
|
||||
AUD0: event_type "0pt.source_queried", capability_id "0pt.query_source",
|
||||
resource_type "source", risk_level "L4" (live external data access with a
|
||||
tenant's own credentials — one level above the "L3" used for Source/
|
||||
Dataset/QualityCheck metadata writes, matching the "L4 = restricted
|
||||
sensitivity" precedent in src/data-platform/services/catalog-service.ts).
|
||||
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 / quality-check-service.ts.
|
||||
```
|
||||
|
||||
## 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
|
||||
@@ -85,8 +185,12 @@ AUD0: event_type "0pt.source_queried", capability_id "0pt.query_source",
|
||||
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.
|
||||
- **In-memory SourceService is not shared across API route modules.**
|
||||
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
|
||||
@@ -95,16 +199,79 @@ AUD0: event_type "0pt.source_queried", capability_id "0pt.query_source",
|
||||
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.
|
||||
The real fix is the same one already pointed at by `sql/002_p0_dataset_quality.sql`
|
||||
(`opt_sources` table) — back `SourceService` with real persistence.
|
||||
- **No CL0UD policy check before executing a query.** `quality-check-service.ts`
|
||||
calls `Cl0udClient.evaluatePolicy()` before creating a N0D job; this
|
||||
synchronous path does not, since it is scoped as a bounded preview read, not
|
||||
a governed job. Worth revisiting once policy-gating on `0pt.query_source`
|
||||
is defined.
|
||||
**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.
|
||||
|
||||
Reference in New Issue
Block a user