diff --git a/README.md b/README.md index 37cadda..c477f88 100644 --- a/README.md +++ b/README.md @@ -15,9 +15,22 @@ shared a repository with its platform, model and products. | 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, with generic unit tests. Example verified 2026-09-18 on the domain platform (9 checks, 12 unit tests); Canonical Party generated from it passes 65 checks and 100 unit tests | -| `source_aligned_data_product/` | Source aligned: one source system's data in its own shape, for audit, replay and debugging | `source-aligned` | Planned | +| [source_aligned_cdc_data_product/](source_aligned_cdc_data_product/README.md) | Source aligned, one product per source system: capture by CDC where there is database access, then the semantic and protocol transform into what a canonical product accepts | `source-aligned` | Available. Runs on the Integration Bus with the `data-bus` CLI. Example verified 2026-09-18: 12 smoke checks, 37 unit tests, ERP customers delivered into Canonical Party | +| `source_aligned_file_data_product/` | Source aligned: the source produces files, which become a stream; files land in the bus object store's `files/` bucket | `source-aligned` | Planned, designed | +| `source_aligned_api_data_product/`, `source_aligned_bus_data_product/` | Source aligned: polling or webhooks; or a bridge from a bus the source already publishes to | `source-aligned` | Planned | | `experience__data_product/` | Experience: shaped for an audience. Several classes, e.g. lake tables built by scheduled dbt models | `consumer-aligned` | Planned | +A canonical product accepts records only on its inbound topics (registered schema, keyed by the +entity's identifier) or through its GraphQL API, so a source-aligned product owns both the +protocol and the semantic transform into that contract, and owns the dead-letter queue for what +it cannot transform. It also archives every raw record to the bus object store, so the records +outlive the topic and can be replayed. The design and the shared contract for the family are in +semprini-data `docs/source-aligned-products.md`. + +The two classes are deployed by different CLIs, because they run in different places: canonical +products by `data-domain`, from the domain repository that runs them; source-aligned products by +`data-bus`, from a semprini-data checkout. + ## Where templates sit between the teams ``` diff --git a/canonical_data_product/example/flink/job.sql b/canonical_data_product/example/flink/job.sql index a48f70c..402840b 100644 --- a/canonical_data_product/example/flink/job.sql +++ b/canonical_data_product/example/flink/job.sql @@ -1,5 +1,8 @@ -- 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. +-- 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. +-- address_inbound reads records keyed by address_id: only messages sharing a key share a +-- partition, and only one partition keeps them in order. SET 'pipeline.name' = 'example-address'; SET 'execution.checkpointing.interval' = '10 s'; diff --git a/canonical_data_product/example/odps.yaml b/canonical_data_product/example/odps.yaml index 46cfc8f..a2b7800 100644 --- a/canonical_data_product/example/odps.yaml +++ b/canonical_data_product/example/odps.yaml @@ -53,7 +53,7 @@ product: name: en: Publish Input description: - en: "Kafka topic accepting canonical Address records." + en: "Kafka topic accepting canonical Address records, keyed by address_id, which is what keeps changes to one address in order." outputPorttype: API format: JSON authenticationMethod: none diff --git a/canonical_data_product/example/product.yaml b/canonical_data_product/example/product.yaml index 72e5d72..022451f 100644 --- a/canonical_data_product/example/product.yaml +++ b/canonical_data_product/example/product.yaml @@ -27,6 +27,7 @@ events: topics: - name: "digital-core.example-address.address.inbound" role: publish-input + key: "address_id" # producers MUST key by this: order holds per key, per partition table: "address" schema: events/schemas/address.schema.json partitions: 3 @@ -34,6 +35,7 @@ events: retention_ms: 604800000 - name: "digital-core.example-address.address.outbound" role: subscribe-output + key: "address_id" # set by the Flink upsert-kafka sink table: "address" schema: events/schemas/address.schema.json partitions: 3 diff --git a/canonical_data_product/example/tests/test_streams.py b/canonical_data_product/example/tests/test_streams.py index 190623e..d8ce3f3 100644 --- a/canonical_data_product/example/tests/test_streams.py +++ b/canonical_data_product/example/tests/test_streams.py @@ -43,15 +43,25 @@ def test_record_round_trip(dp): 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}" + inbound = next(t for t in dp.product.topics if t.table == table and t.role == "publish-input") + assert inbound.key, f"{inbound.name} declares no key in product.yaml; producers cannot keep changes in order" + try: - # Publish input -> Flink -> ODS - dp.publish(dp.topic(table, "publish-input"), [record]) + # Publish input -> Flink -> ODS, keyed as the contract requires + dp.publish(inbound.name, [record], key_field=inbound.key) 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}]) + # Two more, published in order under the same key: one partition, so the last one wins + column, value = next(iter(update.items())) + ordered = [dict(record, **{column: f"{value} first"}), dict(record, **{column: f"{value} second"})] + dp.publish(inbound.name, ordered, key_field=inbound.key) + dp.eventually(lambda: (dp.sql(f"SELECT {column} FROM {schema}.{table} WHERE {where}") or [{}])[0].get(column) + == f"{value} second") + # CRUD API update -> subscribe output and lake assignments = ", ".join(f'{camel(c)}: "{v}"' for c, v in update.items()) data = dp.graphql( @@ -60,7 +70,6 @@ def test_record_round_trip(dp): ) 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 diff --git a/canonical_data_product/flink/job.sql b/canonical_data_product/flink/job.sql index dece9cd..f0ca0e4 100644 --- a/canonical_data_product/flink/job.sql +++ b/canonical_data_product/flink/job.sql @@ -3,7 +3,9 @@ -- ${ODS_PASSWORD} is substituted from the domain's .env at submission and never committed. -- -- Per entity table, four Flink tables and two continuous INSERTs: --- _inbound kafka Publish Input: records producers publish (JSON, schema in events/schemas) +--
_inbound kafka Publish Input: records producers publish (JSON, schema in events/schemas), +-- keyed by
_id: only messages sharing a key share a partition, +-- and only one partition keeps them in order --
_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 diff --git a/canonical_data_product/odps.yaml b/canonical_data_product/odps.yaml index b9b3b5c..c6059fe 100644 --- a/canonical_data_product/odps.yaml +++ b/canonical_data_product/odps.yaml @@ -60,7 +60,7 @@ product: 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." + en: "Kafka topics that accept canonical records, one per entity. JSON payloads conform to the schema registered for the topic, and each message is keyed by the entity's identifier, which is what keeps changes to one entity in order." outputPorttype: API format: JSON authenticationMethod: none diff --git a/canonical_data_product/product.yaml b/canonical_data_product/product.yaml index cbc0c95..d2d2ee7 100644 --- a/canonical_data_product/product.yaml +++ b/canonical_data_product/product.yaml @@ -32,6 +32,7 @@ events: - name: "{{domain.slug}}.{{product.slug}}.{{table}}.inbound" role: publish-input # producers publish canonical records here table: "{{table}}" + key: "{{table}}_id" # producers MUST key by this: order holds per key, per partition schema: events/schemas/{{table}}.schema.json partitions: 3 cleanup_policy: delete @@ -39,6 +40,7 @@ events: - name: "{{domain.slug}}.{{product.slug}}.{{table}}.outbound" role: subscribe-output # every change to the ODS table, keyed by {{table}}_id table: "{{table}}" + key: "{{table}}_id" # set by the Flink upsert-kafka sink schema: events/schemas/{{table}}.schema.json partitions: 3 cleanup_policy: compact diff --git a/canonical_data_product/tests/test_streams.py b/canonical_data_product/tests/test_streams.py index 190623e..d8ce3f3 100644 --- a/canonical_data_product/tests/test_streams.py +++ b/canonical_data_product/tests/test_streams.py @@ -43,15 +43,25 @@ def test_record_round_trip(dp): 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}" + inbound = next(t for t in dp.product.topics if t.table == table and t.role == "publish-input") + assert inbound.key, f"{inbound.name} declares no key in product.yaml; producers cannot keep changes in order" + try: - # Publish input -> Flink -> ODS - dp.publish(dp.topic(table, "publish-input"), [record]) + # Publish input -> Flink -> ODS, keyed as the contract requires + dp.publish(inbound.name, [record], key_field=inbound.key) 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}]) + # Two more, published in order under the same key: one partition, so the last one wins + column, value = next(iter(update.items())) + ordered = [dict(record, **{column: f"{value} first"}), dict(record, **{column: f"{value} second"})] + dp.publish(inbound.name, ordered, key_field=inbound.key) + dp.eventually(lambda: (dp.sql(f"SELECT {column} FROM {schema}.{table} WHERE {where}") or [{}])[0].get(column) + == f"{value} second") + # CRUD API update -> subscribe output and lake assignments = ", ".join(f'{camel(c)}: "{v}"' for c, v in update.items()) data = dp.graphql( @@ -60,7 +70,6 @@ def test_record_round_trip(dp): ) 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 diff --git a/source_aligned_cdc_data_product/README.md b/source_aligned_cdc_data_product/README.md new file mode 100644 index 0000000..84e7cf0 --- /dev/null +++ b/source_aligned_cdc_data_product/README.md @@ -0,0 +1,177 @@ +# source_aligned_cdc_data_product + +The template for a **source-aligned data product whose source system has a database you can +read**. One product per source system. It captures the system's tables by change data capture, +keeps the source's own records, and turns them into what a canonical data product accepts. + +It runs on the **Integration Bus** (semprini-data `compose.data-bus.yml`), not inside a domain: +capture is shared infrastructure and one source system often feeds several domains. The CLI is +`data-bus`, and this document is the contract between what the template produces and what that +CLI applies. + +Verified 2026-09-18 on the bus with the worked [example/](example/) — 12 smoke checks, 37 unit +tests — delivering ERP customers into Canonical Party in the digital-core domain. + +## What a source-aligned product is responsible for + +A canonical product accepts exactly two things: records on its inbound Kafka topics, in the +JSON Schema registered for the topic and keyed by the entity's identifier, or calls to its +GraphQL API. Nothing writes to its ODS. So this product owns both transforms: + +| | From | To | +|---|---|---| +| **Protocol** | change events in the source's wire format | Kafka records with a registered schema | +| **Semantic** | the source system's names, types, codes and keys | the canonical model's entities, enums and identifiers | + +``` + source DB ──Debezium──▶ raw... ──Flink──▶ ..
.inbound + │ │ + s3://raw//… └──rejected──▶ .dlq + (archive, for replay) (record + reason) +``` + +Five properties the template exists to guarantee, and the tests that hold it to them: + +| Property | Why | Test | +|---|---|---| +| **Raw records are kept** in the source's own shape | Canonical records can be rebuilt without going back to the source, and an engineer can see what was actually sent | `test_capture.py` | +| **Identity is deterministic** | A re-snapshot upserts rather than duplicating | `test_transform.py` | +| **Every record is validated before publishing** | A record the canonical ODS refuses fails its Flink job's JDBC sink, which takes down every job on that TaskManager | `test_dlq.py` | +| **Records are keyed by the canonical identifier** | Only a key keeps changes to one entity in order | `test_transform.py` | +| **The archive can be replayed** | Topics age out; source records have to stay reproducible | `test_archive.py` | + +## What the CLI does with it + +| `data-bus` | Reads | Does | +|---|---|---| +| `fixture up\|down` | `capture.fixture` | Starts or stops the test stand-in for the source system | +| `deploy` | the whole manifest | Creates the topics, registers the schemas in Apicurio, checks the target's inbound topics exist, registers the connector on bus-connect, submits the transform | +| `test` | the whole manifest | Smoke-tests topics, schemas, connector, transform, targets, archive and dead-letter depth | +| `unit` | `tests/` | Runs pytest with the bus fixtures against the deployed product | +| `replay` | `archive.replay` | Puts archived raw records back on the raw topic, for a date range | +| `register` / `unregister` | `odps.yaml` | Publishes the product and its topics in OpenMetadata, with lineage into the canonical product | +| `undeploy` | the whole manifest | Cancels the transform, discards the capture position, deletes the connector, topics and schemas | + +## Layout + +``` +/ +├── product.yaml the manifest: the contract above, filled in +├── odps.yaml the catalogue entry (ODPS v4) +├── connectors/.json Debezium connector config; credentials as ${NAME} +├── events/schemas/ +│ ├── raw....json the raw contract: the source's shape +│ ├── .dlq.json the dead-letter contract +│ └── .dlq.capture.json what Connect could not parse at all +├── flink/job.sql capture → canonical: identity, mapping, validation, archive +├── flink/replay.sql archive → raw topic, for `data-bus replay` +├── fixture/ a stand-in for the source system, for tests only +│ ├── compose.fixture.yml +│ └── init/010_.sql its schema and a seed, including rows that must be rejected +└── tests/ + ├── expectations.yaml everything specific to this product + ├── conftest.py, test_*.py generic: copy them unchanged + └── capture, transform, dead letters, delivery, archive +``` + +The test modules are the same in every product of this class. Only `expectations.yaml` changes. + +## Placeholders + +| Placeholder | Meaning | Example | +|---|---|---| +| `{{product_name}}`, `{{slug}}` | The product | `ERP Party`, `erp-party` | +| `{{system}}` | Source system id; names topics, registry group, DLQ, archive | `erp` | +| `{{source_host}}`, `{{source_db_name}}`, `{{source_db_user}}` | How to reach the source database | `erp-db.internal`, `erp`, `debezium` | +| `{{source_schema}}`, `{{source_object}}`, `{{source_key}}` | The object captured and its key | `public`, `customer`, `id` | +| `{{slot_name}}` | The replication slot, one per connector | `erp_party` | +| `{{target_domain}}`, `{{target_product}}`, `{{target_product_name}}` | The canonical product fed | `digital-core`, `canonical-party`, `Canonical Party` | +| `{{target_table}}`, `{{target_key}}` | Its table and identifier | `party`, `party_id` | +| `{{catalogue_domain}}`, `{{owner_email}}` | Catalogue placement and owner | `digital-core`, `integration@example.com` | + +`${NAME}` and `${NAME:-default}` are **not** placeholders: they are substituted when the product +is deployed, from the environment or semprini-data `.env`. The connector's `${SOURCE_PASSWORD}` +is the one to rename per system (`ERP_SOURCE_PASSWORD`) when several products share an `.env`. +The transform gets `${BUS_KAFKA}`, `${TARGET_BOOTSTRAP}`, `${RAW_TOPIC}`, `${DLQ}` and +`${ARCHIVE_PATH}` from the manifest; the replay job also gets `${SINCE}` and `${UNTIL}`. + +## Generating one + +What the generating agent needs: + +1. The **source system's schema** for the objects to capture: columns, types, keys, and the + meaning of its codes. This is the part no model holds. +2. The **canonical product's contract**: the inbound topic, its JSON Schema, its key, and the + rules its ODS enforces (NOT NULLs, CHECK constraints, enums). Read them from the canonical + product's `events/schemas/*.json` and `ods/*.sql`. +3. The **mapping** between them, including how every source code becomes a model enum value, + and what makes a record unacceptable. + +Then: fill the placeholders, write the mapping and the reason expression in `flink/job.sql`, +write `tests/expectations.yaml` from the fixture's seed, and run + +``` +uv run data-bus fixture up # only if the source is not reachable +uv run data-bus deploy +uv run data-bus test +uv run data-bus unit +uv run data-bus register +``` + +from a semprini-data checkout, with the bus and the target domain running. + +## Type mapping + +Debezium's JSON, with `schemas.enable=false` and the default `time.precision.mode`: + +| PostgreSQL | On the raw topic | Declare in Flink | Canonical side | +|---|---|---|---| +| `int2`, `int4` | number | `INT` | as modelled | +| `int8` | number | `BIGINT` | as modelled | +| `text`, `varchar`, `char` | string | `STRING` | `STRING` | +| `bool` | boolean | `BOOLEAN` | `BOOLEAN` | +| `date` | days since 1970-01-01 | `INT` | `DATE_FORMAT(TO_TIMESTAMP_LTZ(d * 86400000, 3), 'yyyy-MM-dd')` | +| `timestamp` | epoch microseconds | `BIGINT` | `TO_TIMESTAMP_LTZ(t / 1000, 3)` | +| `timestamptz` | ISO-8601 string | `STRING` | as it stands | +| `numeric` | base64 string (unless `decimal.handling.mode=string`) | `STRING` | set `decimal.handling.mode=string` on the connector | +| `uuid` | string | `STRING` | `STRING` | +| `json`, `jsonb` | string | `STRING` | parse in SQL if fields are needed | + +## Prerequisites + +* The bus is running with its object store: `./stack-data.sh up bus` in semprini-data. +* The target domain is running, and its Kafka joins `semprini_bus` as `kafka-:39092` + (every domain built on semprini-data-domain does). +* The target canonical product is deployed, so its inbound topics exist. `deploy` warns rather + than failing if they do not, because a product may legitimately be deployed first. +* For PostgreSQL sources: `wal_level=logical`, a role that may replicate, and + `REPLICA IDENTITY FULL` on the captured tables if updates and deletes must carry the old row. + +## What this template does not do + +* **It fills one canonical table.** A canonical product's subtype and child tables (Person under + Party, Contact Address under Party Role) have foreign keys to their parents, and publishing a + child before its parent has arrived fails the canonical product's JDBC sink. Kafka gives no + ordering across topics, so a product that must fill both waits for the canonical product to + accept a composite record. Until then: one table, the parent. +* **It does not delete.** A canonical product's inbound contract has no delete, so a CDC delete + is sent to the dead-letter topic with that reason rather than silently dropped. Removing a + party is done through the canonical product's own interface. +* **It does not validate against the registered JSON Schema.** Validation is the SQL in the + transform, written from the canonical product's rules. The two can drift; the tests are what + catch it. +* **It carries no history.** The raw topic and the archive hold what the source sent, in order; + what a record looked like at a point in time is the canonical product's lake, not this. +* **One replication slot per connector.** Capturing many tables from one system means one + connector with several tables in `table.include.list`, not one product per table. + +## Known gaps + +* `data-bus undeploy` discards the connector's capture position but does not drop the source's + replication slot: that needs a privileged connection to the source. Drop it by hand + (`SELECT pg_drop_replication_slot('')`) or set `slot.drop.on.stop` on a lab connector. +* The archive is written by the same Flink job as the transform, so an object-store failure + fails the product's job. Splitting them costs a second job and a second checkpoint. +* Connect's own dead letters land on `.dlq.capture` with the payload unchanged, so that + topic has no useful schema — its contract is "whatever could not be parsed, with the failure + in the headers". diff --git a/source_aligned_cdc_data_product/connectors/{{slug}}.json b/source_aligned_cdc_data_product/connectors/{{slug}}.json new file mode 100644 index 0000000..3514d6f --- /dev/null +++ b/source_aligned_cdc_data_product/connectors/{{slug}}.json @@ -0,0 +1,38 @@ +{ + "name": "{{slug}}", + "config": { + "connector.class": "io.debezium.connector.postgresql.PostgresConnector", + + "database.hostname": "{{source_host}}", + "database.port": "5432", + "database.dbname": "{{source_db_name}}", + "database.user": "{{source_db_user}}", + "database.password": "${SOURCE_PASSWORD}", + + "topic.prefix": "raw.{{system}}", + "table.include.list": "{{source_schema}}.{{source_object}}", + "plugin.name": "pgoutput", + "publication.autocreate.mode": "filtered", + "slot.name": "{{slot_name}}", + "snapshot.mode": "initial", + "tombstones.on.delete": "false", + + "transforms": "unwrap", + "transforms.unwrap.type": "io.debezium.transforms.ExtractNewRecordState", + "transforms.unwrap.add.fields": "op,table,lsn,source.ts_ms", + "transforms.unwrap.delete.handling.mode": "rewrite", + + "key.converter": "org.apache.kafka.connect.json.JsonConverter", + "key.converter.schemas.enable": "false", + "value.converter": "org.apache.kafka.connect.json.JsonConverter", + "value.converter.schemas.enable": "false", + + "errors.tolerance": "all", + "errors.log.enable": "true", + "errors.deadletterqueue.topic.name": "{{system}}.dlq.capture", + "errors.deadletterqueue.topic.replication.factor": "1", + "errors.deadletterqueue.context.headers.enable": "true", + + "tasks.max": "1" + } +} diff --git a/source_aligned_cdc_data_product/events/schemas/raw.{{system}}.{{source_schema}}.{{source_object}}.json b/source_aligned_cdc_data_product/events/schemas/raw.{{system}}.{{source_schema}}.{{source_object}}.json new file mode 100644 index 0000000..68aa7c1 --- /dev/null +++ b/source_aligned_cdc_data_product/events/schemas/raw.{{system}}.{{source_schema}}.{{source_object}}.json @@ -0,0 +1,23 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:bus:{{system}}:raw:{{source_schema}}.{{source_object}}", + "title": "ERP customer (raw)", + "description": "A row of the ERP's {{source_schema}}.{{source_object}} table as Debezium captured it, with the source's own column names, codes and key. The __ fields are the capture's own: which operation produced the record, the table it came from, the log position, and when the source committed it. This is the source's truth, unreshaped: it is kept so the canonical records can be rebuilt without going back to the ERP.", + "type": "object", + "additionalProperties": true, + "required": ["id"], + "properties": { + "id": {"type": "integer", "description": "The ERP's own customer key. The message key of this topic."}, + "cust_name": {"type": ["string", "null"], "description": "Customer name as the ERP holds it. The ERP allows it to be empty."}, + "cust_type": {"type": ["string", "null"], "description": "I = individual, O = organisation. Any other value is a record the transform rejects."}, + "status_code": {"type": ["string", "null"], "description": "A active, P prospect, S suspended, I inactive, C closed."}, + "birth_date": {"type": ["integer", "null"], "description": "Days since 1970-01-01, as Debezium encodes a DATE. Individuals only."}, + "trading_name": {"type": ["string", "null"], "description": "Trading name, organisations only."}, + "updated": {"type": ["string", "null"], "format": "date-time", "description": "When the ERP last changed the row."}, + "__op": {"type": ["string", "null"], "description": "r snapshot read, c insert, u update, d delete."}, + "__table": {"type": ["string", "null"], "description": "The source table."}, + "__lsn": {"type": ["integer", "null"], "description": "PostgreSQL log sequence number of the change."}, + "__source_ts_ms": {"type": ["integer", "null"], "description": "When the source committed the change, epoch milliseconds."}, + "__deleted": {"type": ["string", "null"], "description": "\"true\" on a record produced by a delete."} + } +} diff --git a/source_aligned_cdc_data_product/events/schemas/{{system}}.dlq.capture.json b/source_aligned_cdc_data_product/events/schemas/{{system}}.dlq.capture.json new file mode 100644 index 0000000..404695d --- /dev/null +++ b/source_aligned_cdc_data_product/events/schemas/{{system}}.dlq.capture.json @@ -0,0 +1,8 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:bus:{{system}}:dlq:capture", + "title": "ERP capture dead letter", + "description": "A record Kafka Connect could not read, convert or transform at all. Connect writes the original message unchanged and puts the failure in the record's headers, so nothing here can be assumed about the payload's shape. Records land here only when the ERP or the connector produce something the converter cannot parse; a record that parses but is not valid canonically goes to {{system}}.dlq.", + "type": ["object", "string", "null"], + "description_of_headers": "__connect.errors.topic, .partition, .offset, .exception.class, .exception.message and .stage identify what failed and where." +} diff --git a/source_aligned_cdc_data_product/events/schemas/{{system}}.dlq.json b/source_aligned_cdc_data_product/events/schemas/{{system}}.dlq.json new file mode 100644 index 0000000..8823169 --- /dev/null +++ b/source_aligned_cdc_data_product/events/schemas/{{system}}.dlq.json @@ -0,0 +1,18 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:bus:{{system}}:dlq", + "title": "{{product_name}} dead letter", + "description": "A record {{product_name}} could not turn into something {{target_product_name}} accepts, with the reason and the original. It is here rather than in the canonical product because a record that fails validation inside a canonical product's Flink job stops that domain's ingestion; the producer owns what it cannot produce. Keyed by the source key, so every rejection of one source row lands on one partition in order.", + "type": "object", + "additionalProperties": false, + "required": ["source_system", "source_object", "source_key", "stage", "reason", "record"], + "properties": { + "source_system": {"type": "string", "description": "The source system the record came from."}, + "source_object": {"type": "string", "description": "The source object, as the source names it."}, + "source_key": {"type": "string", "description": "The source's own key for the record."}, + "stage": {"type": "string", "enum": ["transform"], "description": "Where it was rejected. Capture failures land on {{system}}.dlq.capture instead."}, + "reason": {"type": "string", "description": "Why it cannot be published: the canonical rule it breaks, in words, naming the field."}, + "record": {"type": "string", "description": "The raw record as JSON text, so it can be corrected at the source and replayed."}, + "rejected_at": {"type": ["string", "null"], "format": "date-time", "description": "When the transform rejected it."} + } +} diff --git a/source_aligned_cdc_data_product/example/connectors/erp-party.json b/source_aligned_cdc_data_product/example/connectors/erp-party.json new file mode 100644 index 0000000..3562068 --- /dev/null +++ b/source_aligned_cdc_data_product/example/connectors/erp-party.json @@ -0,0 +1,38 @@ +{ + "name": "erp-party", + "config": { + "connector.class": "io.debezium.connector.postgresql.PostgresConnector", + + "database.hostname": "source-erp", + "database.port": "5432", + "database.dbname": "erp", + "database.user": "erp", + "database.password": "${ERP_SOURCE_PASSWORD:-erp}", + + "topic.prefix": "raw.erp", + "table.include.list": "public.customer", + "plugin.name": "pgoutput", + "publication.autocreate.mode": "filtered", + "slot.name": "erp_party", + "snapshot.mode": "initial", + "tombstones.on.delete": "false", + + "transforms": "unwrap", + "transforms.unwrap.type": "io.debezium.transforms.ExtractNewRecordState", + "transforms.unwrap.add.fields": "op,table,lsn,source.ts_ms", + "transforms.unwrap.delete.handling.mode": "rewrite", + + "key.converter": "org.apache.kafka.connect.json.JsonConverter", + "key.converter.schemas.enable": "false", + "value.converter": "org.apache.kafka.connect.json.JsonConverter", + "value.converter.schemas.enable": "false", + + "errors.tolerance": "all", + "errors.log.enable": "true", + "errors.deadletterqueue.topic.name": "erp.dlq.capture", + "errors.deadletterqueue.topic.replication.factor": "1", + "errors.deadletterqueue.context.headers.enable": "true", + + "tasks.max": "1" + } +} diff --git a/source_aligned_cdc_data_product/example/events/schemas/erp.dlq.capture.json b/source_aligned_cdc_data_product/example/events/schemas/erp.dlq.capture.json new file mode 100644 index 0000000..66cbd7e --- /dev/null +++ b/source_aligned_cdc_data_product/example/events/schemas/erp.dlq.capture.json @@ -0,0 +1,8 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:bus:erp:dlq:capture", + "title": "ERP capture dead letter", + "description": "A record Kafka Connect could not read, convert or transform at all. Connect writes the original message unchanged and puts the failure in the record's headers, so nothing here can be assumed about the payload's shape. Records land here only when the ERP or the connector produce something the converter cannot parse; a record that parses but is not valid canonically goes to erp.dlq.", + "type": ["object", "string", "null"], + "description_of_headers": "__connect.errors.topic, .partition, .offset, .exception.class, .exception.message and .stage identify what failed and where." +} diff --git a/source_aligned_cdc_data_product/example/events/schemas/erp.dlq.json b/source_aligned_cdc_data_product/example/events/schemas/erp.dlq.json new file mode 100644 index 0000000..f33940c --- /dev/null +++ b/source_aligned_cdc_data_product/example/events/schemas/erp.dlq.json @@ -0,0 +1,18 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:bus:erp:dlq", + "title": "ERP Party dead letter", + "description": "A record ERP Party could not turn into something Canonical Party accepts, with the reason and the original. It is here rather than in the canonical product because a record that fails validation inside a canonical product's Flink job stops that domain's ingestion; the producer owns what it cannot produce. Keyed by the source key, so every rejection of one source row lands on one partition in order.", + "type": "object", + "additionalProperties": false, + "required": ["source_system", "source_object", "source_key", "stage", "reason", "record"], + "properties": { + "source_system": {"type": "string", "description": "The source system the record came from."}, + "source_object": {"type": "string", "description": "The source object, as the source names it."}, + "source_key": {"type": "string", "description": "The source's own key for the record."}, + "stage": {"type": "string", "enum": ["transform"], "description": "Where it was rejected. Capture failures land on erp.dlq.capture instead."}, + "reason": {"type": "string", "description": "Why it cannot be published: the canonical rule it breaks, in words, naming the field."}, + "record": {"type": "string", "description": "The raw record as JSON text, so it can be corrected at the source and replayed."}, + "rejected_at": {"type": ["string", "null"], "format": "date-time", "description": "When the transform rejected it."} + } +} diff --git a/source_aligned_cdc_data_product/example/events/schemas/raw.erp.public.customer.json b/source_aligned_cdc_data_product/example/events/schemas/raw.erp.public.customer.json new file mode 100644 index 0000000..bdb6224 --- /dev/null +++ b/source_aligned_cdc_data_product/example/events/schemas/raw.erp.public.customer.json @@ -0,0 +1,23 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "urn:bus:erp:raw:public.customer", + "title": "ERP customer (raw)", + "description": "A row of the ERP's public.customer table as Debezium captured it, with the source's own column names, codes and key. The __ fields are the capture's own: which operation produced the record, the table it came from, the log position, and when the source committed it. This is the source's truth, unreshaped: it is kept so the canonical records can be rebuilt without going back to the ERP.", + "type": "object", + "additionalProperties": true, + "required": ["id"], + "properties": { + "id": {"type": "integer", "description": "The ERP's own customer key. The message key of this topic."}, + "cust_name": {"type": ["string", "null"], "description": "Customer name as the ERP holds it. The ERP allows it to be empty."}, + "cust_type": {"type": ["string", "null"], "description": "I = individual, O = organisation. Any other value is a record the transform rejects."}, + "status_code": {"type": ["string", "null"], "description": "A active, P prospect, S suspended, I inactive, C closed."}, + "birth_date": {"type": ["integer", "null"], "description": "Days since 1970-01-01, as Debezium encodes a DATE. Individuals only."}, + "trading_name": {"type": ["string", "null"], "description": "Trading name, organisations only."}, + "updated": {"type": ["string", "null"], "format": "date-time", "description": "When the ERP last changed the row."}, + "__op": {"type": ["string", "null"], "description": "r snapshot read, c insert, u update, d delete."}, + "__table": {"type": ["string", "null"], "description": "The source table."}, + "__lsn": {"type": ["integer", "null"], "description": "PostgreSQL log sequence number of the change."}, + "__source_ts_ms": {"type": ["integer", "null"], "description": "When the source committed the change, epoch milliseconds."}, + "__deleted": {"type": ["string", "null"], "description": "\"true\" on a record produced by a delete."} + } +} diff --git a/source_aligned_cdc_data_product/example/fixture/compose.fixture.yml b/source_aligned_cdc_data_product/example/fixture/compose.fixture.yml new file mode 100644 index 0000000..b6c7419 --- /dev/null +++ b/source_aligned_cdc_data_product/example/fixture/compose.fixture.yml @@ -0,0 +1,54 @@ +# A stand-in for the ERP, for tests only. +# +# The real source system belongs to another team and is not on this machine, so the product +# ships the smallest thing that behaves like it: the same table, the same types, logical +# decoding switched on so Debezium can replicate from it, and a seed of rows — including the +# rows that must be rejected. +# +# uv run data-bus fixture up semprini-data-product-templates/source_aligned_cdc_data_product/example +# uv run data-bus fixture down ... (removes the volume, so the next start reseeds) +# +# It joins semprini_bus because that is where bus-connect reaches it. Nothing else may depend +# on it: it is not part of the bus stack, and a deployed product points at the real ERP. + +services: + source-erp: + image: postgres:17.6-bookworm + container_name: source-erp + restart: unless-stopped + mem_limit: 384m + command: + - postgres + - -c + - wal_level=logical # Debezium reads the write-ahead log; without this there is no CDC + - -c + - max_replication_slots=4 + - -c + - max_wal_senders=4 + environment: + POSTGRES_USER: erp + POSTGRES_PASSWORD: ${ERP_SOURCE_PASSWORD:-erp} + POSTGRES_DB: erp + volumes: + - ./init:/docker-entrypoint-initdb.d:ro + - source-erp-data:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U erp -d erp"] + interval: 5s + timeout: 5s + retries: 20 + logging: + driver: json-file + options: + max-size: "10m" + max-file: "2" + networks: + - bus + +volumes: + source-erp-data: + +networks: + bus: + name: semprini_bus # created by semprini-data/stack-data.sh + external: true diff --git a/source_aligned_cdc_data_product/example/fixture/init/010_customer.sql b/source_aligned_cdc_data_product/example/fixture/init/010_customer.sql new file mode 100644 index 0000000..ff8f987 --- /dev/null +++ b/source_aligned_cdc_data_product/example/fixture/init/010_customer.sql @@ -0,0 +1,27 @@ +-- The ERP's customer table, as the ERP wrote it: its own names, its own codes, its own key. +-- A source-aligned product never asks a source system to change; this is what it is given. + +CREATE TABLE public.customer ( + id integer PRIMARY KEY, + cust_name text, -- the ERP allows this to be empty; Party does not + cust_type char(1), -- I = individual, O = organisation + status_code text, -- A active, P prospect, S suspended, I inactive, C closed + birth_date date, -- individuals only + trading_name text, -- organisations only + updated timestamptz DEFAULT now() +); + +COMMENT ON TABLE public.customer IS 'ERP customers. Captured by the ERP Party source-aligned data product.'; + +-- Four rows that map cleanly, and two that must not: a source system always has both. +INSERT INTO public.customer (id, cust_name, cust_type, status_code, birth_date, trading_name) VALUES + (1, 'Ada Lovelace', 'I', 'A', DATE '1815-12-10', NULL), + (2, 'Grace Hopper', 'I', 'P', DATE '1906-12-09', NULL), + (3, 'Semprini Holdings Ltd','O', 'A', NULL, 'Semprini'), + (4, 'Northwind Trading Co', 'O', 'C', NULL, 'Northwind'), + (5, 'Bad Status Ltd', 'O', 'Z', NULL, NULL), -- Z is not a Party Status + (6, 'Bad Type Ltd', 'X', 'A', NULL, NULL); -- X is neither I nor O + +-- Debezium replicates by logical decoding and needs the whole row, not just the key, to +-- publish updates and deletes the transform can read. +ALTER TABLE public.customer REPLICA IDENTITY FULL; diff --git a/source_aligned_cdc_data_product/example/flink/job.sql b/source_aligned_cdc_data_product/example/flink/job.sql new file mode 100644 index 0000000..65ee95e --- /dev/null +++ b/source_aligned_cdc_data_product/example/flink/job.sql @@ -0,0 +1,228 @@ +-- ERP Party: the transform. +-- +-- Reads the raw topic the CDC connector writes, and produces the canonical records Canonical +-- Party accepts on its inbound topic. Everything a source-aligned product exists for is here: +-- +-- identity the ERP's integer key becomes the canonical party_id, deterministically, so +-- re-snapshotting the table produces the same identifier and upserts rather than +-- duplicates. +-- semantics cust_type I/O becomes Party Type Person/Company; status_code A/P/S/I/C becomes +-- Party Status; trading_name becomes also_known_as. +-- validation every record is checked against the rules Canonical Party enforces, before it +-- is published. What fails goes to this product's dead-letter topic with the +-- reason, and never reaches the canonical product's Flink job, which would stop +-- the whole domain's ingestion on it. +-- provenance where each record came from, in headers, so the payload stays canonical. +-- archive every raw record is also written to the bus object store, partitioned by the day +-- the source committed it, because a Kafka topic is kept for days and a source +-- system's records have to be reproducible for longer than that. +-- +-- ${BUS_KAFKA}, ${TARGET_BOOTSTRAP} and ${DLQ} are substituted by `data-bus deploy` from the +-- manifest; no address or credential is committed here. + +SET 'pipeline.name' = 'erp-party'; +SET 'execution.checkpointing.interval' = '10 s'; +SET 'table.local-time-zone' = 'UTC'; + +-- --------------------------------------------------------------------------------------- +-- The source's truth, as the connector wrote it. +-- --------------------------------------------------------------------------------------- +CREATE TABLE erp_customer_raw ( + id INT, + cust_name STRING, + cust_type STRING, + status_code STRING, + birth_date INT, -- Debezium encodes DATE as days since 1970-01-01 + trading_name STRING, + `updated` STRING, + __op STRING, + __lsn BIGINT, + __source_ts_ms BIGINT +) WITH ( + 'connector' = 'kafka', + 'topic' = 'raw.erp.public.customer', + 'properties.bootstrap.servers' = '${BUS_KAFKA}', + 'properties.group.id' = 'erp-party-transform', + 'scan.startup.mode' = 'earliest-offset', + 'format' = 'json', + 'json.ignore-parse-errors' = 'false' +); + +-- --------------------------------------------------------------------------------------- +-- Canonical Party's inbound topic. It belongs to the digital-core domain: this product only +-- publishes to it, keyed by party_id, in the schema registered for it. +-- --------------------------------------------------------------------------------------- +CREATE TABLE party_inbound ( + party_id STRING, + party_type STRING, + legal_name STRING, + also_known_as STRING, + party_status STRING, + headers MAP METADATA +) WITH ( + 'connector' = 'kafka', + 'topic' = 'digital-core.canonical-party.party.inbound', + 'properties.bootstrap.servers' = '${TARGET_BOOTSTRAP}', + 'format' = 'json', + 'json.timestamp-format.standard' = 'ISO-8601', + 'key.format' = 'raw', + 'key.fields' = 'party_id', + 'value.fields-include' = 'ALL' +); + +-- --------------------------------------------------------------------------------------- +-- This product's dead-letter topic. +-- --------------------------------------------------------------------------------------- +CREATE TABLE erp_dlq ( + source_system STRING, + source_object STRING, + source_key STRING, + stage STRING, + reason STRING, + record STRING, + rejected_at TIMESTAMP_LTZ(3) +) WITH ( + 'connector' = 'kafka', + 'topic' = '${DLQ}', + 'properties.bootstrap.servers' = '${BUS_KAFKA}', + 'format' = 'json', + 'json.timestamp-format.standard' = 'ISO-8601', + 'key.format' = 'raw', + 'key.fields' = 'source_key', + 'value.fields-include' = 'ALL' +); + +-- --------------------------------------------------------------------------------------- +-- The raw archive in the bus object store: the same records as the raw topic, kept beyond its +-- retention and partitioned by capture day so a replay can ask for a date range. Files are +-- rolled often here so an archived record appears within a minute, which is what the tests +-- need; a busy product would roll on size, or every few minutes, to keep files large. +-- --------------------------------------------------------------------------------------- +CREATE TABLE erp_customer_archive ( + id INT, + cust_name STRING, + cust_type STRING, + status_code STRING, + birth_date INT, + trading_name STRING, + `updated` STRING, + __op STRING, + __lsn BIGINT, + __source_ts_ms BIGINT, + dt STRING +) PARTITIONED BY (dt) WITH ( + 'connector' = 'filesystem', + 'path' = '${ARCHIVE_PATH}', + 'format' = 'json', + 'sink.rolling-policy.rollover-interval' = '30 s', + 'sink.rolling-policy.check-interval' = '10 s', + 'sink.partition-commit.policy.kind' = 'success-file' +); + +-- --------------------------------------------------------------------------------------- +-- The mapping, in one place: every record is mapped and judged once, so what is published and +-- what is rejected cannot drift apart. reason IS NULL is the definition of acceptable. +-- +-- party_id is a version 3 UUID over the text 'erp:public.customer:': the MD5 of that name, +-- with the RFC 4122 version nibble set to 3 and the variant nibble to 'a'. Deterministic, so a +-- re-snapshot upserts the same party; derived from the source key, so no crosswalk table has +-- to be kept in step. semprini_data_bus.testing.deterministic_id computes the same value, and +-- the tests assert against it. +-- --------------------------------------------------------------------------------------- +CREATE TEMPORARY VIEW erp_customer_mapped AS +SELECT + id, + CONCAT( + SUBSTRING(MD5(CONCAT('erp:public.customer:', CAST(id AS STRING))), 1, 8), '-', + SUBSTRING(MD5(CONCAT('erp:public.customer:', CAST(id AS STRING))), 9, 4), '-', + '3', SUBSTRING(MD5(CONCAT('erp:public.customer:', CAST(id AS STRING))), 14, 3), '-', + 'a', SUBSTRING(MD5(CONCAT('erp:public.customer:', CAST(id AS STRING))), 18, 3), '-', + SUBSTRING(MD5(CONCAT('erp:public.customer:', CAST(id AS STRING))), 21, 12) + ) AS party_id, + CASE cust_type WHEN 'I' THEN 'Person' WHEN 'O' THEN 'Company' END AS party_type, + TRIM(cust_name) AS legal_name, + trading_name AS also_known_as, + CASE status_code + WHEN 'A' THEN 'Active' + WHEN 'P' THEN 'Prospect' + WHEN 'S' THEN 'Suspended' + WHEN 'I' THEN 'Inactive' + WHEN 'C' THEN 'Closed' + END AS party_status, + -- Why this record cannot be published, or NULL if it can. The order is the order a person + -- would read it in: what happened to the record, then the fields, left to right. + CASE + WHEN __op = 'd' THEN + 'delete: Canonical Party''s inbound contract has no delete; remove the party through its own interface' + WHEN cust_name IS NULL OR CHAR_LENGTH(TRIM(cust_name)) = 0 THEN + 'legal_name: cust_name is empty, and every Party must have a legal name' + WHEN cust_type IS NULL OR cust_type NOT IN ('I', 'O') THEN + 'party_type: cust_type ' || COALESCE('''' || cust_type || '''', 'NULL') + || ' is neither I (Person) nor O (Company)' + WHEN status_code IS NOT NULL AND status_code NOT IN ('A', 'P', 'S', 'I', 'C') THEN + 'party_status: status_code ''' || status_code || ''' is not one of A, P, S, I, C' + END AS reason, + -- The original, so a rejected record can be corrected at the source and replayed. + JSON_OBJECT( + 'id' VALUE id, + 'cust_name' VALUE cust_name, + 'cust_type' VALUE cust_type, + 'status_code' VALUE status_code, + 'birth_date' VALUE birth_date, + 'trading_name' VALUE trading_name, + 'updated' VALUE `updated`, + '__op' VALUE __op, + '__lsn' VALUE __lsn, + '__source_ts_ms' VALUE __source_ts_ms + ) AS raw_record, + __lsn, + __source_ts_ms +FROM erp_customer_raw; + +-- --------------------------------------------------------------------------------------- +-- One statement set, so both sinks run in one job and one checkpoint covers them. +-- birth_date is captured but not published: date_of_birth belongs to Canonical Party's person +-- table, and a child record must not be published before its parent exists (see the template +-- README, "What this template does not do"). +-- --------------------------------------------------------------------------------------- +EXECUTE STATEMENT SET +BEGIN + +INSERT INTO party_inbound +SELECT + party_id, + party_type, + legal_name, + also_known_as, + party_status, + MAP[ + 'source_system', ENCODE('erp', 'UTF-8'), + 'source_object', ENCODE('public.customer', 'UTF-8'), + 'source_key', ENCODE(CAST(id AS STRING), 'UTF-8'), + 'source_lsn', ENCODE(COALESCE(CAST(__lsn AS STRING), ''), 'UTF-8'), + 'capture_ts', ENCODE(COALESCE(CAST(__source_ts_ms AS STRING), ''), 'UTF-8'), + 'produced_by', ENCODE('erp-party', 'UTF-8') + ] +FROM erp_customer_mapped +WHERE reason IS NULL; + +INSERT INTO erp_customer_archive +SELECT + id, cust_name, cust_type, status_code, birth_date, trading_name, `updated`, + __op, __lsn, __source_ts_ms, + DATE_FORMAT(TO_TIMESTAMP_LTZ(COALESCE(__source_ts_ms, 0), 3), 'yyyy-MM-dd') +FROM erp_customer_raw; + +INSERT INTO erp_dlq +SELECT + 'erp', + 'public.customer', + CAST(id AS STRING), + 'transform', + reason, + raw_record, + CURRENT_TIMESTAMP +FROM erp_customer_mapped +WHERE reason IS NOT NULL; + +END; diff --git a/source_aligned_cdc_data_product/example/flink/replay.sql b/source_aligned_cdc_data_product/example/flink/replay.sql new file mode 100644 index 0000000..4de7501 --- /dev/null +++ b/source_aligned_cdc_data_product/example/flink/replay.sql @@ -0,0 +1,60 @@ +-- ERP Party: replay. +-- +-- Reads the product's raw archive out of the bus object store and publishes it back onto the +-- raw topic, exactly as the capture connector wrote it — same records, same keys — so the +-- transform runs again and the canonical product is upserted under the same identifiers. +-- +-- Submitted by `data-bus replay [--since] [--until]`, which substitutes the +-- path, the topic and the date range. It runs in batch mode, so it ends when the archive has +-- been read rather than waiting for more. + +SET 'pipeline.name' = 'erp-party-replay'; +SET 'execution.runtime-mode' = 'batch'; +SET 'table.local-time-zone' = 'UTC'; + +CREATE TABLE erp_customer_archive ( + id INT, + cust_name STRING, + cust_type STRING, + status_code STRING, + birth_date INT, + trading_name STRING, + `updated` STRING, + __op STRING, + __lsn BIGINT, + __source_ts_ms BIGINT, + dt STRING +) PARTITIONED BY (dt) WITH ( + 'connector' = 'filesystem', + 'path' = '${ARCHIVE_PATH}', + 'format' = 'json' +); + +-- The raw topic, keyed the way the CDC connector keys it: the source key, as JSON. +CREATE TABLE erp_customer_raw ( + id INT, + cust_name STRING, + cust_type STRING, + status_code STRING, + birth_date INT, + trading_name STRING, + `updated` STRING, + __op STRING, + __lsn BIGINT, + __source_ts_ms BIGINT +) WITH ( + 'connector' = 'kafka', + 'topic' = '${RAW_TOPIC}', + 'properties.bootstrap.servers' = '${BUS_KAFKA}', + 'format' = 'json', + 'key.format' = 'json', + 'key.fields' = 'id', + 'value.fields-include' = 'ALL' +); + +INSERT INTO erp_customer_raw +SELECT + id, cust_name, cust_type, status_code, birth_date, trading_name, `updated`, + __op, __lsn, __source_ts_ms +FROM erp_customer_archive +WHERE dt >= '${SINCE}' AND dt <= '${UNTIL}'; diff --git a/source_aligned_cdc_data_product/example/odps.yaml b/source_aligned_cdc_data_product/example/odps.yaml new file mode 100644 index 0000000..d22dce9 --- /dev/null +++ b/source_aligned_cdc_data_product/example/odps.yaml @@ -0,0 +1,90 @@ +# ERP Party: Open Data Product Specification v4.0 manifest, the product's entry in the catalogue. +# Read by `uv run data-bus register example`, which imports it into OpenMetadata and attaches +# the product's topics as its assets and output ports. +# +# A source-aligned product's consumers are not people writing queries: they are the canonical +# products it feeds, and the engineers who have to work out why a record was rejected. So the +# description says what it captures, what it guarantees, and what it refuses. +schema: https://opendataproducts.org/v4.0/schema/odps.yaml +version: 4.0 +product: + details: + en: + name: "ERP Party" + productID: "bus.erp-party" + description: "The ERP's customers, captured by change data capture and published as the canonical Party records Canonical Party accepts. It is the only thing that knows the ERP's schema: its integer customer key, its I/O customer types and its single-letter status codes. Every record it publishes has been checked against Canonical Party's rules first; what fails is on erp.dlq with the reason, not in the digital-core domain. Identifiers are derived from the ERP key, so a re-snapshot upserts rather than duplicates." + visibility: organisation + status: draft + type: dataset # MD-DDL class: source-aligned + productVersion: "0.1.0" + categories: + - "Integration" + outputFileFormats: + - JSON + + SLA: + declarative: + default: + name: + en: Default SLA + description: + en: "Service levels for ERP Party" + dimensions: + - dimension: updateFrequency + displaytitle: + en: Data Freshness + objective: 1 # streaming; a change is published within a minute + unit: minutes + - dimension: uptime + displaytitle: + en: Availability + objective: 99.0 + unit: percent + support: + email: "integration@example.com" + + dataQuality: + declarative: + default: + name: + en: Validation before publishing + description: + en: "Every record is checked against Canonical Party's rules before it is published: a legal name is present, the customer type is one the model knows, and the status code maps to a Party Status. What fails is published to erp.dlq with the reason and the original record, and is not sent to the canonical product." + dimensions: + - dimension: accuracy + displaytitle: + en: Records accepted by the canonical product + objective: 100 + unit: percent + + dataAccess: + raw: + name: + en: Raw records + description: + en: "The ERP's customer rows as the ERP holds them, captured by Debezium and kept for seven days so canonical records can be rebuilt without going back to the source. Keyed by the ERP's customer key." + outputPorttype: API + format: JSON + authenticationMethod: none # lab stack only + accessURL: "kafka://localhost:19092/raw.erp.public.customer" + specsURL: "http://localhost:8081/apis/registry/v3/groups/bus.erp/artifacts" + deadletter: + name: + en: Dead letters + description: + en: "Records that could not be turned into canonical records, each with the reason it was refused and the original record as JSON, so it can be corrected in the ERP and replayed. Kept for thirty days." + outputPorttype: API + format: JSON + authenticationMethod: none + accessURL: "kafka://localhost:19092/erp.dlq" + specsURL: "http://localhost:8081/apis/registry/v3/groups/bus.erp/artifacts" + + dataHolder: + en: + legalName: "Semprini" + email: "integration@example.com" + + license: + en: + scope: + restrictions: "Internal use within the organisation. The raw topic carries the source system's records unchanged, including personal data, and is subject to the ERP's own handling rules." diff --git a/source_aligned_cdc_data_product/example/product.yaml b/source_aligned_cdc_data_product/example/product.yaml new file mode 100644 index 0000000..a11ac6a --- /dev/null +++ b/source_aligned_cdc_data_product/example/product.yaml @@ -0,0 +1,82 @@ +# ERP Party: source-aligned data product manifest (worked example of the CDC template). +# Read by `uv run data-bus deploy|test|unit|register|undeploy example`, run from semprini-data. +# +# One source system, one product. It captures the ERP's customer table by CDC, keeps the +# source's own records on a raw topic, and transforms them into what Canonical Party accepts. +# Nothing here creates anything in the digital-core domain: that product's inbound topics are +# its contract, and belong to its team. + +product: + name: "ERP Party" + slug: "erp-party" + class: source-aligned + system: "erp" # the source system: names the topics, the registry group and the DLQ + mechanism: cdc # this product came from source_aligned_cdc_data_product/ + version: "0.1.0" + owner: "integration@example.com" + domain: "digital-core" # the catalogue domain; defaults to the first target's + +capture: + connector: connectors/erp-party.json + connector_name: "erp-party" + # The real ERP is not on this machine. The fixture is a stand-in with the same table, so the + # product can be deployed and proved end to end; `data-bus fixture up example` starts it. + fixture: + compose: fixture/compose.fixture.yml + container: source-erp + user: erp + database: erp + +events: + registry_group: "bus.erp" + compatibility: BACKWARD + topics: + # The source's truth, unreshaped, keyed by the source's own key and kept for replay. + - name: "raw.erp.public.customer" + role: raw + object: "public.customer" + key: "id" + schema: events/schemas/raw.erp.public.customer.json + partitions: 3 + cleanup_policy: delete + retention_ms: 604800000 # 7 days + + # What the transform could not turn into a canonical record, with the reason. + - name: "erp.dlq" + role: dead-letter + key: "source_key" + schema: events/schemas/erp.dlq.json + partitions: 1 + cleanup_policy: delete + retention_ms: 2592000000 # 30 days + + # What Kafka Connect could not read or convert at all: the original bytes, with the + # failure in the record's headers. A different shape, so a different topic. + - name: "erp.dlq.capture" + role: dead-letter + schema: events/schemas/erp.dlq.capture.json + partitions: 1 + cleanup_policy: delete + retention_ms: 2592000000 + +transform: + job: flink/job.sql + name: "erp-party" + +# Every raw record is also written to the bus object store as it streams. The raw topic is kept +# for seven days; this is kept for as long as the ERP's records have to be reproducible, and is +# what `data-bus replay` reads to put records back on the raw topic. +archive: + bucket: "raw" + path: "erp/public.customer" + format: json + replay: flink/replay.sql + +targets: + - domain: "digital-core" + product: "canonical-party" + bootstrap: "kafka-digital-core:39092" # the domain's BUS listener, on semprini_bus + topics: + - name: "digital-core.canonical-party.party.inbound" + key: "party_id" # every record must be keyed by this + source: "raw.erp.public.customer" diff --git a/source_aligned_cdc_data_product/example/tests/conftest.py b/source_aligned_cdc_data_product/example/tests/conftest.py new file mode 100644 index 0000000..9079a96 --- /dev/null +++ b/source_aligned_cdc_data_product/example/tests/conftest.py @@ -0,0 +1,43 @@ +"""Leave the target domain as we found it. + +A source-aligned product's tests deliver real records into someone else's domain, and that +domain's canonical product has its own seed and its own tests that count rows. So when this +suite finishes, every party it created is removed again. Generic: the keys come from +expectations.yaml, through the platform's identity rule. +""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +from semprini_data_bus.bus import Bus +from semprini_data_bus.manifest import load +from semprini_data_bus.testing import ( + SourceProductClient, + deterministic_id, + expectations_for, + find_target_domain, +) + +EXPECT = expectations_for(__file__) + + +@pytest.fixture(scope="session", autouse=True) +def leave_the_target_domain_as_we_found_it(): + yield + source, transform, delivery = EXPECT["source"], EXPECT["transform"], EXPECT["delivery"] + product = load(Path(__file__).resolve().parent.parent) + bus = Bus.for_path(product.dir) + client = SourceProductClient(bus, product, find_target_domain(bus, product.targets[0], product.dir)) + if client.target_platform is None: + return + keys = [c["source_key"] for c in transform["accepted"]] + keys += [c["source_key"] for c in transform.get("rejected", [])] + keys += [p["source_key"] for p in (transform.get("probe_records") or {}).values()] + keys += [EXPECT["capture"]["probe"]["source_key"]] if "probe" in EXPECT["capture"] else [] + ids = ", ".join(f"'{deterministic_id(source['system'], source['object'], k)}'" for k in keys) + client.target_execute( + f"DELETE FROM {delivery['schema']}.{delivery['table']} WHERE {delivery['key']} IN ({ids})" + ) diff --git a/source_aligned_cdc_data_product/example/tests/expectations.yaml b/source_aligned_cdc_data_product/example/tests/expectations.yaml new file mode 100644 index 0000000..2f3cc52 --- /dev/null +++ b/source_aligned_cdc_data_product/example/tests/expectations.yaml @@ -0,0 +1,85 @@ +# What the source fixture holds, and what ERP Party must make of it. +# +# The test modules beside this file are generic: they are the same in every source-aligned CDC +# product, and everything specific to this one is here. Rows come from +# fixture/init/010_customer.sql; the canonical identifiers are not written down, because the +# tests derive them with the platform's identity rule, which is what the transform implements. + +source: + system: "erp" + object: "public.customer" + table: "public.customer" + key: "id" + rows: 6 + # The columns a test replays a source row with. Only what the transform reads: a replayed + # record is JSON on the raw topic, and a column the raw contract types differently (a DATE + # the connector encodes as a number) would be refused by the transform's parser. + replay_columns: ["id", "cust_name", "cust_type", "status_code", "trading_name"] + +capture: + raw_topic: "raw.erp.public.customer" + # What the capture adds around a source row. A record a test puts on the raw topic carries it + # too, so a replayed record is indistinguishable from a captured one. + replay_envelope: {"__op": "r", "__lsn": 0, "__source_ts_ms": 0} + # Fields the capture adds to every record, so a consumer can tell what happened and when. + provenance_fields: ["__op", "__lsn", "__source_ts_ms"] + # A row inserted by a test, to prove capture is live rather than a one-off snapshot. It is + # removed again afterwards; ids above 900 are the tests' own. + probe: + insert: "INSERT INTO public.customer (id, cust_name, cust_type, status_code) VALUES (900, 'Live Capture Ltd', 'O', 'A')" + delete: "DELETE FROM public.customer WHERE id = 900" + source_key: 900 + +transform: + target_topic: "digital-core.canonical-party.party.inbound" + target_key: "party_id" + headers: ["source_system", "source_object", "source_key", "produced_by"] + accepted: + - source_key: 1 + record: + party_type: "Person" + legal_name: "Ada Lovelace" + also_known_as: null + party_status: "Active" + - source_key: 2 + record: + party_type: "Person" + legal_name: "Grace Hopper" + also_known_as: null + party_status: "Prospect" + - source_key: 3 + record: + party_type: "Company" + legal_name: "Semprini Holdings Ltd" + also_known_as: "Semprini" + party_status: "Active" + - source_key: 4 + record: + party_type: "Company" + legal_name: "Northwind Trading Co" + also_known_as: "Northwind" + party_status: "Closed" + rejected: + - source_key: 5 + reason_contains: "party_status" + - source_key: 6 + reason_contains: "party_type" + # Records put straight onto the raw topic, as the connector would have written them: one the + # transform must refuse, one it must accept. Together they prove a bad record is quarantined + # rather than stopping the flow. + probe_records: + bad: + record: {"id": 901, "cust_name": "Poison Ltd", "cust_type": "Q", "status_code": "A", "__op": "c", "__lsn": 0, "__source_ts_ms": 0} + source_key: 901 + reason_contains: "party_type" + good: + record: {"id": 902, "cust_name": "Survivor Ltd", "cust_type": "O", "status_code": "A", "__op": "c", "__lsn": 0, "__source_ts_ms": 0} + source_key: 902 + party_type: "Company" + legal_name: "Survivor Ltd" + +delivery: + # Where the canonical product puts what this product sends it. + schema: "canonical_party" + table: "party" + key: "party_id" diff --git a/source_aligned_cdc_data_product/example/tests/test_archive.py b/source_aligned_cdc_data_product/example/tests/test_archive.py new file mode 100644 index 0000000..010db57 --- /dev/null +++ b/source_aligned_cdc_data_product/example/tests/test_archive.py @@ -0,0 +1,72 @@ +"""Archive and replay: the raw records outlive the topic, and can be put back on it. + +A raw topic is retained for days. The records on it are what every canonical record downstream +was built from, so they are also written to the bus object store as they stream, and a replay +reads them back onto the topic. That is what makes it possible to correct a transform and +rebuild, or to answer what the source actually sent months later. +""" + +from __future__ import annotations + +import pytest + +from semprini_data_bus.testing import expectations_for + +EXPECT = expectations_for(__file__) +SOURCE = EXPECT["source"] +ACCEPTED = EXPECT["transform"]["accepted"] + + +def archived_keys(sp) -> set: + return {r[SOURCE["key"]] for r in sp.archive_records()} + + +def test_every_captured_record_is_archived(sp): + keys = sp.eventually(lambda: archived_keys(sp), timeout=120) + missing = {r[SOURCE["key"]] for r in sp.source_sql(f"SELECT {SOURCE['key']} FROM {SOURCE['table']}")} - keys + assert not missing, f"source rows captured but not archived: {sorted(missing)}" + + +def test_archived_records_are_the_source_records_unchanged(sp): + """The archive holds what the source sent, not what the transform made of it.""" + archived = {r[SOURCE["key"]]: r for r in sp.archive_records()} + for row in sp.source_sql(f"SELECT * FROM {SOURCE['table']} WHERE {SOURCE['key']} < 900"): + record = archived.get(row[SOURCE["key"]]) + assert record is not None + assert record["cust_name"] == row["cust_name"] + assert record["cust_type"] == row["cust_type"] + + +def test_the_archive_is_partitioned_by_day(sp): + """A replay asks for a date range, so the archive has to be partitioned by one.""" + partitions = sp.archive_partitions() + assert partitions, "the archive has no dt= partitions" + for day in partitions: + assert len(day) == 10 and day[4] == "-", f"{day} is not a yyyy-MM-dd partition" + + +@pytest.mark.slow +def test_replaying_the_archive_puts_the_records_back_on_the_raw_topic(sp): + """The whole point of keeping the archive, end to end: the records come back, the transform + runs again, and the canonical product is upserted rather than duplicated.""" + topic = EXPECT["capture"]["raw_topic"] + day = sp.archive_partitions()[-1] + before = len([1 for _, value in sp.raw(topic) if value]) + sp.replay(since=day, until=day) + + after = sp.eventually( + lambda: len([1 for _, value in sp.raw(topic) if value]) > before and + len([1 for _, value in sp.raw(topic) if value]), + timeout=180, + ) + assert after > before, "the replay put nothing back on the raw topic" + + delivery = EXPECT["delivery"] + for case in ACCEPTED: + from semprini_data_bus.testing import deterministic_id + + key = deterministic_id(SOURCE["system"], SOURCE["object"], case["source_key"]) + rows = sp.eventually(lambda: sp.target_sql( + f"SELECT * FROM {delivery['schema']}.{delivery['table']} WHERE {delivery['key']} = '{key}'" + )) + assert len(rows) == 1, f"the replay duplicated source {case['source_key']}" diff --git a/source_aligned_cdc_data_product/example/tests/test_capture.py b/source_aligned_cdc_data_product/example/tests/test_capture.py new file mode 100644 index 0000000..15c033e --- /dev/null +++ b/source_aligned_cdc_data_product/example/tests/test_capture.py @@ -0,0 +1,75 @@ +"""Capture: the source system's rows reach the raw topic, unreshaped and keyed by the source key. + +Generic: everything specific to a product is in expectations.yaml. Run with +``uv run data-bus unit `` from semprini-data, after ``data-bus fixture up`` and +``data-bus deploy``. +""" + +from __future__ import annotations + +import json + +import pytest + +from semprini_data_bus.testing import expectations_for + +EXPECT = expectations_for(__file__) +SOURCE = EXPECT["source"] +CAPTURE = EXPECT["capture"] + + +def test_the_source_fixture_holds_the_rows_the_expectations_describe(sp): + rows = sp.source_sql(f"SELECT count(*) AS n FROM {SOURCE['table']} WHERE {SOURCE['key']} < 900") + assert rows[0]["n"] == SOURCE["rows"], "the fixture was reseeded or a test left a row behind" + + +def test_every_source_row_is_on_the_raw_topic(sp): + keys = {json.loads(key)[SOURCE["key"]] for key, _ in sp.raw(CAPTURE["raw_topic"]) if key} + missing = {r[SOURCE["key"]] for r in sp.source_sql(f"SELECT {SOURCE['key']} FROM {SOURCE['table']}")} - keys + assert not missing, f"source rows never captured: {sorted(missing)}" + + +def test_raw_records_keep_the_source_shape(sp): + values = [value for _, value in sp.raw(CAPTURE["raw_topic"]) if value] + assert values, "the raw topic is empty" + columns = {c["column_name"] for c in sp.source_sql( + "SELECT column_name FROM information_schema.columns " + f"WHERE table_schema || '.' || table_name = '{SOURCE['object']}'" + )} + for value in values: + present = {k for k in value if not k.startswith("__")} + assert present <= columns, f"the raw record has fields the source does not: {present - columns}" + + +def test_raw_records_are_keyed_by_the_source_key(sp): + for key, value in sp.raw(CAPTURE["raw_topic"]): + assert key, "a raw record has no key: changes to one source row would not stay in order" + assert json.loads(key)[SOURCE["key"]] == value[SOURCE["key"]] + + +@pytest.mark.parametrize("field", CAPTURE["provenance_fields"]) +def test_raw_records_carry_capture_provenance(sp, field): + """Every record for a row the source still holds says where and when it came from. + + Scoped to those rows because the raw topic is an audit log kept for days: it also holds + records for rows since deleted, and records earlier test runs put there. + """ + current = {r[SOURCE["key"]] for r in sp.source_sql(f"SELECT {SOURCE['key']} FROM {SOURCE['table']}")} + records = [v for _, v in sp.raw(CAPTURE["raw_topic"]) if v and v.get(SOURCE["key"]) in current] + assert records, "no record on the raw topic belongs to a row the source still holds" + for value in records: + assert field in value, f"{field} is missing: the record cannot be traced back to the source" + + +@pytest.mark.skipif("probe" not in CAPTURE, reason="the product declares no capture probe") +def test_a_new_source_row_is_captured_while_the_product_runs(sp): + """Capture is live, not a snapshot taken once at deploy time.""" + probe = CAPTURE["probe"] + sp.source_execute(probe["insert"]) + try: + sp.eventually(lambda: any( + value and value[SOURCE["key"]] == probe["source_key"] + for _, value in sp.raw(CAPTURE["raw_topic"]) + )) + finally: + sp.source_execute(probe["delete"]) diff --git a/source_aligned_cdc_data_product/example/tests/test_delivery.py b/source_aligned_cdc_data_product/example/tests/test_delivery.py new file mode 100644 index 0000000..eb35668 --- /dev/null +++ b/source_aligned_cdc_data_product/example/tests/test_delivery.py @@ -0,0 +1,83 @@ +"""Delivery: the records arrive in the canonical product, and a replay does not duplicate them. + +These tests reach into the target domain, so they need its repository on this machine +(``SEMPRINI_DOMAIN_DIR``, the target's ``repo`` in product.yaml, or a checkout beside +semprini-data). They skip when it is not there, because a source-aligned product is deployable +without it — but nothing proves the contract like the row appearing on the other side. + +They do not rely on the delivery that happened once, when the product was first deployed: +they replay the source rows first, which is exactly what a re-snapshot does, so the delivery is +proved again on every run. conftest.py removes the parties afterwards, so the canonical +product's own seed and tests are unaffected. +""" + +from __future__ import annotations + +import pytest + +from semprini_data_bus.testing import deterministic_id, expectations_for + +EXPECT = expectations_for(__file__) +SOURCE = EXPECT["source"] +TRANSFORM = EXPECT["transform"] +DELIVERY = EXPECT["delivery"] +ACCEPTED = TRANSFORM["accepted"] +REJECTED = TRANSFORM.get("rejected", []) +TABLE = f"{DELIVERY['schema']}.{DELIVERY['table']}" + + +def canonical_id(source_key) -> str: + return deterministic_id(SOURCE["system"], SOURCE["object"], source_key) + + +def rows_for(sp, party_id) -> list[dict]: + return sp.target_sql(f"SELECT * FROM {TABLE} WHERE {DELIVERY['key']} = '{party_id}'") + + +def replay(sp, source_keys) -> None: + """Put the source's own rows back on the raw topic, as a re-snapshot would.""" + columns = ", ".join(SOURCE["replay_columns"]) + keys = ", ".join(str(k) for k in source_keys) + rows = sp.source_sql( + f"SELECT {columns} FROM {SOURCE['table']} WHERE {SOURCE['key']} IN ({keys})" + ) + envelope = EXPECT["capture"].get("replay_envelope") or {} + sp.publish_raw(EXPECT["capture"]["raw_topic"], [{**row, **envelope} for row in rows], SOURCE["key"]) + + +@pytest.fixture(scope="module", autouse=True) +def delivered(sp): + """Deliver the rows this module asserts on, every run.""" + replay(sp, [c["source_key"] for c in ACCEPTED] + [c["source_key"] for c in REJECTED]) + + +@pytest.mark.parametrize("case", ACCEPTED, ids=[str(c["source_key"]) for c in ACCEPTED]) +def test_an_accepted_record_reaches_the_canonical_product(sp, case): + rows = sp.eventually(lambda: rows_for(sp, canonical_id(case["source_key"]))) + assert len(rows) == 1 + for field, expected in case["record"].items(): + assert rows[0][field] == expected, f"{field} of source {case['source_key']} in {TABLE}" + + +@pytest.mark.parametrize("case", REJECTED, ids=[str(c["source_key"]) for c in REJECTED]) +def test_a_rejected_record_never_reaches_the_canonical_product(sp, case): + assert rows_for(sp, canonical_id(case["source_key"])) == [], ( + f"source {case['source_key']} breaks a canonical rule but is in {TABLE}" + ) + + +def test_replaying_a_source_record_upserts_rather_than_duplicates(sp): + """A re-snapshot, a restarted connector or a replayed raw topic must not create a second + party: that is what deriving the identifier from the source key buys.""" + case = ACCEPTED[0] + key = canonical_id(case["source_key"]) + sp.eventually(lambda: rows_for(sp, key)) + replay(sp, [case["source_key"]]) + + def one_row_still(): + rows = rows_for(sp, key) + assert len(rows) == 1, f"the replay produced {len(rows)} rows for {key}" + return rows + + rows = sp.eventually(one_row_still, timeout=45) + assert rows[0]["legal_name"] == case["record"]["legal_name"] diff --git a/source_aligned_cdc_data_product/example/tests/test_dlq.py b/source_aligned_cdc_data_product/example/tests/test_dlq.py new file mode 100644 index 0000000..ce65b6e --- /dev/null +++ b/source_aligned_cdc_data_product/example/tests/test_dlq.py @@ -0,0 +1,72 @@ +"""Dead letters: what cannot be transformed is quarantined with its reason, and the flow continues. + +This is why a source-aligned product exists between a source system and a canonical one. A +record the canonical product's ODS would refuse fails its Flink job's JDBC sink, and that +failure takes down the TaskManager and every other product's job on it +(semprini-data/docs/technology-review-2026-09-18.md). Validating here, before publishing, +keeps a bad row in the source system from stopping a domain. +""" + +from __future__ import annotations + +import json + +import pytest + +from semprini_data_bus.testing import deterministic_id, expectations_for + +EXPECT = expectations_for(__file__) +SOURCE = EXPECT["source"] +TRANSFORM = EXPECT["transform"] +REJECTED = TRANSFORM.get("rejected", []) +PROBES = TRANSFORM.get("probe_records") or {} + + +def dead_letters(sp, source_key) -> list[dict]: + return [d for d in sp.dlq() if d.get("source_key") == str(source_key)] + + +@pytest.mark.parametrize("case", REJECTED, ids=[str(c["source_key"]) for c in REJECTED]) +def test_a_record_that_breaks_a_canonical_rule_is_on_the_dead_letter_topic(sp, case): + letters = sp.eventually(lambda: dead_letters(sp, case["source_key"])) + assert any(case["reason_contains"] in d["reason"] for d in letters), ( + f"source {case['source_key']} was rejected, but no reason mentions " + f"{case['reason_contains']}: {[d['reason'] for d in letters]}" + ) + + +@pytest.mark.parametrize("case", REJECTED, ids=[str(c["source_key"]) for c in REJECTED]) +def test_a_dead_letter_carries_the_original_record_and_where_it_came_from(sp, case): + """A dead letter is only useful if it can be corrected at the source and replayed.""" + letter = sp.eventually(lambda: dead_letters(sp, case["source_key"]))[0] + assert letter["source_system"] == SOURCE["system"] + assert letter["source_object"] == SOURCE["object"] + assert letter["stage"] == "transform" + original = json.loads(letter["record"]) + assert original[SOURCE["key"]] == case["source_key"] + + +def test_dead_letters_are_keyed_by_the_source_key(sp): + dlq = sp.product.dlq + for key, value in sp.raw(dlq.name): + if value is not None: + assert key == value["source_key"], "rejections of one source row would not stay in order" + + +@pytest.mark.skipif(not PROBES, reason="the product declares no transform probe records") +def test_a_poison_record_is_quarantined_and_the_next_record_still_arrives(sp): + """The property the whole design rests on: one bad record costs one record, not the flow.""" + bad, good = PROBES["bad"], PROBES["good"] + topic = EXPECT["capture"]["raw_topic"] + sp.publish_raw(topic, [bad["record"], good["record"]], key_field=SOURCE["key"]) + + letters = sp.eventually(lambda: dead_letters(sp, bad["source_key"])) + assert any(bad["reason_contains"] in d["reason"] for d in letters) + + key = deterministic_id(SOURCE["system"], SOURCE["object"], good["source_key"]) + record = sp.eventually(lambda: {k: v for k, v in sp.target_records(TRANSFORM["target_topic"])}.get(key)) + assert record["legal_name"] == good["legal_name"] + assert record["party_type"] == good["party_type"] + assert deterministic_id(SOURCE["system"], SOURCE["object"], bad["source_key"]) not in { + k for k, _ in sp.target_records(TRANSFORM["target_topic"]) + } diff --git a/source_aligned_cdc_data_product/example/tests/test_transform.py b/source_aligned_cdc_data_product/example/tests/test_transform.py new file mode 100644 index 0000000..3f8f1c8 --- /dev/null +++ b/source_aligned_cdc_data_product/example/tests/test_transform.py @@ -0,0 +1,72 @@ +"""Transform: source records become canonical records, keyed by the canonical identifier. + +The semantic half of a source-aligned product. Generic: the mapping itself is in +expectations.yaml, and the identifiers are derived with the platform's identity rule rather +than written down, so these tests check the rule the transform implements. +""" + +from __future__ import annotations + +import pytest + +from semprini_data_bus.testing import deterministic_id, expectations_for + +EXPECT = expectations_for(__file__) +SOURCE = EXPECT["source"] +TRANSFORM = EXPECT["transform"] +ACCEPTED = TRANSFORM["accepted"] +REJECTED = TRANSFORM.get("rejected", []) + + +def canonical_id(source_key) -> str: + return deterministic_id(SOURCE["system"], SOURCE["object"], source_key) + + +def published(sp) -> dict[str, dict]: + """The latest record published for each canonical identifier.""" + return {key: value for key, value in sp.target_records(TRANSFORM["target_topic"]) if value} + + +@pytest.mark.parametrize("case", ACCEPTED, ids=[str(c["source_key"]) for c in ACCEPTED]) +def test_an_acceptable_source_record_is_published_as_a_canonical_record(sp, case): + key = canonical_id(case["source_key"]) + record = sp.eventually(lambda: published(sp).get(key)) + for field, expected in case["record"].items(): + assert record[field] == expected, f"{field} of source {case['source_key']}" + + +def test_published_records_are_keyed_by_the_canonical_identifier(sp): + """Only a key keeps changes to one entity in order, and the key must be the one the + canonical product upserts on.""" + target_key = TRANSFORM["target_key"] + for key, value in sp.target_records(TRANSFORM["target_topic"]): + assert key, "a record was published without a key" + if value is not None: + assert value[target_key] == key, f"message key {key} is not the record's {target_key}" + + +def test_the_identifier_is_derived_from_the_source_key(sp): + """Deterministic identity: re-capturing the same source row must upsert, not duplicate.""" + keys = set(published(sp)) + for case in ACCEPTED: + assert canonical_id(case["source_key"]) in keys, ( + f"source {case['source_key']} was published under an identifier that is not derived " + "from its source key" + ) + + +@pytest.mark.parametrize("header", TRANSFORM["headers"]) +def test_every_published_record_carries_provenance(sp, header): + """Where a record came from travels in headers, so the payload stays canonical.""" + messages = [m for m in sp.target_messages(TRANSFORM["target_topic"]) + if m["key"] in {canonical_id(c["source_key"]) for c in ACCEPTED}] + assert messages, "none of the expected records are on the target topic" + for message in messages: + assert message["headers"].get(header), f"{header} is missing from {message['key']}" + + +@pytest.mark.parametrize("case", REJECTED, ids=[str(c["source_key"]) for c in REJECTED]) +def test_a_rejected_source_record_is_never_published(sp, case): + assert canonical_id(case["source_key"]) not in published(sp), ( + f"source {case['source_key']} reached the canonical product although it breaks its rules" + ) diff --git a/source_aligned_cdc_data_product/fixture/compose.fixture.yml b/source_aligned_cdc_data_product/fixture/compose.fixture.yml new file mode 100644 index 0000000..e4d18af --- /dev/null +++ b/source_aligned_cdc_data_product/fixture/compose.fixture.yml @@ -0,0 +1,54 @@ +# A stand-in for the ERP, for tests only. +# +# The real source system belongs to another team and is not on this machine, so the product +# ships the smallest thing that behaves like it: the same table, the same types, logical +# decoding switched on so Debezium can replicate from it, and a seed of rows — including the +# rows that must be rejected. +# +# uv run data-bus fixture up semprini-data-product-templates/source_aligned_cdc_data_product/example +# uv run data-bus fixture down ... (removes the volume, so the next start reseeds) +# +# It joins semprini_bus because that is where bus-connect reaches it. Nothing else may depend +# on it: it is not part of the bus stack, and a deployed product points at the real ERP. + +services: + source-{{system}}: + image: postgres:17.6-bookworm + container_name: source-{{system}} + restart: unless-stopped + mem_limit: 384m + command: + - postgres + - -c + - wal_level=logical # Debezium reads the write-ahead log; without this there is no CDC + - -c + - max_replication_slots=4 + - -c + - max_wal_senders=4 + environment: + POSTGRES_USER: {{system}} + POSTGRES_PASSWORD: ${ERP_SOURCE_PASSWORD:-{{system}}} + POSTGRES_DB: {{system}} + volumes: + - ./init:/docker-entrypoint-initdb.d:ro + - source-{{system}}-data:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U {{system}} -d {{system}}"] + interval: 5s + timeout: 5s + retries: 20 + logging: + driver: json-file + options: + max-size: "10m" + max-file: "2" + networks: + - bus + +volumes: + source-{{system}}-data: + +networks: + bus: + name: semprini_bus # created by semprini-data/stack-data.sh + external: true diff --git a/source_aligned_cdc_data_product/fixture/init/010_{{source_object}}.sql b/source_aligned_cdc_data_product/fixture/init/010_{{source_object}}.sql new file mode 100644 index 0000000..13c877d --- /dev/null +++ b/source_aligned_cdc_data_product/fixture/init/010_{{source_object}}.sql @@ -0,0 +1,27 @@ +-- The ERP's customer table, as the ERP wrote it: its own names, its own codes, its own key. +-- A source-aligned product never asks a source system to change; this is what it is given. + +CREATE TABLE {{source_schema}}.{{source_object}} ( + id integer PRIMARY KEY, + cust_name text, -- the ERP allows this to be empty; Party does not + cust_type char(1), -- I = individual, O = organisation + status_code text, -- A active, P prospect, S suspended, I inactive, C closed + birth_date date, -- individuals only + trading_name text, -- organisations only + updated timestamptz DEFAULT now() +); + +COMMENT ON TABLE {{source_schema}}.{{source_object}} IS 'ERP customers. Captured by the {{product_name}} source-aligned data product.'; + +-- Four rows that map cleanly, and two that must not: a source system always has both. +INSERT INTO {{source_schema}}.{{source_object}} (id, cust_name, cust_type, status_code, birth_date, trading_name) VALUES + (1, 'Ada Lovelace', 'I', 'A', DATE '1815-12-10', NULL), + (2, 'Grace Hopper', 'I', 'P', DATE '1906-12-09', NULL), + (3, 'Semprini Holdings Ltd','O', 'A', NULL, 'Semprini'), + (4, 'Northwind Trading Co', 'O', 'C', NULL, 'Northwind'), + (5, 'Bad Status Ltd', 'O', 'Z', NULL, NULL), -- Z is not a Party Status + (6, 'Bad Type Ltd', 'X', 'A', NULL, NULL); -- X is neither I nor O + +-- Debezium replicates by logical decoding and needs the whole row, not just the key, to +-- publish updates and deletes the transform can read. +ALTER TABLE {{source_schema}}.{{source_object}} REPLICA IDENTITY FULL; diff --git a/source_aligned_cdc_data_product/flink/job.sql b/source_aligned_cdc_data_product/flink/job.sql new file mode 100644 index 0000000..4318519 --- /dev/null +++ b/source_aligned_cdc_data_product/flink/job.sql @@ -0,0 +1,246 @@ +-- {{product_name}}: the transform. +-- +-- Reads the raw topic the CDC connector writes, and produces the canonical records +-- {{target_product_name}} accepts on its inbound topic. Everything a source-aligned product +-- exists for is here: +-- +-- identity the source's own key becomes the canonical identifier, deterministically, so +-- re-snapshotting the table produces the same identifier and upserts rather than +-- duplicates. +-- semantics the source's codes become the model's enums, its names become the model's +-- fields — one mapping, written once, in the view below. +-- validation every record is checked against the rules {{target_product_name}} enforces, before it +-- is published. What fails goes to this product's dead-letter topic with the +-- reason, and never reaches the canonical product's Flink job, which would stop +-- the whole domain's ingestion on it. +-- provenance where each record came from, in headers, so the payload stays canonical. +-- archive every raw record is also written to the bus object store, partitioned by the day +-- the source committed it, because a Kafka topic is kept for days and a source +-- system's records have to be reproducible for longer than that. +-- +-- ${BUS_KAFKA}, ${TARGET_BOOTSTRAP} and ${DLQ} are substituted by `data-bus deploy` from the +-- manifest; no address or credential is committed here. + +SET 'pipeline.name' = '{{slug}}'; +SET 'execution.checkpointing.interval' = '10 s'; +SET 'table.local-time-zone' = 'UTC'; + +-- --------------------------------------------------------------------------------------- +-- The source's truth, as the connector wrote it. +-- +-- REPLACE the columns with the source object's own, in the types Debezium produces for them: +-- a DATE arrives as days since 1970-01-01 (INT), a TIMESTAMPTZ as an ISO-8601 STRING, a +-- NUMERIC as a STRING unless decimal.handling.mode says otherwise. The __ columns are what the +-- connector adds, and every template keeps them: they are the record's provenance. +-- --------------------------------------------------------------------------------------- +CREATE TABLE {{system}}_{{source_object}}_raw ( + id INT, + cust_name STRING, + cust_type STRING, + status_code STRING, + birth_date INT, -- Debezium encodes DATE as days since 1970-01-01 + trading_name STRING, + `updated` STRING, + __op STRING, + __lsn BIGINT, + __source_ts_ms BIGINT +) WITH ( + 'connector' = 'kafka', + 'topic' = 'raw.{{system}}.{{source_schema}}.{{source_object}}', + 'properties.bootstrap.servers' = '${BUS_KAFKA}', + 'properties.group.id' = '{{slug}}-transform', + 'scan.startup.mode' = 'earliest-offset', + 'format' = 'json', + 'json.ignore-parse-errors' = 'false' +); + +-- --------------------------------------------------------------------------------------- +-- {{target_product_name}}'s inbound topic. It belongs to the {{target_domain}} domain: this +-- product only publishes to it, keyed by {{target_key}}, in the schema registered for it. +-- +-- REPLACE the columns with the target's inbound JSON Schema, which the canonical product +-- registered in Apicurio. Send what the source knows and leave the rest out; the ODS fills in +-- what it owns. Keep the headers column: provenance travels in headers, not in the payload. +-- --------------------------------------------------------------------------------------- +CREATE TABLE party_inbound ( + party_id STRING, + party_type STRING, + legal_name STRING, + also_known_as STRING, + party_status STRING, + headers MAP METADATA +) WITH ( + 'connector' = 'kafka', + 'topic' = '{{target_domain}}.{{target_product}}.{{target_table}}.inbound', + 'properties.bootstrap.servers' = '${TARGET_BOOTSTRAP}', + 'format' = 'json', + 'json.timestamp-format.standard' = 'ISO-8601', + 'key.format' = 'raw', + 'key.fields' = 'party_id', + 'value.fields-include' = 'ALL' +); + +-- --------------------------------------------------------------------------------------- +-- This product's dead-letter topic. +-- --------------------------------------------------------------------------------------- +CREATE TABLE erp_dlq ( + source_system STRING, + source_object STRING, + source_key STRING, + stage STRING, + reason STRING, + record STRING, + rejected_at TIMESTAMP_LTZ(3) +) WITH ( + 'connector' = 'kafka', + 'topic' = '${DLQ}', + 'properties.bootstrap.servers' = '${BUS_KAFKA}', + 'format' = 'json', + 'json.timestamp-format.standard' = 'ISO-8601', + 'key.format' = 'raw', + 'key.fields' = 'source_key', + 'value.fields-include' = 'ALL' +); + +-- --------------------------------------------------------------------------------------- +-- The raw archive in the bus object store: the same records as the raw topic, kept beyond its +-- retention and partitioned by capture day so a replay can ask for a date range. Files are +-- rolled often here so an archived record appears within a minute, which is what the tests +-- need; a busy product would roll on size, or every few minutes, to keep files large. +-- --------------------------------------------------------------------------------------- +CREATE TABLE {{system}}_{{source_object}}_archive ( + id INT, + cust_name STRING, + cust_type STRING, + status_code STRING, + birth_date INT, + trading_name STRING, + `updated` STRING, + __op STRING, + __lsn BIGINT, + __source_ts_ms BIGINT, + dt STRING +) PARTITIONED BY (dt) WITH ( + 'connector' = 'filesystem', + 'path' = '${ARCHIVE_PATH}', + 'format' = 'json', + 'sink.rolling-policy.rollover-interval' = '30 s', + 'sink.rolling-policy.check-interval' = '10 s', + 'sink.partition-commit.policy.kind' = 'success-file' +); + +-- --------------------------------------------------------------------------------------- +-- The mapping, in one place: every record is mapped and judged once, so what is published and +-- what is rejected cannot drift apart. reason IS NULL is the definition of acceptable. +-- +-- REPLACE the mapping and the reason: they are what this product is. The rules to check are +-- the ones the canonical product's ODS enforces — its NOT NULLs, its CHECK constraints, its +-- enums — because a record it refuses fails its Flink job's JDBC sink, and that takes down +-- every job on that TaskManager. +-- +-- The identifier is a version 3 UUID over the text +-- '{{system}}:{{source_schema}}.{{source_object}}:': the MD5 of that name, with the +-- RFC 4122 version nibble set to 3 and the variant nibble to 'a'. Deterministic, so a +-- re-snapshot upserts the same record; derived from the source key, so no crosswalk table has +-- to be kept in step. semprini_data_bus.testing.deterministic_id computes the same value, and +-- the tests assert against it. Keep this expression as it stands unless the canonical +-- identifier already exists somewhere else, and say so in the product's README if you change it. +-- --------------------------------------------------------------------------------------- +CREATE TEMPORARY VIEW {{system}}_{{source_object}}_mapped AS +SELECT + id, + CONCAT( + SUBSTRING(MD5(CONCAT('{{system}}:{{source_schema}}.{{source_object}}:', CAST(id AS STRING))), 1, 8), '-', + SUBSTRING(MD5(CONCAT('{{system}}:{{source_schema}}.{{source_object}}:', CAST(id AS STRING))), 9, 4), '-', + '3', SUBSTRING(MD5(CONCAT('{{system}}:{{source_schema}}.{{source_object}}:', CAST(id AS STRING))), 14, 3), '-', + 'a', SUBSTRING(MD5(CONCAT('{{system}}:{{source_schema}}.{{source_object}}:', CAST(id AS STRING))), 18, 3), '-', + SUBSTRING(MD5(CONCAT('{{system}}:{{source_schema}}.{{source_object}}:', CAST(id AS STRING))), 21, 12) + ) AS party_id, + CASE cust_type WHEN 'I' THEN 'Person' WHEN 'O' THEN 'Company' END AS party_type, + TRIM(cust_name) AS legal_name, + trading_name AS also_known_as, + CASE status_code + WHEN 'A' THEN 'Active' + WHEN 'P' THEN 'Prospect' + WHEN 'S' THEN 'Suspended' + WHEN 'I' THEN 'Inactive' + WHEN 'C' THEN 'Closed' + END AS party_status, + -- Why this record cannot be published, or NULL if it can. The order is the order a person + -- would read it in: what happened to the record, then the fields, left to right. + CASE + WHEN __op = 'd' THEN + 'delete: {{target_product_name}}''s inbound contract has no delete; remove the party through its own interface' + WHEN cust_name IS NULL OR CHAR_LENGTH(TRIM(cust_name)) = 0 THEN + 'legal_name: cust_name is empty, and every Party must have a legal name' + WHEN cust_type IS NULL OR cust_type NOT IN ('I', 'O') THEN + 'party_type: cust_type ' || COALESCE('''' || cust_type || '''', 'NULL') + || ' is neither I (Person) nor O (Company)' + WHEN status_code IS NOT NULL AND status_code NOT IN ('A', 'P', 'S', 'I', 'C') THEN + 'party_status: status_code ''' || status_code || ''' is not one of A, P, S, I, C' + END AS reason, + -- The original, so a rejected record can be corrected at the source and replayed. + JSON_OBJECT( + 'id' VALUE id, + 'cust_name' VALUE cust_name, + 'cust_type' VALUE cust_type, + 'status_code' VALUE status_code, + 'birth_date' VALUE birth_date, + 'trading_name' VALUE trading_name, + 'updated' VALUE `updated`, + '__op' VALUE __op, + '__lsn' VALUE __lsn, + '__source_ts_ms' VALUE __source_ts_ms + ) AS raw_record, + __lsn, + __source_ts_ms +FROM {{system}}_{{source_object}}_raw; + +-- --------------------------------------------------------------------------------------- +-- One statement set, so both sinks run in one job and one checkpoint covers them. +-- A column captured but not published is normal: publish only what the target's inbound +-- contract accepts, and only to one table. A child record must not be published before its +-- parent exists, which Kafka cannot express across topics (see the template README, "What this +-- template does not do"). +-- --------------------------------------------------------------------------------------- +EXECUTE STATEMENT SET +BEGIN + +INSERT INTO party_inbound +SELECT + party_id, + party_type, + legal_name, + also_known_as, + party_status, + MAP[ + 'source_system', ENCODE('{{system}}', 'UTF-8'), + 'source_object', ENCODE('{{source_schema}}.{{source_object}}', 'UTF-8'), + 'source_key', ENCODE(CAST(id AS STRING), 'UTF-8'), + 'source_lsn', ENCODE(COALESCE(CAST(__lsn AS STRING), ''), 'UTF-8'), + 'capture_ts', ENCODE(COALESCE(CAST(__source_ts_ms AS STRING), ''), 'UTF-8'), + 'produced_by', ENCODE('{{slug}}', 'UTF-8') + ] +FROM {{system}}_{{source_object}}_mapped +WHERE reason IS NULL; + +INSERT INTO {{system}}_{{source_object}}_archive +SELECT + id, cust_name, cust_type, status_code, birth_date, trading_name, `updated`, + __op, __lsn, __source_ts_ms, + DATE_FORMAT(TO_TIMESTAMP_LTZ(COALESCE(__source_ts_ms, 0), 3), 'yyyy-MM-dd') +FROM {{system}}_{{source_object}}_raw; + +INSERT INTO erp_dlq +SELECT + '{{system}}', + '{{source_schema}}.{{source_object}}', + CAST(id AS STRING), + 'transform', + reason, + raw_record, + CURRENT_TIMESTAMP +FROM {{system}}_{{source_object}}_mapped +WHERE reason IS NOT NULL; + +END; diff --git a/source_aligned_cdc_data_product/flink/replay.sql b/source_aligned_cdc_data_product/flink/replay.sql new file mode 100644 index 0000000..be68679 --- /dev/null +++ b/source_aligned_cdc_data_product/flink/replay.sql @@ -0,0 +1,60 @@ +-- {{product_name}}: replay. +-- +-- Reads the product's raw archive out of the bus object store and publishes it back onto the +-- raw topic, exactly as the capture connector wrote it — same records, same keys — so the +-- transform runs again and the canonical product is upserted under the same identifiers. +-- +-- Submitted by `data-bus replay [--since] [--until]`, which substitutes the +-- path, the topic and the date range. It runs in batch mode, so it ends when the archive has +-- been read rather than waiting for more. + +SET 'pipeline.name' = '{{slug}}-replay'; +SET 'execution.runtime-mode' = 'batch'; +SET 'table.local-time-zone' = 'UTC'; + +CREATE TABLE {{system}}_{{source_object}}_archive ( + id INT, + cust_name STRING, + cust_type STRING, + status_code STRING, + birth_date INT, + trading_name STRING, + `updated` STRING, + __op STRING, + __lsn BIGINT, + __source_ts_ms BIGINT, + dt STRING +) PARTITIONED BY (dt) WITH ( + 'connector' = 'filesystem', + 'path' = '${ARCHIVE_PATH}', + 'format' = 'json' +); + +-- The raw topic, keyed the way the CDC connector keys it: the source key, as JSON. +CREATE TABLE {{system}}_{{source_object}}_raw ( + id INT, + cust_name STRING, + cust_type STRING, + status_code STRING, + birth_date INT, + trading_name STRING, + `updated` STRING, + __op STRING, + __lsn BIGINT, + __source_ts_ms BIGINT +) WITH ( + 'connector' = 'kafka', + 'topic' = '${RAW_TOPIC}', + 'properties.bootstrap.servers' = '${BUS_KAFKA}', + 'format' = 'json', + 'key.format' = 'json', + 'key.fields' = 'id', + 'value.fields-include' = 'ALL' +); + +INSERT INTO {{system}}_{{source_object}}_raw +SELECT + id, cust_name, cust_type, status_code, birth_date, trading_name, `updated`, + __op, __lsn, __source_ts_ms +FROM {{system}}_{{source_object}}_archive +WHERE dt >= '${SINCE}' AND dt <= '${UNTIL}'; diff --git a/source_aligned_cdc_data_product/odps.yaml b/source_aligned_cdc_data_product/odps.yaml new file mode 100644 index 0000000..2398aaf --- /dev/null +++ b/source_aligned_cdc_data_product/odps.yaml @@ -0,0 +1,90 @@ +# {{product_name}}: Open Data Product Specification v4.0 manifest, the product's entry in the catalogue. +# Read by `uv run data-bus register example`, which imports it into OpenMetadata and attaches +# the product's topics as its assets and output ports. +# +# A source-aligned product's consumers are not people writing queries: they are the canonical +# products it feeds, and the engineers who have to work out why a record was rejected. So the +# description says what it captures, what it guarantees, and what it refuses. +schema: https://opendataproducts.org/v4.0/schema/odps.yaml +version: 4.0 +product: + details: + en: + name: "{{product_name}}" + productID: "bus.{{slug}}" + description: "The ERP's customers, captured by change data capture and published as the canonical Party records {{target_product_name}} accepts. It is the only thing that knows the ERP's schema: its integer customer key, its I/O customer types and its single-letter status codes. Every record it publishes has been checked against {{target_product_name}}'s rules first; what fails is on {{system}}.dlq with the reason, not in the {{target_domain}} domain. Identifiers are derived from the ERP key, so a re-snapshot upserts rather than duplicates." + visibility: organisation + status: draft + type: dataset # MD-DDL class: source-aligned + productVersion: "0.1.0" + categories: + - "Integration" + outputFileFormats: + - JSON + + SLA: + declarative: + default: + name: + en: Default SLA + description: + en: "Service levels for {{product_name}}" + dimensions: + - dimension: updateFrequency + displaytitle: + en: Data Freshness + objective: 1 # streaming; a change is published within a minute + unit: minutes + - dimension: uptime + displaytitle: + en: Availability + objective: 99.0 + unit: percent + support: + email: "integration@example.com" + + dataQuality: + declarative: + default: + name: + en: Validation before publishing + description: + en: "Every record is checked against {{target_product_name}}'s rules before it is published: a legal name is present, the customer type is one the model knows, and the status code maps to a Party Status. What fails is published to {{system}}.dlq with the reason and the original record, and is not sent to the canonical product." + dimensions: + - dimension: accuracy + displaytitle: + en: Records accepted by the canonical product + objective: 100 + unit: percent + + dataAccess: + raw: + name: + en: Raw records + description: + en: "The ERP's customer rows as the ERP holds them, captured by Debezium and kept for seven days so canonical records can be rebuilt without going back to the source. Keyed by the ERP's customer key." + outputPorttype: API + format: JSON + authenticationMethod: none # lab stack only + accessURL: "kafka://localhost:19092/raw.{{system}}.{{source_schema}}.{{source_object}}" + specsURL: "http://localhost:8081/apis/registry/v3/groups/bus.{{system}}/artifacts" + deadletter: + name: + en: Dead letters + description: + en: "Records that could not be turned into canonical records, each with the reason it was refused and the original record as JSON, so it can be corrected in the ERP and replayed. Kept for thirty days." + outputPorttype: API + format: JSON + authenticationMethod: none + accessURL: "kafka://localhost:19092/{{system}}.dlq" + specsURL: "http://localhost:8081/apis/registry/v3/groups/bus.{{system}}/artifacts" + + dataHolder: + en: + legalName: "Semprini" + email: "integration@example.com" + + license: + en: + scope: + restrictions: "Internal use within the organisation. The raw topic carries the source system's records unchanged, including personal data, and is subject to the ERP's own handling rules." diff --git a/source_aligned_cdc_data_product/product.yaml b/source_aligned_cdc_data_product/product.yaml new file mode 100644 index 0000000..b5a410c --- /dev/null +++ b/source_aligned_cdc_data_product/product.yaml @@ -0,0 +1,81 @@ +# {{product_name}}: source-aligned data product manifest. +# Read by `uv run data-bus deploy|test|unit|register|replay|undeploy `, run from +# semprini-data. Names every part of the product the Integration Bus owns. One source system, +# one product; see README.md for how to fill this in. + +product: + name: "{{product_name}}" # e.g. "ERP Party" + slug: "{{slug}}" # kebab-case, e.g. "erp-party" + class: source-aligned + system: "{{system}}" # the source system id: names topics, registry group and DLQ + mechanism: cdc # this template captures by change data capture + version: "0.1.0" + owner: "{{owner_email}}" + domain: "{{catalogue_domain}}" # the OpenMetadata domain; defaults to the first target's + +capture: + connector: connectors/{{slug}}.json + connector_name: "{{slug}}" + # A stand-in for the source system, for tests only. Leave it out if the real system is + # reachable from this machine and the tests capture from it. + fixture: + compose: fixture/compose.fixture.yml + container: source-{{system}} + user: "{{source_db_user}}" + database: "{{source_db_name}}" + +events: + registry_group: "bus.{{system}}" + compatibility: BACKWARD + topics: + # One raw topic per source object, in the source's own shape, keyed by the source's key. + - name: "raw.{{system}}.{{source_schema}}.{{source_object}}" + role: raw + object: "{{source_schema}}.{{source_object}}" + key: "{{source_key}}" + schema: events/schemas/raw.{{system}}.{{source_schema}}.{{source_object}}.json + partitions: 3 + cleanup_policy: delete + retention_ms: 604800000 # 7 days; the archive keeps them for longer + + # What the transform could not turn into a canonical record, with the reason. Required: + # a source-aligned product owns what it cannot produce. + - name: "{{system}}.dlq" + role: dead-letter + key: "source_key" + schema: events/schemas/{{system}}.dlq.json + partitions: 1 + cleanup_policy: delete + retention_ms: 2592000000 # 30 days + + # What Kafka Connect could not read or convert at all: the original bytes, with the failure + # in the record's headers. A different shape, so a different topic. + - name: "{{system}}.dlq.capture" + role: dead-letter + schema: events/schemas/{{system}}.dlq.capture.json + partitions: 1 + cleanup_policy: delete + retention_ms: 2592000000 + +transform: + job: flink/job.sql + name: "{{slug}}" + +# Every raw record is also written to the bus object store as it streams, so records outlive +# the topic's retention and `data-bus replay` can put them back. +archive: + bucket: "raw" + path: "{{system}}/{{source_schema}}.{{source_object}}" + format: json + replay: flink/replay.sql + +targets: + # The canonical products this feeds. They belong to other teams: nothing here creates or + # changes them, and their inbound topics are their contract. + - domain: "{{target_domain}}" + product: "{{target_product}}" + bootstrap: "kafka-{{target_domain}}:39092" # the domain's BUS listener on semprini_bus + topics: + - name: "{{target_domain}}.{{target_product}}.{{target_table}}.inbound" + key: "{{target_key}}" + source: "raw.{{system}}.{{source_schema}}.{{source_object}}" diff --git a/source_aligned_cdc_data_product/tests/conftest.py b/source_aligned_cdc_data_product/tests/conftest.py new file mode 100644 index 0000000..9079a96 --- /dev/null +++ b/source_aligned_cdc_data_product/tests/conftest.py @@ -0,0 +1,43 @@ +"""Leave the target domain as we found it. + +A source-aligned product's tests deliver real records into someone else's domain, and that +domain's canonical product has its own seed and its own tests that count rows. So when this +suite finishes, every party it created is removed again. Generic: the keys come from +expectations.yaml, through the platform's identity rule. +""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +from semprini_data_bus.bus import Bus +from semprini_data_bus.manifest import load +from semprini_data_bus.testing import ( + SourceProductClient, + deterministic_id, + expectations_for, + find_target_domain, +) + +EXPECT = expectations_for(__file__) + + +@pytest.fixture(scope="session", autouse=True) +def leave_the_target_domain_as_we_found_it(): + yield + source, transform, delivery = EXPECT["source"], EXPECT["transform"], EXPECT["delivery"] + product = load(Path(__file__).resolve().parent.parent) + bus = Bus.for_path(product.dir) + client = SourceProductClient(bus, product, find_target_domain(bus, product.targets[0], product.dir)) + if client.target_platform is None: + return + keys = [c["source_key"] for c in transform["accepted"]] + keys += [c["source_key"] for c in transform.get("rejected", [])] + keys += [p["source_key"] for p in (transform.get("probe_records") or {}).values()] + keys += [EXPECT["capture"]["probe"]["source_key"]] if "probe" in EXPECT["capture"] else [] + ids = ", ".join(f"'{deterministic_id(source['system'], source['object'], k)}'" for k in keys) + client.target_execute( + f"DELETE FROM {delivery['schema']}.{delivery['table']} WHERE {delivery['key']} IN ({ids})" + ) diff --git a/source_aligned_cdc_data_product/tests/expectations.yaml b/source_aligned_cdc_data_product/tests/expectations.yaml new file mode 100644 index 0000000..6ba7253 --- /dev/null +++ b/source_aligned_cdc_data_product/tests/expectations.yaml @@ -0,0 +1,85 @@ +# What the source fixture holds, and what {{product_name}} must make of it. +# +# The test modules beside this file are generic: they are the same in every source-aligned CDC +# product, and everything specific to this one is here. Rows come from +# fixture/init/010_customer.sql; the canonical identifiers are not written down, because the +# tests derive them with the platform's identity rule, which is what the transform implements. + +source: + system: "{{system}}" + object: "{{source_schema}}.{{source_object}}" + table: "{{source_schema}}.{{source_object}}" + key: "id" + rows: 6 + # The columns a test replays a source row with. Only what the transform reads: a replayed + # record is JSON on the raw topic, and a column the raw contract types differently (a DATE + # the connector encodes as a number) would be refused by the transform's parser. + replay_columns: ["id", "cust_name", "cust_type", "status_code", "trading_name"] + +capture: + raw_topic: "raw.{{system}}.{{source_schema}}.{{source_object}}" + # What the capture adds around a source row. A record a test puts on the raw topic carries it + # too, so a replayed record is indistinguishable from a captured one. + replay_envelope: {"__op": "r", "__lsn": 0, "__source_ts_ms": 0} + # Fields the capture adds to every record, so a consumer can tell what happened and when. + provenance_fields: ["__op", "__lsn", "__source_ts_ms"] + # A row inserted by a test, to prove capture is live rather than a one-off snapshot. It is + # removed again afterwards; ids above 900 are the tests' own. + probe: + insert: "INSERT INTO {{source_schema}}.{{source_object}} (id, cust_name, cust_type, status_code) VALUES (900, 'Live Capture Ltd', 'O', 'A')" + delete: "DELETE FROM {{source_schema}}.{{source_object}} WHERE id = 900" + source_key: 900 + +transform: + target_topic: "{{target_domain}}.{{target_product}}.{{target_table}}.inbound" + target_key: "party_id" + headers: ["source_system", "source_object", "source_key", "produced_by"] + accepted: + - source_key: 1 + record: + party_type: "Person" + legal_name: "Ada Lovelace" + also_known_as: null + party_status: "Active" + - source_key: 2 + record: + party_type: "Person" + legal_name: "Grace Hopper" + also_known_as: null + party_status: "Prospect" + - source_key: 3 + record: + party_type: "Company" + legal_name: "Semprini Holdings Ltd" + also_known_as: "Semprini" + party_status: "Active" + - source_key: 4 + record: + party_type: "Company" + legal_name: "Northwind Trading Co" + also_known_as: "Northwind" + party_status: "Closed" + rejected: + - source_key: 5 + reason_contains: "party_status" + - source_key: 6 + reason_contains: "party_type" + # Records put straight onto the raw topic, as the connector would have written them: one the + # transform must refuse, one it must accept. Together they prove a bad record is quarantined + # rather than stopping the flow. + probe_records: + bad: + record: {"id": 901, "cust_name": "Poison Ltd", "cust_type": "Q", "status_code": "A", "__op": "c", "__lsn": 0, "__source_ts_ms": 0} + source_key: 901 + reason_contains: "party_type" + good: + record: {"id": 902, "cust_name": "Survivor Ltd", "cust_type": "O", "status_code": "A", "__op": "c", "__lsn": 0, "__source_ts_ms": 0} + source_key: 902 + party_type: "Company" + legal_name: "Survivor Ltd" + +delivery: + # Where the canonical product puts what this product sends it. + schema: "canonical_party" + table: "party" + key: "party_id" diff --git a/source_aligned_cdc_data_product/tests/test_archive.py b/source_aligned_cdc_data_product/tests/test_archive.py new file mode 100644 index 0000000..010db57 --- /dev/null +++ b/source_aligned_cdc_data_product/tests/test_archive.py @@ -0,0 +1,72 @@ +"""Archive and replay: the raw records outlive the topic, and can be put back on it. + +A raw topic is retained for days. The records on it are what every canonical record downstream +was built from, so they are also written to the bus object store as they stream, and a replay +reads them back onto the topic. That is what makes it possible to correct a transform and +rebuild, or to answer what the source actually sent months later. +""" + +from __future__ import annotations + +import pytest + +from semprini_data_bus.testing import expectations_for + +EXPECT = expectations_for(__file__) +SOURCE = EXPECT["source"] +ACCEPTED = EXPECT["transform"]["accepted"] + + +def archived_keys(sp) -> set: + return {r[SOURCE["key"]] for r in sp.archive_records()} + + +def test_every_captured_record_is_archived(sp): + keys = sp.eventually(lambda: archived_keys(sp), timeout=120) + missing = {r[SOURCE["key"]] for r in sp.source_sql(f"SELECT {SOURCE['key']} FROM {SOURCE['table']}")} - keys + assert not missing, f"source rows captured but not archived: {sorted(missing)}" + + +def test_archived_records_are_the_source_records_unchanged(sp): + """The archive holds what the source sent, not what the transform made of it.""" + archived = {r[SOURCE["key"]]: r for r in sp.archive_records()} + for row in sp.source_sql(f"SELECT * FROM {SOURCE['table']} WHERE {SOURCE['key']} < 900"): + record = archived.get(row[SOURCE["key"]]) + assert record is not None + assert record["cust_name"] == row["cust_name"] + assert record["cust_type"] == row["cust_type"] + + +def test_the_archive_is_partitioned_by_day(sp): + """A replay asks for a date range, so the archive has to be partitioned by one.""" + partitions = sp.archive_partitions() + assert partitions, "the archive has no dt= partitions" + for day in partitions: + assert len(day) == 10 and day[4] == "-", f"{day} is not a yyyy-MM-dd partition" + + +@pytest.mark.slow +def test_replaying_the_archive_puts_the_records_back_on_the_raw_topic(sp): + """The whole point of keeping the archive, end to end: the records come back, the transform + runs again, and the canonical product is upserted rather than duplicated.""" + topic = EXPECT["capture"]["raw_topic"] + day = sp.archive_partitions()[-1] + before = len([1 for _, value in sp.raw(topic) if value]) + sp.replay(since=day, until=day) + + after = sp.eventually( + lambda: len([1 for _, value in sp.raw(topic) if value]) > before and + len([1 for _, value in sp.raw(topic) if value]), + timeout=180, + ) + assert after > before, "the replay put nothing back on the raw topic" + + delivery = EXPECT["delivery"] + for case in ACCEPTED: + from semprini_data_bus.testing import deterministic_id + + key = deterministic_id(SOURCE["system"], SOURCE["object"], case["source_key"]) + rows = sp.eventually(lambda: sp.target_sql( + f"SELECT * FROM {delivery['schema']}.{delivery['table']} WHERE {delivery['key']} = '{key}'" + )) + assert len(rows) == 1, f"the replay duplicated source {case['source_key']}" diff --git a/source_aligned_cdc_data_product/tests/test_capture.py b/source_aligned_cdc_data_product/tests/test_capture.py new file mode 100644 index 0000000..15c033e --- /dev/null +++ b/source_aligned_cdc_data_product/tests/test_capture.py @@ -0,0 +1,75 @@ +"""Capture: the source system's rows reach the raw topic, unreshaped and keyed by the source key. + +Generic: everything specific to a product is in expectations.yaml. Run with +``uv run data-bus unit `` from semprini-data, after ``data-bus fixture up`` and +``data-bus deploy``. +""" + +from __future__ import annotations + +import json + +import pytest + +from semprini_data_bus.testing import expectations_for + +EXPECT = expectations_for(__file__) +SOURCE = EXPECT["source"] +CAPTURE = EXPECT["capture"] + + +def test_the_source_fixture_holds_the_rows_the_expectations_describe(sp): + rows = sp.source_sql(f"SELECT count(*) AS n FROM {SOURCE['table']} WHERE {SOURCE['key']} < 900") + assert rows[0]["n"] == SOURCE["rows"], "the fixture was reseeded or a test left a row behind" + + +def test_every_source_row_is_on_the_raw_topic(sp): + keys = {json.loads(key)[SOURCE["key"]] for key, _ in sp.raw(CAPTURE["raw_topic"]) if key} + missing = {r[SOURCE["key"]] for r in sp.source_sql(f"SELECT {SOURCE['key']} FROM {SOURCE['table']}")} - keys + assert not missing, f"source rows never captured: {sorted(missing)}" + + +def test_raw_records_keep_the_source_shape(sp): + values = [value for _, value in sp.raw(CAPTURE["raw_topic"]) if value] + assert values, "the raw topic is empty" + columns = {c["column_name"] for c in sp.source_sql( + "SELECT column_name FROM information_schema.columns " + f"WHERE table_schema || '.' || table_name = '{SOURCE['object']}'" + )} + for value in values: + present = {k for k in value if not k.startswith("__")} + assert present <= columns, f"the raw record has fields the source does not: {present - columns}" + + +def test_raw_records_are_keyed_by_the_source_key(sp): + for key, value in sp.raw(CAPTURE["raw_topic"]): + assert key, "a raw record has no key: changes to one source row would not stay in order" + assert json.loads(key)[SOURCE["key"]] == value[SOURCE["key"]] + + +@pytest.mark.parametrize("field", CAPTURE["provenance_fields"]) +def test_raw_records_carry_capture_provenance(sp, field): + """Every record for a row the source still holds says where and when it came from. + + Scoped to those rows because the raw topic is an audit log kept for days: it also holds + records for rows since deleted, and records earlier test runs put there. + """ + current = {r[SOURCE["key"]] for r in sp.source_sql(f"SELECT {SOURCE['key']} FROM {SOURCE['table']}")} + records = [v for _, v in sp.raw(CAPTURE["raw_topic"]) if v and v.get(SOURCE["key"]) in current] + assert records, "no record on the raw topic belongs to a row the source still holds" + for value in records: + assert field in value, f"{field} is missing: the record cannot be traced back to the source" + + +@pytest.mark.skipif("probe" not in CAPTURE, reason="the product declares no capture probe") +def test_a_new_source_row_is_captured_while_the_product_runs(sp): + """Capture is live, not a snapshot taken once at deploy time.""" + probe = CAPTURE["probe"] + sp.source_execute(probe["insert"]) + try: + sp.eventually(lambda: any( + value and value[SOURCE["key"]] == probe["source_key"] + for _, value in sp.raw(CAPTURE["raw_topic"]) + )) + finally: + sp.source_execute(probe["delete"]) diff --git a/source_aligned_cdc_data_product/tests/test_delivery.py b/source_aligned_cdc_data_product/tests/test_delivery.py new file mode 100644 index 0000000..eb35668 --- /dev/null +++ b/source_aligned_cdc_data_product/tests/test_delivery.py @@ -0,0 +1,83 @@ +"""Delivery: the records arrive in the canonical product, and a replay does not duplicate them. + +These tests reach into the target domain, so they need its repository on this machine +(``SEMPRINI_DOMAIN_DIR``, the target's ``repo`` in product.yaml, or a checkout beside +semprini-data). They skip when it is not there, because a source-aligned product is deployable +without it — but nothing proves the contract like the row appearing on the other side. + +They do not rely on the delivery that happened once, when the product was first deployed: +they replay the source rows first, which is exactly what a re-snapshot does, so the delivery is +proved again on every run. conftest.py removes the parties afterwards, so the canonical +product's own seed and tests are unaffected. +""" + +from __future__ import annotations + +import pytest + +from semprini_data_bus.testing import deterministic_id, expectations_for + +EXPECT = expectations_for(__file__) +SOURCE = EXPECT["source"] +TRANSFORM = EXPECT["transform"] +DELIVERY = EXPECT["delivery"] +ACCEPTED = TRANSFORM["accepted"] +REJECTED = TRANSFORM.get("rejected", []) +TABLE = f"{DELIVERY['schema']}.{DELIVERY['table']}" + + +def canonical_id(source_key) -> str: + return deterministic_id(SOURCE["system"], SOURCE["object"], source_key) + + +def rows_for(sp, party_id) -> list[dict]: + return sp.target_sql(f"SELECT * FROM {TABLE} WHERE {DELIVERY['key']} = '{party_id}'") + + +def replay(sp, source_keys) -> None: + """Put the source's own rows back on the raw topic, as a re-snapshot would.""" + columns = ", ".join(SOURCE["replay_columns"]) + keys = ", ".join(str(k) for k in source_keys) + rows = sp.source_sql( + f"SELECT {columns} FROM {SOURCE['table']} WHERE {SOURCE['key']} IN ({keys})" + ) + envelope = EXPECT["capture"].get("replay_envelope") or {} + sp.publish_raw(EXPECT["capture"]["raw_topic"], [{**row, **envelope} for row in rows], SOURCE["key"]) + + +@pytest.fixture(scope="module", autouse=True) +def delivered(sp): + """Deliver the rows this module asserts on, every run.""" + replay(sp, [c["source_key"] for c in ACCEPTED] + [c["source_key"] for c in REJECTED]) + + +@pytest.mark.parametrize("case", ACCEPTED, ids=[str(c["source_key"]) for c in ACCEPTED]) +def test_an_accepted_record_reaches_the_canonical_product(sp, case): + rows = sp.eventually(lambda: rows_for(sp, canonical_id(case["source_key"]))) + assert len(rows) == 1 + for field, expected in case["record"].items(): + assert rows[0][field] == expected, f"{field} of source {case['source_key']} in {TABLE}" + + +@pytest.mark.parametrize("case", REJECTED, ids=[str(c["source_key"]) for c in REJECTED]) +def test_a_rejected_record_never_reaches_the_canonical_product(sp, case): + assert rows_for(sp, canonical_id(case["source_key"])) == [], ( + f"source {case['source_key']} breaks a canonical rule but is in {TABLE}" + ) + + +def test_replaying_a_source_record_upserts_rather_than_duplicates(sp): + """A re-snapshot, a restarted connector or a replayed raw topic must not create a second + party: that is what deriving the identifier from the source key buys.""" + case = ACCEPTED[0] + key = canonical_id(case["source_key"]) + sp.eventually(lambda: rows_for(sp, key)) + replay(sp, [case["source_key"]]) + + def one_row_still(): + rows = rows_for(sp, key) + assert len(rows) == 1, f"the replay produced {len(rows)} rows for {key}" + return rows + + rows = sp.eventually(one_row_still, timeout=45) + assert rows[0]["legal_name"] == case["record"]["legal_name"] diff --git a/source_aligned_cdc_data_product/tests/test_dlq.py b/source_aligned_cdc_data_product/tests/test_dlq.py new file mode 100644 index 0000000..ce65b6e --- /dev/null +++ b/source_aligned_cdc_data_product/tests/test_dlq.py @@ -0,0 +1,72 @@ +"""Dead letters: what cannot be transformed is quarantined with its reason, and the flow continues. + +This is why a source-aligned product exists between a source system and a canonical one. A +record the canonical product's ODS would refuse fails its Flink job's JDBC sink, and that +failure takes down the TaskManager and every other product's job on it +(semprini-data/docs/technology-review-2026-09-18.md). Validating here, before publishing, +keeps a bad row in the source system from stopping a domain. +""" + +from __future__ import annotations + +import json + +import pytest + +from semprini_data_bus.testing import deterministic_id, expectations_for + +EXPECT = expectations_for(__file__) +SOURCE = EXPECT["source"] +TRANSFORM = EXPECT["transform"] +REJECTED = TRANSFORM.get("rejected", []) +PROBES = TRANSFORM.get("probe_records") or {} + + +def dead_letters(sp, source_key) -> list[dict]: + return [d for d in sp.dlq() if d.get("source_key") == str(source_key)] + + +@pytest.mark.parametrize("case", REJECTED, ids=[str(c["source_key"]) for c in REJECTED]) +def test_a_record_that_breaks_a_canonical_rule_is_on_the_dead_letter_topic(sp, case): + letters = sp.eventually(lambda: dead_letters(sp, case["source_key"])) + assert any(case["reason_contains"] in d["reason"] for d in letters), ( + f"source {case['source_key']} was rejected, but no reason mentions " + f"{case['reason_contains']}: {[d['reason'] for d in letters]}" + ) + + +@pytest.mark.parametrize("case", REJECTED, ids=[str(c["source_key"]) for c in REJECTED]) +def test_a_dead_letter_carries_the_original_record_and_where_it_came_from(sp, case): + """A dead letter is only useful if it can be corrected at the source and replayed.""" + letter = sp.eventually(lambda: dead_letters(sp, case["source_key"]))[0] + assert letter["source_system"] == SOURCE["system"] + assert letter["source_object"] == SOURCE["object"] + assert letter["stage"] == "transform" + original = json.loads(letter["record"]) + assert original[SOURCE["key"]] == case["source_key"] + + +def test_dead_letters_are_keyed_by_the_source_key(sp): + dlq = sp.product.dlq + for key, value in sp.raw(dlq.name): + if value is not None: + assert key == value["source_key"], "rejections of one source row would not stay in order" + + +@pytest.mark.skipif(not PROBES, reason="the product declares no transform probe records") +def test_a_poison_record_is_quarantined_and_the_next_record_still_arrives(sp): + """The property the whole design rests on: one bad record costs one record, not the flow.""" + bad, good = PROBES["bad"], PROBES["good"] + topic = EXPECT["capture"]["raw_topic"] + sp.publish_raw(topic, [bad["record"], good["record"]], key_field=SOURCE["key"]) + + letters = sp.eventually(lambda: dead_letters(sp, bad["source_key"])) + assert any(bad["reason_contains"] in d["reason"] for d in letters) + + key = deterministic_id(SOURCE["system"], SOURCE["object"], good["source_key"]) + record = sp.eventually(lambda: {k: v for k, v in sp.target_records(TRANSFORM["target_topic"])}.get(key)) + assert record["legal_name"] == good["legal_name"] + assert record["party_type"] == good["party_type"] + assert deterministic_id(SOURCE["system"], SOURCE["object"], bad["source_key"]) not in { + k for k, _ in sp.target_records(TRANSFORM["target_topic"]) + } diff --git a/source_aligned_cdc_data_product/tests/test_transform.py b/source_aligned_cdc_data_product/tests/test_transform.py new file mode 100644 index 0000000..3f8f1c8 --- /dev/null +++ b/source_aligned_cdc_data_product/tests/test_transform.py @@ -0,0 +1,72 @@ +"""Transform: source records become canonical records, keyed by the canonical identifier. + +The semantic half of a source-aligned product. Generic: the mapping itself is in +expectations.yaml, and the identifiers are derived with the platform's identity rule rather +than written down, so these tests check the rule the transform implements. +""" + +from __future__ import annotations + +import pytest + +from semprini_data_bus.testing import deterministic_id, expectations_for + +EXPECT = expectations_for(__file__) +SOURCE = EXPECT["source"] +TRANSFORM = EXPECT["transform"] +ACCEPTED = TRANSFORM["accepted"] +REJECTED = TRANSFORM.get("rejected", []) + + +def canonical_id(source_key) -> str: + return deterministic_id(SOURCE["system"], SOURCE["object"], source_key) + + +def published(sp) -> dict[str, dict]: + """The latest record published for each canonical identifier.""" + return {key: value for key, value in sp.target_records(TRANSFORM["target_topic"]) if value} + + +@pytest.mark.parametrize("case", ACCEPTED, ids=[str(c["source_key"]) for c in ACCEPTED]) +def test_an_acceptable_source_record_is_published_as_a_canonical_record(sp, case): + key = canonical_id(case["source_key"]) + record = sp.eventually(lambda: published(sp).get(key)) + for field, expected in case["record"].items(): + assert record[field] == expected, f"{field} of source {case['source_key']}" + + +def test_published_records_are_keyed_by_the_canonical_identifier(sp): + """Only a key keeps changes to one entity in order, and the key must be the one the + canonical product upserts on.""" + target_key = TRANSFORM["target_key"] + for key, value in sp.target_records(TRANSFORM["target_topic"]): + assert key, "a record was published without a key" + if value is not None: + assert value[target_key] == key, f"message key {key} is not the record's {target_key}" + + +def test_the_identifier_is_derived_from_the_source_key(sp): + """Deterministic identity: re-capturing the same source row must upsert, not duplicate.""" + keys = set(published(sp)) + for case in ACCEPTED: + assert canonical_id(case["source_key"]) in keys, ( + f"source {case['source_key']} was published under an identifier that is not derived " + "from its source key" + ) + + +@pytest.mark.parametrize("header", TRANSFORM["headers"]) +def test_every_published_record_carries_provenance(sp, header): + """Where a record came from travels in headers, so the payload stays canonical.""" + messages = [m for m in sp.target_messages(TRANSFORM["target_topic"]) + if m["key"] in {canonical_id(c["source_key"]) for c in ACCEPTED}] + assert messages, "none of the expected records are on the target topic" + for message in messages: + assert message["headers"].get(header), f"{header} is missing from {message['key']}" + + +@pytest.mark.parametrize("case", REJECTED, ids=[str(c["source_key"]) for c in REJECTED]) +def test_a_rejected_source_record_is_never_published(sp, case): + assert canonical_id(case["source_key"]) not in published(sp), ( + f"source {case['source_key']} reached the canonical product although it breaks its rules" + )