feat(data-os): P0 capability layer — source registry, search, quality, dataset versions, metadata, analytics, features, ER

- Source Registry (§10): rights/license/purpose metadata, provenance,
  freshness SLA, health checks, describe/query; purpose gate FAILS CLOSED
  (no rights record => deny); cross-tenant probes => NOT_FOUND.
- Search (§10/§42): OpenSearch REST adapter (no SDK) + SearchService with
  MANDATORY tenant + purpose/rights filtering, versioned index definitions,
  bulk, generation-per-rebuild (opt-{name}--g{n}) with atomic alias cutover,
  rollback, failed-rebuild generation discard. OpenSearch never canonical.
- Quality (§10): versioned rule registry (GE-JSON interchange), local
  engine for the GE core subset (never silently passes unsupported types),
  runs/results/issues/score/trend, whole-run delegation to the GE backend
  via N0D (0pt.quality.ge_run) - never fabricated results.
- Dataset (§10/§5/§53): immutable numbered versions holding canonical
  st0re:artifact refs only, idempotent createVersion, export registers the
  ST0RE artifact + AUD0 evidence + OpenLineage.
- Metadata (§10): OpenMetadata PUT /api/v1/tables projection adapter +
  projectAll rebuild path; projection never canonical.
- Analytics (§10): ClickHouse HTTP adapter, closed metric-query DSL with
  FORCED tenant predicate + readonly/max_execution_time/max_result_rows,
  TTL retention. Zero connection to b0ts/quarantined pipelines.
- Features (§10): versioned feature-view registry, real Feast
  get-online-features adapter, materialize/get-historical as N0D delegation.
- ER (§10): generic candidate API with deterministic blocking + transparent
  scoring + per-field explanations, product hard-rule hook (force both
  directions), review-band handoff, Splink batch via N0D contract.

93 new unit/contract tests; suite 248 passed / 1 skipped.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Simon Axelsson
2026-08-31 16:49:32 +02:00
co-authored by Claude Fable 5
parent da58176735
commit b46807da75
19 changed files with 4038 additions and 0 deletions
+198
View File
@@ -0,0 +1,198 @@
/**
* src/search/opensearch-adapter.ts
* =================================
* 0pt's OpenSearch adapter (Master-DoD §10 Search). Raw REST via fetch — no
* OpenSearch SDK dependency (same "small surface, explicit wire" posture as
* the platform clients; the REST calls used here are stable public API:
* PUT index, POST _bulk, POST _search, POST _aliases, DELETE index).
*
* This adapter is DUMB on purpose: it knows OpenSearch, not 0pt's rules.
* Tenant scoping, purpose/rights filtering, generation naming and rebuild
* orchestration live in SearchService — the adapter never decides what is
* safe to return.
*
* OpenSearch is NEVER canonical truth (§42): nothing here is the system of
* record; everything can be deleted and rebuilt via SearchService.rebuild.
*/
import { SiaxError, siaxErrorCodeForUpstreamStatus } from "../platform/errors";
export interface OpenSearchAdapterOptions {
baseUrl: string;
/** Basic auth as "user:pass" — local/dev clusters often run security-disabled. */
basicAuth?: string;
timeoutMs?: number;
}
export interface OpenSearchSearchBody {
query: unknown;
from?: number;
size?: number;
sort?: unknown[];
track_total_hits?: boolean;
}
export interface OpenSearchAdapter {
createIndex(physicalIndex: string, mappings: Record<string, unknown>): Promise<void>;
deleteIndex(physicalIndex: string): Promise<void>;
indexExists(physicalIndex: string): Promise<boolean>;
bulkIndex(physicalIndex: string, docs: { id: string; body: Record<string, unknown> }[]): Promise<{
errors: { doc_id: string; error: string }[];
}>;
search(target: string, body: OpenSearchSearchBody): Promise<{
total: number;
hits: { _id: string; _score: number | null; _index: string; _source: Record<string, unknown> }[];
}>;
/** Atomic alias cutover: remove alias from all current indices, add to `physicalIndex`. */
switchAlias(alias: string, physicalIndex: string): Promise<void>;
/** Physical indices an alias points at (empty when alias unknown). */
aliasTargets(alias: string): Promise<string[]>;
/** List physical indices matching a pattern. */
listIndices(pattern: string): Promise<string[]>;
refresh(physicalIndex: string): Promise<void>;
health(): Promise<{ status: string }>;
}
export class HttpOpenSearchAdapter implements OpenSearchAdapter {
private readonly baseUrl: string;
private readonly authHeader?: string;
private readonly timeoutMs: number;
constructor(opts: OpenSearchAdapterOptions) {
this.baseUrl = opts.baseUrl.replace(/\/+$/, "");
this.authHeader = opts.basicAuth ? `Basic ${Buffer.from(opts.basicAuth).toString("base64")}` : undefined;
this.timeoutMs = opts.timeoutMs ?? 30_000;
}
private async request(
method: string,
path: string,
body?: unknown,
opts?: { ndjson?: string; acceptStatuses?: number[] }
): Promise<{ status: number; json: unknown }> {
const headers: Record<string, string> = {
"Content-Type": opts?.ndjson !== undefined ? "application/x-ndjson" : "application/json",
};
if (this.authHeader) headers["Authorization"] = this.authHeader;
let res: Response;
try {
res = await fetch(`${this.baseUrl}${path}`, {
method,
headers,
body: opts?.ndjson !== undefined ? opts.ndjson : body === undefined ? undefined : JSON.stringify(body),
signal: AbortSignal.timeout(this.timeoutMs),
});
} catch (cause) {
throw new SiaxError("DEPENDENCY_UNAVAILABLE", "opensearch", `${method} ${path} unreachable`, { cause });
}
const json = (await res.json().catch(() => undefined)) as unknown;
if (!res.ok && !(opts?.acceptStatuses ?? []).includes(res.status)) {
const reason =
(json as { error?: { type?: string; reason?: string } } | undefined)?.error?.type ?? `http_${res.status}`;
throw new SiaxError(
siaxErrorCodeForUpstreamStatus(res.status),
"opensearch",
`${method} ${path} → HTTP ${res.status} (${reason})`
);
}
return { status: res.status, json };
}
async createIndex(physicalIndex: string, mappings: Record<string, unknown>): Promise<void> {
await this.request("PUT", `/${encodeURIComponent(physicalIndex)}`, {
settings: { number_of_shards: 1, number_of_replicas: 0 },
mappings,
});
}
async deleteIndex(physicalIndex: string): Promise<void> {
await this.request("DELETE", `/${encodeURIComponent(physicalIndex)}`, undefined, { acceptStatuses: [404] });
}
async indexExists(physicalIndex: string): Promise<boolean> {
const res = await this.request("HEAD", `/${encodeURIComponent(physicalIndex)}`, undefined, {
acceptStatuses: [404],
});
return res.status === 200;
}
async bulkIndex(
physicalIndex: string,
docs: { id: string; body: Record<string, unknown> }[]
): Promise<{ errors: { doc_id: string; error: string }[] }> {
if (docs.length === 0) return { errors: [] };
const lines: string[] = [];
for (const doc of docs) {
lines.push(JSON.stringify({ index: { _index: physicalIndex, _id: doc.id } }));
lines.push(JSON.stringify(doc.body));
}
const res = await this.request("POST", "/_bulk", undefined, { ndjson: lines.join("\n") + "\n" });
const body = res.json as {
errors?: boolean;
items?: { index?: { _id?: string; error?: { type?: string; reason?: string } } }[];
};
const errors: { doc_id: string; error: string }[] = [];
if (body.errors && body.items) {
for (const item of body.items) {
if (item.index?.error) {
errors.push({ doc_id: item.index._id ?? "?", error: item.index.error.type ?? "bulk_error" });
}
}
}
return { errors };
}
async search(
target: string,
body: OpenSearchSearchBody
): Promise<{
total: number;
hits: { _id: string; _score: number | null; _index: string; _source: Record<string, unknown> }[];
}> {
const res = await this.request("POST", `/${encodeURIComponent(target)}/_search`, {
track_total_hits: true,
...body,
});
const json = res.json as {
hits?: {
total?: { value?: number };
hits?: { _id: string; _score: number | null; _index: string; _source: Record<string, unknown> }[];
};
};
return { total: json.hits?.total?.value ?? 0, hits: json.hits?.hits ?? [] };
}
async switchAlias(alias: string, physicalIndex: string): Promise<void> {
const current = await this.aliasTargets(alias);
const actions: unknown[] = current.map((idx) => ({ remove: { index: idx, alias } }));
actions.push({ add: { index: physicalIndex, alias } });
await this.request("POST", "/_aliases", { actions });
}
async aliasTargets(alias: string): Promise<string[]> {
const res = await this.request("GET", `/_alias/${encodeURIComponent(alias)}`, undefined, {
acceptStatuses: [404],
});
if (res.status === 404) return [];
return Object.keys((res.json as Record<string, unknown>) ?? {});
}
async listIndices(pattern: string): Promise<string[]> {
const res = await this.request(
"GET",
`/_cat/indices/${encodeURIComponent(pattern)}?format=json&h=index`,
undefined,
{ acceptStatuses: [404] }
);
if (res.status === 404) return [];
return ((res.json as { index: string }[]) ?? []).map((r) => r.index);
}
async refresh(physicalIndex: string): Promise<void> {
await this.request("POST", `/${encodeURIComponent(physicalIndex)}/_refresh`);
}
async health(): Promise<{ status: string }> {
const res = await this.request("GET", "/_cluster/health");
return { status: (res.json as { status?: string })?.status ?? "unknown" };
}
}
+353
View File
@@ -0,0 +1,353 @@
/**
* src/search/search-service.ts
* =============================
* 0pt's Search capability (Master-DoD §10 Search):
*
* search.index -> registerIndexDefinition + indexDocuments (bulk)
* search.query -> query (tenant + purpose/rights filtering ENFORCED)
* search.rebuild -> rebuild (new generation, bulk load, validate)
* search.alias.switch -> switchGeneration (atomic alias cutover)
*
* Non-negotiables encoded here:
* - OpenSearch is NEVER canonical truth (§42): a rebuild takes a caller-
* supplied `DocumentSource` (an async iterator over canonical data) and
* can rebuild any index from an empty cluster. Deleting every index
* loses nothing canonical.
* - Tenant filter is applied by THIS service on every query — a caller
* cannot opt out; a missing tenant_id is INVALID_REQUEST (§31).
* - Purpose/rights filtering (§10): every document carries purpose_tags +
* rights_tags (mandatory on the envelope); every query names its purpose
* and gets only documents tagged for it. Documents with an EMPTY
* purpose_tags list are never returnable — fail closed.
* - Generation switch: physical indices are `opt-{name}--g{n}`; the alias
* `opt-{name}` points at exactly one generation; cutover is atomic
* (§42 generation isolation + cutover).
*
* Lineage: every completed rebuild emits an OpenLineage COMPLETE run to AUD0
* (inputs: the document source name; outputs: the physical index).
*/
import { SiaxError } from "../platform/errors";
import type { OpenSearchAdapter } from "./opensearch-adapter";
import { LineageEmitter } from "../lineage/lineage-emitter";
import type { Aud0Client } from "../clients/aud0-client";
import {
MAX_SEARCH_PAGE_SIZE,
type BulkIndexResult,
type IndexGenerationState,
type RebuildResult,
type SearchDocument,
type SearchIndexDefinition,
type SearchQuery,
type SearchResult,
} from "./search-types";
/** An async source of canonical documents for (re)builds. */
export interface DocumentSource {
/** Name for lineage, e.g. "postgres:opt_datasets" or "0pt:dataset:ds_x". */
name: string;
iterate(): AsyncIterable<SearchDocument>;
}
const ENVELOPE_MAPPINGS: Record<string, unknown> = {
tenant_id: { type: "keyword" },
purpose_tags: { type: "keyword" },
rights_tags: { type: "keyword" },
source_refs: { type: "keyword" },
doc_id: { type: "keyword" },
};
export class SearchService {
private readonly definitions = new Map<string, SearchIndexDefinition>();
private readonly lineage?: LineageEmitter;
constructor(
private readonly adapter: OpenSearchAdapter,
opts?: { aud0Client?: Aud0Client }
) {
this.lineage = opts?.aud0Client ? new LineageEmitter(opts.aud0Client) : undefined;
}
// ---------------------------------------------------------------------
// Index definitions
// ---------------------------------------------------------------------
registerIndexDefinition(def: SearchIndexDefinition): SearchIndexDefinition {
for (const f of def.default_search_fields) {
if (def.fields[f] !== "text") {
throw new SiaxError(
"INVALID_REQUEST",
"0pt.search",
`default_search_field "${f}" must be a text field in index "${def.index_name}"`
);
}
}
for (const reserved of Object.keys(ENVELOPE_MAPPINGS)) {
if (reserved in def.fields) {
throw new SiaxError(
"INVALID_REQUEST",
"0pt.search",
`field "${reserved}" is reserved by the 0pt search envelope`
);
}
}
this.definitions.set(def.index_name, def);
return def;
}
getIndexDefinition(indexName: string): SearchIndexDefinition {
const def = this.definitions.get(indexName);
if (!def) throw new SiaxError("NOT_FOUND", "0pt.search", `no index definition "${indexName}"`);
return def;
}
listIndexDefinitions(): SearchIndexDefinition[] {
return [...this.definitions.values()];
}
aliasFor(indexName: string): string {
return `opt-${indexName}`;
}
physicalIndexFor(indexName: string, generation: number): string {
return `opt-${indexName}--g${generation}`;
}
private mappingsFor(def: SearchIndexDefinition): Record<string, unknown> {
const properties: Record<string, unknown> = { ...ENVELOPE_MAPPINGS };
for (const [field, type] of Object.entries(def.fields)) {
properties[field] = { type };
}
return { properties, _meta: { opt_definition_version: def.version } };
}
// ---------------------------------------------------------------------
// search.index — bulk write into the ACTIVE generation
// ---------------------------------------------------------------------
async indexDocuments(indexName: string, docs: SearchDocument[]): Promise<BulkIndexResult> {
const def = this.getIndexDefinition(indexName);
const state = await this.generationState(indexName);
if (state.active_generation === undefined) {
throw new SiaxError(
"CONFLICT",
"0pt.search",
`index "${indexName}" has no active generation — run a rebuild first`
);
}
this.validateDocuments(def, docs);
const physical = this.physicalIndexFor(indexName, state.active_generation);
const result = await this.adapter.bulkIndex(
physical,
docs.map((d) => ({ id: this.docKey(d), body: this.toIndexBody(d) }))
);
return { indexed: docs.length - result.errors.length, errors: result.errors };
}
// ---------------------------------------------------------------------
// search.query — tenant + purpose/rights filtering ENFORCED here
// ---------------------------------------------------------------------
async query(indexName: string, q: SearchQuery): Promise<SearchResult> {
const def = this.getIndexDefinition(indexName);
if (!q.tenant_id?.trim()) {
throw new SiaxError("INVALID_REQUEST", "0pt.search", "tenant_id is required on every search query");
}
if (!q.purpose?.trim()) {
throw new SiaxError("INVALID_REQUEST", "0pt.search", "purpose is required on every search query (§10)");
}
const size = Math.min(q.size ?? 25, MAX_SEARCH_PAGE_SIZE);
const filter: unknown[] = [
{ term: { tenant_id: q.tenant_id } },
// Purpose fit: the document must be tagged for THIS query's purpose.
// Docs with empty purpose_tags match nothing — fail closed by shape.
{ term: { purpose_tags: q.purpose } },
{ term: { rights_tags: q.rights_tag ?? "internal" } },
];
for (const [field, value] of Object.entries(q.filters ?? {})) {
if (!(field in def.fields)) {
throw new SiaxError("INVALID_REQUEST", "0pt.search", `unknown filter field "${field}"`);
}
filter.push({ term: { [field]: value } });
}
const must = q.text?.trim()
? [{ multi_match: { query: q.text, fields: def.default_search_fields } }]
: [{ match_all: {} }];
const res = await this.adapter.search(this.aliasFor(indexName), {
query: { bool: { must, filter } },
from: q.from ?? 0,
size,
});
return {
total: res.total,
served_by: res.hits[0]?._index ?? this.aliasFor(indexName),
hits: res.hits.map((h) => {
const { tenant_id: _t, purpose_tags: _p, rights_tags: _r, doc_id, source_refs, ...payload } = h._source as Record<
string,
unknown
> & { doc_id?: string; source_refs?: string[] };
return {
doc_id: (doc_id as string) ?? h._id,
score: h._score,
payload,
source_refs: source_refs as string[] | undefined,
};
}),
};
}
// ---------------------------------------------------------------------
// search.rebuild — new generation from canonical truth (§42)
// ---------------------------------------------------------------------
async rebuild(
indexName: string,
source: DocumentSource,
opts?: {
/** Switch the alias to the new generation when done (default true). */
switch?: boolean;
/** Delete superseded generations after a successful switch (default false — keep for rollback). */
prune?: boolean;
batchSize?: number;
tenant_id?: string;
correlation_id?: string;
}
): Promise<RebuildResult> {
const def = this.getIndexDefinition(indexName);
const state = await this.generationState(indexName);
const newGeneration = (state.active_generation ?? 0) + 1;
const physical = this.physicalIndexFor(indexName, newGeneration);
await this.adapter.createIndex(physical, this.mappingsFor(def));
const batchSize = opts?.batchSize ?? 500;
let batch: SearchDocument[] = [];
let docsIndexed = 0;
const flush = async () => {
if (batch.length === 0) return;
this.validateDocuments(def, batch);
const res = await this.adapter.bulkIndex(
physical,
batch.map((d) => ({ id: this.docKey(d), body: this.toIndexBody(d) }))
);
if (res.errors.length > 0) {
// A rebuild must be all-or-nothing: destroy the failed generation and
// leave the active alias untouched (generation isolation, §42).
await this.adapter.deleteIndex(physical);
throw new SiaxError(
"RETRYABLE_FAILURE",
"0pt.search",
`rebuild of "${indexName}" g${newGeneration} failed on ${res.errors.length} document(s); generation discarded`
);
}
docsIndexed += batch.length;
batch = [];
};
for await (const doc of source.iterate()) {
batch.push(doc);
if (batch.length >= batchSize) await flush();
}
await flush();
await this.adapter.refresh(physical);
const shouldSwitch = opts?.switch !== false;
if (shouldSwitch) {
await this.adapter.switchAlias(this.aliasFor(indexName), physical);
if (opts?.prune) {
for (const idx of state.physical_indices.filter((i) => i !== physical)) {
await this.adapter.deleteIndex(idx);
}
}
}
await this.lineage?.emit({
tenant_id: opts?.tenant_id ?? "t_platform",
capability_id: "0pt.search.rebuild.v1",
run_id: `search-rebuild:${indexName}:g${newGeneration}`,
event_type: "COMPLETE",
inputs: [{ name: source.name }],
outputs: [{ name: `opensearch/${physical}` }],
correlation_id: opts?.correlation_id,
run_facets: { siaxSearchRebuild: { docs_indexed: docsIndexed, switched: shouldSwitch } },
});
return {
index_name: indexName,
new_generation: newGeneration,
physical_index: physical,
docs_indexed: docsIndexed,
switched: shouldSwitch,
};
}
// ---------------------------------------------------------------------
// search.alias.switch — explicit generation cutover / rollback
// ---------------------------------------------------------------------
async switchGeneration(indexName: string, generation: number): Promise<IndexGenerationState> {
const physical = this.physicalIndexFor(indexName, generation);
if (!(await this.adapter.indexExists(physical))) {
throw new SiaxError("NOT_FOUND", "0pt.search", `generation g${generation} of "${indexName}" does not exist`);
}
await this.adapter.switchAlias(this.aliasFor(indexName), physical);
return this.generationState(indexName);
}
async generationState(indexName: string): Promise<IndexGenerationState> {
const alias = this.aliasFor(indexName);
const physical = await this.adapter.listIndices(`opt-${indexName}--g*`);
const targets = await this.adapter.aliasTargets(alias);
const active = targets
.map((t) => Number(/--g(\d+)$/.exec(t)?.[1]))
.filter((n) => Number.isFinite(n))
.sort((a, b) => b - a)[0];
return {
index_name: indexName,
active_generation: active,
physical_indices: physical.sort(),
alias,
};
}
// ---------------------------------------------------------------------
// internals
// ---------------------------------------------------------------------
private docKey(d: SearchDocument): string {
// Physical _id is tenant-prefixed so two tenants can use the same doc_id
// without collision — defense in depth under the tenant term filter.
return `${d.tenant_id}:${d.doc_id}`;
}
private toIndexBody(d: SearchDocument): Record<string, unknown> {
return {
doc_id: d.doc_id,
tenant_id: d.tenant_id,
purpose_tags: d.purpose_tags,
rights_tags: d.rights_tags,
...(d.source_refs ? { source_refs: d.source_refs } : {}),
...d.payload,
};
}
private validateDocuments(def: SearchIndexDefinition, docs: SearchDocument[]): void {
for (const d of docs) {
if (!d.tenant_id?.trim()) {
throw new SiaxError("INVALID_REQUEST", "0pt.search", `document ${d.doc_id} is missing tenant_id`);
}
if (!Array.isArray(d.purpose_tags)) {
throw new SiaxError("INVALID_REQUEST", "0pt.search", `document ${d.doc_id} is missing purpose_tags`);
}
if (!Array.isArray(d.rights_tags) || d.rights_tags.length === 0) {
throw new SiaxError("INVALID_REQUEST", "0pt.search", `document ${d.doc_id} is missing rights_tags`);
}
for (const field of Object.keys(d.payload)) {
if (!(field in def.fields)) {
throw new SiaxError(
"INVALID_REQUEST",
"0pt.search",
`document ${d.doc_id} has field "${field}" not in index definition "${def.index_name}" v${def.version}`
);
}
}
}
}
}
+93
View File
@@ -0,0 +1,93 @@
/**
* src/search/search-types.ts
* ===========================
* Types for 0pt's Search capability (Master-DoD §10 Search). Doctrine:
* OpenSearch is NEVER canonical truth — every index is a rebuildable
* projection; deleting all of it must lose nothing canonical (§42).
*/
/** Field types 0pt index definitions may declare (mapped to OpenSearch types). */
export type SearchFieldType = "keyword" | "text" | "long" | "double" | "date" | "boolean";
/** A versioned logical index definition. */
export interface SearchIndexDefinition {
/** Logical name, e.g. "companies". Physical indices are `opt-{name}--g{generation}`. */
index_name: string;
/** Definition version — bump on breaking mapping changes; drives rebuilds. */
version: number;
/** Payload fields (the envelope fields tenant_id/purpose_tags/rights_tags are always added). */
fields: Record<string, SearchFieldType>;
/** Fields included in the default full-text query. Must be `text` fields. */
default_search_fields: string[];
}
/**
* The document envelope. `tenant_id` + `purpose_tags` + `rights_tags` are
* MANDATORY on every document so tenant and purpose/rights filtering can be
* enforced at the query layer (never left to the caller's goodwill).
*/
export interface SearchDocument {
doc_id: string;
tenant_id: string;
/** Purposes this document's data may serve (from source rights). */
purpose_tags: string[];
/** Rights/redistribution tags, e.g. "internal", "customer_deliverable". */
rights_tags: string[];
/** Canonical refs back to the truth this doc was projected from. */
source_refs?: string[];
/** The searchable payload — keys must exist in the index definition. */
payload: Record<string, unknown>;
}
export interface SearchQuery {
tenant_id: string;
/** The purpose of THIS query — only docs tagged with it are returned. */
purpose: string;
/** Free-text query over default_search_fields; omitted = match_all. */
text?: string;
/** Exact-match filters on payload fields. */
filters?: Record<string, string | number | boolean>;
/** Rights tag the caller is entitled to see; omitted = "internal". */
rights_tag?: string;
from?: number;
/** Page size; clamped to MAX_SEARCH_PAGE_SIZE. */
size?: number;
}
export const MAX_SEARCH_PAGE_SIZE = 200;
export interface SearchHit {
doc_id: string;
score: number | null;
payload: Record<string, unknown>;
source_refs?: string[];
}
export interface SearchResult {
total: number;
hits: SearchHit[];
/** The physical generation index that served the query. */
served_by: string;
}
export interface BulkIndexResult {
indexed: number;
errors: { doc_id: string; error: string }[];
}
export interface RebuildResult {
index_name: string;
new_generation: number;
physical_index: string;
docs_indexed: number;
/** True when the alias now points at the new generation. */
switched: boolean;
}
/** Generation state for one logical index. */
export interface IndexGenerationState {
index_name: string;
active_generation?: number;
physical_indices: string[];
alias: string;
}