Skip to content
BIASED
Back to topic

Optional

Answer-save SLO: counts and windows

Reproduce request budgets and alert times on fictional traffic. Check observation weighting, low volume and no-data behavior. No downloads or third-party libraries.

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 .ipynb

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.

Answer-save SLO: counts and alert windows / SLO сохранения ответов

Activity version / версия: 2. Python standard library only; no downloads. Только стандартная библиотека Python, без скачиваний.

Reproduce the lesson's fictional request counts and detector. Distinguish a request budget from elapsed time, then inspect detection and recovery. This optional notebook does not affect mastery or certificates.

Воспроизведите вымышленные счётчики и детектор из темы. Разделите бюджет запросов и время, затем проверьте обнаружение и снятие условий. Необязательный ноутбук не влияет на освоение или сертификаты.

Origin / происхождение. Adapted from Fedor Pakhurov's reviewed, newly authored FP note, Russian version and deterministic verifier at 8110032. The fictional fixture and code were drafted and checked with AI assistance. No third-party incident dataset or notebook results are used. The underlying SLO/burn-rate concepts remain credited in the note. This notebook adds explanations and self-checks; it removes the verifier's local website-file checks so it runs on its own.

Данные и код происходят из проверенной авторской заметки FP и её скрипта по указанной ревизии. Они подготовлены с помощью ИИ; чужих наборов инцидентов или результатов ноутбуков нет. Концептуальные источники SLO и burn rate сохранены в заметке. Здесь добавлены пояснения и самопроверки; проверки локальных файлов сайта убраны для самостоятельного запуска.

1. Give each request one vote / Одинаковый вес попыток

Eleven minutes have 100 good attempts each. One minute has one bad attempt. Compare the ratio of total counts with an unweighted average of minute ratios.

Одиннадцать минут содержат по 100 успешных попыток. Одна минута — одну неудачную. Сравните отношение суммарных счётчиков со средним минутных долей.

from fractions import Fraction
 
attempts = [100] * 11 + [1]
bad = [0] * 11 + [1]
by_request = Fraction(sum(bad), sum(attempts))
by_minute = sum(Fraction(b, n) for b, n in zip(bad, attempts)) / 12
assert by_request == Fraction(1, 1101)
assert by_minute == Fraction(1, 12)
print(f"request-weighted: {float(by_request) * 100:.6f}%")
print(f"minute-weighted:  {float(by_minute) * 100:.6f}%")
 

2. Reproduce the full trace / Полный трафик

SLO: 99.5% good eligible attempts over 14 days. Good means durable acknowledgement within 800 ms. A failed or later acknowledgement is bad once. Invalid requests are excluded. The fixture stores integer counts of already classified attempts.

SLO: 99.5% хороших учитываемых попыток за 14 дней. Хорошая попытка получает подтверждение надёжной записи за 800 мс. Отказ или позднее подтверждение считается одной неудачей. Невалидные запросы исключены. В данных — целые счётчики уже классифицированных попыток.

Normally all attempts are good. Traffic is 1000 attempts/minute from 08:00 to 18:00 and 100 otherwise. Day numbers start at zero. Each reported evaluation timestamp is the exclusive end of its last minute bucket.

Обычно все попытки успешны. С 08:00 до 18:00 поступает по 1000 попыток в минуту, иначе —100. Дни нумеруются с нуля; метка оценки — исключённая правая граница последнего минутного интервала.

Event / событие Definition / условие
Quiet failure / тихий отказ Day 2 at 03:00: one bad attempt replaces 100 good ones / одна неудача вместо 100 успешных
Deployment / релиз Day 4, 11:10–11:22:200 bad of 1000 each minute
Slow acknowledgement / задержки Day 9, 23:00 for 180 min: 3 bad of 100 each minute

Page: 12/3-minute windows, at least 5% bad in both, at least 900 attempts in the long window. Ticket: 180/30 minutes, at least 1% in both, at least 600 attempts. These are example inputs, not universal recommendations.

Вызов: окна 12/3 минуты, не менее 5% неудач в обоих и минимум 900 попыток в длинном. Задача: 180/30 минут, не менее 1% в обоих и минимум 600 попыток. Это условия примера, а не универсальные рекомендации.

The next cell embeds the complete reference calculation; no network or project files are needed. Следующая ячейка содержит весь расчёт; сеть и файлы проекта не нужны.

import json
from fractions import Fraction
 
PERIOD = 14 * 24 * 60
OBJECTIVE = Fraction(995, 1000)
EVENTS = {
    "isolated": (2 * 1440 + 3 * 60, 1),
    "busy_failure": (4 * 1440 + 11 * 60 + 10, 12),
    "slow_ack": (9 * 1440 + 23 * 60, 180),
}
 
 
def series():
    attempts, bad = [], []
    for minute in range(PERIOD):
        hour = minute % 1440 // 60
        attempts.append(1000 if 8 <= hour < 18 else 100)
        bad.append(0)
    start, length = EVENTS["isolated"]
    attempts[start], bad[start] = 1, 1
    for event, count in [("busy_failure", 200), ("slow_ack", 3)]:
        start, length = EVENTS[event]
        bad[start:start + length] = [count] * length
    return attempts, bad
 
 
def prefix(values):
    result = [0]
    for value in values:
        result.append(result[-1] + value)
    return result
 
 
def run(attempts, bad, long_window, short_window, threshold, minimum):
    counts, failures = prefix(attempts), prefix(bad)
    firing = []
    for end in range(1, len(attempts) + 1):
        if end < long_window:
            continue
        total_long = counts[end] - counts[end - long_window]
        bad_long = failures[end] - failures[end - long_window]
        total_short = counts[end] - counts[end - short_window]
        bad_short = failures[end] - failures[end - short_window]
        if (total_long >= minimum and total_short > 0
                and bad_long * threshold.denominator >= total_long * threshold.numerator
                and bad_short * threshold.denominator >= total_short * threshold.numerator):
            firing.append(end)
    return firing
 
 
def timestamp(end):
    day, minute = divmod(end, 1440)
    hour, minute = divmod(minute, 60)
    return f"day {day} {hour:02d}:{minute:02d}"
 
 
def intervals(points):
    result = []
    for point in points:
        if not result or point != result[-1][1] + 1:
            result.append([point, point])
        else:
            result[-1][1] = point
    return [{"first": timestamp(start), "last": timestamp(end),
             "evaluations": end - start + 1} for start, end in result]
 
 
def evaluate():
    attempts, bad = series()
    pages = run(attempts, bad, 12, 3, Fraction(5, 100), 900)
    tickets = run(attempts, bad, 180, 30, Fraction(1, 100), 600)
    isolated, _ = EVENTS["isolated"]
    busy, busy_length = EVENTS["busy_failure"]
    slow, slow_length = EVENTS["slow_ack"]
    assert pages[0] == busy + 3
    assert pages[-1] == busy + busy_length + 2
    assert not any(isolated <= end <= isolated + 180 for end in pages + tickets)
    assert not any(slow <= end <= slow + slow_length for end in pages)
    slow_tickets = [end for end in tickets if slow <= end <= slow + slow_length]
    assert slow_tickets[0] == slow + 60
 
    # A ratio-of-sums gives each request one vote. A mean of minute ratios does not.
    fixture_attempts, fixture_bad = [100] * 11 + [1], [0] * 11 + [1]
    weighted = Fraction(sum(fixture_bad), sum(fixture_attempts))
    unweighted = sum((Fraction(b, n) for n, b in zip(fixture_attempts, fixture_bad)), Fraction()) / 12
    assert weighted < Fraction(5, 100) < unweighted
 
    # A full outage below the volume floor is intentionally invisible to this rule.
    assert run([1] * 20, [1] * 20, 12, 3, Fraction(5, 100), 900) == []
    # No requests is missing availability evidence, not a perfect SLI.
    assert run([0] * 20, [0] * 20, 12, 3, Fraction(5, 100), 900) == []
 
    total, failed = sum(attempts), sum(bad)
    allowed = (1 - OBJECTIVE) * total
    return {
        "provenance": "Original fictional answer-save traffic fixture; Fedor Pakhurov with AI assistance; no external dataset.",
        "evaluation": "Whole-minute buckets; event starts use zero-based day numbers; timestamps are exclusive bucket ends.",
        "attempts": total, "bad": failed,
        "sli_percent": round(float(1 - Fraction(failed, total)) * 100, 6),
        "allowed_bad": float(allowed),
        "budget_used_percent": round(float(Fraction(failed, 1) / allowed) * 100, 6),
        "page_intervals": intervals(pages), "ticket_intervals_before_deduplication": intervals(tickets),
        "slow_ticket_delay_minutes": slow_tickets[0] - slow,
        "unequal_traffic": {"ratio_of_sums_percent": round(float(weighted) * 100, 6),
                            "mean_of_ratios_percent": round(float(unweighted) * 100, 6)},
        "availability": {"series": 0.998 * 0.999, "independent_pair": 1 - 0.002 ** 2,
                         "pair_with_shared_failure": 0.999 * (1 - 0.002 ** 2)},
    }
 
 
result = evaluate()
print(json.dumps(result, ensure_ascii=False, indent=2))
 

3. Check the detector's blind spots / Ограничения детектора

A volume floor can suppress a total outage when traffic is small. No attempts is missing evidence, not perfect success. These checks concern the reference detector, not actual alert delivery.

Порог объёма может скрыть полный отказ при малом трафике. Нет попыток — нет наблюдений, а не идеальный успех. Проверяем эталонный детектор, а не реальную доставку уведомлений.

low_traffic_pages = run([1] * 20, [1] * 20, 12, 3, Fraction(5, 100), 900)
no_data_pages = run([0] * 20, [0] * 20, 12, 3, Fraction(5, 100), 900)
assert low_traffic_pages == []
assert no_data_pages == []
print("total low-traffic outage, page evaluations:", len(low_traffic_pages))
print("no observations, page evaluations:", len(no_data_pages))
print("Neither result proves the service is healthy.")
 

4. Interpret the result / Интерпретация

The period SLO passes while the deployment needs a page. The same deployment activates both raw page and ticket conditions; group them as one incident. A separate slow-acknowledgement incident produces a ticket after 60 minutes.

Цель за период выполнена, хотя релиз требует вызова. Он активирует и исходное условие вызова, и условие задачи; это один инцидент. Отдельный инцидент с задержками создаёт задачу через 60 минут.

The verified outputs are 9,575,901 attempts, 2941 bad, SLI 99.969287% and budget used 6.142503%. The program checks exact threshold boundaries using fractions. It does not simulate scrapes, counter resets, missing series, routing or operator acknowledgement.

Проверенный результат: 9,575,901 попытка, 2941 неудача, SLI 99.969287%, использовано 6.142503% бюджета. Точные границы порогов проверяются дробями. Здесь нет моделирования сбора метрик, сбросов счётчиков, пропавших рядов, маршрутизации или подтверждения оператором.

Explore safely: call run with a different volume floor or recent window in a new cell, keeping the reference cell unchanged. Explain which failure your change now catches and which false alarm it might introduce; a new trace result is not evidence of real-world precision or recall.

Для исследования вызовите run с другим минимумом попыток или недавним окном в новой ячейке, оставив эталонную без изменений. Объясните, какой отказ теперь виден и какое ложное оповещение возможно. Результат нового расчёта не доказывает precision или recall в эксплуатации.