Files
0pt/src/analytics/ingestion/analytics-ingestion-service.ts
T
Claude Opus 5 b5ab885a67
CI (SIAX Cloud) / security (push) Successful in 27s
Security Scan (SIAX Cloud) / security (push) Successful in 30s
CI (SIAX Cloud) / quality (push) Successful in 39s
CI (SIAX Cloud) / security (pull_request) Successful in 43s
CI (SIAX Cloud) / integration (push) Successful in 51s
CI (SIAX Cloud) / quality (pull_request) Successful in 54s
CI (SIAX Cloud) / integration (pull_request) Successful in 1m15s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 13s
feat(analytics): BI-P129 — ConnectorProvider, and four gates on where data lands
BI-P129 names four provider kinds (native, dlt, Meltano/Singer, Airbyte-if-
licensed). This commit ships the seam and the `native` provider; dlt and
Singer follow on this branch.

What is deliberately NOT here: a second ingestion stack. 0pt already has the
P061 connector contract, the P062 runner with durable checkpoints and
crash/resume tests, the schema registry, the quality gate and the idempotency
ledger. A provider's job is to hand back a P061 `Connector`; the highway is
the one that exists.

What is new is the question the P061 stack has no opinion about: an ingestion
run has to LAND somewhere, and where it lands is an analytics contract
question. Four fail-closed gates, each attacked with the guard (must refuse)
AND without it (must succeed — otherwise the guard is decoration):

  1. tier — source data lands in RAW, or NORMALIZED with a declared
     normalization. Never directly in CURATED/SERVING. BI-P003's "no business
     dashboard reads arbitrary raw ingestion tables" is defeated in one line
     by relabelling the landing table SERVING; the tier is therefore checked
     at WRITE, not only at read.
  2. contract coverage — every field discovery actually reported must be
     declared in the BI-P004 contract. An undeclared column is an
     unclassified column. The counterfactual test lands `personnummer` into a
     RAW table whose contract says pii_classification "none", and the runner
     reports success: that is the harm, shown rather than asserted.
  3. physical home — RAW/NORMALIZED land as Parquet/Iceberg in ST0RE
     (st0re#45 shapes), never straight into ClickHouse.
  4. provider readiness — a provider whose own providerReadiness() says
     verified:false cannot run in a production runtime without a recorded,
     named exception. This is the structural form of the honesty rule 0pt#35
     set with MetricFlow.

Airbyte is a declared kind with NO implementation: its server is ELv2, which
restricts offering the software as a managed service, and that is exactly
what 0pt does. Registering or planning one is refused at the registry, in one
place, so a future licence review has a single constant to change.

BI-P129 DoD — "two real source types ingest into canonical analytics tiers" —
is proven with the two real, heterogeneous P061 connectors: a JSONL file on
actual disk (cursor = line offset, real CDC deletes) and an HTTP JSON API
driven through a real fetch/Response cycle (cursor = opaque server token).
Both run through the real runner into the declared RAW tier, paged, with
9 rows landed each and distinct envelope ids.

Verification: 24 tests. Mutation-checked — neutering gates 1 and 2 fails 5 of
them, so they are load-bearing rather than incidental.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-09-07 06:22:07 +02:00

144 lines
5.7 KiB
TypeScript

/**
* src/analytics/ingestion/analytics-ingestion-service.ts
* =======================================================
* BI-P129: one entry point that takes an `AnalyticsIngestionSpec` and lands
* rows in a canonical analytics tier, whichever provider supplies the
* connector.
*
* The sequence, and why it is this sequence:
*
* 1. plan — every gate checkable without touching the source
* (tier, physical home, licence, provider readiness).
* Cheap checks first: a spec that can never be legal
* should not open a session to find that out.
* 2. connect+discover— ask the source what it actually looks like.
* 3. landability — the discovered shape must satisfy the BI-P004
* contract. This is the check that cannot be done at
* step 1, and doing it here is the whole reason the
* service exists rather than a bare `planX()` call.
* 4. run — hand the connector to the EXISTING P062 runner with
* a landing sink. The runner owns paging, envelopes,
* schema conformance, quality gating, the idempotency
* ledger and the durable checkpoint. None of that is
* re-implemented here.
* 5. disconnect — always, including on failure.
*
* Step 4 is worth spelling out because it is where a "new ingestion system"
* would normally get built by accident. There is no second runner. The
* analytics plane contributes a TARGET and four GATES; the highway is the one
* that already exists and already has crash/resume tests.
*/
import { SiaxError } from '../../platform/errors';
import { IngestionRunner, type IngestionRunReport } from '../../ingestion/ingestion-runner';
import type { IngestionRepository } from '../../repositories/ingestion-repository';
import type { SchemaRegistry } from '../../schema/schema-registry';
import type { LineageStore } from '../../lineage/lineage-store';
import type { QualityEnforcementPolicy } from '../../quality/quality-policy';
import type { RecordSchemaFields } from '../../schema/record-schema';
import {
planAnalyticsIngestion,
type AnalyticsConnectorProvider,
type AnalyticsIngestionSpec,
type PlannedAnalyticsIngestion,
} from './connector-provider';
import { assertDiscoveryLandable, landingSink, type LandingWriter } from './landing';
export interface AnalyticsIngestionDeps {
repo: IngestionRepository;
schemas: SchemaRegistry;
writer: LandingWriter;
lineage?: LineageStore;
/** Runtime environment name; "production" turns gate 4 on. */
runtimeEnv: string;
}
export interface AnalyticsIngestionResult {
plan: PlannedAnalyticsIngestion;
/** What discovery reported, per partition — recorded so a later drift is provable. */
discovered: Record<string, RecordSchemaFields>;
run: IngestionRunReport;
}
export interface AnalyticsIngestionOptions {
run_id?: string;
page_size?: number;
max_pages?: number;
partition_key?: string;
quality_policy?: QualityEnforcementPolicy;
correlation_id?: string;
}
export class AnalyticsIngestionService {
constructor(private readonly deps: AnalyticsIngestionDeps) {}
/** Gates 1, 3 and 4 — no IO, no session. Safe to call from a UI pre-flight. */
plan(provider: AnalyticsConnectorProvider, spec: AnalyticsIngestionSpec): PlannedAnalyticsIngestion {
return planAnalyticsIngestion(provider, spec, this.deps.runtimeEnv);
}
async ingest(
provider: AnalyticsConnectorProvider,
spec: AnalyticsIngestionSpec,
options: AnalyticsIngestionOptions = {},
): Promise<AnalyticsIngestionResult> {
const plan = this.plan(provider, spec);
const runId = options.run_id ?? `run_${spec.source_id}_${Date.now()}`;
const connector = plan.connector;
const discovered: Record<string, RecordSchemaFields> = {};
await connector.connect(spec.config, {
tenant_id: spec.tenant_id,
project_id: spec.project_id,
source_id: spec.source_id,
run_id: runId,
});
try {
const discovery = await connector.discover();
for (const partition of discovery.partitions) {
if (options.partition_key && partition.partition_key !== options.partition_key) continue;
discovered[partition.partition_key] = partition.schema;
}
// Gate 2 — the one that needs the source to have answered.
assertDiscoveryLandable(spec.target, discovered);
} finally {
// The runner opens its own session; this discovery session is ours to close.
await connector.disconnect();
}
const runner = new IngestionRunner(this.deps.repo, this.deps.schemas, this.deps.lineage);
const run = await runner.run({
source_id: spec.source_id,
tenant_id: spec.tenant_id,
project_id: spec.project_id,
mode: spec.mode,
connector,
config: spec.config,
sink: landingSink({
target: spec.target,
tenant_id: spec.tenant_id,
project_id: spec.project_id,
run_id: runId,
writer: this.deps.writer,
}),
run_id: runId,
page_size: options.page_size,
max_pages: options.max_pages,
partition_key: options.partition_key,
quality_policy: options.quality_policy,
output_ref: `0pt:dataset:${spec.target.dataset_id}`,
correlation_id: options.correlation_id,
});
if (run.status === 'failed') {
throw new SiaxError(
'RETRYABLE_FAILURE',
'0pt.analytics.ingestion',
`ingestion run ${run.run_id} for dataset ${spec.target.dataset_id} failed: ` +
`${run.failure?.code ?? 'unknown'} ${run.failure?.detail ?? ''}`.trim(),
);
}
return { plan, discovered, run };
}
}