CI (SIAX Cloud) / quality (push) Successful in 51s
Security Scan (SIAX Cloud) / security (push) Successful in 26s
CI (SIAX Cloud) / security (push) Successful in 28s
CI (SIAX Cloud) / integration (push) Successful in 1m1s
CI (SIAX Cloud) / integration (pull_request) Successful in 30s
CI (SIAX Cloud) / security (pull_request) Successful in 24s
CI (SIAX Cloud) / quality (pull_request) Successful in 48s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 22s
Tenant isolation (security-critical): every app/api/0pt/** route reading
tenant_id from client-controlled query/body never cross-checked it against
the token middleware.ts already verified (x-0pt-verified-tenant). Adds a
shared assertTenantMatchesVerified guard and wires it into all 20+ affected
routes. Also closes two full-leak-by-omission bugs found in this pass
(documents/capture and lakehouse/mappings GETs returned every tenant's rows
when tenant_id was simply omitted) and two "no tenant check at all" reads
(rate-policies/[id], lakehouse/mappings/[id]) reachable by ID alone.
Duplicate-delivery idempotency (correctness-critical): POST /api/orders now
honors Idempotency-Key (sql/006, replay-or-409-on-conflict, Postgres +
in-memory); the Python orchestrator's POST /orders/{id}/run — the actual
delivery trigger — is now idempotent under an asyncio lock, closing a real
concurrent-request race, not just the sequential-retry case.
Engine-duplication resolution: adaptive_router.py's docstring wrongly
invited a bypass ("see b0ts for scraping") contradicting the product's own
compliance stance; corrected, and given real (additive, not escalating)
block-signal tracking so a rate-limited/blocked source is excluded from the
plan instead of hammered. Also fixes a previously-undiscovered production
bug: the Python engine's only call into the TS quality bridge
(X-Internal-Token) was unconditionally 401'd by middleware.ts, which never
checked that credential — the advisory quality bridge was unreachable in any
environment enforcing auth.
Restore drill: executed for real against throwaway Docker Postgres
containers (not simulated). Found and fixed two real blockers along the way:
sql/004 referenced opt_datasets, which no migration ever created (chain was
never actually runnable end to end); lib/db.ts hardcoded ssl:"require",
making any non-TLS Postgres (incl. compose.dev.yaml's own local-dev
container) unreachable. After both fixes: full migration chain applies
cleanly, pg_dump/pg_restore round-trip is byte-identical (row counts +
content checksums), and real application code (lib/orders-store.ts,
SourceRegistryService's Postgres repository) reads the restored data back
correctly, including cross-tenant isolation still holding.
82 new tests (55 TS + 27 Python), all passing; full existing suite (291 TS +
55 Python) still green; typecheck clean on every changed/added file.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
343 lines
14 KiB
TypeScript
343 lines
14 KiB
TypeScript
import type { DatasetIcebergMapping } from "../types/dataset-iceberg-mapping";
|
|
import { createCl0udClient, type Cl0udClient } from "../clients/cl0ud-client";
|
|
import { createN0dClient, type N0dClient } from "../clients/n0d-client";
|
|
import { createAud0Client, type Aud0Client } from "../clients/aud0-client";
|
|
import {
|
|
createSt0reLakehouseClient,
|
|
type St0reLakehouseClient,
|
|
type IcebergTableFormat,
|
|
type TableSnapshotType,
|
|
} from "../clients/st0re-lakehouse-client";
|
|
import { DatasetService } from "./dataset-service";
|
|
import { DatasetIcebergMappingService } from "./dataset-iceberg-mapping-service";
|
|
|
|
/**
|
|
* IcebergWriteService -- 0pt's write-path entrypoint for Iceberg tables.
|
|
*
|
|
* This is the concrete implementation of docs/ICEBERG_WRITE_BOUNDARY.md /
|
|
* docs/11-lakehouse-write-plan.md items 1, 3, 6, 7, 8: 0pt is the canonical
|
|
* writer of Iceberg tables, and it writes THROUGH ST0RE's table registry
|
|
* (`St0reLakehouseClient`) rather than persisting any lakehouse table,
|
|
* catalog, or snapshot state itself. This service holds NO table/snapshot
|
|
* state of its own -- only `DatasetIcebergMappingService`'s lightweight
|
|
* dataset-to-table-id pointer, which is a reference, not a copy.
|
|
*
|
|
* Two entry points:
|
|
* - `mapDatasetToIcebergTable` -- registers a NEW Iceberg table in ST0RE for
|
|
* a dataset that does not have one yet, then records the mapping. This is
|
|
* the "first test dataset written to Iceberg through ST0RE's table
|
|
* registry" proof path (see tests/p0/iceberg-write-service.test.ts).
|
|
* - `requestIcebergWrite` -- registers a new snapshot (an actual write) for
|
|
* an already-mapped dataset, optionally routed through an N0D job when the
|
|
* write is heavy (item 7: 0pt REQUESTS N0D jobs for heavy writes/
|
|
* compactions, it does not execute them itself, and it never owns the
|
|
* result of that job beyond the ST0RE-registered snapshot ref).
|
|
*
|
|
* Byte-level writes (actually producing Parquet/Iceberg data files) are OUT
|
|
* OF SCOPE for this pass, same honest boundary ST0RE itself documents for
|
|
* its own snapshot routes ("ST0RE doesn't itself write the Iceberg
|
|
* metadata.json... this registry tracks the pointer/version history for
|
|
* whatever the caller's own catalog write produced" --
|
|
* sax3l/st0re src/api/routes/lakehouse.ts). What this service proves is the
|
|
* OWNERSHIP path -- that 0pt requests the write and registers its result
|
|
* through ST0RE, never anywhere else.
|
|
*/
|
|
export interface MapDatasetToIcebergTableInput {
|
|
tenant_id: string;
|
|
project_id: string;
|
|
dataset_id: string;
|
|
dataset_iceberg_mapping_id: string;
|
|
namespace: string;
|
|
table_name: string;
|
|
storage_uri: string;
|
|
catalog_ref: string;
|
|
table_format?: IcebergTableFormat;
|
|
actor_id: string;
|
|
correlation_id: string;
|
|
}
|
|
|
|
export interface MapDatasetToIcebergTableResult {
|
|
mapping: DatasetIcebergMapping;
|
|
iceberg_table_id: string;
|
|
namespace_id: string;
|
|
policy_decision_id: string;
|
|
}
|
|
|
|
export interface RequestIcebergWriteInput {
|
|
dataset_iceberg_mapping_id: string;
|
|
/**
|
|
* P014: optional so existing trusted in-process callers are unaffected,
|
|
* but the HTTP route (app/api/0pt/lakehouse/mappings/[mappingId]/writes)
|
|
* always supplies it now. When present, it must match the mapping's own
|
|
* tenant_id or the write is refused as not-found -- see getMapping's
|
|
* doc comment for the gap this closes (a foreign mapping_id used to let
|
|
* any caller register a snapshot against another tenant's table).
|
|
*/
|
|
tenant_id?: string;
|
|
actor_id: string;
|
|
correlation_id: string;
|
|
snapshot_type?: TableSnapshotType;
|
|
schema_version: string;
|
|
manifest_uri: string;
|
|
record_count?: number;
|
|
size_bytes?: number;
|
|
/** True for large backfills/table maintenance -- routes through an N0D job request rather than 0pt executing in-process (docs/11-lakehouse-write-plan.md item 7). */
|
|
heavy?: boolean;
|
|
}
|
|
|
|
export interface RequestIcebergWriteResult {
|
|
snapshot_id: string;
|
|
iceberg_table_id: string;
|
|
policy_decision_id: string;
|
|
n0d_job_id?: string;
|
|
}
|
|
|
|
export class IcebergWriteService {
|
|
private cl0ud: Cl0udClient;
|
|
private n0d: N0dClient;
|
|
private st0reLakehouse: St0reLakehouseClient;
|
|
private aud0: Aud0Client;
|
|
private datasetService: DatasetService;
|
|
private mappingService: DatasetIcebergMappingService;
|
|
|
|
constructor(opts?: {
|
|
cl0udBaseUrl?: string;
|
|
n0dBaseUrl?: string;
|
|
st0reBaseUrl?: string;
|
|
aud0BaseUrl?: string;
|
|
datasetService?: DatasetService;
|
|
mappingService?: DatasetIcebergMappingService;
|
|
}) {
|
|
this.cl0ud = createCl0udClient(opts?.cl0udBaseUrl);
|
|
this.n0d = createN0dClient(opts?.n0dBaseUrl);
|
|
this.st0reLakehouse = createSt0reLakehouseClient(opts?.st0reBaseUrl);
|
|
this.aud0 = createAud0Client(opts?.aud0BaseUrl);
|
|
this.datasetService = opts?.datasetService ?? new DatasetService(opts?.aud0BaseUrl);
|
|
this.mappingService = opts?.mappingService ?? new DatasetIcebergMappingService({ aud0BaseUrl: opts?.aud0BaseUrl, datasetService: this.datasetService });
|
|
}
|
|
|
|
async mapDatasetToIcebergTable(input: MapDatasetToIcebergTableInput): Promise<MapDatasetToIcebergTableResult> {
|
|
const dataset = await this.datasetService.getDataset(input.dataset_id); // throws if missing
|
|
|
|
// CL0UD policy boundary -- same L3 gate ST0RE's own table-registration
|
|
// route applies (sax3l/st0re src/api/routes/lakehouse.ts,
|
|
// 'st0re.lakehouse.write_table'), checked here too since 0pt is the
|
|
// caller initiating the write, not just relying on ST0RE to gate it.
|
|
const policy = await this.cl0ud.evaluatePolicy({
|
|
tenant_id: input.tenant_id,
|
|
project_id: input.project_id,
|
|
actor_id: input.actor_id,
|
|
capability_id: "0pt.write_iceberg_table",
|
|
resource_type: "dataset",
|
|
resource_id: input.dataset_id,
|
|
risk_level: "L3",
|
|
correlation_id: input.correlation_id,
|
|
});
|
|
if (policy.decision === "deny") throw new Error(`Policy denied: ${policy.reason}`);
|
|
if (policy.decision === "approval_required") throw new Error(`Policy requires approval: ${policy.reason}`);
|
|
|
|
const ctx = { tenantId: input.tenant_id, actorId: input.actor_id };
|
|
|
|
// Register (or reuse) the namespace THROUGH ST0RE's namespace registry
|
|
// first, so the mapping can carry a real `namespace_id` (ST0RE's
|
|
// LakehouseNamespace.namespaceId) rather than only the bare namespace
|
|
// name string. See findOrRegisterNamespace's doc comment for why this is
|
|
// a lookup-or-create, not a bare create.
|
|
const namespace = await this.findOrRegisterNamespace(input.tenant_id, input.project_id, input.namespace, ctx);
|
|
|
|
// Register the table THROUGH ST0RE's table registry -- 0pt does not
|
|
// create or track lakehouse table state on its own. NOTE: `datasetId` is
|
|
// deliberately NOT sent -- it is a foreign key into ST0RE's OWN
|
|
// dataset/artifact table (live-verified: sending 0pt's `dataset_id` here
|
|
// 400s with a Postgres FK violation, since 0pt datasets are never rows in
|
|
// ST0RE's dataset table). 0pt's dataset<->table linkage is carried
|
|
// entirely by the DatasetIcebergMapping row created below.
|
|
const table = await this.st0reLakehouse.registerTable(
|
|
{
|
|
tenantId: input.tenant_id,
|
|
projectId: input.project_id,
|
|
namespace: input.namespace,
|
|
tableName: input.table_name,
|
|
tableFormat: input.table_format ?? "iceberg", // ADR-0030: Iceberg is canonical; Delta/Hudi accepted only for bridge/import scenarios, never chosen by default here.
|
|
storageUri: input.storage_uri,
|
|
catalogRef: input.catalog_ref,
|
|
ownerProduct: "0pt",
|
|
createdBy: input.actor_id,
|
|
},
|
|
ctx
|
|
);
|
|
|
|
const mapping = await this.mappingService.createMapping({
|
|
dataset_iceberg_mapping_id: input.dataset_iceberg_mapping_id,
|
|
tenant_id: input.tenant_id,
|
|
project_id: input.project_id,
|
|
dataset_id: input.dataset_id,
|
|
iceberg_table_id: table.tableId,
|
|
namespace_id: namespace.namespaceId,
|
|
namespace: input.namespace,
|
|
table_name: input.table_name,
|
|
mapping_status: "active",
|
|
mapped_by: input.actor_id,
|
|
correlation_id: input.correlation_id,
|
|
});
|
|
|
|
return { mapping, iceberg_table_id: table.tableId, namespace_id: namespace.namespaceId, policy_decision_id: policy.decision_id };
|
|
}
|
|
|
|
async requestIcebergWrite(input: RequestIcebergWriteInput): Promise<RequestIcebergWriteResult> {
|
|
const mapping = await this.mappingService.getMapping(input.dataset_iceberg_mapping_id, input.tenant_id);
|
|
if (mapping.mapping_status !== "active") {
|
|
throw new Error(`Dataset Iceberg mapping ${input.dataset_iceberg_mapping_id} is not active (status=${mapping.mapping_status})`);
|
|
}
|
|
|
|
const policy = await this.cl0ud.evaluatePolicy({
|
|
tenant_id: mapping.tenant_id,
|
|
project_id: mapping.project_id,
|
|
actor_id: input.actor_id,
|
|
capability_id: "0pt.write_iceberg_table",
|
|
resource_type: "dataset",
|
|
resource_id: mapping.dataset_id,
|
|
risk_level: "L3",
|
|
correlation_id: input.correlation_id,
|
|
});
|
|
if (policy.decision === "deny") throw new Error(`Policy denied: ${policy.reason}`);
|
|
if (policy.decision === "approval_required") throw new Error(`Policy requires approval: ${policy.reason}`);
|
|
|
|
// 0pt.iceberg_write_requested -- fired when 0pt requests the write,
|
|
// before the write lands (docs/11-lakehouse-write-plan.md event list).
|
|
await this.aud0.ingestEvent({
|
|
event_id: `evt_0pt_iceberg_write_requested_${input.dataset_iceberg_mapping_id}_${Date.now()}`,
|
|
event_type: "0pt.iceberg_write_requested",
|
|
tenant_id: mapping.tenant_id,
|
|
project_id: mapping.project_id,
|
|
actor_id: input.actor_id,
|
|
app_id: "0pt",
|
|
capability_id: "0pt.write_iceberg_table",
|
|
resource_type: "iceberg_table",
|
|
resource_id: mapping.iceberg_table_id,
|
|
risk_level: "L3",
|
|
payload: { dataset_id: mapping.dataset_id, dataset_iceberg_mapping_id: mapping.dataset_iceberg_mapping_id, heavy: input.heavy ?? false },
|
|
created_at: new Date().toISOString(),
|
|
correlation_id: input.correlation_id,
|
|
});
|
|
|
|
// Heavy writes/compactions are REQUESTED from N0D, never executed
|
|
// in-process by 0pt (docs/11-lakehouse-write-plan.md item 7). N0D
|
|
// executes; it does not own the schema or the decision of what to
|
|
// write -- the snapshot registration below still goes through ST0RE
|
|
// regardless of who performed the write.
|
|
let n0dJobId: string | undefined;
|
|
if (input.heavy) {
|
|
const job = await this.n0d.createJob({
|
|
tenant_id: mapping.tenant_id,
|
|
project_id: mapping.project_id,
|
|
job_type: "0pt.iceberg_write_job",
|
|
capability_id: "0pt.write_iceberg_table",
|
|
requested_by_app_id: "0pt",
|
|
requested_by_actor_id: input.actor_id,
|
|
input_dataset_ids: [mapping.dataset_id],
|
|
output_artifact_type: "iceberg_table_snapshot",
|
|
requires_backbone: true,
|
|
requires_gpu: false,
|
|
required_node_roles: ["compute_general"],
|
|
resource_profile: "cpu_io_large",
|
|
risk_level: "L3",
|
|
correlation_id: input.correlation_id,
|
|
});
|
|
n0dJobId = job.job_id;
|
|
}
|
|
|
|
// Register the snapshot THROUGH ST0RE's table registry -- the one and
|
|
// only place 0pt persists that a write landed.
|
|
const snapshot = await this.st0reLakehouse.createSnapshot(
|
|
mapping.iceberg_table_id,
|
|
{
|
|
snapshotType: input.snapshot_type ?? "append",
|
|
schemaVersion: input.schema_version,
|
|
manifestUri: input.manifest_uri,
|
|
createdByJobId: n0dJobId,
|
|
createdByCapability: "0pt.write_iceberg_table",
|
|
recordCount: input.record_count,
|
|
sizeBytes: input.size_bytes,
|
|
},
|
|
{ tenantId: mapping.tenant_id, actorId: input.actor_id }
|
|
);
|
|
|
|
// 0pt.iceberg_snapshot_created -- fired once the write lands and ST0RE
|
|
// has registered a new snapshot, carrying table ref + snapshot id + row
|
|
// count + dataset id for AUD0 to build source -> dataset -> snapshot
|
|
// lineage.
|
|
await this.aud0.ingestEvent({
|
|
event_id: `evt_0pt_iceberg_snapshot_created_${snapshot.snapshotId}`,
|
|
event_type: "0pt.iceberg_snapshot_created",
|
|
tenant_id: mapping.tenant_id,
|
|
project_id: mapping.project_id,
|
|
actor_id: input.actor_id,
|
|
app_id: "0pt",
|
|
capability_id: "0pt.write_iceberg_table",
|
|
resource_type: "iceberg_snapshot",
|
|
resource_id: snapshot.snapshotId,
|
|
risk_level: "L2",
|
|
payload: {
|
|
dataset_id: mapping.dataset_id,
|
|
iceberg_table_id: mapping.iceberg_table_id,
|
|
snapshot_id: snapshot.snapshotId,
|
|
record_count: input.record_count,
|
|
n0d_job_id: n0dJobId,
|
|
},
|
|
created_at: new Date().toISOString(),
|
|
correlation_id: input.correlation_id,
|
|
});
|
|
|
|
await this.aud0.ingestLineageEvent({
|
|
lineage_event_id: `lineage_0pt_iceberg_snapshot_${snapshot.snapshotId}`,
|
|
tenant_id: mapping.tenant_id,
|
|
project_id: mapping.project_id,
|
|
app_id: "0pt",
|
|
capability_id: "0pt.write_iceberg_table",
|
|
source_type: "dataset",
|
|
source_id: mapping.dataset_id,
|
|
target_type: "iceberg_snapshot",
|
|
target_id: snapshot.snapshotId,
|
|
lineage_type: "produced",
|
|
metadata: { iceberg_table_id: mapping.iceberg_table_id, n0d_job_id: n0dJobId },
|
|
created_at: new Date().toISOString(),
|
|
correlation_id: input.correlation_id,
|
|
});
|
|
|
|
return {
|
|
snapshot_id: snapshot.snapshotId,
|
|
iceberg_table_id: mapping.iceberg_table_id,
|
|
policy_decision_id: policy.decision_id,
|
|
n0d_job_id: n0dJobId,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Looks up an existing ST0RE lakehouse namespace by (tenantId, projectId,
|
|
* name) before creating one. ST0RE has no upsert route and enforces a real
|
|
* unique constraint on that triple (live-verified 2026-07-13: a second
|
|
* `registerNamespace` call for the same triple 400s with
|
|
* `duplicate key value violates unique constraint
|
|
* "st0re_lakehouse_namespaces_tenant_id_project_id_name_key"`), so a bare
|
|
* "always create" call is not idempotent and would break every
|
|
* `mapDatasetToIcebergTable` call after the first for a given namespace.
|
|
*
|
|
* ST0RE's list route does not reliably scope or filter results (see the
|
|
* `listNamespaces` doc comment in st0re-lakehouse-client.ts, live-verified
|
|
* finding #4) so the match is done here, client-side, against the full
|
|
* returned list.
|
|
*/
|
|
private async findOrRegisterNamespace(
|
|
tenantId: string,
|
|
projectId: string,
|
|
name: string,
|
|
ctx: { tenantId: string; actorId: string }
|
|
) {
|
|
const existing = await this.st0reLakehouse.listNamespaces(ctx);
|
|
const match = existing.find((n) => n.tenantId === tenantId && n.projectId === projectId && n.name === name);
|
|
if (match) return match;
|
|
return this.st0reLakehouse.registerNamespace({ tenantId, projectId, name, ownerProduct: "0pt" }, ctx);
|
|
}
|
|
}
|