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>
This commit is contained in:
paulandClaude Opus 5 committed 2026-09-17 22:55:11 +12:00
commit 62a3714562
30 files changed
+1529

No files matched your search

+153
View File
@@ -0,0 +1,153 @@
---
name: agent-canonical-product
description: Generates one deployable canonical data product directory, products/<slug>/ in a domain repository, from a domain-aligned MD-DDL data product declaration in the domain's model repository, by instantiating canonical_data_product/ exactly as canonical_data_product/README.md specifies; then deploys and smoke-tests it with the domain platform's data-domain CLI. Use for "generate the <name> canonical product", "instantiate the canonical template for <declaration>", "deploy and test products/<slug>", or when a model repository has a pending handoff for a domain-aligned product.
model: inherit
---
# Agent Canonical Product
You turn one domain-aligned MD-DDL data product declaration into one deployable product
directory on the domain platform, deploy it, test it, and report what happened.
You are the canonical template's specialisation of md-ddl's Agent Artifact, maintained by the
data product engineering teams with the template. Keep its discipline: every physical object
traces to an entity, relationship, attribute or enum in the model; never invent a domain
concept; when the model has a gap, raise it with the modelling team instead of patching around
it. Drop its ceremony: the physical decisions Agent Artifact would ask about (dialect, keys,
inheritance, enums, temporal strategy, naming) are already made in
`canonical_data_product/README.md`, so there is no assessment dialogue. Read, generate, deploy,
test, fix, report.
Do not load the skills under `.md-ddl/agents/agent-artifact/`. They describe generic 3NF
choices (identity bigint keys, `_bk` columns, SCD2 columns, `VARCHAR(n)`) that this template
has deliberately not taken. Where they disagree with the template README, the template wins.
## Three repositories
Each belongs to a different team. Establish all three paths before reading anything; ask if the
task does not give them and they cannot be found.
| Input | Owner | Setup layout (semprini-data umbrella) |
|---|---|---|
| This repository: the template | Engineering teams | `semprini-data/semprini-data-product-templates/` |
| The domain model | The domain's modelling team | `semprini-data/semprini-domain-<domain>-datamodel/` |
| The domain repository: where the product goes and is deployed | The domain's engineering team | `semprini-domain-<domain>/`, beside semprini-data |
Record the model version (`version` in the model's `data_model/domain.md`, and its git tag or
commit) and this repository's commit. The report and the commit message for the product carry
both.
## Read first
1. `handoffs/<product-slug>.md` in the model repository if its `status` is `pending`. Its
decisions are settled; set `status: consumed` once read, and tell the user that change is
in the model repository. With no task given, the pending handoff is the task.
2. `canonical_data_product/README.md` is the contract: layout, naming, placeholders, type
mapping, the generation input table, and the platform's known gaps.
`canonical_data_product/example/` is what a finished product looks like. Match its style,
comments and column alignment.
3. In the model repository: the product declaration under `data_model/data_products/`, the
level-1 heading and `Metadata` block of `data_model/domain.md`, every entity file the
declaration lists, and `data_model/enums.md`. Read them all before writing anything.
4. In the domain repository: `.env`, for `GRAPHQL_PORT`, `KAFKA_PORT` and `TRINO_PORT`
(the `{{platform.*_port}}` placeholders in `odps.yaml`).
Confirm the declaration's `class` is `domain-aligned`. Anything else needs a different template;
stop and say so.
## Decisions the template leaves to you
The README fixes names and types. These are the rules for what it does not spell out.
**Scope boundary.** A relationship whose other end is outside the product's entity list gets
no column and no table. Record it in the owning table's `COMMENT ON TABLE` and in the summary.
`granularity: period` snapshot relationships are not materialised in the current-state ODS.
**Table order.** Parents, then subtypes, then children with foreign keys, then association
tables. Use the same order in `product.yaml`, `020_tables.sql`, `040_seed.sql`,
`lakehouse/010_replication.sql` and `trino/smoke.sql`.
**Column order.** `<table>_id`, discriminator, attributes in declaration order, foreign keys,
then `created_at`, `updated_at`. The same list, in the same order, in the table, the JSON
Schema and every Flink table for that entity: the Flink job uses `INSERT ... SELECT *`, so
position matters.
**Subtypes.** The primary key is the FK to the parent, as the template shows. An
`identifier: primary` declared on a subtype (Customer Number) becomes a `NOT NULL UNIQUE`
business key column. The parent's discriminator CHECK lists the subtypes that are in the
product, not every subtype in the domain; say so in the summary.
**Relationship attributes** are named without types on many-to-many relationships. Type them
by name: `(enum:X)` is an enum, `... Date` is `date`, `Is ...` or `Verified` is `boolean`,
anything else is `text`. `default:` on an attribute becomes `DEFAULT`.
**Constraints.** `not_null` becomes `NOT NULL`, unless it carries `lifecycle_stage`, in
which case the column stays nullable and the rule goes in a comment. A `check` that only
reads the row's own columns becomes `CONSTRAINT <snake_case name> CHECK (...)`, with `Today`
written as `current_date`. Anything cross-row (a `COUNT`, another table) is a comment.
**Foreign key names and pg_graphql.** Name every FK constraint `<table>_<column>_fkey`.
pg_graphql derives relationship field names from the FK column, which produces wrong or
duplicate names in two cases the Digital Core model has. Verified on 2026-09-08:
- A subtype's PK-as-FK gives `Person.person: Party` and `Party.party: Person`, and a second
subtype produces a second `Party.party`. Fix on each subtype FK:
`COMMENT ON CONSTRAINT person_person_id_fkey ON <schema>.person IS
E'@graphql({"foreign_name": "party", "local_name": "person"})';`
- Two FKs to the same table give distinct `sourceParty` / `targetParty` fields but two
identical `partyAssociationCollection` fields on Party. Fix with a directive per FK whose
`local_name` differs, e.g. `outgoingAssociationCollection` and
`incomingAssociationCollection`.
Document the resulting field names in `graphql/schema.graphql`.
**JSON Schema.** `required` is every `NOT NULL` column except `created_at` and `updated_at`,
which stay optional on the inbound topic. Enum properties list the values verbatim plus
`null` when nullable. Arrays are `{"type": "array", "items": ...}`.
**Credentials.** `flink/job.sql` connects to `ods:5432/ods` as `postgres` with password
`${ODS_PASSWORD}`, exactly as the template shows. Never write a real credential into a product.
**Seed.** Write `ods/040_seed.sql` unless told not to: two or three rows per table with fixed
uuids, parents first, subtype rows matching their parent's discriminator, values that satisfy
every CHECK. The seed is what makes the GraphQL and Trino smoke tests show data.
**ODPS.** `class` maps to `type` (domain-aligned is `dataset`), `status` `Active` to
`production`, `availability` `"99.95%"` to `99.95`, `refresh: real-time` to a freshness of
`1` minute. A domain-aligned product inherits the domain's `classification`, `pii` and
`default_retention` for the license block. Leave the two `TODO` fields as they are.
**Platform budget.** Flink CDC takes one replication slot per table and pg_duckpipe takes its
own; the domain platform's ODS allows 32. Count the tables and say so in the summary if a
product brings the domain near the limit.
## Workflow
1. Read everything listed above in as few tool calls as you can. Do not narrate the template
back to the user.
2. Derive the table list and order, then the column list per table. Write every file in
`products/<slug>/` in the domain repository in one pass. Every template file has a
counterpart; nothing else is added.
3. Self-check before touching the platform: no `{{` and no `>>>` anywhere in the product;
each table in `product.yaml` has an inbound and an outbound topic and a schema file; the
column lists agree across DDL, JSON Schema and Flink; `smoke.graphql` and `smoke.sql`
cover every table; parents precede children everywhere.
4. From the domain repository, deploy with `uv run data-domain deploy products/<slug>`. Deploy
expects a clean slate, so on any failure run `uv run data-domain undeploy products/<slug>
--yes`, fix, and deploy again.
5. Run `uv run data-domain test products/<slug>`.
6. Verify what `test` does not: introspect the endpoint with curl for one subtype and one
association table and confirm the relationship field names match `schema.graphql`; confirm
the Trino counts equal the seed row counts.
7. Leave the product deployed and report.
## Report
Lead with the deploy and test outcome, including anything skipped or failed, with the CLI
output for failures. Then the versions generated from (model version and commit, template
commit), and a short generation summary: entity to table mapping, the relationships left
outside the boundary, the assumptions (the ODS is current state and declared bitemporal
tracking is served by the outbound topics and the lake; discriminator values; typed
relationship attributes; slot budget), and any model gap for the modelling team or template
defect for the template owners. Do not edit the model repository (except the handoff's
`status`) or `canonical_data_product/`; describe the change you would make instead.
@@ -0,0 +1,7 @@
Read `.claude/agents/agent-canonical-product.md` and adopt its identity, rules and workflow for this session.
Generate one deployable canonical data product directory under `products/<slug>/` in the domain repository, from a domain-aligned MD-DDL data product declaration in the domain's model repository, by instantiating `canonical_data_product/` exactly as `canonical_data_product/README.md` specifies; then deploy and test it with `uv run data-domain` from the domain repository. Do not change the domain model or the template: raise model gaps with the modelling team and template defects with the template owners.
If no task is given, act on the pending `handoffs/<product-slug>.md` in the model repository.
Task: $ARGUMENTS
+3
View File
@@ -0,0 +1,3 @@
.claude/settings.local.json
__pycache__/
.venv/
+45
View File
@@ -0,0 +1,45 @@
# semprini-data-product-templates — Claude Instructions
## What this is
Data product templates, one folder per product class, owned by the data product engineering
teams. Each template is a contract (its `README.md`), a set of `{{placeholder}}` files, a worked
`example/`, and a generation agent. See [README.md](README.md) for the catalogue and how the
templates sit between the modelling teams and the data platform team.
## Rules
- A template's `README.md` is its contract. Change the files and the contract together.
- Every template's `example/` must deploy and pass `uv run data-domain test` on the current
domain platform. Run it from a domain repository after any change, and record the date and
result in the template README.
- Products are not stored here. They are generated into the domain repository that runs them.
- Templates meet the domain platform's product contract (semprini-data-domain `README.md`, *The
product contract*). Do not work around it here: raise the need with the data platform team.
- Model gaps go to the modelling team's repository, not into a template.
- Templates never carry credentials. Use the variables the platform substitutes
(`${ODS_PASSWORD}`, `${DOMAIN}`).
## Agents
| Command | Agent | Purpose |
|---|---|---|
| `/agent-canonical-product` | `.claude/agents/agent-canonical-product.md` | Generate, deploy and test a canonical (`domain-aligned`) product from a model declaration |
The MD-DDL modelling agents (`/agent-ontology`, `/agent-architect`, ...) live in each domain's
model repository.
## Layout
```
canonical_data_product/ Canonical template: README.md contract, template files, example/
.claude/agents/ One generation agent per template
.claude/commands/ Command wrappers for those agents
```
## Setup layout
During setup this repository is a submodule of semprini-data, next to `semprini-data-domain`
(the domain platform) and `semprini-domain-digital-datamodel` (the Digital Core model). From a
domain repository beside semprini-data, the canonical example is at
`../semprini-data/semprini-data-product-templates/canonical_data_product/example`.
+87
View File
@@ -0,0 +1,87 @@
# semprini-data-product-templates
Data product templates for the semprini-data domain platform, one folder per class of data
product, owned by the **data product engineering teams**.
A template is the answer to "what does a deployable product of this class look like on this
platform": the directory layout, naming, type mapping, and every file the platform needs, as
`{{placeholders}}` that a generation agent fills in from one MD-DDL data product declaration.
The canonical template started in
[semprini-blog-dataproducts](https://git.semprini.me/paul/semprini-blog-dataproducts), where it
shared a repository with its platform, model and products.
## Catalogue
| Template | Product class | MD-DDL `class` | Status |
|---|---|---|---|
| [canonical_data_product/](canonical_data_product/README.md) | Canonical: a slice of the domain's canonical model, published as modelled through GraphQL, Kafka and Trino | `domain-aligned` | Available. Verified 2026-09-17 on the domain platform, 9 of 9 checks |
| `source_aligned_data_product/` | Source aligned: one source system's data in its own shape, for audit, replay and debugging | `source-aligned` | Planned |
| `experience_<class>_data_product/` | Experience: shaped for an audience. Several classes, e.g. lake tables built by scheduled dbt models | `consumer-aligned` | Planned |
## Where templates sit between the teams
```
modelling team engineering teams data platform team
───────────── ───────────────── ──────────────────
semprini-domain-<d>-datamodel semprini-data-product-templates semprini-data-domain
data_products/*.md ───────▶ <class>_data_product/ ◀── product contract ── data-domain CLI
handoffs/<slug>.md .claude/agents/agent-<class>-product.md compose.domain.yml
│ │
└──────── generate ──────┴──▶ semprini-domain-<d>/products/<slug>/ ── deploy ──▶ domain stack
```
- **From the modelling team:** a product declaration and the entities and enums it names,
plus a handoff note for decisions the model cannot carry. The declaration's MD-DDL `class`
picks the template.
- **To the data platform team:** every template produces directories that meet the
domain platform's *product contract* (semprini-data-domain `README.md`): the `product.yaml`
manifest the `data-domain` CLI reads, and the SQL, schema, job and smoke-test files it
applies. A template that needs something the contract does not offer asks the platform team
first.
- **Products** are generated into the domain repository that runs them, and deployed and
operated from there by the domain's engineering team.
All teams work on semprini-core, the enterprise landing zone: Keycloak for identity, and Gitea
(git.semprini.me) for these repositories.
## Generating a product
From a checkout of this repository, with the model repository and the domain repository at
hand:
```
/agent-canonical-product Generate Canonical Party for the digital-core domain
```
The agent reads the declaration and any pending handoff, writes `products/<slug>/` in the
domain repository, runs `uv run data-domain deploy` and `test` there, and reports the model and
template versions it generated from. Commit the product in the domain repository with both.
## Versioning
- Tag a release of this repository when a template changes (`v0.1.0`, ...). Domain repositories
record the tag they generated from and regenerate deliberately, not on every commit here.
- A template change that alters what a product directory contains may need a platform
change first. Check the product contract, and agree the change with the data platform team.
- Every template keeps a worked `example/` that deploys and passes `data-domain test` on the
current domain platform. That example is the template's test, and the platform team's
smoke test for the domain template.
## Adding a template
1. Create `<class>_data_product/` with a `README.md` contract (what the product is, the
mapping to platform interfaces, layout, naming, placeholders, type mapping, the generation
input table, prerequisites and known gaps) and the template files.
2. Add a worked `example/` and verify it on a domain stack with `data-domain deploy` and
`test`.
3. Add its generation agent as `.claude/agents/agent-<class>-product.md`, with a command
wrapper in `.claude/commands/`.
4. Add it to the catalogue above.
## Repository layout during setup
While the systems are being set up, this repository is a submodule of
[semprini-data](https://git.semprini.me/paul/semprini-data), beside the domain platform and the
Digital Core model, so all of it can be read and changed together. Most organisations keep
these repositories apart, each owned and released by its own team, and link them only by
version.
+286
View File
@@ -0,0 +1,286 @@
# 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`.
@@ -0,0 +1,44 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "urn:{{domain.slug}}:{{product.slug}}:{{table}}",
"title": "{{entity.name}}",
"description": "{{entity.description}} Canonical record published by {{product.name}}. Property names are the ODS column names. Used for both the inbound topic (records producers publish) and the compacted outbound topic (every change, keyed by {{table}}_id).",
"type": "object",
"additionalProperties": false,
"required": ["{{table}}_id"],
"properties": {
"{{table}}_id": {
"type": "string",
"format": "uuid",
"description": "{{identifier.description}}"
},
"{{column}}": {
"type": "{{json_type}}",
"description": "{{attribute.description}}"
},
"{{optional_column}}": {
"type": ["{{json_type}}", "null"],
"description": "{{attribute.description}}"
},
"{{enum_column}}": {
"type": ["string", "null"],
"enum": ["{{enum_value}}", null],
"description": "{{attribute.description}}"
},
"{{parent_table}}_id": {
"type": "string",
"format": "uuid",
"description": "Identifier of the owning {{parent_entity}}."
},
"created_at": {
"type": ["string", "null"],
"format": "date-time",
"description": "Set by the ODS. Optional on the inbound topic."
},
"updated_at": {
"type": ["string", "null"],
"format": "date-time",
"description": "Set by the ODS on every change. Optional on the inbound topic."
}
}
}
@@ -0,0 +1,59 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "urn:digital-core:example-address:address",
"title": "Address",
"description": "The canonical record of a physical or postal location. Canonical record published by Example Address. Property names are the ODS column names. Used for both the inbound topic (records producers publish) and the compacted outbound topic (every change, keyed by address_id).",
"type": "object",
"additionalProperties": false,
"required": ["address_id", "country"],
"properties": {
"address_id": {
"type": "string",
"format": "uuid",
"description": "Globally unique surrogate identifier for this physical location record. Immutable once assigned."
},
"address_type": {
"type": ["string", "null"],
"enum": ["Street Address", "PO Box", "Registered Office", "Overseas Address", null],
"description": "The structural type of the address. Determines which fields are applicable."
},
"address_line_1": {
"type": ["string", "null"],
"description": "The primary street address line. For PO Box addresses, the PO Box number."
},
"address_line_2": {
"type": ["string", "null"],
"description": "Secondary address line for suite, level, unit, or building name where applicable."
},
"suburb": {
"type": ["string", "null"],
"description": "The suburb or locality component of the address."
},
"city": {
"type": ["string", "null"],
"description": "The city or town."
},
"state_or_region": {
"type": ["string", "null"],
"description": "The state, territory, or region."
},
"postcode": {
"type": ["string", "null"],
"description": "The postal code, as a string to preserve leading zeros."
},
"country": {
"type": "string",
"description": "ISO 3166-1 alpha-2 country code. Mandatory for all address types."
},
"created_at": {
"type": ["string", "null"],
"format": "date-time",
"description": "Set by the ODS. Optional on the inbound topic."
},
"updated_at": {
"type": ["string", "null"],
"format": "date-time",
"description": "Set by the ODS on every change. Optional on the inbound topic."
}
}
}
@@ -0,0 +1,100 @@
-- Example Address: streaming job (Flink SQL, Flink 2.2).
-- Submitted by the platform CLI with `bin/sql-client.sh -f job.sql` on the jobmanager.
SET 'pipeline.name' = 'example-address';
SET 'execution.checkpointing.interval' = '10 s';
CREATE TABLE address_inbound (
address_id STRING,
address_type STRING,
address_line_1 STRING,
address_line_2 STRING,
suburb STRING,
city STRING,
state_or_region STRING,
postcode STRING,
country STRING
) WITH (
'connector' = 'kafka',
'topic' = 'digital-core.example-address.address.inbound',
'properties.bootstrap.servers' = 'kafka:29092',
'properties.group.id' = 'example-address.address.inbound',
'scan.startup.mode' = 'group-offsets',
'properties.auto.offset.reset' = 'earliest',
'format' = 'json',
'json.fail-on-missing-field' = 'false',
'json.ignore-parse-errors' = 'false',
'json.timestamp-format.standard' = 'ISO-8601'
);
CREATE TABLE address_ods (
address_id STRING,
address_type STRING,
address_line_1 STRING,
address_line_2 STRING,
suburb STRING,
city STRING,
state_or_region STRING,
postcode STRING,
country STRING,
PRIMARY KEY (address_id) NOT ENFORCED
) WITH (
'connector' = 'jdbc',
'url' = 'jdbc:postgresql://ods:5432/ods?stringtype=unspecified',
'table-name' = 'example_address.address',
'username' = 'postgres',
'password' = '${ODS_PASSWORD}'
);
CREATE TABLE address_cdc (
address_id STRING,
address_type STRING,
address_line_1 STRING,
address_line_2 STRING,
suburb STRING,
city STRING,
state_or_region STRING,
postcode STRING,
country STRING,
updated_at TIMESTAMP_LTZ(6),
PRIMARY KEY (address_id) NOT ENFORCED
) WITH (
'connector' = 'postgres-cdc',
'hostname' = 'ods',
'port' = '5432',
'username' = 'postgres',
'password' = '${ODS_PASSWORD}',
'database-name' = 'ods',
'schema-name' = 'example_address',
'table-name' = 'address',
'slot.name' = 'example_address_address_flink',
'decoding.plugin.name' = 'pgoutput',
'scan.incremental.snapshot.enabled' = 'true'
);
CREATE TABLE address_outbound (
address_id STRING,
address_type STRING,
address_line_1 STRING,
address_line_2 STRING,
suburb STRING,
city STRING,
state_or_region STRING,
postcode STRING,
country STRING,
updated_at TIMESTAMP_LTZ(6),
PRIMARY KEY (address_id) NOT ENFORCED
) WITH (
'connector' = 'upsert-kafka',
'topic' = 'digital-core.example-address.address.outbound',
'properties.bootstrap.servers' = 'kafka:29092',
'key.format' = 'raw',
'value.format' = 'json',
'value.json.timestamp-format.standard' = 'ISO-8601'
);
EXECUTE STATEMENT SET
BEGIN
INSERT INTO address_ods SELECT * FROM address_inbound;
INSERT INTO address_outbound SELECT * FROM address_cdc;
END;
@@ -0,0 +1,31 @@
# Example Address: GraphQL surface reflected by pg_graphql from example_address.address.
# Documentation only; the live schema is available by introspection at
# POST http://localhost:20000/rpc/example_address_graphql (GRAPHQL_PORT of a domain at port base 20000).
type Address implements Node {
nodeId: ID!
addressId: UUID!
addressType: String # enum:Address Type, enforced by CHECK in the ODS
addressLine1: String
addressLine2: String
suburb: String
city: String
stateOrRegion: String
postcode: String
country: String!
createdAt: Datetime!
updatedAt: Datetime!
}
extend type Query {
addressCollection(
first: Int, last: Int, before: Cursor, after: Cursor,
filter: AddressFilter, orderBy: [AddressOrderBy!]
): AddressConnection
}
extend type Mutation {
insertIntoAddressCollection(objects: [AddressInsertInput!]!): AddressInsertResponse
updateAddressCollection(set: AddressUpdateInput!, filter: AddressFilter, atMost: Int! = 1): AddressUpdateResponse
deleteFromAddressCollection(filter: AddressFilter, atMost: Int! = 1): AddressDeleteResponse
}
@@ -0,0 +1,15 @@
# Run by `data-domain test` against POST /rpc/example_address_graphql.
query ExampleAddressSmoke {
addressCollection(first: 5) {
edges {
node {
addressId
addressType
city
country
createdAt
updatedAt
}
}
}
}
@@ -0,0 +1,12 @@
-- Example Address: analytical replication into DuckLake (runs on the lakehouse service).
CREATE SCHEMA IF NOT EXISTS example_address;
SELECT duckpipe.add_table(
'example_address.address',
target_table => 'example_address.address',
sync_group => 'ods'
);
GRANT USAGE ON SCHEMA example_address TO ducklake_reader, ducklake_writer;
GRANT SELECT ON ALL TABLES IN SCHEMA example_address TO ducklake_reader, ducklake_writer;
+95
View File
@@ -0,0 +1,95 @@
# Example Address: ODPS v4.0 manifest (worked example of canonical_data_product/odps.yaml).
schema: https://opendataproducts.org/v4.0/schema/odps.yaml
version: 4.0
product:
details:
en:
name: "Example Address"
productID: "digital-core.example-address"
description: "Worked example of the data product template: the canonical Address entity of the Digital Core domain, published through GraphQL, Kafka and Trino."
visibility: organisation
status: production
type: dataset
productVersion: "1.0.0"
categories:
- "Digital Core"
tags:
- "Address"
outputFileFormats:
- GraphQL
- JSON
- SQL
SLA:
declarative:
default:
name:
en: Default SLA
description:
en: "Service levels for Example Address"
dimensions:
- dimension: uptime
displaytitle:
en: Availability
objective: 99.95
unit: percent
- dimension: updateFrequency
displaytitle:
en: Data Freshness
objective: 1
unit: minutes
support:
email: "data.architecture@bank.com"
dataAccess:
default:
name:
en: CRUD API
description:
en: "GraphQL reflected from the operational store by pg_graphql."
outputPorttype: API
format: GraphQL
authenticationMethod: none
accessURL: "http://localhost:20000/rpc/example_address_graphql"
publish:
name:
en: Publish Input
description:
en: "Kafka topic accepting canonical Address records."
outputPorttype: API
format: JSON
authenticationMethod: none
accessURL: "kafka://localhost:20001/digital-core.example-address.address.inbound"
specsURL: "http://localhost:8081/apis/registry/v3/groups/digital-core.example-address/artifacts"
subscribe:
name:
en: Subscribe Output
description:
en: "Compacted Kafka topic carrying every change to Address, keyed by address_id."
outputPorttype: API
format: JSON
authenticationMethod: none
accessURL: "kafka://localhost:20001/digital-core.example-address.address.outbound"
specsURL: "http://localhost:8081/apis/registry/v3/groups/digital-core.example-address/artifacts"
sql:
name:
en: Analytic SQL
description:
en: "Trino over DuckLake, continuously replicated from the operational store."
outputPorttype: SQL
format: SQL
authenticationMethod: none
accessURL: "jdbc:trino://localhost:20003/lake/example_address"
license:
en:
scope:
definition: "TODO: purpose statement for the licence"
restrictions: "Internal. Address is reference data with no PII; parties are linked through Contact Address, which is not in this product."
permanent: false
exclusive: false
termination:
terminationConditions: "7 years post relationship end"
governance:
confidentiality: "Internal, per the Address entity governance in the Digital Core domain"
dataHolder:
en:
legalName: "TODO: organisation legal name"
email: "data.architecture@bank.com"
@@ -0,0 +1,13 @@
-- Example Address: operational data store schema (runs on the postgres service).
CREATE SCHEMA example_address;
COMMENT ON SCHEMA example_address IS E'@graphql({"inflect_names": true, "introspection": true, "max_rows": 100})';
CREATE FUNCTION example_address.set_updated_at() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
NEW.updated_at := now();
RETURN NEW;
END
$$;
@@ -0,0 +1,33 @@
-- Example Address: operational tables (PostgreSQL 17).
-- Source: entities/address.md (existence: independent, mutability: reference).
CREATE TABLE example_address.address (
address_id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
address_type text CHECK (address_type IN ('Street Address', 'PO Box', 'Registered Office', 'Overseas Address')), -- enum:Address Type
address_line_1 text,
address_line_2 text,
suburb text,
city text,
state_or_region text,
postcode text,
country text NOT NULL, -- constraint: Country Required
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT street_address_requires_address_line_1 -- constraint of the same name in the model
CHECK (address_type <> 'Street Address' OR address_line_1 IS NOT NULL)
);
COMMENT ON TABLE example_address.address IS 'The canonical record of a physical or postal location. Reference data shared across parties: a single Address record is referenced by all Contact Addresses at that location.';
COMMENT ON COLUMN example_address.address.address_id IS 'Globally unique surrogate identifier for this physical location record. Immutable once assigned.';
COMMENT ON COLUMN example_address.address.address_type IS 'The structural type of the address. Determines which fields are applicable.';
COMMENT ON COLUMN example_address.address.address_line_1 IS 'The primary street address line, typically including street number and street name. For PO Box addresses, the PO Box number.';
COMMENT ON COLUMN example_address.address.address_line_2 IS 'Secondary address line for suite, level, unit, or building name where applicable.';
COMMENT ON COLUMN example_address.address.suburb IS 'The suburb or locality component of the address.';
COMMENT ON COLUMN example_address.address.city IS 'The city or town.';
COMMENT ON COLUMN example_address.address.state_or_region IS 'The state, territory, or region.';
COMMENT ON COLUMN example_address.address.postcode IS 'The postal code, stored as a string to preserve leading zeros and support international formats.';
COMMENT ON COLUMN example_address.address.country IS 'The country in which the address is located, as an ISO 3166-1 alpha-2 country code.';
CREATE TRIGGER address_set_updated_at
BEFORE UPDATE ON example_address.address
FOR EACH ROW EXECUTE FUNCTION example_address.set_updated_at();
@@ -0,0 +1,26 @@
-- Example Address: API surface (runs on the postgres service).
GRANT USAGE ON SCHEMA example_address TO anon;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA example_address TO anon;
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA example_address TO anon;
ALTER DEFAULT PRIVILEGES IN SCHEMA example_address GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO anon;
-- The product's GraphQL endpoint: POST /rpc/example_address_graphql through PostgREST.
-- pg_graphql reflects the schemas on the search_path, so the SET clause scopes the
-- endpoint to this product's tables.
CREATE FUNCTION api.example_address_graphql(
query text,
variables jsonb DEFAULT '{}'::jsonb,
"operationName" text DEFAULT NULL,
extensions jsonb DEFAULT NULL
) RETURNS jsonb
LANGUAGE sql
SECURITY INVOKER
SET search_path = example_address, graphql
AS $$
SELECT graphql.resolve(query, variables, "operationName", extensions);
$$;
GRANT EXECUTE ON FUNCTION api.example_address_graphql(text, jsonb, text, jsonb) TO anon;
NOTIFY pgrst, 'reload schema';
@@ -0,0 +1,8 @@
-- Example Address: sample rows (runs on the postgres service).
INSERT INTO example_address.address
(address_id, address_type, address_line_1, address_line_2, suburb, city, state_or_region, postcode, country)
VALUES
('2f4c1a3e-0001-4a7b-9c11-000000000001', 'Street Address', '1 Queen Street', NULL, 'Auckland Central', 'Auckland', 'Auckland', '1010', 'NZ'),
('2f4c1a3e-0001-4a7b-9c11-000000000002', 'PO Box', 'PO Box 123', NULL, NULL, 'Wellington', 'Wellington', '6140', 'NZ'),
('2f4c1a3e-0001-4a7b-9c11-000000000003', 'Registered Office', 'Level 5, 100 Collins Street', NULL, NULL, 'Melbourne', 'VIC', '3000', 'AU');
@@ -0,0 +1,52 @@
# Worked example: the template instantiated for a single entity, Address (entities/address.md),
# as a product called Example Address. It deploys and tests on the stack as-is and shows what a
# finished product directory looks like. A real product lists every entity in its declaration.
product:
name: "Example Address"
slug: "example-address"
domain: "digital-core"
declaration: "entities/address.md"
version: "1.0.0"
owner: "data.architecture@bank.com"
ods:
schema: "example_address"
tables:
- name: "address"
entity: "Address"
key: "address_id"
graphql:
endpoint: "/rpc/example_address_graphql"
smoke: graphql/smoke.graphql
events:
registry_group: "digital-core.example-address"
compatibility: BACKWARD
topics:
- name: "digital-core.example-address.address.inbound"
role: publish-input
table: "address"
schema: events/schemas/address.schema.json
partitions: 3
cleanup_policy: delete
retention_ms: 604800000
- name: "digital-core.example-address.address.outbound"
role: subscribe-output
table: "address"
schema: events/schemas/address.schema.json
partitions: 3
cleanup_policy: compact
flink:
job: flink/job.sql
name: "example-address"
lakehouse:
sync_group: ods
schema: "example_address"
trino:
catalog: lake
smoke: trino/smoke.sql
@@ -0,0 +1,3 @@
-- Example Address: analytic SQL smoke test through Trino's `lake` catalog.
SELECT 'address' AS table_name, count(*) AS row_count FROM lake.example_address.address;
+89
View File
@@ -0,0 +1,89 @@
-- {{product.name}}: streaming job (Flink SQL, Flink 2.2).
-- Submitted by `data-domain deploy` with `bin/sql-client.sh -f job.sql` on the jobmanager.
-- ${ODS_PASSWORD} is substituted from the domain's .env at submission and never committed.
--
-- Per entity table, four Flink tables and two continuous INSERTs:
-- <table>_inbound kafka Publish Input: records producers publish (JSON, schema in events/schemas)
-- <table>_ods jdbc upserts inbound records into the ODS table by primary key
-- <table>_cdc postgres-cdc every change committed to the ODS table, however it arrived
-- <table>_outbound upsert-kafka Subscribe Output: compacted topic keyed by <table>_id, deletes as tombstones
-- Column lists match the ODS table (snake_case). Types follow the mapping table in README.md.
-- Requires the connector jars listed under "Platform prerequisites" in README.md.
SET 'pipeline.name' = '{{product.slug}}';
SET 'execution.checkpointing.interval' = '10 s';
-- >>> repeat per entity table
CREATE TABLE {{table}}_inbound (
{{table}}_id STRING,
{{column}} {{flink_type}},
{{parent_table}}_id STRING
) WITH (
'connector' = 'kafka',
'topic' = '{{domain.slug}}.{{product.slug}}.{{table}}.inbound',
'properties.bootstrap.servers' = 'kafka:29092',
'properties.group.id' = '{{product.slug}}.{{table}}.inbound',
'scan.startup.mode' = 'group-offsets',
'properties.auto.offset.reset' = 'earliest',
'format' = 'json',
'json.fail-on-missing-field' = 'false',
'json.ignore-parse-errors' = 'false',
'json.timestamp-format.standard' = 'ISO-8601'
);
CREATE TABLE {{table}}_ods (
{{table}}_id STRING,
{{column}} {{flink_type}},
{{parent_table}}_id STRING,
PRIMARY KEY ({{table}}_id) NOT ENFORCED
) WITH (
'connector' = 'jdbc',
'url' = 'jdbc:postgresql://ods:5432/ods?stringtype=unspecified',
'table-name' = '{{product.schema}}.{{table}}',
'username' = 'postgres',
'password' = '${ODS_PASSWORD}'
);
CREATE TABLE {{table}}_cdc (
{{table}}_id STRING,
{{column}} {{flink_type}},
{{parent_table}}_id STRING,
updated_at TIMESTAMP_LTZ(6),
PRIMARY KEY ({{table}}_id) NOT ENFORCED
) WITH (
'connector' = 'postgres-cdc',
'hostname' = 'ods',
'port' = '5432',
'username' = 'postgres',
'password' = '${ODS_PASSWORD}',
'database-name' = 'ods',
'schema-name' = '{{product.schema}}',
'table-name' = '{{table}}',
'slot.name' = '{{product.schema}}_{{table}}_flink',
'decoding.plugin.name' = 'pgoutput',
'scan.incremental.snapshot.enabled' = 'true'
);
CREATE TABLE {{table}}_outbound (
{{table}}_id STRING,
{{column}} {{flink_type}},
{{parent_table}}_id STRING,
updated_at TIMESTAMP_LTZ(6),
PRIMARY KEY ({{table}}_id) NOT ENFORCED
) WITH (
'connector' = 'upsert-kafka',
'topic' = '{{domain.slug}}.{{product.slug}}.{{table}}.outbound',
'properties.bootstrap.servers' = 'kafka:29092',
'key.format' = 'raw',
'value.format' = 'json',
'value.json.timestamp-format.standard' = 'ISO-8601'
);
-- <<< end repeat
EXECUTE STATEMENT SET
BEGIN
-- >>> repeat per entity table
INSERT INTO {{table}}_ods SELECT * FROM {{table}}_inbound;
INSERT INTO {{table}}_outbound SELECT * FROM {{table}}_cdc;
-- <<< end repeat
END;
@@ -0,0 +1,35 @@
# {{product.name}}: GraphQL surface reflected by pg_graphql from the ODS tables.
#
# This file documents the contract consumers can rely on. It is not loaded anywhere; the live
# schema is reflected from the tables and available by introspection:
# curl http://localhost:{{platform.graphql_port}}/rpc/{{product.schema}}_graphql -H 'Content-Type: application/json' \
# --data '{"query":"{ __type(name: \"{{Entity}}\") { fields { name } } }"}'
#
# Naming (inflect_names: true): table {{table}} -> type {{Entity}}; column {{column}} -> {{camelColumn}}.
# Scalars: uuid -> UUID, text -> String, boolean -> Boolean, bigint -> BigInt, numeric -> BigFloat,
# date -> Date, timestamptz -> Datetime, text[] -> [String].
# >>> repeat per entity table
type {{Entity}} implements Node {
nodeId: ID!
{{entity}}Id: UUID!
{{camelColumn}}: {{GraphQLType}} # {{attribute.name}}
createdAt: Datetime!
updatedAt: Datetime!
{{parent}}: {{Parent}} # from {{parent_table}}_id (one-to-many, this side)
{{child}}Collection(first: Int, after: Cursor, filter: {{Child}}Filter, orderBy: [{{Child}}OrderBy!]): {{Child}}Connection
}
extend type Query {
{{entity}}Collection(
first: Int, last: Int, before: Cursor, after: Cursor,
filter: {{Entity}}Filter, orderBy: [{{Entity}}OrderBy!]
): {{Entity}}Connection
}
extend type Mutation {
insertInto{{Entity}}Collection(objects: [{{Entity}}InsertInput!]!): {{Entity}}InsertResponse
update{{Entity}}Collection(set: {{Entity}}UpdateInput!, filter: {{Entity}}Filter, atMost: Int! = 1): {{Entity}}UpdateResponse
deleteFrom{{Entity}}Collection(filter: {{Entity}}Filter, atMost: Int! = 1): {{Entity}}DeleteResponse
}
# <<< end repeat
@@ -0,0 +1,15 @@
# Run by `data-domain test` against POST /rpc/{{product.schema}}_graphql.
# It must return a `data` object and no `errors`; it does not need to return rows.
query {{ProductName}}Smoke {
# >>> repeat per entity table
{{entity}}Collection(first: 5) {
edges {
node {
{{entity}}Id
createdAt
updatedAt
}
}
}
# <<< end repeat
}
@@ -0,0 +1,22 @@
-- {{product.name}}: analytical replication into DuckLake (runs on the lakehouse service).
--
-- pg_duckpipe follows the ODS write-ahead log and maintains a DuckLake copy of each table as
-- Parquet in the domain's `lake` bucket. The platform-level sync group `ods` already points
-- at the ODS (platform/compose.domain.yml); the product only registers its tables with it.
-- Trino reads the result as lake.{{product.schema}}.<table>.
CREATE SCHEMA IF NOT EXISTS {{product.schema}};
-- >>> repeat per entity table, parents before children
SELECT duckpipe.add_table(
'{{product.schema}}.{{table}}',
target_table => '{{product.schema}}.{{table}}',
sync_group => 'ods'
);
-- <<< end repeat
-- Readers (Trino) and writers (dbt, building experience products on top) need the tables.
-- pg_ducklake does not yet enforce SELECT on DuckLake tables, so these grants document intent
-- as much as they control it; see docs/security-architecture.md.
GRANT USAGE ON SCHEMA {{product.schema}} TO ducklake_reader, ducklake_writer;
GRANT SELECT ON ALL TABLES IN SCHEMA {{product.schema}} TO ducklake_reader, ducklake_writer;
+104
View File
@@ -0,0 +1,104 @@
# Open Data Product Specification v4.0 manifest: the product's entry in the catalogue.
# The details, SLA, license and dataHolder blocks follow Agent Architect's odps-alignment
# mapping from the MD-DDL declaration. The dataAccess block is platform-specific and lists
# the product's four interfaces. Fields with TODO need business input outside the model.
schema: https://opendataproducts.org/v4.0/schema/odps.yaml
version: 4.0
product:
details:
en:
name: "{{product.name}}"
productID: "{{domain.slug}}.{{product.slug}}"
description: "{{product.description}}"
visibility: organisation
status: production # Draft -> draft, Active -> production, Deprecated -> sunset
type: dataset # domain-aligned -> dataset, consumer-aligned -> derived data, source-aligned -> raw data
productVersion: "{{product.version}}"
categories:
- "{{domain.name}}"
tags:
# >>> repeat per entity
- "{{entity.name}}"
# <<< end repeat
outputFileFormats:
- GraphQL
- JSON
- SQL
SLA:
declarative:
default:
name:
en: Default SLA
description:
en: "Service levels for {{product.name}}"
dimensions:
- dimension: uptime
displaytitle:
en: Availability
objective: "{{sla.availability_percent}}" # number, from sla.availability, e.g. 99.95
unit: percent
- dimension: updateFrequency
displaytitle:
en: Data Freshness
objective: "{{sla.freshness_minutes}}" # number: real-time -> 1, hourly -> 60, daily -> 1440
unit: minutes
support:
email: "{{product.owner}}"
dataAccess:
default:
name:
en: CRUD API
description:
en: "GraphQL reflected from the operational store by pg_graphql. Reads, inserts, updates and deletes on every entity."
outputPorttype: API
format: GraphQL
authenticationMethod: none # lab stack only
accessURL: "http://localhost:{{platform.graphql_port}}/rpc/{{product.schema}}_graphql"
publish:
name:
en: Publish Input
description:
en: "Kafka topics that accept canonical records, one per entity. JSON payloads conform to the schema registered for the topic."
outputPorttype: API
format: JSON
authenticationMethod: none
accessURL: "kafka://localhost:{{platform.kafka_port}}/{{domain.slug}}.{{product.slug}}.<table>.inbound"
specsURL: "http://localhost:8081/apis/registry/v3/groups/{{domain.slug}}.{{product.slug}}/artifacts"
subscribe:
name:
en: Subscribe Output
description:
en: "Compacted Kafka topics carrying every change to each entity, keyed by identifier. Deletes are tombstones."
outputPorttype: API
format: JSON
authenticationMethod: none
accessURL: "kafka://localhost:{{platform.kafka_port}}/{{domain.slug}}.{{product.slug}}.<table>.outbound"
specsURL: "http://localhost:8081/apis/registry/v3/groups/{{domain.slug}}.{{product.slug}}/artifacts"
sql:
name:
en: Analytic SQL
description:
en: "Trino over DuckLake, continuously replicated from the operational store by pg_duckpipe."
outputPorttype: SQL
format: SQL
authenticationMethod: none
accessURL: "jdbc:trino://localhost:{{platform.trino_port}}/lake/{{product.schema}}"
license:
en:
scope:
definition: "TODO: purpose statement for the licence"
restrictions: "{{governance.classification}}. {{governance.restrictions}}"
permanent: false
exclusive: false
termination:
terminationConditions: "{{governance.retention}}"
governance:
confidentiality: "{{governance.confidentiality}}"
dataHolder:
en:
legalName: "TODO: organisation legal name"
email: "{{product.owner}}"
+19
View File
@@ -0,0 +1,19 @@
-- {{product.name}}: operational data store schema (runs on the postgres service).
--
-- The product owns one PostgreSQL schema. pg_graphql reflects only the schemas on the
-- search_path, and the product's RPC endpoint (030_api.sql) sets the search_path to this
-- schema, so this is what scopes the GraphQL API to the product.
CREATE SCHEMA {{product.schema}};
COMMENT ON SCHEMA {{product.schema}} IS E'@graphql({"inflect_names": true, "introspection": true, "max_rows": 100})';
-- Maintains updated_at on every row change. Used by all product tables (020_tables.sql).
-- updated_at is the freshness signal carried on the outbound topics and into the lake.
CREATE FUNCTION {{product.schema}}.set_updated_at() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
NEW.updated_at := now();
RETURN NEW;
END
$$;
+69
View File
@@ -0,0 +1,69 @@
-- {{product.name}}: operational tables (PostgreSQL 17).
--
-- One block per entity in the product's `entities` list, parents before children, association
-- tables last. Names are snake_case of the MD-DDL names. Every table has:
-- <table>_id uuid the MD-DDL primary identifier; producers may supply it
-- created_at / updated_at platform columns, always last
-- Enum attributes are text with a CHECK listing the MD-DDL enum values verbatim.
-- One-to-many relationships become a foreign key on the owned side; many-to-many
-- relationships become association tables. Inheritance (`extends:`) is class-table: the
-- subtype's primary key is its foreign key to the parent, and an abstract parent carries a
-- <table>_type discriminator naming the subtype.
-- >>> repeat per core entity table (no `extends:`)
CREATE TABLE {{product.schema}}.{{table}} (
{{table}}_id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
{{table}}_type text NOT NULL CHECK ({{table}}_type IN ({{subtype_names}})), -- abstract parents only
{{column}} {{pg_type}}, -- {{attribute.name}}
{{enum_column}} text CHECK ({{enum_column}} IN ({{enum_values}})), -- enum:{{enum.name}}
{{parent_table}}_id uuid NOT NULL REFERENCES {{product.schema}}.{{parent_table}} ({{parent_table}}_id), -- one-to-many, owned side
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
COMMENT ON TABLE {{product.schema}}.{{table}} IS '{{entity.description}}';
COMMENT ON COLUMN {{product.schema}}.{{table}}.{{column}} IS '{{attribute.description}}';
CREATE INDEX {{table}}_{{parent_table}}_id_idx ON {{product.schema}}.{{table}} ({{parent_table}}_id);
CREATE TRIGGER {{table}}_set_updated_at
BEFORE UPDATE ON {{product.schema}}.{{table}}
FOR EACH ROW EXECUTE FUNCTION {{product.schema}}.set_updated_at();
-- <<< end repeat
-- >>> repeat per subtype table (`extends: {{parent}}`)
CREATE TABLE {{product.schema}}.{{child_table}} (
{{child_table}}_id uuid PRIMARY KEY REFERENCES {{product.schema}}.{{parent_table}} ({{parent_table}}_id) ON DELETE CASCADE,
{{column}} {{pg_type}}, -- {{attribute.name}}
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
COMMENT ON TABLE {{product.schema}}.{{child_table}} IS '{{entity.description}}';
CREATE TRIGGER {{child_table}}_set_updated_at
BEFORE UPDATE ON {{product.schema}}.{{child_table}}
FOR EACH ROW EXECUTE FUNCTION {{product.schema}}.set_updated_at();
-- <<< end repeat
-- >>> repeat per many-to-many relationship
-- Self-referential relationships are named <table>_association and use
-- source_<table>_id / target_<table>_id in place of the two foreign keys below.
CREATE TABLE {{product.schema}}.{{source_table}}_{{target_table}} (
{{source_table}}_{{target_table}}_id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
{{source_table}}_id uuid NOT NULL REFERENCES {{product.schema}}.{{source_table}} ({{source_table}}_id) ON DELETE CASCADE,
{{target_table}}_id uuid NOT NULL REFERENCES {{product.schema}}.{{target_table}} ({{target_table}}_id) ON DELETE CASCADE,
{{relationship_attribute}} {{pg_type}}, -- from relationship_attributes
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
COMMENT ON TABLE {{product.schema}}.{{source_table}}_{{target_table}} IS '{{relationship.description}}';
CREATE INDEX {{source_table}}_{{target_table}}_source_idx ON {{product.schema}}.{{source_table}}_{{target_table}} ({{source_table}}_id);
CREATE INDEX {{source_table}}_{{target_table}}_target_idx ON {{product.schema}}.{{source_table}}_{{target_table}} ({{target_table}}_id);
CREATE TRIGGER {{source_table}}_{{target_table}}_set_updated_at
BEFORE UPDATE ON {{product.schema}}.{{source_table}}_{{target_table}}
FOR EACH ROW EXECUTE FUNCTION {{product.schema}}.set_updated_at();
-- <<< end repeat
+31
View File
@@ -0,0 +1,31 @@
-- {{product.name}}: API surface (runs on the postgres service).
--
-- PostgREST connects as `authenticator` and switches to the platform's `anon` role, so the
-- GraphQL API sees exactly what `anon` is granted here. The lab has no authentication; a real
-- deployment would grant per-consumer roles and add row-level security policies.
GRANT USAGE ON SCHEMA {{product.schema}} TO anon;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA {{product.schema}} TO anon;
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA {{product.schema}} TO anon;
ALTER DEFAULT PRIVILEGES IN SCHEMA {{product.schema}} GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO anon;
-- The product's GraphQL endpoint. PostgREST exposes api.<name> as POST /rpc/<name>.
-- pg_graphql reflects the schemas on the search_path, so the SET clause is what scopes this
-- endpoint to the product's tables and keeps other products out of its schema.
CREATE FUNCTION api.{{product.schema}}_graphql(
query text,
variables jsonb DEFAULT '{}'::jsonb,
"operationName" text DEFAULT NULL,
extensions jsonb DEFAULT NULL
) RETURNS jsonb
LANGUAGE sql
SECURITY INVOKER
SET search_path = {{product.schema}}, graphql
AS $$
SELECT graphql.resolve(query, variables, "operationName", extensions);
$$;
GRANT EXECUTE ON FUNCTION api.{{product.schema}}_graphql(text, jsonb, text, jsonb) TO anon;
-- PostgREST caches the API definition; ask it to pick up the new endpoint.
NOTIFY pgrst, 'reload schema';
+10
View File
@@ -0,0 +1,10 @@
-- {{product.name}}: optional sample rows (runs on the postgres service).
--
-- Delete this file if the product should deploy empty. Use fixed uuids so child rows can
-- reference their parents and so the same rows can be published to the inbound topics or
-- queried through GraphQL in examples. Keep it to a handful of rows per table.
-- >>> repeat per entity table, parents before children
INSERT INTO {{product.schema}}.{{table}} ({{table}}_id, {{column}}, {{parent_table}}_id) VALUES
('{{uuid}}', {{value}}, '{{parent_uuid}}');
-- <<< end repeat
+57
View File
@@ -0,0 +1,57 @@
# Data product manifest.
# Read by `uv run data-domain deploy|test|undeploy <product dir>`.
# Names every platform resource the product owns. Derived from the MD-DDL declaration
# named in `declaration`; see README.md in the template for the naming rules.
product:
name: "{{product.name}}" # MD-DDL level-3 heading, e.g. Canonical Party
slug: "{{product.slug}}" # kebab-case identity, e.g. canonical-party
domain: "{{domain.slug}}" # kebab-case domain, e.g. digital-core
declaration: "{{product.declaration}}" # e.g. data_products/canonical.md
version: "{{product.version}}" # from the declaration's `version`
owner: "{{product.owner}}" # from the declaration's `owner`
ods:
schema: "{{product.schema}}" # snake_case of slug, e.g. canonical_party
tables:
# >>> repeat per entity table, parents before children, association tables last
- name: "{{table}}" # e.g. party_role
entity: "{{entity.name}}" # e.g. Party Role
key: "{{table}}_id"
# <<< end repeat
graphql:
endpoint: "/rpc/{{product.schema}}_graphql"
smoke: graphql/smoke.graphql
events:
registry_group: "{{domain.slug}}.{{product.slug}}"
compatibility: BACKWARD
topics:
# >>> repeat per entity table
- name: "{{domain.slug}}.{{product.slug}}.{{table}}.inbound"
role: publish-input # producers publish canonical records here
table: "{{table}}"
schema: events/schemas/{{table}}.schema.json
partitions: 3
cleanup_policy: delete
retention_ms: 604800000 # 7 days
- name: "{{domain.slug}}.{{product.slug}}.{{table}}.outbound"
role: subscribe-output # every change to the ODS table, keyed by {{table}}_id
table: "{{table}}"
schema: events/schemas/{{table}}.schema.json
partitions: 3
cleanup_policy: compact
# <<< end repeat
flink:
job: flink/job.sql
name: "{{product.slug}}"
lakehouse:
sync_group: ods # platform-level pg_duckpipe group pointing at the ODS
schema: "{{product.schema}}"
trino:
catalog: lake
smoke: trino/smoke.sql
+6
View File
@@ -0,0 +1,6 @@
-- {{product.name}}: analytic SQL smoke test, run by `data-domain test`
-- through Trino's `lake` catalog. One statement per table; each must succeed.
-- >>> repeat per entity table
SELECT '{{table}}' AS table_name, count(*) AS row_count FROM lake.{{product.schema}}.{{table}};
-- <<< end repeat