diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6453f65 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +__pycache__/ +.pytest_cache/ +.claude/settings.local.json diff --git a/README.md b/README.md new file mode 100644 index 0000000..681f1a0 --- /dev/null +++ b/README.md @@ -0,0 +1,61 @@ +# semprini-domain-cdp-digital-core + +**Canonical data products of the Digital Core domain**, owned and operated by the domain's data +product engineering team. Each folder is one product directory: generated from the canonical +template, deployed onto the digital-core domain, unit-tested against its seed data, and +registered in the data management zone. + +| Product | MD-DDL declaration | Generated from | Status | +|---|---|---|---| +| [canonical-party/](canonical-party/) | Canonical Party, `data_model/data_products/canonical.md` in semprini-domain-digital-datamodel 1.0.0 | semprini-blog-dataproducts' template, adapted to the domain platform; now `canonical_data_product/` in semprini-data-product-templates | Deployed on digital-core: 65 of 65 smoke checks, 100 unit tests, registered in OpenMetadata (2026-09-18) | + +## Where this sits + +| Repository | Team | What it gives this one | +|---|---|---| +| semprini-domain-digital-datamodel | Digital Core modelling team | The product declarations and entities products are generated from | +| semprini-data-product-templates | Data product engineering | `canonical_data_product/`: the template, its generic unit tests, and `/agent-canonical-product` | +| semprini-data-domain | Data platform | The domain platform and the `data-domain` CLI that deploys, tests and registers products | +| semprini-domain-digital-core | Digital Core engineering | The running domain: `compose.yml`, `.env`, the stack these products deploy onto | + +## Operating a product + +Everything runs from the domain repository (`semprini-domain-digital-core`), which the CLI acts +on. With this repository at `../semprini-data/semprini-domain-cdp-digital-core`: + +```bash +cd semprini-domain-digital-core +P=../semprini-data/semprini-domain-cdp-digital-core/canonical-party + +uv run data-domain deploy $P # ODS, lake, topics, Apicurio schemas, Flink job +uv run data-domain test $P # every interface answers (smoke) +uv run data-domain unit $P # behaviour against the seed data (pytest, about a minute) +uv run data-domain register $P # OpenMetadata: tables, topics, data product, lineage +uv run data-domain unregister $P +uv run data-domain undeploy $P --yes +``` + +`deploy` expects a clean slate: after changing the DDL, `undeploy` first. `register` needs the +domain registered with the management zone (`platform/domain-integration.sh register mgmt` in the +domain repository). + +## Unit tests + +`canonical-party/tests/` holds the canonical template's generic test modules, unchanged, and +`expectations.yaml`, which is this product's own: seed row counts and sample rows, the updates +each constraint must refuse, the relationship traversals in `graphql/schema.graphql`, and one +record to follow from the inbound topic through every interface. Keep `expectations.yaml` in step +with `ods/040_seed.sql` and `ods/020_tables.sql`; the test modules are updated by copying them +from the template. + +## Changing a product + +Regenerate from a model release and a template release rather than editing by hand, and name +both in the commit message. A hand fix to a generated product is a template or model defect: +raise it with the template owners or the modelling team as well. + +## Setup layout + +While the systems are being set up this repository is a submodule of semprini-data. Most +organisations keep product repositories apart from the platform and the templates, linked only by +version. diff --git a/canonical-party/flink/job.sql b/canonical-party/flink/job.sql index 0f413c2..bc7e4e0 100644 --- a/canonical-party/flink/job.sql +++ b/canonical-party/flink/job.sql @@ -1,4 +1,4 @@ --- Canonical Party: streaming job (Flink SQL, Flink 2.1). +-- Canonical Party: streaming job (Flink SQL, Flink 2.2). -- Submitted by the platform CLI with `bin/sql-client.sh -f job.sql` on the jobmanager. -- -- Per entity table, four Flink tables and two continuous INSERTs: @@ -6,8 +6,8 @@ -- _ods jdbc upserts inbound records into the ODS table by primary key --
_cdc postgres-cdc every change committed to the ODS table, however it arrived --
_outbound upsert-kafka Subscribe Output: compacted topic keyed by
_id, deletes as tombstones --- Column lists match the ODS table (snake_case). Types follow the mapping table in template/README.md. --- Requires the connector jars listed under "Platform prerequisites" in template/README.md. +-- Column lists match the ODS table (snake_case). Types follow the mapping table in canonical_data_product/README.md. +-- Requires the connector jars listed under "Platform prerequisites" in canonical_data_product/README.md. -- Nine tables: with pg_duckpipe's two slots this job needs eleven replication slots on the ODS, -- one more than max_replication_slots=10 allows; raise the limit before submitting it. @@ -44,10 +44,10 @@ CREATE TABLE party_ods ( PRIMARY KEY (party_id) NOT ENFORCED ) WITH ( 'connector' = 'jdbc', - 'url' = 'jdbc:postgresql://postgres:5432/digital?stringtype=unspecified', + 'url' = 'jdbc:postgresql://ods:5432/ods?stringtype=unspecified', 'table-name' = 'canonical_party.party', - 'username' = 'semprini', - 'password' = 'semprini' + 'username' = 'postgres', + 'password' = '${ODS_PASSWORD}' ); CREATE TABLE party_cdc ( @@ -60,11 +60,11 @@ CREATE TABLE party_cdc ( PRIMARY KEY (party_id) NOT ENFORCED ) WITH ( 'connector' = 'postgres-cdc', - 'hostname' = 'postgres', + 'hostname' = 'ods', 'port' = '5432', - 'username' = 'semprini', - 'password' = 'semprini', - 'database-name' = 'digital', + 'username' = 'postgres', + 'password' = '${ODS_PASSWORD}', + 'database-name' = 'ods', 'schema-name' = 'canonical_party', 'table-name' = 'party', 'slot.name' = 'canonical_party_party_flink', @@ -127,10 +127,10 @@ CREATE TABLE address_ods ( PRIMARY KEY (address_id) NOT ENFORCED ) WITH ( 'connector' = 'jdbc', - 'url' = 'jdbc:postgresql://postgres:5432/digital?stringtype=unspecified', + 'url' = 'jdbc:postgresql://ods:5432/ods?stringtype=unspecified', 'table-name' = 'canonical_party.address', - 'username' = 'semprini', - 'password' = 'semprini' + 'username' = 'postgres', + 'password' = '${ODS_PASSWORD}' ); CREATE TABLE address_cdc ( @@ -147,11 +147,11 @@ CREATE TABLE address_cdc ( PRIMARY KEY (address_id) NOT ENFORCED ) WITH ( 'connector' = 'postgres-cdc', - 'hostname' = 'postgres', + 'hostname' = 'ods', 'port' = '5432', - 'username' = 'semprini', - 'password' = 'semprini', - 'database-name' = 'digital', + 'username' = 'postgres', + 'password' = '${ODS_PASSWORD}', + 'database-name' = 'ods', 'schema-name' = 'canonical_party', 'table-name' = 'address', 'slot.name' = 'canonical_party_address_flink', @@ -208,10 +208,10 @@ CREATE TABLE person_ods ( PRIMARY KEY (person_id) NOT ENFORCED ) WITH ( 'connector' = 'jdbc', - 'url' = 'jdbc:postgresql://postgres:5432/digital?stringtype=unspecified', + 'url' = 'jdbc:postgresql://ods:5432/ods?stringtype=unspecified', 'table-name' = 'canonical_party.person', - 'username' = 'semprini', - 'password' = 'semprini' + 'username' = 'postgres', + 'password' = '${ODS_PASSWORD}' ); CREATE TABLE person_cdc ( @@ -223,11 +223,11 @@ CREATE TABLE person_cdc ( PRIMARY KEY (person_id) NOT ENFORCED ) WITH ( 'connector' = 'postgres-cdc', - 'hostname' = 'postgres', + 'hostname' = 'ods', 'port' = '5432', - 'username' = 'semprini', - 'password' = 'semprini', - 'database-name' = 'digital', + 'username' = 'postgres', + 'password' = '${ODS_PASSWORD}', + 'database-name' = 'ods', 'schema-name' = 'canonical_party', 'table-name' = 'person', 'slot.name' = 'canonical_party_person_flink', @@ -283,10 +283,10 @@ CREATE TABLE company_ods ( PRIMARY KEY (company_id) NOT ENFORCED ) WITH ( 'connector' = 'jdbc', - 'url' = 'jdbc:postgresql://postgres:5432/digital?stringtype=unspecified', + 'url' = 'jdbc:postgresql://ods:5432/ods?stringtype=unspecified', 'table-name' = 'canonical_party.company', - 'username' = 'semprini', - 'password' = 'semprini' + 'username' = 'postgres', + 'password' = '${ODS_PASSWORD}' ); CREATE TABLE company_cdc ( @@ -300,11 +300,11 @@ CREATE TABLE company_cdc ( PRIMARY KEY (company_id) NOT ENFORCED ) WITH ( 'connector' = 'postgres-cdc', - 'hostname' = 'postgres', + 'hostname' = 'ods', 'port' = '5432', - 'username' = 'semprini', - 'password' = 'semprini', - 'database-name' = 'digital', + 'username' = 'postgres', + 'password' = '${ODS_PASSWORD}', + 'database-name' = 'ods', 'schema-name' = 'canonical_party', 'table-name' = 'company', 'slot.name' = 'canonical_party_company_flink', @@ -362,10 +362,10 @@ CREATE TABLE party_role_ods ( PRIMARY KEY (party_role_id) NOT ENFORCED ) WITH ( 'connector' = 'jdbc', - 'url' = 'jdbc:postgresql://postgres:5432/digital?stringtype=unspecified', + 'url' = 'jdbc:postgresql://ods:5432/ods?stringtype=unspecified', 'table-name' = 'canonical_party.party_role', - 'username' = 'semprini', - 'password' = 'semprini' + 'username' = 'postgres', + 'password' = '${ODS_PASSWORD}' ); CREATE TABLE party_role_cdc ( @@ -379,11 +379,11 @@ CREATE TABLE party_role_cdc ( PRIMARY KEY (party_role_id) NOT ENFORCED ) WITH ( 'connector' = 'postgres-cdc', - 'hostname' = 'postgres', + 'hostname' = 'ods', 'port' = '5432', - 'username' = 'semprini', - 'password' = 'semprini', - 'database-name' = 'digital', + 'username' = 'postgres', + 'password' = '${ODS_PASSWORD}', + 'database-name' = 'ods', 'schema-name' = 'canonical_party', 'table-name' = 'party_role', 'slot.name' = 'canonical_party_party_role_flink', @@ -437,10 +437,10 @@ CREATE TABLE customer_ods ( PRIMARY KEY (customer_id) NOT ENFORCED ) WITH ( 'connector' = 'jdbc', - 'url' = 'jdbc:postgresql://postgres:5432/digital?stringtype=unspecified', + 'url' = 'jdbc:postgresql://ods:5432/ods?stringtype=unspecified', 'table-name' = 'canonical_party.customer', - 'username' = 'semprini', - 'password' = 'semprini' + 'username' = 'postgres', + 'password' = '${ODS_PASSWORD}' ); CREATE TABLE customer_cdc ( @@ -452,11 +452,11 @@ CREATE TABLE customer_cdc ( PRIMARY KEY (customer_id) NOT ENFORCED ) WITH ( 'connector' = 'postgres-cdc', - 'hostname' = 'postgres', + 'hostname' = 'ods', 'port' = '5432', - 'username' = 'semprini', - 'password' = 'semprini', - 'database-name' = 'digital', + 'username' = 'postgres', + 'password' = '${ODS_PASSWORD}', + 'database-name' = 'ods', 'schema-name' = 'canonical_party', 'table-name' = 'customer', 'slot.name' = 'canonical_party_customer_flink', @@ -520,10 +520,10 @@ CREATE TABLE contact_address_ods ( PRIMARY KEY (contact_address_id) NOT ENFORCED ) WITH ( 'connector' = 'jdbc', - 'url' = 'jdbc:postgresql://postgres:5432/digital?stringtype=unspecified', + 'url' = 'jdbc:postgresql://ods:5432/ods?stringtype=unspecified', 'table-name' = 'canonical_party.contact_address', - 'username' = 'semprini', - 'password' = 'semprini' + 'username' = 'postgres', + 'password' = '${ODS_PASSWORD}' ); CREATE TABLE contact_address_cdc ( @@ -541,11 +541,11 @@ CREATE TABLE contact_address_cdc ( PRIMARY KEY (contact_address_id) NOT ENFORCED ) WITH ( 'connector' = 'postgres-cdc', - 'hostname' = 'postgres', + 'hostname' = 'ods', 'port' = '5432', - 'username' = 'semprini', - 'password' = 'semprini', - 'database-name' = 'digital', + 'username' = 'postgres', + 'password' = '${ODS_PASSWORD}', + 'database-name' = 'ods', 'schema-name' = 'canonical_party', 'table-name' = 'contact_address', 'slot.name' = 'canonical_party_contact_address_flink', @@ -601,10 +601,10 @@ CREATE TABLE party_role_contact_address_ods ( PRIMARY KEY (party_role_contact_address_id) NOT ENFORCED ) WITH ( 'connector' = 'jdbc', - 'url' = 'jdbc:postgresql://postgres:5432/digital?stringtype=unspecified', + 'url' = 'jdbc:postgresql://ods:5432/ods?stringtype=unspecified', 'table-name' = 'canonical_party.party_role_contact_address', - 'username' = 'semprini', - 'password' = 'semprini' + 'username' = 'postgres', + 'password' = '${ODS_PASSWORD}' ); CREATE TABLE party_role_contact_address_cdc ( @@ -615,11 +615,11 @@ CREATE TABLE party_role_contact_address_cdc ( PRIMARY KEY (party_role_contact_address_id) NOT ENFORCED ) WITH ( 'connector' = 'postgres-cdc', - 'hostname' = 'postgres', + 'hostname' = 'ods', 'port' = '5432', - 'username' = 'semprini', - 'password' = 'semprini', - 'database-name' = 'digital', + 'username' = 'postgres', + 'password' = '${ODS_PASSWORD}', + 'database-name' = 'ods', 'schema-name' = 'canonical_party', 'table-name' = 'party_role_contact_address', 'slot.name' = 'canonical_party_party_role_contact_address_flink', @@ -676,10 +676,10 @@ CREATE TABLE party_association_ods ( PRIMARY KEY (party_association_id) NOT ENFORCED ) WITH ( 'connector' = 'jdbc', - 'url' = 'jdbc:postgresql://postgres:5432/digital?stringtype=unspecified', + 'url' = 'jdbc:postgresql://ods:5432/ods?stringtype=unspecified', 'table-name' = 'canonical_party.party_association', - 'username' = 'semprini', - 'password' = 'semprini' + 'username' = 'postgres', + 'password' = '${ODS_PASSWORD}' ); CREATE TABLE party_association_cdc ( @@ -694,11 +694,11 @@ CREATE TABLE party_association_cdc ( PRIMARY KEY (party_association_id) NOT ENFORCED ) WITH ( 'connector' = 'postgres-cdc', - 'hostname' = 'postgres', + 'hostname' = 'ods', 'port' = '5432', - 'username' = 'semprini', - 'password' = 'semprini', - 'database-name' = 'digital', + 'username' = 'postgres', + 'password' = '${ODS_PASSWORD}', + 'database-name' = 'ods', 'schema-name' = 'canonical_party', 'table-name' = 'party_association', 'slot.name' = 'canonical_party_party_association_flink', diff --git a/canonical-party/graphql/schema.graphql b/canonical-party/graphql/schema.graphql index 854da18..f68ed21 100644 --- a/canonical-party/graphql/schema.graphql +++ b/canonical-party/graphql/schema.graphql @@ -2,7 +2,7 @@ # # 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:3000/rpc/canonical_party_graphql -H 'Content-Type: application/json' \ +# curl http://localhost:20000/rpc/canonical_party_graphql -H 'Content-Type: application/json' \ # --data '{"query":"{ __type(name: \"Party\") { fields { name } } }"}' # # Naming (inflect_names: true): table party_role -> type PartyRole; column role_status -> roleStatus. @@ -20,7 +20,7 @@ type Party implements Node { partyId: UUID! partyType: String! # discriminator: 'Person' | 'Company' legalName: String! - alsoKnownAs: String # semicolon-separated; see template/README.md type mapping + alsoKnownAs: String # semicolon-separated; see canonical_data_product/README.md type mapping partyStatus: String # enum:Party Status, enforced by CHECK in the ODS createdAt: Datetime! updatedAt: Datetime! diff --git a/canonical-party/graphql/smoke.graphql b/canonical-party/graphql/smoke.graphql index 61cf90e..036070e 100644 --- a/canonical-party/graphql/smoke.graphql +++ b/canonical-party/graphql/smoke.graphql @@ -1,4 +1,4 @@ -# Run by `semprini-blog-dataproducts test` against POST /rpc/canonical_party_graphql. +# Run by `data-domain test` against POST /rpc/canonical_party_graphql. # It must return a `data` object and no `errors`; it does not need to return rows. The # relationship traversals exercise the field names documented in schema.graphql. query CanonicalPartySmoke { diff --git a/canonical-party/lakehouse/010_replication.sql b/canonical-party/lakehouse/010_replication.sql index 851b3ca..ddac0c3 100644 --- a/canonical-party/lakehouse/010_replication.sql +++ b/canonical-party/lakehouse/010_replication.sql @@ -1,8 +1,8 @@ -- Canonical Party: 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 digital-lake bucket. The platform-level sync group `digital_oltp` already --- points at the ODS (see compose.yml); the product only registers its tables with it. +-- 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.canonical_party.
. CREATE SCHEMA IF NOT EXISTS canonical_party; @@ -10,53 +10,59 @@ CREATE SCHEMA IF NOT EXISTS canonical_party; SELECT duckpipe.add_table( 'canonical_party.party', target_table => 'canonical_party.party', - sync_group => 'digital_oltp' + sync_group => 'ods' ); SELECT duckpipe.add_table( 'canonical_party.address', target_table => 'canonical_party.address', - sync_group => 'digital_oltp' + sync_group => 'ods' ); SELECT duckpipe.add_table( 'canonical_party.person', target_table => 'canonical_party.person', - sync_group => 'digital_oltp' + sync_group => 'ods' ); SELECT duckpipe.add_table( 'canonical_party.company', target_table => 'canonical_party.company', - sync_group => 'digital_oltp' + sync_group => 'ods' ); SELECT duckpipe.add_table( 'canonical_party.party_role', target_table => 'canonical_party.party_role', - sync_group => 'digital_oltp' + sync_group => 'ods' ); SELECT duckpipe.add_table( 'canonical_party.customer', target_table => 'canonical_party.customer', - sync_group => 'digital_oltp' + sync_group => 'ods' ); SELECT duckpipe.add_table( 'canonical_party.contact_address', target_table => 'canonical_party.contact_address', - sync_group => 'digital_oltp' + sync_group => 'ods' ); SELECT duckpipe.add_table( 'canonical_party.party_role_contact_address', target_table => 'canonical_party.party_role_contact_address', - sync_group => 'digital_oltp' + sync_group => 'ods' ); SELECT duckpipe.add_table( 'canonical_party.party_association', target_table => 'canonical_party.party_association', - sync_group => 'digital_oltp' + sync_group => 'ods' ); + +-- 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. +GRANT USAGE ON SCHEMA canonical_party TO ducklake_reader, ducklake_writer; +GRANT SELECT ON ALL TABLES IN SCHEMA canonical_party TO ducklake_reader, ducklake_writer; diff --git a/canonical-party/odps.yaml b/canonical-party/odps.yaml index 127d603..fdf82fc 100644 --- a/canonical-party/odps.yaml +++ b/canonical-party/odps.yaml @@ -60,7 +60,7 @@ product: outputPorttype: API format: GraphQL authenticationMethod: none # lab stack only - accessURL: "http://localhost:3000/rpc/canonical_party_graphql" + accessURL: "http://localhost:20000/rpc/canonical_party_graphql" publish: name: en: Publish Input @@ -69,8 +69,8 @@ product: outputPorttype: API format: JSON authenticationMethod: none - accessURL: "kafka://localhost:9092/digital-core.canonical-party.
.inbound" - specsURL: "http://localhost:8082/apis/registry/v3/groups/digital-core.canonical-party/artifacts" + accessURL: "kafka://localhost:20001/digital-core.canonical-party.
.inbound" + specsURL: "http://localhost:8081/apis/registry/v3/groups/digital-core.canonical-party/artifacts" subscribe: name: en: Subscribe Output @@ -79,8 +79,8 @@ product: outputPorttype: API format: JSON authenticationMethod: none - accessURL: "kafka://localhost:9092/digital-core.canonical-party.
.outbound" - specsURL: "http://localhost:8082/apis/registry/v3/groups/digital-core.canonical-party/artifacts" + accessURL: "kafka://localhost:20001/digital-core.canonical-party.
.outbound" + specsURL: "http://localhost:8081/apis/registry/v3/groups/digital-core.canonical-party/artifacts" sql: name: en: Analytic SQL @@ -89,7 +89,7 @@ product: outputPorttype: SQL format: SQL authenticationMethod: none - accessURL: "jdbc:trino://localhost:8083/lake/canonical_party" + accessURL: "jdbc:trino://localhost:20003/lake/canonical_party" license: en: diff --git a/canonical-party/ods/010_schema.sql b/canonical-party/ods/010_schema.sql index 01c92ad..9920819 100644 --- a/canonical-party/ods/010_schema.sql +++ b/canonical-party/ods/010_schema.sql @@ -1,4 +1,4 @@ --- Canonical Party: operational data store schema (runs on the postgres service). +-- Canonical Party: operational data store schema (runs on the ods 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 diff --git a/canonical-party/ods/030_api.sql b/canonical-party/ods/030_api.sql index 0adb4e6..edeccd4 100644 --- a/canonical-party/ods/030_api.sql +++ b/canonical-party/ods/030_api.sql @@ -1,4 +1,4 @@ --- Canonical Party: API surface (runs on the postgres service). +-- Canonical Party: API surface (runs on the ods 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 diff --git a/canonical-party/ods/040_seed.sql b/canonical-party/ods/040_seed.sql index b7ab4fe..c0f441c 100644 --- a/canonical-party/ods/040_seed.sql +++ b/canonical-party/ods/040_seed.sql @@ -1,4 +1,4 @@ --- Canonical Party: sample rows (runs on the postgres service). +-- Canonical Party: sample rows (runs on the ods service). -- -- 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. The second uuid group numbers diff --git a/canonical-party/product.yaml b/canonical-party/product.yaml index b85d92d..fe2c23a 100644 --- a/canonical-party/product.yaml +++ b/canonical-party/product.yaml @@ -1,7 +1,7 @@ # Canonical Party: data product manifest. -# Read by `uv run semprini-blog-dataproducts deploy|test|undeploy products/canonical-party`. +# Read by `uv run data-domain deploy|test|undeploy canonical-party`, run from the domain repository. # Names every platform resource the product owns. Derived from the MD-DDL declaration -# named in `declaration`; see template/README.md for the naming rules. +# named in `declaration`; see canonical_data_product/README.md in semprini-data-product-templates. product: name: "Canonical Party" @@ -175,7 +175,7 @@ flink: name: "canonical-party" lakehouse: - sync_group: digital_oltp + sync_group: ods schema: "canonical_party" trino: diff --git a/canonical-party/tests/expectations.yaml b/canonical-party/tests/expectations.yaml new file mode 100644 index 0000000..d57593f --- /dev/null +++ b/canonical-party/tests/expectations.yaml @@ -0,0 +1,193 @@ +# Canonical Party: unit test expectations, generated with ods/040_seed.sql and kept in step with it. +# Read by the generic tests beside this file (test_*.py, copied from the canonical template). +# Run from the domain repository: uv run data-domain unit + +tables: + # rows: how many rows the seed inserts + # samples: seed rows checked by value in the ODS, through GraphQL and in the lake (the key + # column is required; the first sample is also the row the reject updates target) + # rejects: updates to the first sample the ODS must refuse, with the constraint named in the + # error ("not-null" for NOT NULL) + party: + rows: 4 + samples: + - party_id: 7d1e5a2c-0001-4a7b-9c11-000000000003 + party_type: Company + legal_name: Kowhai Trading Limited + also_known_as: "Kowhai Trading; KTL" + party_status: Active + rejects: + - set: {party_type: Robot} + violates: party_party_type_check + - set: {party_status: Dormant} + violates: party_party_status_check + - set: {legal_name: null} + violates: not-null + + address: + rows: 3 + samples: + - address_id: 7d1e5a2c-0002-4a7b-9c11-000000000001 + address_type: Street Address + address_line_1: 1 Queen Street + suburb: Auckland Central + city: Auckland + postcode: "1010" + country: NZ + rejects: + - set: {address_line_1: null} + violates: street_address_requires_address_line_1 + - set: {address_type: Castle} + violates: address_address_type_check + - set: {country: null} + violates: not-null + + person: + rows: 2 + samples: + - person_id: 7d1e5a2c-0001-4a7b-9c11-000000000001 + date_of_birth: 1985-03-14 + preferred_name: Alice + country_of_residence: NZ + rejects: + - set: {date_of_birth: "2999-01-01"} + violates: date_of_birth_not_in_future + - set: {person_id: 7d1e5a2c-0001-4a7b-9c11-00000000ffff} + violates: person_person_id_fkey + + company: + rows: 2 + samples: + - company_id: 7d1e5a2c-0001-4a7b-9c11-000000000004 + company_registration_number: "123456789" + incorporation_country: AU + incorporation_date: 2005-03-15 + legal_structure: Private Company + rejects: + - set: {legal_structure: Guild} + violates: company_legal_structure_check + + party_role: + rows: 3 + samples: + - party_role_id: 7d1e5a2c-0003-4a7b-9c11-000000000003 + party_role_type: Customer + role_status: Closed + role_start_date: 2021-03-01 + role_end_date: 2024-08-31 + party_id: 7d1e5a2c-0001-4a7b-9c11-000000000002 + rejects: + - set: {role_end_date: null} + violates: closed_role_requires_end_date + - set: {role_end_date: "2020-01-01"} + violates: role_end_after_start + - set: {party_role_type: Merchant} + violates: party_role_party_role_type_check + - set: {party_id: 7d1e5a2c-0001-4a7b-9c11-00000000ffff} + violates: party_role_party_id_fkey + + customer: + rows: 3 + samples: + - customer_id: 7d1e5a2c-0003-4a7b-9c11-000000000002 + customer_number: CUST-000002 + onboarding_date: 2018-06-01 + relationship_start_date: 2015-06-01 + rejects: + - set: {customer_number: CUST-000001} + violates: customer_customer_number_key + - set: {customer_number: null} + violates: not-null + + contact_address: + rows: 3 + samples: + - contact_address_id: 7d1e5a2c-0004-4a7b-9c11-000000000001 + address_purpose: Home + is_primary: true + verification_status: Verified + verification_date: 2024-02-10 + verification_method: Documentary + valid_from: 2019-12-01 + party_id: 7d1e5a2c-0001-4a7b-9c11-000000000001 + address_id: 7d1e5a2c-0002-4a7b-9c11-000000000001 + rejects: + - set: {verification_date: null} + violates: verification_date_required_when_verified + - set: {valid_to: "2019-01-01"} + violates: valid_to_after_valid_from + - set: {verification_method: Telepathy} + violates: contact_address_verification_method_check + - set: {address_id: 7d1e5a2c-0002-4a7b-9c11-00000000ffff} + violates: contact_address_address_id_fkey + + party_role_contact_address: + rows: 3 + samples: + - party_role_contact_address_id: 7d1e5a2c-0005-4a7b-9c11-000000000003 + party_role_id: 7d1e5a2c-0003-4a7b-9c11-000000000002 + contact_address_id: 7d1e5a2c-0004-4a7b-9c11-000000000003 + rejects: + - set: {party_role_id: 7d1e5a2c-0003-4a7b-9c11-00000000ffff} + violates: party_role_contact_address_party_role_id_fkey + + party_association: + rows: 3 + samples: + - party_association_id: 7d1e5a2c-0006-4a7b-9c11-000000000003 + source_party_id: 7d1e5a2c-0001-4a7b-9c11-000000000002 + target_party_id: 7d1e5a2c-0001-4a7b-9c11-000000000001 + association_type: Partner + association_start_date: 2016-06-01 + verified: false + rejects: + - set: {association_type: Nemesis} + violates: party_association_association_type_check + - set: {target_party_id: null} + violates: not-null + +# Relationship traversals in graphql/schema.graphql, checked against the seed. `expect` must be +# contained in the response (lists compare item by item, in order). +graphql: + - name: person-extends-party + query: '{ personCollection(filter: {personId: {eq: "7d1e5a2c-0001-4a7b-9c11-000000000001"}}) { edges { node { preferredName party { legalName partyType } } } } }' + expect: + personCollection: {edges: [{node: {preferredName: Alice, party: {legalName: Alice Margaret Ng, partyType: Person}}}]} + - name: party-has-its-company-subtype + query: '{ partyCollection(filter: {partyId: {eq: "7d1e5a2c-0001-4a7b-9c11-000000000004"}}) { edges { node { company { incorporationCountry } person { preferredName } } } } }' + expect: + partyCollection: {edges: [{node: {company: {incorporationCountry: AU}, person: null}}]} + - name: customer-role-of-party + query: '{ customerCollection(filter: {customerNumber: {eq: "CUST-000001"}}) { edges { node { partyRole { roleStatus party { legalName } } } } } }' + expect: + customerCollection: {edges: [{node: {partyRole: {roleStatus: Active, party: {legalName: Alice Margaret Ng}}}}]} + - name: role-uses-contact-addresses + query: '{ partyRoleCollection(filter: {partyRoleId: {eq: "7d1e5a2c-0003-4a7b-9c11-000000000001"}}) { edges { node { partyRoleContactAddressCollection(orderBy: [{partyRoleContactAddressId: AscNullsLast}]) { edges { node { contactAddress { addressPurpose address { city } } } } } } } } }' + expect: + partyRoleCollection: {edges: [{node: {partyRoleContactAddressCollection: {edges: [ + {node: {contactAddress: {addressPurpose: Home, address: {city: Auckland}}}}, + {node: {contactAddress: {addressPurpose: Mailing, address: {city: Wellington}}}}]}}}]} + - name: associations-are-directional + query: '{ partyCollection(filter: {partyId: {eq: "7d1e5a2c-0001-4a7b-9c11-000000000001"}}) { edges { node { outgoingAssociationCollection(orderBy: [{partyAssociationId: AscNullsLast}]) { edges { node { associationType targetParty { legalName } } } } incomingAssociationCollection { edges { node { associationType sourceParty { legalName } } } } } } } }' + expect: + partyCollection: {edges: [{node: { + outgoingAssociationCollection: {edges: [ + {node: {associationType: Director, targetParty: {legalName: Kowhai Trading Limited}}}, + {node: {associationType: Authorised Signatory, targetParty: {legalName: Kowhai Trading Limited}}}]}, + incomingAssociationCollection: {edges: [ + {node: {associationType: Partner, sourceParty: {legalName: Rangi Parata}}}]}}}]} + +# One record published to an inbound topic and followed through every interface, then updated +# and deleted through GraphQL. Use a table without required foreign keys, and a key no seed row +# uses; the test refuses to publish a record the ODS would reject. +round_trip: + table: address + record: + address_id: 7d1e5a2c-0002-4a7b-9c11-00000000e2e0 + address_type: PO Box + address_line_1: PO Box 999 + city: Nelson + postcode: "7040" + country: NZ + update: + city: Richmond diff --git a/canonical-party/tests/test_constraints.py b/canonical-party/tests/test_constraints.py new file mode 100644 index 0000000..046240a --- /dev/null +++ b/canonical-party/tests/test_constraints.py @@ -0,0 +1,48 @@ +"""Constraints and triggers: the ODS refuses what the model forbids, and keeps updated_at current. + +Every statement runs in a transaction that is rolled back, so the seed is untouched. Each +rejected update in expectations.yaml is applied to the table's first sample row and must fail +with the named constraint (or "not-null") in PostgreSQL's error. +""" + +import pytest + +from semprini_data_domain.testing import expectations_for + +TABLES = list(expectations_for(__file__)["tables"].items()) +REJECTS = [(table, reject) for table, spec in TABLES for reject in spec.get("rejects", [])] + + +def key_of(dp, table): + return next(t.key for t in dp.product.tables if t.name == table) + + +def first_sample_key(dp, table, spec): + assert spec.get("samples"), f"{table} needs a sample in expectations.yaml" + return spec["samples"][0][key_of(dp, table)] + + +@pytest.mark.parametrize( + "table,reject", REJECTS, ids=[f"{t}-{r['violates']}" for t, r in REJECTS] +) +def test_update_is_refused(dp, table, reject): + spec = dict(TABLES)[table] + key = key_of(dp, table) + assignments = ", ".join(f"{column} = {dp.sql_literal(value)}" for column, value in reject["set"].items()) + error = dp.sql_error( + f"UPDATE {dp.product.schema}.{table} SET {assignments} " + f"WHERE {key} = '{first_sample_key(dp, table, spec)}'" + ) + assert error is not None, f"{table}: update {reject['set']} was accepted" + assert reject["violates"] in error, error + + +@pytest.mark.parametrize("table,spec", TABLES, ids=[t for t, _ in TABLES]) +def test_update_sets_updated_at(dp, table, spec): + key = key_of(dp, table) + sample_key = first_sample_key(dp, table, spec) + rows = dp.sql_rolled_back( + f"UPDATE {dp.product.schema}.{table} SET {key} = {key} WHERE {key} = '{sample_key}'", + f"SELECT updated_at > created_at AS moved FROM {dp.product.schema}.{table} WHERE {key} = '{sample_key}'", + ) + assert rows == [{"moved": True}] diff --git a/canonical-party/tests/test_graphql.py b/canonical-party/tests/test_graphql.py new file mode 100644 index 0000000..d8ac7b4 --- /dev/null +++ b/canonical-party/tests/test_graphql.py @@ -0,0 +1,47 @@ +"""CRUD API: pg_graphql reflects every column of every table, serves the seed rows, and +resolves the relationships the product documents in graphql/schema.graphql. +""" + +import pytest + +from semprini_data_domain.platform import camel, pascal +from semprini_data_domain.testing import contains, expectations_for, same_value + +EXPECT = expectations_for(__file__) +TABLES = list(EXPECT["tables"].items()) +SAMPLES = [(table, sample) for table, spec in TABLES for sample in spec.get("samples", [])] +QUERIES = EXPECT.get("graphql", []) + + +def key_of(dp, table): + return next(t.key for t in dp.product.tables if t.name == table) + + +@pytest.mark.parametrize("table,spec", TABLES, ids=[t for t, _ in TABLES]) +def test_type_reflects_every_column(dp, table, spec): + data = dp.graphql(f'{{ __type(name: "{pascal(table)}") {{ fields {{ name }} }} }}') + assert data["__type"], f"type {pascal(table)} not reflected" + fields = {f["name"] for f in data["__type"]["fields"]} + missing = [camel(c) for c in dp.columns(table) if camel(c) not in fields] + assert not missing, f"{pascal(table)} lacks {missing}" + + +@pytest.mark.parametrize("table,sample", SAMPLES, ids=[t for t, _ in SAMPLES]) +def test_seed_row_through_graphql(dp, table, sample): + key = key_of(dp, table) + fields = " ".join(camel(column) for column in sample) + data = dp.graphql( + f'{{ {camel(table)}Collection(filter: {{{camel(key)}: {{eq: "{sample[key]}"}}}}) ' + f"{{ edges {{ node {{ {fields} }} }} }} }}" + ) + edges = data[f"{camel(table)}Collection"]["edges"] + assert len(edges) == 1, f"{table} {sample[key]}: {edges}" + node = edges[0]["node"] + for column, expected in sample.items(): + assert same_value(expected, node[camel(column)]), f"{camel(column)}: {node[camel(column)]!r} != {expected!r}" + + +@pytest.mark.parametrize("case", QUERIES, ids=[q["name"] for q in QUERIES]) +def test_relationship(dp, case): + data = dp.graphql(case["query"]) + assert contains(case["expect"], data), f"{data} does not contain {case['expect']}" diff --git a/canonical-party/tests/test_lake.py b/canonical-party/tests/test_lake.py new file mode 100644 index 0000000..d16802f --- /dev/null +++ b/canonical-party/tests/test_lake.py @@ -0,0 +1,33 @@ +"""Analytic SQL: pg_duckpipe has replicated every seed row into the lake, and Trino serves it.""" + +import pytest + +from semprini_data_domain.testing import expectations_for, same_value + +TABLES = list(expectations_for(__file__)["tables"].items()) +SAMPLES = [(table, sample) for table, spec in TABLES for sample in spec.get("samples", [])] + + +def key_of(dp, table): + return next(t.key for t in dp.product.tables if t.name == table) + + +@pytest.mark.parametrize("table,spec", TABLES, ids=[t for t, _ in TABLES]) +def test_lake_matches_ods(dp, table, spec): + lake = f"{dp.product.trino_catalog}.{dp.product.lake_schema}.{table}" + ods = dp.sql(f"SELECT count(*) AS n FROM {dp.product.schema}.{table}")[0]["n"] + assert ods == spec["rows"] + dp.eventually(lambda: dp.trino(f"SELECT count(*) AS n FROM {lake}") == [{"n": ods}]) + + +@pytest.mark.parametrize("table,sample", SAMPLES, ids=[t for t, _ in SAMPLES]) +def test_seed_row_in_lake(dp, table, sample): + key = key_of(dp, table) + lake = f"{dp.product.trino_catalog}.{dp.product.lake_schema}.{table}" + # Every column is cast to varchar so dates and uuids compare as text, the way the seed writes them. + columns = ", ".join(f"CAST({column} AS varchar) AS {column}" for column in sample) + rows = dp.trino(f"SELECT {columns} FROM {lake} WHERE CAST({key} AS varchar) = '{sample[key]}'") + assert len(rows) == 1, f"{sample[key]} not in {lake}" + for column, expected in sample.items(): + want = None if expected is None else (str(expected).lower() if isinstance(expected, bool) else expected) + assert same_value(want, rows[0][column]), f"{column}: {rows[0][column]!r} != {expected!r}" diff --git a/canonical-party/tests/test_seed.py b/canonical-party/tests/test_seed.py new file mode 100644 index 0000000..979185a --- /dev/null +++ b/canonical-party/tests/test_seed.py @@ -0,0 +1,31 @@ +"""Seed data: every ODS table holds the rows ods/040_seed.sql inserts, with the values it inserts. + +Generic canonical-product test, copied unchanged into every product. What to expect comes +from expectations.yaml beside it. Run from the domain repository: data-domain unit . +""" + +import pytest + +from semprini_data_domain.testing import expectations_for, same_value + +TABLES = list(expectations_for(__file__)["tables"].items()) +SAMPLES = [(table, sample) for table, spec in TABLES for sample in spec.get("samples", [])] + + +def key_of(dp, table): + return next(t.key for t in dp.product.tables if t.name == table) + + +@pytest.mark.parametrize("table,spec", TABLES, ids=[t for t, _ in TABLES]) +def test_seed_row_count(dp, table, spec): + rows = dp.sql(f"SELECT count(*) AS n FROM {dp.product.schema}.{table}") + assert rows[0]["n"] == spec["rows"] + + +@pytest.mark.parametrize("table,sample", SAMPLES, ids=[t for t, _ in SAMPLES]) +def test_seed_row_values(dp, table, sample): + key = key_of(dp, table) + rows = dp.sql(f"SELECT * FROM {dp.product.schema}.{table} WHERE {key} = '{sample[key]}'") + assert len(rows) == 1, f"seed row {sample[key]} not in {table}" + for column, expected in sample.items(): + assert same_value(expected, rows[0][column]), f"{table}.{column}: {rows[0][column]!r} != {expected!r}" diff --git a/canonical-party/tests/test_streams.py b/canonical-party/tests/test_streams.py new file mode 100644 index 0000000..190623e --- /dev/null +++ b/canonical-party/tests/test_streams.py @@ -0,0 +1,75 @@ +"""Publish input and subscribe output. + +Every row is on the table's compacted outbound topic, and one record published to an inbound +topic travels through every interface: ODS, outbound topic, lake, then a GraphQL update and a +GraphQL delete that follow it back out. The record is checked against the ODS constraints +before it is published, because a record the ODS refuses stops the product's Flink job. +""" + +import pytest + +from semprini_data_domain.platform import camel, pascal +from semprini_data_domain.testing import contains, expectations_for + +EXPECT = expectations_for(__file__) +TABLES = list(EXPECT["tables"].items()) +ROUND_TRIP = EXPECT.get("round_trip") + + +def key_of(dp, table): + return next(t.key for t in dp.product.tables if t.name == table) + + +@pytest.mark.parametrize("table,spec", TABLES, ids=[t for t, _ in TABLES]) +def test_outbound_topic_carries_every_row(dp, table, spec): + key = key_of(dp, table) + ods_keys = {r[key] for r in dp.sql(f"SELECT {key} FROM {dp.product.schema}.{table}")} + topic = dp.topic(table, "subscribe-output") + dp.eventually(lambda: ods_keys <= {k for k, v in dp.latest(topic).items() if v is not None}, timeout=60) + + +@pytest.mark.skipif(not ROUND_TRIP, reason="no round_trip in expectations.yaml") +def test_record_round_trip(dp): + table, record, update = ROUND_TRIP["table"], ROUND_TRIP["record"], ROUND_TRIP["update"] + schema, key = dp.product.schema, key_of(dp, table) + record_key = record[key] + lake = f"{dp.product.trino_catalog}.{dp.product.lake_schema}.{table}" + outbound = dp.topic(table, "subscribe-output") + columns = ", ".join(record) + values = ", ".join(dp.sql_literal(v) for v in record.values()) + where = f"{key} = '{record_key}'" + + assert not dp.sql(f"SELECT 1 FROM {schema}.{table} WHERE {where}"), f"{record_key} already exists; clean up first" + refused = dp.sql_error(f"INSERT INTO {schema}.{table} ({columns}) VALUES ({values})") + assert refused is None, f"the ODS would refuse the round-trip record, so it is not published: {refused}" + + try: + # Publish input -> Flink -> ODS + dp.publish(dp.topic(table, "publish-input"), [record]) + dp.eventually(lambda: contains(record, (dp.sql(f"SELECT * FROM {schema}.{table} WHERE {where}") or [None])[0])) + + # ODS -> Flink CDC -> subscribe output, and ODS -> pg_duckpipe -> lake + dp.eventually(lambda: contains(record, dp.latest(outbound).get(record_key))) + dp.eventually(lambda: dp.trino(f"SELECT count(*) AS n FROM {lake} WHERE CAST({key} AS varchar) = '{record_key}'") == [{"n": 1}]) + + # CRUD API update -> subscribe output and lake + assignments = ", ".join(f'{camel(c)}: "{v}"' for c, v in update.items()) + data = dp.graphql( + f"mutation {{ update{pascal(table)}Collection(set: {{{assignments}}}, " + f'filter: {{{camel(key)}: {{eq: "{record_key}"}}}}) {{ affectedCount }} }}' + ) + assert data[f"update{pascal(table)}Collection"]["affectedCount"] == 1 + dp.eventually(lambda: contains(update, dp.latest(outbound).get(record_key))) + column, value = next(iter(update.items())) + dp.eventually(lambda: dp.trino(f"SELECT CAST({column} AS varchar) AS v FROM {lake} WHERE CAST({key} AS varchar) = '{record_key}'") == [{"v": str(value)}]) + + # CRUD API delete -> tombstone on subscribe output, row gone from the lake + data = dp.graphql( + f"mutation {{ deleteFrom{pascal(table)}Collection(" + f'filter: {{{camel(key)}: {{eq: "{record_key}"}}}}, atMost: 1) {{ affectedCount }} }}' + ) + assert data[f"deleteFrom{pascal(table)}Collection"]["affectedCount"] == 1 + dp.eventually(lambda: (lambda state: record_key in state and state[record_key] is None)(dp.latest(outbound))) + dp.eventually(lambda: dp.trino(f"SELECT count(*) AS n FROM {lake} WHERE CAST({key} AS varchar) = '{record_key}'") == [{"n": 0}]) + finally: + dp.execute(f"DELETE FROM {schema}.{table} WHERE {where}") diff --git a/canonical-party/trino/smoke.sql b/canonical-party/trino/smoke.sql index 9e2abd9..8a368eb 100644 --- a/canonical-party/trino/smoke.sql +++ b/canonical-party/trino/smoke.sql @@ -1,4 +1,4 @@ --- Canonical Party: analytic SQL smoke test, run by `semprini-blog-dataproducts test` +-- Canonical Party: analytic SQL smoke test, run by `data-domain test` -- through Trino's `lake` catalog. One statement per table and each must succeed. SELECT 'party' AS table_name, count(*) AS row_count FROM lake.canonical_party.party;