37  Change-data-capture on a trigger topic — publish, filtered subscribe, resume

Verbs: register_topic · publish_topic · subscribe_collect (predicate / from_offset / replay_only / max_batches) · list_topics · Background: the offset-addressed, append-only commit log — Kafka-style publish → replay-from-offset (Kreps, Narkhede, and Rao 2011) — as the streaming complement of the append-only result log (Kleppmann 2017) · Checked: measurement (every collected stream equals the change set it claims to carry, counted from the source tables).

The result log writes derived results once, append-only (Kleppmann 2017). A trigger topic is its streaming complement: an offset-addressed, append-only commit log of events. You register_topic with a row schema and publish_topic batches onto it, each landing at the next 0-based offset; a consumer collects by replaying the log from an offset it chose. That is the Kafka model (Kreps, Narkhede, and Rao 2011), and it is the substrate change-data-capture (CDC) rides: a stream of record changes that a downstream subscribes to selectively and resumes from a checkpoint.

The changes here are real: the ogbn-arxiv corpus as it grew. Each publication year is one batch of events — an add for every paper published that year and a cite for every citation those papers make. The embedded Database runs the topic on its in-process broker, with no server and no external broker.

import tempfile
import threading

import jammi
import pyarrow as pa
import pyarrow.compute as pc
from jammi_cookbook import datasets, scale
from jammi_cookbook.claims import claim

SCALE = scale.current()
db = jammi.connect(f"file://{tempfile.mkdtemp()}")
arxiv = datasets.arxiv(db, SCALE)
PAPERS = f"{arxiv.papers}.public.{arxiv.papers}"
CITES = f"{arxiv.cites}.public.{arxiv.cites}"

37.1 Register the topic and publish the corpus’s history

A change event names its operation, the paper it concerns, and the year it happened; ref is the paper’s subject for an add and the cited paper for a cite.

SCHEMA = pa.schema([
    ("op", pa.string()),
    ("paper_id", pa.string()),
    ("year", pa.int64()),
    ("ref", pa.string()),
])
db.register_topic("paper_changes", schema=SCHEMA)
print(db.list_topics())

changes = db.sql(
    f"SELECT 'add' AS op, paper_id, year, subject AS ref FROM {PAPERS} "
    f"UNION ALL SELECT 'cite' AS op, c.src AS paper_id, p.year, c.dst AS ref "
    f"FROM {CITES} c JOIN {PAPERS} p ON c.src = p.paper_id"
).cast(SCHEMA)
years = sorted(set(changes.column("year").to_pylist()))
offset_of = {
    year: db.publish_topic("paper_changes", batch=changes.filter(pc.equal(changes["year"], year)))
    for year in years
}
print(f"{changes.num_rows} events in {len(years)} yearly batches, offsets 0..{len(years) - 1}")
['paper_changes']
1977 events in 7 yearly batches, offsets 0..6
claim("each publish takes the next offset", list(offset_of.values()) == list(range(len(years))))
✓ each publish takes the next offset

37.2 Replay the log — a collect is a finite drain

subscribe_collect replays the topic’s backing table from from_offset and returns: every batch published so far, as one table. The log is the source’s history, so the replay holds exactly one event per paper and one per citation.

def rows(sql: str) -> int:
    return db.sql(sql).column(0)[0].as_py()


papers, cites = rows(f"SELECT COUNT(*) FROM {PAPERS}"), rows(f"SELECT COUNT(*) FROM {CITES}")
replay = db.subscribe_collect("paper_changes", from_offset=0)
print(f"replayed {replay.num_rows} events = {papers} papers + {cites} citations")
replayed 1977 events = 400 papers + 1577 citations
claim("the replay holds exactly one event per paper and one per citation",
      replay.num_rows == papers + cites, f"{replay.num_rows} = {papers} + {cites}")
✓ the replay holds exactly one event per paper and one per citation (1977 = 400 + 1577)

37.3 A selective subscribe — only the new papers

A downstream that indexes papers wants the adds alone. The predicate is SQL over the topic’s schema, applied as the log is read; a batch with no matching row is not delivered at all.

adds = db.subscribe_collect("paper_changes", predicate="op = 'add'", from_offset=0)
print(f"{adds.num_rows} add events; the first few:")
for event in adds.slice(0, 3).to_pylist():
    print(" ", event)
400 add events; the first few:
  {'op': 'add', 'paper_id': '1522301498', 'year': 2014, 'ref': 'arxiv cs lg'}
  {'op': 'add', 'paper_id': '1583912456', 'year': 2014, 'ref': 'arxiv cs lg'}
  {'op': 'add', 'paper_id': '1779483307', 'year': 2015, 'ref': 'arxiv cs lg'}
claim("the predicate delivers every add and nothing else",
      adds.num_rows == papers and set(adds.column("op").to_pylist()) == {"add"})
✓ the predicate delivers every add and nothing else

37.4 Resume from a checkpoint

A CDC consumer stores its progress as an offset and resumes from it. One that has processed the corpus through 2018 resumes at the first test-era batch, and reads exactly the changes it has not seen.

CHECKPOINT = offset_of[min(y for y in years if y >= 2019)]
tail = db.subscribe_collect("paper_changes", from_offset=CHECKPOINT)
unseen = rows(
    f"SELECT (SELECT COUNT(*) FROM {PAPERS} WHERE year >= 2019) + "
    f"(SELECT COUNT(*) FROM {CITES} c JOIN {PAPERS} p ON c.src = p.paper_id WHERE p.year >= 2019)"
)
print(f"resumed at offset {CHECKPOINT}: {tail.num_rows} events ({unseen} changes since 2018)")
resumed at offset 5: 701 events (701 changes since 2018)
claim("resuming at the checkpoint reads exactly the changes not yet seen",
      tail.num_rows == unseen, f"{tail.num_rows} events")
✓ resuming at the checkpoint reads exactly the changes not yet seen (701 events)

37.5 Resume and filter — a downstream feature, kept current

The two compose. A consumer maintaining each paper’s citation in-degree (the feature of the feature-store chapter) resumes at its checkpoint and reads only the cite events: each is one unit of in-degree for the paper it names in ref. Folded, the stream gives exactly the in-degree the test era added.

new_cites = db.subscribe_collect(
    "paper_changes", predicate="op = 'cite'", from_offset=CHECKPOINT
)
increments = new_cites.group_by("ref").aggregate([("ref", "count")])
from_source = db.sql(
    f"SELECT c.dst AS ref, COUNT(*) AS n FROM {CITES} c "
    f"JOIN {PAPERS} p ON c.src = p.paper_id WHERE p.year >= 2019 GROUP BY c.dst"
).to_pylist()
agree = dict(zip(increments["ref"].to_pylist(), increments["ref_count"].to_pylist())) == {
    r["ref"]: r["n"] for r in from_source
}
print(f"{new_cites.num_rows} new citations across {increments.num_rows} papers; "
      f"stream agrees with the source: {agree}")
605 new citations across 208 papers; stream agrees with the source: True
claim("the folded stream gives exactly the in-degree the test era added", agree,
      f"{new_cites.num_rows} citations")
✓ the folded stream gives exactly the in-degree the test era added (605 citations)

37.6 Following the live tail

A replay ends; a live consumer does not. With replay_only=False the collect reads the replay and then follows the broker, waiting for what is published next, and returns once max_batches batches have arrived. The tail never ends on its own, so max_batches is required; without it the call is refused rather than left to wait forever. Here a follower waits on the next offset while a correction — a paper retracted — is published.

next_offset = len(years)
followed = {}
follower = threading.Thread(
    target=lambda: followed.setdefault(
        "batch",
        db.subscribe_collect(
            "paper_changes", from_offset=next_offset, replay_only=False, max_batches=1
        ),
    )
)
follower.start()
retracted = adds.column("paper_id")[0].as_py()
db.publish_topic(
    "paper_changes",
    batch=pa.table({"op": ["retract"], "paper_id": [retracted], "year": [2020], "ref": [None]},
                   schema=SCHEMA),
)
follower.join(timeout=60)
print(followed["batch"].to_pylist())
[{'op': 'retract', 'paper_id': '1522301498', 'year': 2020, 'ref': None}]
claim("the follower receives the correction published while it waited",
      followed["batch"].column("op").to_pylist() == ["retract"])
✓ the follower receives the correction published while it waited
db.close()

37.7 Bridge note

A trigger topic is an offset-addressed commit log. The engine writes derived results as an append-only log of immutable Parquet (Kleppmann 2017); a topic is the streaming complement — an append-only log of events a consumer replays from an offset it stored, the Kafka model (Kreps, Narkhede, and Rao 2011). CDC rides it directly: publish a source’s changes, collect them with a predicate, resume from a checkpoint, or follow the live tail. The measured property is the one CDC depends on — the collected stream is exactly the change set it claims to carry: every paper, every citation, the unseen tail, and the feature it folds into.

Kleppmann, Martin. 2017. Designing Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and Maintainable Systems. O’Reilly Media.
Kreps, Jay, Neha Narkhede, and Jun Rao. 2011. “Kafka: A Distributed Messaging System for Log Processing.” In Proceedings of the NetDB Workshop on Networking Meets Databases, 1–7.