Importing weather data again: checkpoints and revisions instead of duplicates
Use Python and MySQL/InnoDB to preserve batch provenance, distinguish replay from correction and resume imports after process termination.
After an importer is interrupted, the hardest question is a simple one: which data have we actually accepted? A process may receive a batch, write some rows and terminate before reporting success. Repeating the request is easy. The harder task is preventing that repetition from adding another copy of the same forecast values while still accepting a genuine correction from the source.
This requires three separate concepts: an immutable batch, the identity of a forecast row and its revision. A checkpoint connects them to completed work. We will use a small Python 3.12+ and MySQL 8.4/InnoDB exercise with PyMySQL[rsa] 1.2.4. All data are fictional, and restarting means opening a new connection to the same retained schema. No external weather service participates in this experiment; database operations use MySQL TCP.
One batch is not one forecast row
Imagine a batch containing humidity forecasts for two fictional places: harbor and ridge. For the twelfth hour of a fictional run, it contains 64 and 71 percent. The next batch might repeat those values, correct one of them or contain a different model. If only the batch number is unique, a repeated row arriving in another batch will enter the table again.
A row's identity in this exercise therefore includes its source, model, run, place, quantity and forecast hour. The batch number is excluded. The hour is a relative index in a synthetic run, not a calendar timestamp. Place identifiers are already assigned: the importer neither searches for towns nor tries to merge them by similar names.
A separate batch key consists of the source and batch_id. This allows two independent sources to use the same batch name while retaining different provenance. However, changing the model or run under an already registered batch key is prohibited because it changes the batch document.
First, pin the source and the received bytes
Registration accepts the document and the expected source from the call's configuration. The document must name that source. An unknown source or a mismatch between configuration and content is rejected. A field inside JSON cannot establish trusted provenance on its own.
The complete document is stored in MySQL in a LONGBLOB column before any rows are processed. Its digest is stored alongside it, but registration compares the actual bytes on a repeated submission. Under the same batch key, identical bytes mean replay; different bytes mean conflict. Even an added newline produces a different document. Registration attempts the insert first; only duplicate-key error 1062 leads to a locking read of the existing document and a byte comparison. Other errors are not disguised as replay. This is a deliberately strict contract for the exercise, not a universal requirement for weather APIs.
That decision matters during recovery. After a restart, the importer reads the pinned document instead of fetching whatever the provider now returns at an old address. Otherwise, position 17 could refer to different rows in two response versions. A real integration may establish immutability through another mechanism, but that mechanism needs its own evidence.
The document also has limits: at most 64 KiB and 100 rows, known fields, unique JSON member names and integer humidity values from 0 to 100. Boolean true is not accepted as a number. These boundaries make the teaching format explicit. They do not describe every weather quantity or a real supplier's rules.
A revision distinguishes correction from replay
An initial row has revision = 1 and previous = 0. A correction must supply the next revision and identify the expected predecessor. For example, humidity at harbor changes from 64 to 66 when moving from revision one to revision two. The ridge row remains unchanged.
| Input | Decision |
|---|---|
| New row, revision 1, predecessor 0 | Store the initial version |
| Known identity and revision, identical content | Record a replay |
| Known identity and revision, different content | Reject the conflict |
| Next revision with the expected current version | Store a correction |
| Revision 3 when the current revision is only 1 | Stop before this row |
Row content is compared using a stable JSON representation of validated fields. Member order does not change its meaning. This is a different layer from pinning the entire batch byte for byte. A new batch may format the same row differently; formatting cannot change under the old batch key.
Revision history is retained separately from the pointer to the current revision. After a correction, an unchanged older row is still recognized as a replay. It does not move the current version backwards. If an old revision is repeated with a different value, the conflict is detected even after a restart.
The program does not guess a missing revision. If revision two arrives before revision one, the batch remains at the unprocessed row. Once revision one arrives, that same pinned batch can continue. Sources that number corrections differently, or provide no such number, require a different agreed contract.
A checkpoint describes a completed prefix
next_index is the position of the next unprocessed row. A value of 1 in a two-row batch means the first row has completed and the second has not. It does not mean “roughly half downloaded” or “the provider confirmed the entire batch.”
Each row is processed in its own transaction. That transaction changes the version history, the current-version pointer, the row's processing receipt and the checkpoint. A replay does not expand version history, but a receipt for its processing in a new batch remains. This shows where the replay arrived without creating another forecast value.
The implementation below contains an explicit schema initializer and the importer. The InnoDB tables use foreign keys and CHECK constraints; textual identities use VARCHAR with utf8mb4_0900_bin, while revision JSON payloads use LONGTEXT. Before use, a separate migrator connection calls Importer.initialize(). MySQL DDL can implicitly commit transactions: this is neither an atomic schema upgrade nor an automatic data transfer from the old SQLite database. The importer constructor executes no DDL; the runtime account has DML privileges only and cannot execute CREATE, ALTER or DROP.
"""Synthetic weather import exercise using native MySQL 8.4/InnoDB.
Initialize explicitly with a migrator connection before using DML-only runtime
connections. Retain the schema, batch bytes and revision history for replay.
Reconnect tests demonstrate committed persistence, not filesystem durability.
There are no external service calls; database operations use MySQL TCP.
"""
from __future__ import annotations
from contextlib import contextmanager
import hashlib
import json
import re
from typing import Callable
import pymysql
from pymysql.connections import Connection
from pymysql.constants.SERVER_STATUS import SERVER_STATUS_IN_TRANS
class Rejected(ValueError):
"""The declared input contract or immutable identity was violated."""
KNOWN_SOURCES = frozenset({"fake-north", "fake-south"})
MAX_BYTES = 65_536
MAX_ROWS = 100
TOKEN = re.compile(r"[a-z][a-z0-9-]{0,39}\Z")
# The existing domain permits at most 162 ASCII characters in canonical identity:
# source(10), model/run/place(3*40), metric(12), hour(3), JSON punctuation(17).
MAX_IDENTITY = 162
SCHEMA = (
"""CREATE TABLE IF NOT EXISTS batches (
source VARCHAR(10) COLLATE utf8mb4_0900_bin NOT NULL,
batch_id VARCHAR(40) COLLATE utf8mb4_0900_bin NOT NULL,
raw_document LONGBLOB NOT NULL,
digest CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
total INT NOT NULL CHECK(total >= 0 AND total <= 100),
next_index INT NOT NULL DEFAULT 0,
PRIMARY KEY(source, batch_id),
CHECK(next_index >= 0 AND next_index <= total)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin""",
"""CREATE TABLE IF NOT EXISTS row_locks (
row_key VARCHAR(162) COLLATE utf8mb4_0900_bin PRIMARY KEY
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin""",
"""CREATE TABLE IF NOT EXISTS versions (
row_key VARCHAR(162) COLLATE utf8mb4_0900_bin NOT NULL,
revision INT NOT NULL CHECK(revision > 0 AND revision <= 1000000),
payload LONGTEXT NOT NULL,
first_source VARCHAR(10) COLLATE utf8mb4_0900_bin NOT NULL,
first_batch_id VARCHAR(40) COLLATE utf8mb4_0900_bin NOT NULL,
PRIMARY KEY(row_key, revision),
FOREIGN KEY(first_source, first_batch_id) REFERENCES batches(source, batch_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin""",
"""CREATE TABLE IF NOT EXISTS current_rows (
row_key VARCHAR(162) COLLATE utf8mb4_0900_bin PRIMARY KEY,
revision INT NOT NULL,
FOREIGN KEY(row_key, revision) REFERENCES versions(row_key, revision)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin""",
"""CREATE TABLE IF NOT EXISTS receipts (
source VARCHAR(10) COLLATE utf8mb4_0900_bin NOT NULL,
batch_id VARCHAR(40) COLLATE utf8mb4_0900_bin NOT NULL,
position INT NOT NULL CHECK(position >= 0 AND position < 100),
row_key VARCHAR(162) COLLATE utf8mb4_0900_bin NOT NULL,
revision INT NOT NULL,
outcome VARCHAR(9) COLLATE utf8mb4_0900_bin NOT NULL,
PRIMARY KEY(source, batch_id, position),
CHECK(outcome IN ('inserted', 'corrected', 'replay')),
FOREIGN KEY(source, batch_id) REFERENCES batches(source, batch_id),
FOREIGN KEY(row_key, revision) REFERENCES versions(row_key, revision)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin""",
)
def canonical(value: object) -> str:
return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
def unique_object(pairs: list[tuple[str, object]]) -> dict:
result = {}
for key, value in pairs:
if key in result:
raise Rejected("duplicate JSON member")
result[key] = value
return result
def token(value: object) -> bool:
return type(value) is str and TOKEN.fullmatch(value) is not None
def integer(value: object, low: int, high: int) -> bool:
return type(value) is int and low <= value <= high
def identity(doc: dict, row: dict) -> str:
return canonical([doc["source"], doc["model"], doc["run"], row["place"],
"humidity_pct", row["valid_hour"]])
def decode(raw: bytes, expected_source: str) -> dict:
if expected_source not in KNOWN_SOURCES:
raise Rejected("unknown configured source")
if type(raw) is not bytes or not 0 < len(raw) <= MAX_BYTES:
raise Rejected("batch byte limit")
try:
doc = json.loads(raw.decode("utf-8"), object_pairs_hook=unique_object)
except (ValueError, UnicodeError, RecursionError) as exc:
raise Rejected("invalid UTF-8 JSON") from exc
if type(doc) is not dict or set(doc) != {"source", "batch_id", "model", "run", "rows"}:
raise Rejected("batch members")
if doc["source"] != expected_source:
raise Rejected("declared source differs from configured source")
if not all(token(doc[k]) for k in ("batch_id", "model", "run")):
raise Rejected("batch token")
if type(doc["rows"]) is not list or len(doc["rows"]) > MAX_ROWS:
raise Rejected("row limit")
for row in doc["rows"]:
if type(row) is not dict or set(row) != {"place", "valid_hour", "revision", "previous", "humidity_pct"}:
raise Rejected("row members")
if not token(row["place"]) or not integer(row["valid_hour"], 0, 168):
raise Rejected("row identity")
if not integer(row["revision"], 1, 1_000_000) or not integer(row["previous"], 0, 999_999):
raise Rejected("revision integer")
if row["revision"] != row["previous"] + 1:
raise Rejected("revision must name its immediate predecessor")
if not integer(row["humidity_pct"], 0, 100):
raise Rejected("humidity integer")
if len(identity(doc, row)) > MAX_IDENTITY:
raise Rejected("row identity length")
return doc
def require_idle(db: Connection) -> None:
if db.server_status & SERVER_STATUS_IN_TRANS:
raise RuntimeError("operation requires no ambient transaction")
class Importer:
def __init__(self, connection: Connection):
if not isinstance(connection, Connection):
raise TypeError("Importer requires a native PyMySQL Connection")
self.db = connection
@staticmethod
def initialize(migrator: Connection) -> None:
"""DDL is explicit, privileged, and never part of a business transaction."""
require_idle(migrator)
with migrator.cursor() as cur:
for statement in SCHEMA:
cur.execute(statement)
@contextmanager
def _transaction(self):
require_idle(self.db)
self.db.begin()
try:
yield
self.db.commit()
except BaseException:
# A deadlock (1213) can already have rolled back the transaction.
# A lock timeout (1205) normally rolls back only its statement.
# Never roll back a transaction supplied by a caller.
if self.db.server_status & SERVER_STATUS_IN_TRANS:
self.db.rollback()
raise
def close(self) -> None:
self.db.close()
def register(self, raw: bytes, expected_source: str) -> str:
"""Pin exact bytes before processing; a batch identity is immutable."""
doc = decode(raw, expected_source)
source, batch_id = doc["source"], doc["batch_id"]
with self._transaction(), self.db.cursor() as cur:
# Insert first: the unique key serializes concurrent registration,
# including the initially absent-key case, without a gap-lock race.
try:
cur.execute(
"INSERT INTO batches(source,batch_id,raw_document,digest,total) VALUES(%s,%s,%s,%s,%s)",
(source, batch_id, raw, hashlib.sha256(raw).hexdigest(), len(doc["rows"])))
except pymysql.err.IntegrityError as exc:
if exc.args[0] != 1062:
raise
cur.execute(
"SELECT raw_document FROM batches WHERE source=%s AND batch_id=%s FOR UPDATE",
(source, batch_id))
old = cur.fetchone()
if old is None:
raise RuntimeError("duplicate batch disappeared") from exc
if old["raw_document"] != raw:
raise Rejected("batch identifier reused with different bytes")
return "replay"
return "registered"
def step(self, source: str, batch_id: str,
boundary: Callable[[str], None] | None = None) -> str:
"""Resolve one row and advance its checkpoint in one owned transaction.
The callback is a crash-injection seam, not a hook for nested operations.
Native lock errors propagate; callers may retry the entire operation.
"""
with self._transaction(), self.db.cursor() as cur:
cur.execute(
"SELECT raw_document,total,next_index FROM batches WHERE source=%s AND batch_id=%s FOR UPDATE",
(source, batch_id))
batch = cur.fetchone()
if batch is None:
raise Rejected("unknown batch")
raw, total, position = batch["raw_document"], batch["total"], batch["next_index"]
if position == total:
return "complete"
doc = decode(raw, source)
row = doc["rows"][position]
key, revision = identity(doc, row), row["revision"]
payload = canonical(row)
# A retained InnoDB mutex row serializes this forecast identity even
# when no current/version row exists yet. It is DML, not advisory or
# connection-lifetime locking. It commits/rolls back with the step.
cur.execute(
"INSERT INTO row_locks(row_key) VALUES(%s) ON DUPLICATE KEY UPDATE row_key=row_key",
(key,))
cur.execute(
"SELECT payload FROM versions WHERE row_key=%s AND revision=%s FOR UPDATE",
(key, revision))
old = cur.fetchone()
if old is not None:
if old["payload"] != payload:
raise Rejected("revision reused with different payload")
outcome = "replay"
else:
cur.execute("SELECT revision FROM current_rows WHERE row_key=%s FOR UPDATE", (key,))
active = cur.fetchone()
current_revision = 0 if active is None else active["revision"]
if current_revision != row["previous"]:
raise Rejected("unexpected current revision")
cur.execute(
"INSERT INTO versions(row_key,revision,payload,first_source,first_batch_id) VALUES(%s,%s,%s,%s,%s)",
(key, revision, payload, source, batch_id))
if active is None:
cur.execute("INSERT INTO current_rows(row_key,revision) VALUES(%s,%s)", (key, revision))
outcome = "inserted"
else:
changed = cur.execute(
"UPDATE current_rows SET revision=%s WHERE row_key=%s AND revision=%s",
(revision, key, row["previous"]))
if changed != 1:
raise Rejected("current revision changed")
outcome = "corrected"
if boundary:
boundary("after_row_before_checkpoint")
cur.execute(
"INSERT INTO receipts(source,batch_id,position,row_key,revision,outcome) VALUES(%s,%s,%s,%s,%s,%s)",
(source, batch_id, position, key, revision, outcome))
cur.execute(
"UPDATE batches SET next_index=%s WHERE source=%s AND batch_id=%s",
(position + 1, source, batch_id))
if boundary:
boundary("after_checkpoint_before_commit")
if boundary:
boundary("after_commit_before_reply")
return outcome
def run(self, source: str, batch_id: str) -> list[str]:
outcomes = []
while (outcome := self.step(source, batch_id)) != "complete":
outcomes.append(outcome)
return outcomes
def checkpoint(self, source: str, batch_id: str) -> tuple[int, int]:
with self.db.cursor() as cur:
cur.execute("SELECT next_index,total FROM batches WHERE source=%s AND batch_id=%s",
(source, batch_id))
row = cur.fetchone()
if row is None:
raise Rejected("unknown batch")
return row["next_index"], row["total"]
def current(self) -> list[dict]:
with self.db.cursor() as cur:
cur.execute("""SELECT v.row_key,v.revision,v.payload,v.first_source,v.first_batch_id
FROM current_rows c JOIN versions v ON c.row_key=v.row_key AND c.revision=v.revision
ORDER BY v.row_key""")
rows = cur.fetchall()
return [{"identity": json.loads(row["row_key"]), "revision": row["revision"],
"humidity_pct": json.loads(row["payload"])["humidity_pct"],
"first_batch": [row["first_source"], row["first_batch_id"]]} for row in rows]
def counts(self) -> tuple[int, int, int]:
result = []
with self.db.cursor() as cur:
for name in ("current_rows", "versions", "receipts"):
cur.execute(f"SELECT COUNT(*) AS n FROM {name}")
result.append(cur.fetchone()["n"])
return tuple(result)
Runtime PyMySQL connections use autocommit=True, but each importer operation explicitly calls begin(), followed by commit() or, on failure, rollback() for its own still-active transaction. These methods work with autocommit enabled; the PyMySQL connection documentation describes them. If the caller has already opened a transaction, the importer refuses the operation without committing or rolling it back.
With MySQL/InnoDB at REPEATABLE READ isolation, a step locks the batch row using SELECT … FOR UPDATE. A separate retained row in row_locks serializes processing of the same forecast identity even before its first revision exists; this is ordinary DML in the same transaction. Lock-wait timeout 1205 and deadlock 1213 propagate to the caller after cleanup of the owned transaction. The InnoDB error-handling documentation explains the difference between statement and transaction rollback. There is no automatic retry scheduler here.
If the first row is stored and the second conflicts, the first remains. The checkpoint points to the second. Another run rejects the conflict again while preserving the completed prefix. The failed batch cannot be replaced with new bytes under the same key. Fixing the source requires a new batch or a separate administrative decision outside this exercise.
Test an actual process termination
This exercise passed 38 unittest tests against actual MySQL 8.4. To repeat them, use Python 3.12+, the package PyMySQL[rsa]==1.2.4 and the shared guarded disposable MySQL lab fixture. From the project root, run bash fixtures/mysql_labs/run.sh python3 -B tools/weather-import-checkpoint-lab/test_importer.py. The tools/mysql_fixture.py helper supplies separate migrator and runtime connections; test setup explicitly initializes tables before the DML checks. Expected initial and corrected rows are declared as separate literal fixtures. The checks count current rows, historical versions and processing receipts, and also cover concurrent connections, native lock errors and the absence of constructor DDL.
Duplicates occur both within one batch and in another batch. This matters: using an empty schema for every replay would conceal the problem itself. Historical-replay checks retain the same schema and all revisions, then reconnect to them. Separate native connections also test concurrent batch registration and processing of identical forecast identities across different batches.
Three checks start a separate process and terminate it in a controlled way with os._exit(73) at selected transaction boundaries; this is not SIGKILL. The Python handler has no opportunity to perform a normal rollback. The child performs DML only: it neither creates tables nor drops the schema. The parent then opens a new connection to the same MySQL schema and checks its state.
| Process termination boundary | State after reopening the database |
|---|---|
| After the row write, before the checkpoint | Neither the new row nor progress is present |
After the checkpoint, before COMMIT |
The entire unfinished transaction is absent |
After COMMIT, before returning to the caller |
The row and checkpoint are already stored |
In the last case, the importer continues with the second row. The previous process's missing response does not require writing the first row again. Revision history, the current pointer, the processing receipt and the checkpoint are reconciled by one InnoDB transaction without DDL. The MySQL transaction documentation describes the boundaries of COMMIT and ROLLBACK. Reconnection checks persistence of committed state on the server, not the durability of an individual file.
These runs test abnormal client-process termination and resumption through a new connection. They do not reproduce a MySQL server crash, a power outage, a failing disk or a network partition, and they do not measure storage durability under those conditions.
What becomes easier to verify
After the first batch, the exercise has two current rows, two historical versions and two processing receipts. After one correction, there are still two current rows, but three historical versions and three receipts. Repeating the initial rows in another batch increases only the processing log: the current values remain corrected.
An empty batch also has a precise meaning: its zero rows are complete, but it created no forecast. A completed import does not establish freshness, complete forecast-horizon coverage or model accuracy. Those are separate properties of the data and display policy.
All knowledge of replays lives in the retained database. The importer deletes neither old batches nor revisions. If the schema and its data are lost, or an empty schema is used instead, history disappears and an old batch looks new again. The test models this with a separate empty MySQL schema, not a replacement file. Backups, retention and migrations must therefore preserve this identity contract.
Finally, the transaction does not cover an external queue, cache or forecast publication in another system. Those effects need their own acknowledgement and recovery protocol. The local checkpoint provides a useful, narrow answer: which rows of this immutable batch have already been reconciled with revision history in this database. That verifiable answer provides a sound starting point for the next import step.
The shared MySQL fixture and its files are introduced in the transaction chapter. Run commands from the single article_demo root; do not create a separate Symfony application for each article.
python3 -m venv .venv-mysql
.venv-mysql/bin/pip install -r tools/requirements-mysql.txt
PYTHONPATH=tools bash fixtures/mysql_labs/run.sh .venv-mysql/bin/python -B -m unittest discover -s tools/weather-import-checkpoint-lab -v