По желанию
Повторить события без удвоения эффекта
Все события и целочисленные часы вымышлены. Локальная публикация использует лишь временный каталог; она не устанавливает удалённый exactly-once или сохранность при потере питания.
- Версия
- v2
- Минут
- ~20
- Проверка
- Самопроверка в ноутбуке
Пока нет автопроверки на платформе: сравните вывод ячеек с ожидаемыми числами в ноутбуке. Это не долг и не влияет на процент освоения.
Скачайте ноутбук и запустите его локально. Требования к окружению указаны внутри.
Содержимое ноутбука
Можно прочитать с телефона. Код ниже не выполнялся в браузере; для запуска скачайте ноутбук.
Replay events without duplicating their effect / Повторить события без удвоения эффекта
Optional practice. Python standard library only. The phone lesson does not require running code. No external dataset, account, model, paid API or production action.
Необязательная практика. Только стандартная библиотека Python. Для темы на телефоне запуск кода не нужен. Без внешнего датасета, аккаунта, модели, платного API или действий в продакшене.
Authored for the Fedor Pakhurov project with Codex assistance. Selected functions and fictional inputs come from the completely reviewed, published first-party revision 840854d82dc3f9e208c0ed88a92180ccde4e3803. Notebook packaging and additional self-checks are newly authored. No guarantee of exclusive copyright is asserted.
Reviewed note: https://github.com/fpakhurov/fpakhurov.com/blob/840854d82dc3f9e208c0ed88a92180ccde4e3803/src/content/notes/mlops/data-pipelines.mdx
First-party fixture: https://github.com/fpakhurov/fpakhurov.com/blob/840854d82dc3f9e208c0ed88a92180ccde4e3803/scripts/notes/mlops-data-cases.py
The note retains primary scientific references. No external source-specific code, figure, dataset or model result is reproduced in this notebook. Saved output environment: Python 3.9.7. Other interpreter versions can change final floating-point digits and hashes containing those computed values. Record the execution environment when comparing artifact identity.
Среда сохранённого вывода: Python 3.9.7. Другие версии интерпретатора могут менять последние знаки чисел с плавающей точкой и хеши, содержащие вычисленные значения. Записывайте среду исполнения при сравнении идентичности артефактов.
Inputs and limits / Входы и границы
All events and integer clocks are fictional. The local publication uses a temporary directory only; it does not establish remote exactly-once effects or power-loss durability.
Все события и целочисленные часы вымышлены. Локальная публикация использует лишь временный каталог; она не устанавливает удалённый exactly-once или сохранность при потере питания.
from collections import Counter
import hashlib
import json
import math
import os
from pathlib import Path
import tempfile
def encoded(value):
return json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()
def sha(value):
return hashlib.sha256(encoded(value)).hexdigest()
def snapshot(events, day, observed_by):
unique = {}
for event in sorted(events, key=lambda row: row["observed_hour"]):
if event["observed_hour"] <= observed_by:
payload = {key: event[key] for key in ["event_id", "card", "event_hour"]}
if event["event_id"] in unique and unique[event["event_id"]] != payload:
raise ValueError("Conflicting payload for one event ID")
unique[event["event_id"]] = payload
selected = [row for row in unique.values() if row["event_hour"] // 24 == day]
return sorted(selected, key=lambda row: row["event_id"])
def pipeline():
events = [dict(event_id=i, card=card, event_hour=event, observed_hour=observed)
for i, card, event, observed in [
("e1", "A", 9, 9), ("e3", "C", 29, 29),
("e2", "B", 15, 31), ("e1", "A", 9, 32), ("e4", "D", 33, 33)]]
early, revised = snapshot(events, 0, 30), snapshot(events, 0, 36)
assert [row["card"] for row in early] == ["A"]
assert [row["card"] for row in revised] == ["A", "B"]
assert revised == snapshot(list(reversed(events)), 0, 36)
# Validate visible event IDs before partitioning, including cross-day conflicts.
for conflicting_hour in [10, 25]:
conflict = dict(event_id="e1", card="A", event_hour=conflicting_hour, observed_hour=34)
assert snapshot(events + [conflict], 0, 33) == snapshot(events, 0, 33)
for day in [0, 1]:
try:
snapshot(events + [conflict], day, 36)
except ValueError:
pass
else:
raise AssertionError("Visible conflicting IDs must fail before partition selection")
with tempfile.TemporaryDirectory(prefix="preview-pipeline-") as directory:
destination = Path(directory) / "day-0.json"
temporary = Path(directory) / "day-0.staging.json"
destination.write_bytes(encoded(early))
temporary.write_bytes(encoded(revised))
before_publish = destination.read_bytes() == encoded(early)
os.replace(temporary, destination)
published = destination.read_bytes()
temporary.write_bytes(encoded(revised))
os.replace(temporary, destination)
retry_identical = destination.read_bytes() == published
watermark, late = float("-inf"), []
for event in events:
if event["event_hour"] < watermark:
late.append(event["event_id"])
watermark = max(watermark, event["event_hour"] - 4)
assert late == ["e2", "e1"]
return {"events": events, "early_observed_by_hour": 30, "revised_observed_by_hour": 36,
"early_day_0": early, "revised_day_0": revised,
"early_sha256": sha(early), "revised_sha256": sha(revised),
"replay_same_bytes": retry_identical, "old_snapshot_visible_before_publish": before_publish,
"watermark_lag_hours": 4, "late_delivery_ids_including_duplicate": late,
"final_watermark": watermark, "backfill_counts_at_36": [len(snapshot(events,d,36)) for d in [0,1]]}result = pipeline()
print(json.dumps(result,indent=2,allow_nan=False))Independent checks / Независимые проверки
Check identities, boundary behavior and separate arithmetic expectations. These checks establish only the stated fixture.
Проверьте идентичности, поведение на границах и отдельные арифметические ожидания. Проверки устанавливают только заданный пример.
events = result["events"]
assert [r["event_id"] for r in snapshot(events,0,30)] == ["e1"]
assert [r["event_id"] for r in snapshot(events,0,31)] == ["e1","e2"]
conflict = dict(event_id="e1",card="A",event_hour=25,observed_hour=34)
for visible in [events+[conflict],list(reversed(events+[conflict]))]:
assert snapshot(visible,0,33) == snapshot(events,0,33)
for day in [0,1]:
try: snapshot(visible,day,34)
except ValueError: pass
else: raise AssertionError("Visible global ID conflict was missed")
assert result["replay_same_bytes"] and result["old_snapshot_visible_before_publish"]
assert result["backfill_counts_at_36"] == [2,2]
print("Self-checks passed: inclusive cutoff, cross-day conflict, order and retry invariants.")Change one assumption / Измените предположение
Move an observation cutoff across a late arrival. Then reuse an ID on another event day and verify that the visible conflict fails before partition selection.
Сдвиньте срок наблюдения через поздний приход. Затем повторно используйте ID в другом дне события и проверьте отказ видимого конфликта до выбора партиции.