Files
0pt/src/validation/0pt-schemas.ts
T
Simon AxelssonandClaude Opus 5 9267576b7c
CI (SIAX Cloud) / integration (push) Successful in 42s
CI (SIAX Cloud) / quality (push) Successful in 1m17s
CI (SIAX Cloud) / security (push) Successful in 46s
Security Scan (SIAX Cloud) / security (push) Successful in 31s
CI (SIAX Cloud) / security (pull_request) Successful in 24s
CI (SIAX Cloud) / integration (pull_request) Successful in 36s
CI (SIAX Cloud) / quality (pull_request) Successful in 1m4s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 27s
feat(data-os): P060-P068 durable ingestion plane — source classification gate, connector contract, common envelope, schema evolution, quality enforcement, queryable lineage, idempotent backfill
BEFORE_STATE (verified, with evidence):

* P060 PARTIAL/BROKEN. The registry persisted rights/provenance/health/
  freshness to Postgres, but carried no authorization, no schedule, no
  checkpoint, no schema and no owner distinct from created_by — and the
  activation DoD was inverted: postgres-source-repository.ts wrote
  `${input.status ?? "active"}`, so a source with no rights, no provenance
  and no authorization was ACTIVE the instant it was registered. No
  activation operation existed at all.
* P061 MISSING. services/api/sources/connectors.py had per-source fetch_*()
  functions only — no lifecycle, no cursor, no resume, no health, no
  conformance suite.
* P062 MISSING, already documented as such in
  services/api/tests/test_known_gaps.py:10-19 (no CDC pipeline anywhere;
  workers/pipeline.py has no persistence at all).
* P063 MISSING. schema_version existed as a free string; no comparison,
  no policy, no versioned source schema.
* P064 PARTIAL. Rules/runs/issues/scores existed, but a failing rule only
  opened an issue and the data flowed on. No quarantine anywhere.
* P065 DUPLICATE (confirmed). Two ER engines: src/er/entity-resolution-
  service.ts (canonical) and services/api/workers/resolve.py (simplified,
  still called by pipeline.py:110).
* P067 PARTIAL. Lineage was emitted to AUD0 but nothing here could ANSWER a
  lineage question — no store, no query, no route.
* P068 MISSING, documented in test_known_gaps.py:44-52 ("no delivery-store
  persistence layer exists to dedupe a backfill against").

BUILT (only what was PARTIAL/BROKEN/MISSING):

* P060 sql/007_ingestion_plane.sql adds authorization/schedule/schemas/
  checkpoints/ledger/quarantine/lineage tables, owner_id, and flips the
  opt_sources status DEFAULT to 'pending' so even a raw psql INSERT cannot
  produce an unclassified-but-active source. SourceRegistryService gains
  classifySource/activateSource/deactivateSource + authorization/schedule
  accessors; registration NEVER activates (asking for status:"active" goes
  through the gate, not around it); a service identity cannot authorize a
  source. Routes: activate (GET classification / POST activate),
  authorization, schedule.
* P061 src/connectors/connector.ts — all nine operations on one interface.
  src/connectors/conformance.ts — a runnable suite (15 checks, no "skip"
  verdict). HttpJsonConnector (real HTTP, opaque cursor) and
  JsonlFileConnector (real file, line offsets, CDC deletes) both pass it.
  The suite caught a real defect while being written: an API that drops
  next_cursor at the end left the connector unable to resume, which is why
  HttpJsonConnectorConfig has cursor_field.
* P062 src/types/ingestion.ts + src/ingestion/{envelope,ingestion-runner}.ts.
  One envelope for batch/stream/cdc; durable per-(source,partition)
  checkpoints; resume proven by killing a run inside the sink.
* P063 src/schema/{record-schema,compatibility,schema-registry}.ts. Two
  enforcement points, both upstream of any consumer write: a discovery gate
  before the first read, and per-record conformance before the page reaches
  the sink. A producer cannot widen its own policy retroactively.
* P064 src/quality/quality-policy.ts composes the EXISTING ExpectationEngine
  (not a second engine) and adds the missing consequence: block /
  quarantine / warn, with quarantine durable and recoverable. No policy is
  reported as "none_declared", never as a pass; an unexecutable expectation
  counts as a violation, never a silent pass.
* P067 src/lineage/{lineage-edge,lineage-store}.ts + GET /api/0pt/lineage.
  AUD0 stays the system of record; this is 0pt's own queryable projection.
* P068 opt_ingestion_ledger + IngestionRunner.backfill: bounded, idempotent
  on repeat, leaves the live checkpoint alone, still re-emits real changes.

A BUG THIS PASS WROTE AND CAUGHT: the first IngestionRepository draft
combined the idempotency check and its recording into one atomic call
BEFORE the sink. The crash/resume test then delivered 7 of 10 records — the
page in flight when the sink died was already marked delivered, so the
resumed run skipped it as a duplicate. Permanent, silent data loss. Fixed by
splitting peekDeliveries/commitDeliveries and committing both the ledger and
the checkpoint only after the sink resolves.

NOT DONE, stated rather than deferred quietly:

* P065 is NOT met. resolve.py is still a second simplified production
  engine. Closing it means rewriting it as an adapter over the canonical
  service, which cannot be verified from this repo today: services/api is
  not built by this repo's Dockerfile, api.0pt.app answers 404, and NO CI
  workflow runs its pytest suite. The duplication is now stated at both
  sites in code and the removal plan is in STATUS.md. The new ingestion
  plane performs no ER, so it adds no third engine.
* P066 (Iceberg) untouched — ST0RE is owned by another workflow. Contract
  read only.
* Delivery is AT-LEAST-ONCE, not exactly-once (no per-partition run lock).
* No CDC *source* exists; the contract is met, a CDC connector is not built.
* 0pt does not schedule itself — the schedule row is a declaration ACT0
  would read.

VERIFIED: pnpm typecheck clean; pnpm test 365 passed / 25 skipped (was
311/18); pnpm build clean with all four new routes in the route table; lint
unchanged at 12 pre-existing errors. Real Postgres 16
(tests/p0/ingestion-plane-postgres.realinfra.test.ts, 7 passed) plus a real
`docker restart` of that container with an identical read-back through the
production code path — that is P060's "a restart preserves all sources",
measured.

DEPLOYMENT REALITY (curl, 2026-09-04): 0pt.app/api/health returns 200 from
Vercel with db:not_configured; 0pt.app/api/0pt/sources returns 404;
api.0pt.app/health returns 404; cd.yml still guards on a placeholder Coolify
app id. None of the capability layer runs in production. Nothing here is
LIVE_VERIFIED and STATUS.md says so.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-04 17:03:14 +02:00

266 lines
11 KiB
TypeScript

/**
* `0pt/validation/0pt-schemas.ts` -- Wave 2 input validation for the 0pt
* capability API's MUTATING routes.
*
* Before Wave 2 every POST/PUT handler did `const body = await request.json()`
* and read fields straight off `body` (an implicit `any`), so a malformed
* payload reached the service layer untyped and surfaced as an opaque 500/400.
* These Zod schemas validate the request body at the edge and produce a typed,
* structured 400. This is VALIDATION ONLY -- it re-encodes the shape each
* handler already destructures; it does not add or change business logic.
*/
import { z } from 'zod';
/** A structured 400 parse result. */
export type ParseResult<T> =
| { ok: true; data: T }
| { ok: false; status: 400; body: { error: 'validation_error'; issues: { path: string; message: string }[] } };
/** Validate `body` against `schema`, returning parsed data or a 400 payload. */
export function parseBody<S extends z.ZodTypeAny>(schema: S, body: unknown): ParseResult<z.infer<S>> {
const result = schema.safeParse(body);
if (result.success) return { ok: true, data: result.data };
return {
ok: false,
status: 400,
body: {
error: 'validation_error',
issues: result.error.issues.map((i) => ({
path: i.path.join('.'),
message: i.message,
})),
},
};
}
// A permissive JSON object (used for opaque config blobs whose inner shape is
// owned by a downstream adapter, not this validation layer).
const jsonObject = z.record(z.string(), z.unknown());
/** POST /api/0pt/documents/capture */
export const documentCaptureSchema = z.object({
mailbox: z.object({
tenant_id: z.string().min(1),
client_id: z.string().min(1),
client_secret: z.string().min(1),
mailbox_address: z.string().min(1),
folder: z.string().min(1).optional(),
}),
since_iso: z.string().min(1).optional(),
top: z.number().int().positive().optional(),
max_pages: z.number().int().positive().optional(),
tenant_id: z.string().min(1),
project_id: z.string().min(1),
actor_id: z.string().min(1).optional(),
correlation_id: z.string().min(1).optional(),
});
/** POST /api/0pt/documents/[documentId]/extraction */
export const documentExtractionSchema = z.object({
tenant_id: z.string().min(1),
project_id: z.string().min(1),
actor_id: z.string().min(1).optional(),
correlation_id: z.string().min(1).optional(),
model_id: z.string().min(1).optional(),
});
/** POST /api/0pt/sources/[sourceId]/query */
export const sourceQuerySchema = z.object({
query: z.string().trim().min(1),
params: z.unknown().optional(),
tenant_id: z.string().min(1),
project_id: z.string().min(1),
actor_id: z.string().min(1).optional(),
correlation_id: z.string().min(1).optional(),
max_rows: z.number().int().positive().optional(),
timeout_ms: z.number().int().positive().optional(),
connection_config: jsonObject,
});
/** POST /api/0pt/sources/rate-policies -- mirrors CreateSourceRatePolicyInput. */
export const createSourceRatePolicySchema = z.object({
source_rate_policy_id: z.string().min(1),
tenant_id: z.string().min(1),
project_id: z.string().min(1),
source_id: z.string().min(1),
rate_limit_per_minute: z.number().int().nonnegative(),
crawl_budget: z.number().int().nonnegative(),
compliance_notes: z.string().optional(),
domain: z.string().min(1).optional(),
robots_ok: z.boolean().optional(),
access: z.enum(['api', 'bulk', 'authorized_web', 'licensed']).optional(),
status: z.enum(['active', 'paused', 'deprecated']).optional(),
correlation_id: z.string().min(1).optional(),
created_by: z.string().min(1).optional(),
});
/** Nested `rights` block on POST /api/0pt/sources, and the body of PUT /api/0pt/sources/[sourceId]/rights -- mirrors SourceRights (minus source_id/tenant_id, which come from the URL/outer body). */
const sourceRightsInputSchema = z.object({
license_id: z.string().min(1),
license_url: z.string().min(1).optional(),
allowed_purposes: z.array(z.string().min(1)).default([]),
pii_allowed: z.boolean(),
redistribution: z.enum(['internal', 'customer_deliverable', 'public', 'prohibited']),
attribution: z.string().min(1).optional(),
verified_at: z.string().min(1),
verified_by: z.string().min(1),
notes: z.string().min(1).optional(),
});
/** Nested `provenance` block on POST /api/0pt/sources, and the body of PUT /api/0pt/sources/[sourceId]/provenance -- mirrors SourceProvenance (minus source_id/tenant_id/updated_at, which are set by the service). */
const sourceProvenanceInputSchema = z.object({
method: z.enum(['official_api', 'bulk_download', 'authorized_web', 'licensed_feed', 'manual_upload']),
authority: z.string().min(1).optional(),
compliance_evidence_ref: z.string().min(1).optional(),
cadence: z.string().min(1).optional(),
freshness_sla_hours: z.number().nonnegative().optional(),
});
/** POST /api/0pt/sources -- source.register. */
export const registerSourceSchema = z.object({
source_id: z.string().min(1),
tenant_id: z.string().min(1),
project_id: z.string().min(1),
source_type: z.enum(['database', 'file', 'web', 'api', 'stream', 'manual']),
name: z.string().min(1),
adapter_id: z.string().min(1).optional(),
access: z.enum(['api', 'bulk', 'authorized_web', 'licensed']).optional(),
description: z.string().min(1).optional(),
status: z.enum(['pending', 'active', 'paused', 'archived', 'deprecated']).optional(),
owner_id: z.string().min(1).optional(),
correlation_id: z.string().min(1).optional(),
created_by: z.string().min(1).optional(),
rights: sourceRightsInputSchema.optional(),
provenance: sourceProvenanceInputSchema.optional(),
});
/** PUT /api/0pt/sources/[sourceId]/rights -- source.set_rights. */
export const setSourceRightsSchema = sourceRightsInputSchema.extend({
tenant_id: z.string().min(1),
});
/** PUT /api/0pt/sources/[sourceId]/provenance -- source.set_provenance. */
export const setSourceProvenanceSchema = sourceProvenanceInputSchema.extend({
tenant_id: z.string().min(1),
});
/** POST /api/0pt/sources/[sourceId]/health -- source.health (record a health check). */
export const recordSourceHealthCheckSchema = z.object({
tenant_id: z.string().min(1),
status: z.enum(['up', 'degraded', 'down', 'unknown']),
checked_at: z.string().min(1).optional(),
latency_ms: z.number().nonnegative().optional(),
detail: z.string().min(1).optional(),
});
/** POST /api/0pt/lakehouse/mappings -- mirrors MapDatasetToIcebergTableInput. */
export const mapDatasetToIcebergTableSchema = z.object({
tenant_id: z.string().min(1),
project_id: z.string().min(1),
dataset_id: z.string().min(1),
dataset_iceberg_mapping_id: z.string().min(1),
namespace: z.string().min(1),
table_name: z.string().min(1),
storage_uri: z.string().min(1),
catalog_ref: z.string().min(1),
table_format: z.string().min(1).optional(),
actor_id: z.string().min(1),
correlation_id: z.string().min(1),
});
/** POST /api/0pt/lakehouse/mappings/[mappingId]/writes -- RequestIcebergWriteInput. */
export const requestIcebergWriteSchema = z.object({
// P014: required so the route can both (a) cross-check it against the
// caller's verified tenant (assertTenantMatchesVerified) and (b) thread it
// into IcebergWriteService.requestIcebergWrite -> getMapping, which
// refuses the write as not-found when it disagrees with the mapping's own
// tenant_id. See getMapping's doc comment for the cross-tenant write gap
// this closes.
tenant_id: z.string().min(1),
actor_id: z.string().min(1),
correlation_id: z.string().min(1),
snapshot_type: z.string().min(1).optional(),
schema_version: z.string().min(1),
manifest_uri: z.string().min(1),
record_count: z.number().int().nonnegative().optional(),
size_bytes: z.number().int().nonnegative().optional(),
heavy: z.boolean().optional(),
});
/** POST /api/0pt/quality/rules -- mirrors CreateQualityRuleInput (src/quality/quality-types.ts). */
export const createQualityRuleSchema = z.object({
rule_id: z.string().min(1),
tenant_id: z.string().min(1),
project_id: z.string().min(1),
dataset_id: z.string().min(1),
name: z.string().min(1),
expectation: z.object({
expectation_type: z.string().min(1),
kwargs: jsonObject,
}),
severity: z.enum(['info', 'warning', 'error', 'critical']).optional(),
supplied_by: z.string().min(1).optional(),
});
/**
* POST /api/0pt/quality/runs -- runs the currently-registered active rules
* for a dataset against caller-supplied rows (QualityService.runQuality).
*/
export const createQualityRunSchema = z.object({
tenant_id: z.string().min(1),
project_id: z.string().min(1),
dataset_id: z.string().min(1),
dataset_version: z.number().int().optional(),
rows: z.array(jsonObject).optional(),
correlation_id: z.string().min(1).optional(),
});
/**
* POST /api/0pt/quality/bridge-run -- the Python engine's (services/api/workers/pipeline.py)
* bridge into the TS QualityService. Auto-provisions a baseline rule set for
* the (tenant, dataset) pair the first time it is called, so the engine never
* has to pre-register rules through the CRUD surface just to get an advisory
* quality read. `rows` is required here (unlike createQualityRunSchema) --
* the bridge always runs synchronously against real, already-produced rows;
* it never triggers a delegated/no-rows run.
*/
export const qualityBridgeRunSchema = z.object({
tenant_id: z.string().min(1),
project_id: z.string().min(1),
dataset_id: z.string().min(1),
dataset_version: z.number().int().optional(),
rows: z.array(jsonObject),
correlation_id: z.string().min(1).optional(),
});
/** Nested `authorization` block on POST /api/0pt/sources, and the body of PUT /api/0pt/sources/[sourceId]/authorization (P060). */
const sourceAuthorizationInputSchema = z.object({
basis: z.enum(['contract', 'public_register', 'consent', 'legitimate_interest', 'internal']),
granted_by: z.string().min(1),
granted_at: z.string().min(1),
expires_at: z.string().min(1).optional(),
evidence_ref: z.string().min(1).optional(),
notes: z.string().min(1).optional(),
});
/** PUT /api/0pt/sources/[sourceId]/authorization -- source.set_authorization (P060). */
export const setSourceAuthorizationSchema = sourceAuthorizationInputSchema.extend({
tenant_id: z.string().min(1),
});
/** PUT /api/0pt/sources/[sourceId]/schedule -- source.set_schedule (P060). */
export const setSourceScheduleSchema = z.object({
tenant_id: z.string().min(1),
mode: z.enum(['batch', 'stream', 'cdc']),
interval_seconds: z.number().int().positive().optional(),
cron: z.string().min(1).optional(),
enabled: z.boolean(),
});
/** POST /api/0pt/sources/[sourceId]/activate -- source.activate (P060 classification gate). */
export const activateSourceSchema = z.object({
tenant_id: z.string().min(1),
actor_id: z.string().min(1).optional(),
});