feat(0pt): canonical structured observations — entities, facts, relations (#480)
masterplan-lock / check (push) Successful in 4s
CI (SIAX Cloud) / sonar (push) Failing after 10s
Security Scan (SIAX Cloud) / security (push) Successful in 22s
CI (SIAX Cloud) / security (push) Successful in 32s
Release chain (G17, ADR-W16-003) / Build, push, G17 (SBOM/scan/attest/verify/evidence) (push) Successful in 1m21s
Deploy to Coolify / deploy (push) Successful in 1m27s
CI (SIAX Cloud) / quality (push) Successful in 10m10s
CI (SIAX Cloud) / integration (push) Successful in 10m10s
masterplan-lock / check (push) Successful in 4s
CI (SIAX Cloud) / sonar (push) Failing after 10s
Security Scan (SIAX Cloud) / security (push) Successful in 22s
CI (SIAX Cloud) / security (push) Successful in 32s
Release chain (G17, ADR-W16-003) / Build, push, G17 (SBOM/scan/attest/verify/evidence) (push) Successful in 1m21s
Deploy to Coolify / deploy (push) Successful in 1m27s
CI (SIAX Cloud) / quality (push) Successful in 10m10s
CI (SIAX Cloud) / integration (push) Successful in 10m10s
This commit was merged in pull request #480.
This commit is contained in:
@@ -0,0 +1,227 @@
|
||||
/**
|
||||
* src/repositories/canonical-fact-repository.ts
|
||||
* =============================================
|
||||
* Storage seam for 0pt canonical entities/facts/relations (sql/020).
|
||||
* Same split as source-repository.ts: one interface, an in-memory
|
||||
* implementation (dev/test) and a Postgres implementation (production),
|
||||
* chosen once via resolveStoreMode.
|
||||
*
|
||||
* Tenant isolation is enforced by the service + route AND by RLS in Postgres
|
||||
* (transaction-local GUC `app.opt_canonical_tenant_id`, same pattern as
|
||||
* 019_document_credit_rls.sql). The in-memory backend scopes by tenant_id in
|
||||
* every read/write.
|
||||
*/
|
||||
import { randomUUID } from "crypto";
|
||||
import { resolveStoreMode } from "../platform/dependency-mode";
|
||||
import type {
|
||||
CanonicalEntity,
|
||||
CanonicalEntityInput,
|
||||
CanonicalFact,
|
||||
CanonicalFactInput,
|
||||
CanonicalQuery,
|
||||
CanonicalRelationInput,
|
||||
} from "../types/canonical-facts";
|
||||
import { getRepositorySql, repositoryDatabaseUrl, type RepositorySql } from "./db";
|
||||
|
||||
export interface CanonicalFactRepository {
|
||||
upsertEntities(tenantId: string, inputs: CanonicalEntityInput[]): Promise<CanonicalEntity[]>;
|
||||
insertFacts(tenantId: string, inputs: CanonicalFactInput[], entityIds: Map<string, string>): Promise<{ inserted: number; duplicates: number }>;
|
||||
insertRelations(tenantId: string, inputs: CanonicalRelationInput[], entityIds: Map<string, string>): Promise<{ inserted: number; duplicates: number }>;
|
||||
queryFacts(query: CanonicalQuery): Promise<CanonicalFact[]>;
|
||||
}
|
||||
|
||||
export function entityKey(e: CanonicalEntityInput): string {
|
||||
return `${e.entity_type}\u0000${e.identity_namespace}\u0000${e.identity_value}`;
|
||||
}
|
||||
|
||||
export function createCanonicalFactRepository(databaseUrl?: string): CanonicalFactRepository {
|
||||
const mode = resolveStoreMode("0pt.canonical_facts", databaseUrl ?? repositoryDatabaseUrl());
|
||||
if (mode.mode === "postgres") {
|
||||
return new PostgresCanonicalFactRepository(getRepositorySql(mode.url));
|
||||
}
|
||||
return new InMemoryCanonicalFactRepository();
|
||||
}
|
||||
|
||||
// ── in-memory (dev/test) ────────────────────────────────────────────────────
|
||||
class InMemoryCanonicalFactRepository implements CanonicalFactRepository {
|
||||
private entities = new Map<string, CanonicalEntity>();
|
||||
private facts = new Map<string, CanonicalFact>();
|
||||
|
||||
async upsertEntities(tenantId: string, inputs: CanonicalEntityInput[]): Promise<CanonicalEntity[]> {
|
||||
const now = new Date().toISOString();
|
||||
return inputs.map((input) => {
|
||||
const key = `${tenantId}\u0000${entityKey(input)}`;
|
||||
const existing = this.entities.get(key);
|
||||
if (existing) return existing;
|
||||
const entity: CanonicalEntity = {
|
||||
...input,
|
||||
entity_id: randomUUID(),
|
||||
tenant_id: tenantId,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
};
|
||||
this.entities.set(key, entity);
|
||||
return entity;
|
||||
});
|
||||
}
|
||||
|
||||
async insertFacts(tenantId: string, inputs: CanonicalFactInput[], entityIds: Map<string, string>): Promise<{ inserted: number; duplicates: number }> {
|
||||
let inserted = 0;
|
||||
let duplicates = 0;
|
||||
for (const input of inputs) {
|
||||
const entityId = entityIds.get(entityKey(input.entity));
|
||||
if (!entityId) continue;
|
||||
const key = `${tenantId}\u0000${entityId}\u0000${input.predicate}\u0000${input.source_ref}\u0000${input.observed_at}`;
|
||||
if (this.facts.has(key)) {
|
||||
duplicates += 1;
|
||||
continue;
|
||||
}
|
||||
this.facts.set(key, {
|
||||
...input,
|
||||
fact_id: randomUUID(),
|
||||
tenant_id: tenantId,
|
||||
entity_id: entityId,
|
||||
created_at: new Date().toISOString(),
|
||||
});
|
||||
inserted += 1;
|
||||
}
|
||||
return { inserted, duplicates };
|
||||
}
|
||||
|
||||
async insertRelations(): Promise<{ inserted: number; duplicates: number }> {
|
||||
// Relations are not persisted in the in-memory backend beyond validation;
|
||||
// tests assert the write path through facts + counts.
|
||||
return { inserted: 0, duplicates: 0 };
|
||||
}
|
||||
|
||||
async queryFacts(query: CanonicalQuery): Promise<CanonicalFact[]> {
|
||||
const limit = query.limit ?? 100;
|
||||
return [...this.facts.values()]
|
||||
.filter((f) => f.tenant_id === query.tenant_id)
|
||||
.filter((f) => (query.entity_id ? f.entity_id === query.entity_id : true))
|
||||
.filter((f) => (query.predicate ? f.predicate === query.predicate : true))
|
||||
.slice(0, limit);
|
||||
}
|
||||
}
|
||||
|
||||
// ── postgres (production) ───────────────────────────────────────────────────
|
||||
class PostgresCanonicalFactRepository implements CanonicalFactRepository {
|
||||
constructor(private readonly sql: RepositorySql) {}
|
||||
|
||||
private async tx<T>(tenantId: string, fn: (tx: RepositorySql) => Promise<T>): Promise<T> {
|
||||
return this.sql.begin(async (tx) => {
|
||||
await tx`SELECT set_config('app.opt_canonical_tenant_id', ${tenantId}, true)`;
|
||||
return fn(tx as unknown as RepositorySql);
|
||||
}) as Promise<T>;
|
||||
}
|
||||
|
||||
async upsertEntities(tenantId: string, inputs: CanonicalEntityInput[]): Promise<CanonicalEntity[]> {
|
||||
if (inputs.length === 0) return [];
|
||||
return this.tx(tenantId, async (tx) => {
|
||||
const out: CanonicalEntity[] = [];
|
||||
for (const input of inputs) {
|
||||
const rows = await tx`
|
||||
INSERT INTO opt_canonical_entities (entity_id, tenant_id, entity_type, identity_namespace, identity_value)
|
||||
VALUES (${randomUUID()}, ${tenantId}, ${input.entity_type}, ${input.identity_namespace}, ${input.identity_value})
|
||||
ON CONFLICT (tenant_id, entity_type, identity_namespace, identity_value)
|
||||
DO UPDATE SET updated_at = now()
|
||||
RETURNING entity_id, tenant_id, entity_type, identity_namespace, identity_value, created_at, updated_at`;
|
||||
const r = rows[0];
|
||||
out.push({
|
||||
entity_id: r.entity_id, tenant_id: r.tenant_id, entity_type: r.entity_type,
|
||||
identity_namespace: r.identity_namespace, identity_value: r.identity_value,
|
||||
created_at: String(r.created_at), updated_at: String(r.updated_at),
|
||||
});
|
||||
}
|
||||
return out;
|
||||
});
|
||||
}
|
||||
|
||||
async insertFacts(tenantId: string, inputs: CanonicalFactInput[], entityIds: Map<string, string>): Promise<{ inserted: number; duplicates: number }> {
|
||||
if (inputs.length === 0) return { inserted: 0, duplicates: 0 };
|
||||
return this.tx(tenantId, async (tx) => {
|
||||
let inserted = 0;
|
||||
for (const input of inputs) {
|
||||
const entityId = entityIds.get(entityKey(input.entity));
|
||||
if (!entityId) continue;
|
||||
const rows = await tx`
|
||||
INSERT INTO opt_canonical_facts (
|
||||
fact_id, tenant_id, entity_id, predicate, value_json, value_type, value_unit,
|
||||
source_ref, source_record_id, st0re_artifact_id, aud0_evidence_ref, run_ref,
|
||||
extractor_version, observed_at, valid_from, valid_to, confidence, quality_status, status
|
||||
) VALUES (
|
||||
${randomUUID()}, ${tenantId}, ${entityId}, ${input.predicate}, ${JSON.stringify(input.value)}::jsonb,
|
||||
${input.value_type ?? "json"}, ${input.value_unit ?? null}, ${input.source_ref},
|
||||
${input.source_record_id ?? null}, ${input.st0re_artifact_id ?? null},
|
||||
${input.aud0_evidence_ref ?? null}, ${input.run_ref ?? null}, ${input.extractor_version},
|
||||
${input.observed_at}, ${input.valid_from ?? null}, ${input.valid_to ?? null},
|
||||
${input.confidence ?? null}, ${input.quality_status ?? "unvalidated"}, ${input.status ?? "observed"}
|
||||
)
|
||||
ON CONFLICT (tenant_id, entity_id, predicate, source_ref, observed_at) DO NOTHING
|
||||
RETURNING fact_id`;
|
||||
if (rows.length > 0) inserted += 1;
|
||||
}
|
||||
return { inserted, duplicates: inputs.length - inserted };
|
||||
});
|
||||
}
|
||||
|
||||
async insertRelations(tenantId: string, inputs: CanonicalRelationInput[], entityIds: Map<string, string>): Promise<{ inserted: number; duplicates: number }> {
|
||||
if (inputs.length === 0) return { inserted: 0, duplicates: 0 };
|
||||
return this.tx(tenantId, async (tx) => {
|
||||
let inserted = 0;
|
||||
for (const input of inputs) {
|
||||
const subjectId = entityIds.get(entityKey(input.subject));
|
||||
const objectId = entityIds.get(entityKey(input.object));
|
||||
if (!subjectId || !objectId) continue;
|
||||
const rows = await tx`
|
||||
INSERT INTO opt_canonical_relations (
|
||||
relation_id, tenant_id, subject_id, predicate, object_id, attributes_json,
|
||||
source_ref, st0re_artifact_id, aud0_evidence_ref, run_ref, extractor_version,
|
||||
observed_at, valid_from, valid_to, confidence
|
||||
) VALUES (
|
||||
${randomUUID()}, ${tenantId}, ${subjectId}, ${input.predicate}, ${objectId},
|
||||
${JSON.stringify(input.attributes ?? {})}::jsonb, ${input.source_ref},
|
||||
${input.st0re_artifact_id ?? null}, ${input.aud0_evidence_ref ?? null},
|
||||
${input.run_ref ?? null}, ${input.extractor_version}, ${input.observed_at},
|
||||
${input.valid_from ?? null}, ${input.valid_to ?? null}, ${input.confidence ?? null}
|
||||
)
|
||||
ON CONFLICT (tenant_id, subject_id, predicate, object_id, source_ref, observed_at) DO NOTHING
|
||||
RETURNING relation_id`;
|
||||
if (rows.length > 0) inserted += 1;
|
||||
}
|
||||
return { inserted, duplicates: inputs.length - inserted };
|
||||
});
|
||||
}
|
||||
|
||||
async queryFacts(query: CanonicalQuery): Promise<CanonicalFact[]> {
|
||||
const limit = query.limit ?? 100;
|
||||
return this.tx(query.tenant_id, async (tx) => {
|
||||
const rows = await tx`
|
||||
SELECT f.*, e.entity_type, e.identity_namespace, e.identity_value
|
||||
FROM opt_canonical_facts f
|
||||
JOIN opt_canonical_entities e ON e.entity_id = f.entity_id
|
||||
WHERE f.tenant_id = ${query.tenant_id}
|
||||
${query.entity_id ? tx`AND f.entity_id = ${query.entity_id}` : tx``}
|
||||
${query.predicate ? tx`AND f.predicate = ${query.predicate}` : tx``}
|
||||
${query.entity_type ? tx`AND e.entity_type = ${query.entity_type}` : tx``}
|
||||
${query.identity_namespace ? tx`AND e.identity_namespace = ${query.identity_namespace}` : tx``}
|
||||
${query.identity_value ? tx`AND e.identity_value = ${query.identity_value}` : tx``}
|
||||
ORDER BY f.observed_at DESC
|
||||
LIMIT ${limit}`;
|
||||
return rows.map((r) => ({
|
||||
fact_id: r.fact_id, tenant_id: r.tenant_id, entity_id: r.entity_id,
|
||||
entity: { entity_type: r.entity_type, identity_namespace: r.identity_namespace, identity_value: r.identity_value },
|
||||
predicate: r.predicate, value: r.value_json, value_type: r.value_type,
|
||||
value_unit: r.value_unit ?? undefined, source_ref: r.source_ref,
|
||||
source_record_id: r.source_record_id ?? undefined,
|
||||
st0re_artifact_id: r.st0re_artifact_id ?? undefined,
|
||||
aud0_evidence_ref: r.aud0_evidence_ref ?? undefined, run_ref: r.run_ref ?? undefined,
|
||||
extractor_version: r.extractor_version, observed_at: String(r.observed_at),
|
||||
valid_from: r.valid_from ? String(r.valid_from) : undefined,
|
||||
valid_to: r.valid_to ? String(r.valid_to) : undefined,
|
||||
confidence: r.confidence === null ? undefined : Number(r.confidence),
|
||||
quality_status: r.quality_status, status: r.status, created_at: String(r.created_at),
|
||||
})) as CanonicalFact[];
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user