Add the source-aligned CDC template, and key the canonical template's topics

The first template of the source-aligned family: one data product per source
system, capturing a database by CDC and turning what it emits into what a
canonical product accepts. It runs on the Integration Bus, not in a domain, and
is deployed with the `data-bus` CLI.

What it produces, and what its tests hold it to: raw topics in the source's own
shape; deterministic identity, so a re-snapshot upserts rather than duplicating;
validation against the canonical product's rules before publishing, with what
fails going to the product's own dead-letter topic with the reason; keying by the
canonical identifier; provenance in headers; and an archive in the bus object
store that can be replayed back onto the raw topic.

The worked example captures an ERP customer table and delivers into Canonical
Party in the digital-core domain: 12 smoke checks, 37 unit tests, including a
poison record that is quarantined while the next record still arrives.

The canonical template's topics now declare the key producers must set, which is
the other half of that contract.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
paulandClaude Opus 5 committed 2026-09-18 10:54:39 +12:00
1 parent ca6bea351a
commit 866bcfe238
44 files changed
+2505 -11

No files matched your search

@@ -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})"
)
@@ -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"
@@ -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']}"
@@ -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 <product dir>`` 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"])
@@ -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"]
@@ -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"])
}
@@ -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"
)