Files
semprini-data-product-templ…/canonical_data_product/README.md
T
paulandClaude Opus 5 62a3714562 Add the canonical data product template
Moves the data product template from semprini-blog-dataproducts, as adapted to
the semprini-data domain platform, into canonical_data_product/. Its worked
example passed 9 of 9 checks on the domain platform on 2026-09-17.

Adds agent-canonical-product, the blog's agent-product adapted to generate a
product into a domain repository from a declaration in the domain's model
repository, and README/CLAUDE.md describing the template catalogue, the
product contract with the domain platform, and team ownership. Source-aligned
and experience templates are planned.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-17 22:55:11 +12:00

287 lines
18 KiB
Markdown

# Canonical data product template
A **canonical** data product publishes a slice of a domain's canonical model as modelled: its
entities, their relationships, no reshaping. In MD-DDL it is a `class: domain-aligned` product
declaration. Canonical Party in the Digital Core domain is the reference instance.
A data product on the domain platform is one directory. Everything the platform needs to run
the product lives in that directory, and everything in the directory is generated from the
domain's MD-DDL model (the modelling team's `semprini-domain-<domain>-datamodel` repository)
plus the product declaration under its `data_model/data_products/`.
This folder is the template, owned by the data product engineering teams. A product is created
by copying it to `products/<slug>/` in the domain repository, replacing every `{{placeholder}}`
and expanding every `>>> repeat` block once per entity table; `/agent-canonical-product` does
this. The domain platform's CLI then applies the directory to the domain's running stack. Run
it from the domain repository:
```bash
uv run data-domain deploy products/<slug>
uv run data-domain test products/<slug>
uv run data-domain undeploy products/<slug>
```
What a product directory must contain is the platform's product contract
(semprini-data-domain `README.md`, *The product contract*); this template is one way to meet it.
## What the architecture maps to
The canonical data product diagram in the top-level README has five internal components and
four interaction points. Each one is owned by a file in this template.
Diagram element | Platform component | Owned by
--- | --- | ---
ODS | PostgreSQL schema `<schema>` on the `ods` service | `ods/010_schema.sql`, `ods/020_tables.sql`
GraphQL / CRUD API | pg_graphql, exposed by PostgREST at `POST /rpc/<schema>_graphql` | `ods/030_api.sql`, `graphql/`
Topics / Publish Input | Kafka topic `<domain>.<slug>.<table>.inbound`, one per table | `product.yaml`, `events/schemas/`
Topics / Subscribe Output | Kafka topic `<domain>.<slug>.<table>.outbound`, compacted, keyed by `<table>_id` | `product.yaml`, `events/schemas/`
Registry | Apicurio group `<domain>.<slug>` in the data management zone, one JSON Schema artifact per topic, BACKWARD compatibility | `events/schemas/*.schema.json`
Stream processing | Flink SQL job named `<slug>` | `flink/job.sql`
Lake-house | DuckLake tables in schema `<schema>` on the `lakehouse` service, fed by pg_duckpipe | `lakehouse/010_replication.sql`
Analytic SQL | Trino catalog `lake`, schema `<schema>` | `trino/smoke.sql`
Catalogue entry | Open Data Product Specification v4 manifest | `odps.yaml`
## How data flows
1. Writes arrive two ways. Applications call the GraphQL API, which pg_graphql turns into SQL
against the ODS. Producers publish canonical records to a table's inbound topic, which the
Flink job upserts into the same ODS table by primary key.
2. Every committed change to an ODS table, whichever way it arrived, is read from the
PostgreSQL write-ahead log twice. Flink CDC publishes it to the table's compacted outbound
topic, so subscribers see the latest state per key and deletes as tombstones. pg_duckpipe
replicates it into DuckLake, where Trino serves it as analytic SQL.
3. The ODS is current state. History lives in the outbound topics and the lake. The template
does not implement the Topics to Lake-house edge in the diagram; event history in the lake
is a later addition.
## Layout
```text
products/<slug>/
product.yaml manifest read by the platform CLI: names every resource the product owns
odps.yaml ODPS v4 manifest for the catalogue, listing the four interfaces
ods/
010_schema.sql schema, pg_graphql directive, shared trigger function
020_tables.sql one CREATE TABLE per entity, foreign keys, association tables
030_api.sql grants for the API role and the product's GraphQL RPC endpoint
040_seed.sql optional sample rows
graphql/
schema.graphql documents the reflected GraphQL surface (not loaded anywhere)
smoke.graphql query run by `test`; must return no errors
events/schemas/
<table>.schema.json JSON Schema of the canonical record, one per table
flink/
job.sql inbound topic -> ODS upsert, ODS CDC -> outbound topic
lakehouse/
010_replication.sql registers each ODS table with pg_duckpipe
trino/
smoke.sql one count per table through Trino
```
The CLI applies `ods/*.sql` and `lakehouse/*.sql` in filename order, so extra files can be
added between the numbered ones.
## Worked example
`example/` is the template instantiated for one entity, Address, as a product called
`example-address`. It is the reference for what a finished product directory looks like, and it
is also the template's test: it deploys, passes every smoke test and undeploys cleanly on a
domain stack. The data platform team also uses it as the domain template's smoke test. From
a domain repository beside semprini-data:
```bash
T=../semprini-data/semprini-data-product-templates/canonical_data_product
uv run data-domain deploy $T/example
uv run data-domain test $T/example
uv run data-domain undeploy $T/example --yes
```
On 2026-09-17 that round trip passed 9 of 9 checks on the domain platform, Flink included.
Both stream paths carried data. A record published to the inbound topic was upserted into
the ODS. A GraphQL update came out on the compacted outbound topic and reached
`lake.example_address.address` through Trino, which reads as the least-privilege `trino`
role. `undeploy` also removed the registry group, which the management zone's Apicurio
allows.
The earlier verification, from semprini-blog-dataproducts:
On 2026-09-08 that round trip verified, on the live stack: the product's GraphQL endpoint
reflects only its own schema (the platform's `customer` table is invisible to it, and its
tables are invisible to the platform endpoint); inserts, updates and the `updated_at` trigger
work through GraphQL and CHECK constraints are enforced; pg_duckpipe accepts the explicit
`target_table` name and a row inserted through GraphQL after registration reaches Trino;
topics are created with the declared cleanup policy and retention; Apicurio stores the JSON
Schema with a BACKWARD rule; undeploy leaves nothing behind except the registry group, which
the platform's default Apicurio settings refuse to delete. The Flink step was skipped on that
run because the connector jars were not yet installed; they are now, but this example has not
been re-run against Flink 2.2 — the blog's `products/canonical-party` is what has.
## Naming
Everything derives from the MD-DDL product heading. For "Canonical Party" in the
"Digital Core" domain:
Thing | Rule | Example
--- | --- | ---
`{{product.slug}}` | kebab-case of the product heading | `canonical-party`
`{{product.schema}}` | snake_case of the slug; PostgreSQL schema in the ODS and in the lake | `canonical_party`
`{{domain.slug}}` | kebab-case of the domain heading | `digital-core`
`{{table}}` | snake_case of the entity heading | `party_role`
`{{column}}` | snake_case of the attribute name | `risk_rating`
Primary key | `<table>_id`, type `uuid` | `party_role_id`
Foreign key | `<referenced table>_id` | `party_id`
Association table | `<source table>_<target table>`; self-referential relationships use `<table>_association` with `source_<table>_id` and `target_<table>_id` | `party_role_contact_address`, `party_association`
GraphQL endpoint | `/rpc/<schema>_graphql` | `/rpc/canonical_party_graphql`
GraphQL type / field | pg_graphql inflection: PascalCase type, camelCase field | `PartyRole`, `partyRoleCollection`, `riskRating`
Inbound topic | `<domain>.<slug>.<table>.inbound` | `digital-core.canonical-party.party.inbound`
Outbound topic | `<domain>.<slug>.<table>.outbound` | `digital-core.canonical-party.party.outbound`
Registry group / artifact | group `<domain>.<slug>`, artifact `<topic>-value` | `digital-core.canonical-party` / `digital-core.canonical-party.party.inbound-value`
Flink job | `<slug>` | `canonical-party`
Flink replication slot | `<schema>_<table>_flink` | `canonical_party_party_flink`
Lake table (Trino) | `lake.<schema>.<table>` | `lake.canonical_party.party`
Kafka payloads and lake columns use the ODS column names. Only GraphQL is camelCase, and that
is done by pg_graphql, not by the template.
## Placeholders
Placeholder | Meaning
--- | ---
`{{product.name}}`, `{{product.slug}}`, `{{product.schema}}`, `{{product.version}}`, `{{product.owner}}`, `{{product.description}}`, `{{product.declaration}}` | From the product's YAML block and heading in `data_model/data_products/`
`{{domain.name}}`, `{{domain.slug}}` | From the level-1 heading of `domain.md`
`{{table}}`, `{{entity.name}}`, `{{entity.description}}`, `{{Entity}}`, `{{entity}}` | Per entity table: snake_case name, MD-DDL heading, first description paragraph, PascalCase and camelCase forms
`{{column}}`, `{{attribute.name}}`, `{{attribute.description}}`, `{{pg_type}}`, `{{flink_type}}`, `{{json_type}}` | Per attribute, typed with the table below
`{{enum_column}}`, `{{enum.name}}`, `{{enum_values}}` | Per enum-typed attribute; values come from `enums.md` verbatim
`{{parent_table}}`, `{{child_table}}`, `{{source_table}}`, `{{target_table}}` | Per relationship or `extends:`
`{{subtype_names}}` | Discriminator values for an abstract parent, e.g. `'Person', 'Company'`
`{{platform.graphql_port}}`, `{{platform.kafka_port}}`, `{{platform.trino_port}}` | `GRAPHQL_PORT`, `KAFKA_PORT`, `TRINO_PORT` from the domain's `.env`; used only in `odps.yaml` access URLs
Blocks between `>>> repeat per ...` and `<<< end repeat` are expanded once per matching
element and the marker comments are removed. A finished product contains no `{{` and no
repeat markers; the CLI refuses a manifest that still has either.
## Type mapping
MD-DDL type | PostgreSQL (ODS) | Flink SQL | JSON Schema
--- | --- | --- | ---
`string` | `text` | `STRING` | `{"type": "string"}`
`string[]`, `string[1..*]` | `text`, semicolon-delimited | `STRING` | `{"type": "string"}`
`integer` | `bigint` | `BIGINT` | `{"type": "integer"}`
`decimal` | `numeric(18,4)` unless precision is declared | `DECIMAL(18,4)` | `{"type": "number"}`
`boolean` | `boolean` | `BOOLEAN` | `{"type": "boolean"}`
`date` | `date` | `DATE` | `{"type": "string", "format": "date"}`
`datetime`, `timestamp` | `timestamptz` | `TIMESTAMP_LTZ(6)` | `{"type": "string", "format": "date-time"}`
`enum:<Name>` | `text` with `CHECK (col IN (...))` | `STRING` | `{"type": "string", "enum": [...]}`
identifier (`identifier: primary`) | `uuid` | `STRING` | `{"type": "string", "format": "uuid"}`
Optional attributes are nullable in PostgreSQL and use `"type": ["string", "null"]` (or the
equivalent) in JSON Schema. `not_null` constraints become `NOT NULL`. `check` constraints that
reference only the row's own columns become `CHECK` constraints; cross-row and lifecycle-stage
constraints are recorded as table comments, not enforced.
**Do not generate PostgreSQL array columns.** pg_duckpipe cannot replicate them: it hands
DuckDB the array's Postgres text form and the insert fails with `Type VARCHAR with value
'{"a",b}' can't be cast to the destination type VARCHAR[]`, which silently costs the whole
table its lake replication. A multi-valued attribute becomes one `text` column holding
semicolon-separated values. If a real collection type is ever needed, use `jsonb`, which does
replicate.
## Generating a product from the model
This is the input contract for `/agent-canonical-product` (this repository's
`.claude/agents/agent-canonical-product.md`), the template's specialisation of MD-DDL's Agent
Artifact. All model paths below are in the domain's model repository. Read the product
declaration under `data_model/data_products/`, then each entity detail file under
`data_model/entities/` and the enums in `data_model/enums.md`, plus the modelling team's
handoff note in `handoffs/<product-slug>.md` when there is one.
File | Source in the model
--- | ---
`product.yaml` | product heading, YAML block, `entities` list, relationships among those entities
`ods/020_tables.sql` | entity attributes and types, `extends:`, relationships, `constraints`, enum values
`ods/030_api.sql` | product schema name only
`graphql/schema.graphql`, `graphql/smoke.graphql` | table and column names, inflected
`events/schemas/<table>.schema.json` | same attributes as the table, same names as the columns
`flink/job.sql` | same columns as the table, Flink types
`lakehouse/010_replication.sql`, `trino/smoke.sql` | table names only
`odps.yaml` | product description, `sla`, `refresh`, governance posture, owner
Rules that are easy to miss:
- Parents before children in `ods/020_tables.sql` and in `product.yaml`, because foreign keys
and the lake registration follow that order.
- Every table, including association tables, has a `<table>_id uuid` primary key and
`created_at` / `updated_at`. The Flink job, the topics and the lake registration assume it.
- Association tables are tables: they get topics, a schema, a Flink block and a lake table.
- Governance and masking are product-level MD-DDL metadata. A domain-aligned product inherits
the domain posture and publishes unmasked canonical data. Consumer-aligned products apply
their `masking` entries in the ODS views and lake tables they generate.
## Deploying
`deploy` is additive and runs in this order: ODS SQL, lakehouse SQL, Kafka topics, Apicurio
group, artifacts and compatibility rules, then the Flink job. It expects a clean slate for the
product; run `undeploy` first to redeploy after changing the DDL. `test` exercises each
interface: a GraphQL introspection check per table plus `graphql/smoke.graphql`, topic
existence, registry artifacts, pg_duckpipe status per table, `trino/smoke.sql`, and whether
the Flink job is running. `undeploy` removes only the objects named in `product.yaml`.
The CLI talks to the stack through `docker compose exec` and the ports published on
127.0.0.1. It acts on the domain repository it runs in: the first folder with `compose.yml`
and `.env` above the current directory, then above the product directory, unless
`SEMPRINI_DOMAIN_DIR` names one. It reads the domain name and ports from that `.env`. Apicurio is the management zone's,
at `http://localhost:8081/apis/registry/v3` unless `APICURIO_URL` says otherwise.
`flink/job.sql` references `${ODS_PASSWORD}`, the only credential a product needs. The
CLI substitutes it from `.env` when submitting the job, then deletes the rendered copy
from the jobmanager. Only `DOMAIN` and `ODS_PASSWORD` are substituted.
## Experience products read canonical ones
An experience product (MD-DDL `consumer-aligned`) is shaped for an audience rather than
published as modelled, and has its own templates in this repository (planned). The first
experience class runs as dbt models in the domain's `dbt/models/<product_schema>/`, reading
canonical products as dbt sources over their lake tables and building DuckLake tables that
Trino serves as `lake.<product_schema>.<table>`. `lakehouse/010_replication.sql` grants
`ducklake_writer` read access to every canonical table for that reason.
## Platform prerequisites and known gaps
Checked against the blog's stack on 2026-09-09, with all 65 checks passing for
the blog's `products/canonical-party` and both Flink paths verified end to end, and against the
domain platform on 2026-09-17 with `example/`.
- Flink runs 2.2 and its image is built with the connectors `flink/job.sql` needs, in
`/opt/flink/lib` of both services: `flink-sql-connector-kafka` `5.0.0-2.2`,
`flink-connector-jdbc-core` and `flink-connector-jdbc-postgres` `4.1.0-2.2`, the PostgreSQL
JDBC driver, and `flink-sql-connector-postgres-cdc` `3.6.0-2.2`. Two traps in that list.
Flink CDC publishes only 1.20 and 2.2 builds — there is no 2.1 — so the platform version is
chosen by the CDC connector, not the other way round. And `flink-connector-jdbc` 4.x is split
into thin jars rather than 3.x's self-contained `flink-sql-connector-jdbc`, so
`io.openlineage:openlineage-java` and `openlineage-sql-java` (`1.32.0`) must be installed
alongside it or the JDBC sink fails at submit with
`ClassNotFoundException: io.openlineage.client.utils.jdbc.JdbcExtractor`.
- `max_replication_slots=32` on the ODS. Flink CDC takes one logical slot per source table and
pg_duckpipe takes its own, so a nine-table product needs more than the PostgreSQL default of
10. Exhausting the slots does not report itself as a slot problem: the CDC source fails with
`Couldn't initialize type registry` and a closed socket.
- The Trino `lake` catalog sets `dynamic-filtering.enabled=false`. Trino sends dynamic filters
as parameterised prepared statements (`WHERE "id" IN ($1,$2,$3)`) and pg_duckdb cannot plan
them — the parameter types are UNKNOWN at plan time, so it raises
`Could not convert DuckDB type: UNKNOWN to Postgres type` (duckdb/pg_duckdb#480). Without the
setting every join across two lake tables fails, though pg_duckdb joins those same tables
fine when queried directly.
- Apicurio is the management zone's, stored in Postgres, with group, artifact and version
deletion enabled (`APICURIO_REST_DELETION_*`), so `undeploy` removes the product's group.
Artifacts are registered with `ifExists=FIND_OR_CREATE_VERSION`, so redeploying is safe.
- One inbound record that breaks a table constraint stops the stream. The JDBC sink fails,
the failure handler shuts down the whole TaskManager, and the record is replayed on
every restart, so valid records behind it never arrive. There is no dead-letter path
yet. To recover, remove the record's topic (`undeploy`, then `deploy`), or move the
consumer group past its offset.
- pg_duckpipe and the Flink CDC and JDBC connectors connect to the ODS as its superuser.
- PostgREST caches the API. `ods/030_api.sql` ends with `NOTIFY pgrst, 'reload schema'` so the
new endpoint appears without a restart.
- The data interfaces are unauthenticated and bound to 127.0.0.1. The ODPS manifest records
`authenticationMethod: none` for that reason. See `docs/security-architecture.md`.