Optional
Incident counters and release boundaries
Reproduce fictional request impact, response intervals, automation payback and policy-only release checks. Standard library; no remote systems.
- Version
- v2
- Minutes
- ~20
- Evidence
- Self-check in the notebook
Until platform auto-check exists, compare cell output with the expected numbers in the notebook. This is not a debt and does not affect mastery.
Download the notebook and run it locally. Its environment requirements are listed inside.
Notebook contents
Readable on your phone. The code below has not been executed in the browser; download the notebook to run it.
Incident counters and release boundaries / Счётчики инцидента и границы релиза
Optional practice for the incident lesson. This notebook uses independently specified fictional inputs from the reviewed FP note. No customer data, network, model or deployment is involved. Python standard library only.
Необязательная практика к теме об инцидентах. Входные данные вымышлены и заданы в проверенном конспекте FP. Здесь нет пользовательских данных, сети, модели или деплоя. Достаточно стандартной библиотеки Python.
Authored for Fedor Pakhurov's project with Codex assistance. Derived from the complete reviewed note at commit 67f4698fb061d93879984860f99d5181e426221b; no guarantee of exclusive copyright in AI-assisted material is asserted.
The note retains conceptual references to Google SRE, OWASP, Git, Kubernetes, Sigstore and SLSA. No external example, code, dataset or figure is included here.
Count attempts / Считаем попытки
The fourteen-day volume is a separate input, not an extrapolation. Failed attempts do not identify unique learners or lost answers. Change the per-minute traffic and see why a time fraction is not the same as a request fraction.
Объём за четырнадцать дней задан отдельно. Ошибки попыток не определяют число разных учеников или потерянных ответов. Измените интенсивность запросов: доля времени и доля запросов расходятся.
from fractions import Fraction
# Complete one-minute buckets: (duration, attempts per minute, bad per minute).
intervals = [(4, 200, 50), (7, 400, 20), (7, 300, 0)]
attempts = sum(minutes * total for minutes, total, bad in intervals)
failures = sum(minutes * bad for minutes, total, bad in intervals)
affected_attempts = sum(minutes * total for minutes, total, bad in intervals if bad)
period_attempts = 500_000
slo = Fraction(995, 1000)
budget = period_attempts * (1 - slo)
budget_used = 100 * failures / budget
success_percent = 100 * (1 - Fraction(failures, period_attempts))
# Minutes from 09:30; the alert is a supplied observation, not a threshold result.
events = {"onset": 0, "alert": 2, "acknowledged": 3,
"partial": 4, "mitigated": 11, "closed": 18}
assert (attempts, failures, affected_attempts) == (5700, 340, 3600)
assert budget == 2500 and budget_used == Fraction(68, 5)
assert success_percent == Fraction(24983, 250)
print(f"attempts={attempts}, failures={failures}, affected_attempts={affected_attempts}")
print(f"budget={budget}, used={float(budget_used):.1f}%, success={float(success_percent):.3f}%")
print("detection:", events["alert"] - events["onset"], "minutes")
print("acknowledgement after alert:", events["acknowledged"] - events["alert"], "minutes")
print("mitigation from onset:", events["mitigated"] - events["onset"], "minutes")
print("verification after mitigation:", events["closed"] - events["mitigated"], "minutes")
Include maintenance / Учитываем поддержку
The result is conditional on the supplied weekly workload. If net savings are zero or negative, this setup has no positive time break-even. Risk and quality are not priced in this small calculation.
Результат зависит от заданной еженедельной работы. При нулевой или отрицательной чистой экономии положительного срока окупаемости нет. Риск и качество в этом расчёте не оценены.
weekly_manual_minutes = 7 * 10
weekly_maintenance_minutes = 10
setup_hours = 9
weekly_saving_hours = Fraction(weekly_manual_minutes - weekly_maintenance_minutes, 60)
break_even_weeks = setup_hours / weekly_saving_hours
net_hours_26_weeks = 26 * weekly_saving_hours - setup_hours
assert (weekly_saving_hours, break_even_weeks, net_hours_26_weeks) == (1, 9, 17)
print("weekly saving:", weekly_saving_hours, "hour")
print("break-even:", break_even_weeks, "weeks")
print("net saving over 26 weeks:", net_hours_26_weeks, "hours")
Enforce a policy after verification / Политика после верификации
The code assumes trusted verification has already happened. Matching JSON fields alone proves nothing about authenticity. The expected identity strings and artifact bytes are newly specified fixtures. No signature, certificate, transparency log or real release is checked.
Код предполагает, что доверенная проверка уже состоялась. Одно совпадение полей JSON ничего не доказывает о подлинности. Строки идентичности и байты артефакта заданы для нового примера. Подписи, сертификаты, журнал прозрачности и реальные релизы не проверяются.
from hashlib import sha256
# Policy-only exercise. These fixtures stand for output from a trusted verifier.
# They do NOT implement or replace cryptographic verification.
artifact = b"fictional-answer-writer-release-v3"
expected = {
"digest": sha256(artifact).hexdigest(),
"repository": "example/answer-writer",
"ref": "refs/tags/v3",
"builder": "example/isolated-builder",
}
def decide(verified_receipt, artifact_bytes):
if verified_receipt is None:
return "missing verified receipt"
if verified_receipt.get("digest") != sha256(artifact_bytes).hexdigest():
return "reject digest"
for field in ("repository", "ref", "builder"):
if verified_receipt.get(field) != expected[field]:
return f"reject {field}"
return "accept"
cases = {
"expected": (dict(expected), artifact),
"changed_bytes": (dict(expected), artifact + b"changed"),
"wrong_repository": ({**expected, "repository": "other/repo"}, artifact),
"wrong_ref": ({**expected, "ref": "refs/heads/unreviewed"}, artifact),
"wrong_builder": ({**expected, "builder": "other/builder"}, artifact),
"missing_receipt": (None, artifact),
}
results = {name: decide(receipt, data) for name, (receipt, data) in cases.items()}
assert list(results.values()) == ["accept", "reject digest", "reject repository",
"reject ref", "reject builder", "missing verified receipt"]
for name, result in results.items():
print(f"{name}: {result}")