| 1 | #!/usr/bin/env python3 |
| 2 | """Check the paused persistence backlog against one-way local ceilings. |
| 3 | |
| 4 | Usage: |
| 5 | python3 scripts/check-persistence-backlog-budget.py |
| 6 | python3 scripts/check-persistence-backlog-budget.py --receipt receipt.json |
| 7 | python3 scripts/check-persistence-backlog-budget.py --update |
| 8 | |
| 9 | A fresh measurement takes ``TIMING_SAMPLES`` samples. Every sample must hold |
| 10 | every structural and RSS ceiling on its own; only ``enqueue_elapsed_ns`` is |
| 11 | judged on the fastest sample. Scheduling noise on a shared runner only ever |
| 12 | adds wall-clock time, so the fastest sample is the closest one to what the |
| 13 | code costs, and extra work on the send path slows every sample, the fastest |
| 14 | included. One sample decided this before, and on hosted macOS the same |
| 15 | commit landed on both sides of the ceiling (ab4fdcb1: 21.8 ms and 27.2 ms; |
| 16 | b1313572: 11.5 ms and 33.3 ms). |
| 17 | |
| 18 | ``--update`` is the receipt command a failing PR runs to land an intended |
| 19 | increase in the same PR: it raises only the exceeded ceilings to the measured |
| 20 | values and never lowers one, because the ceilings carry deliberate measurement |
| 21 | noise headroom. Tighten by hand, with the reason recorded in the budget. |
| 22 | """ |
| 23 | |
| 24 | from __future__ import annotations |
| 25 | |
| 26 | import argparse |
| 27 | import json |
| 28 | import os |
| 29 | import re |
| 30 | import subprocess |
| 31 | import sys |
| 32 | from pathlib import Path |
| 33 | from typing import Any |
| 34 | |
| 35 | |
| 36 | ROOT = Path(__file__).resolve().parent.parent |
| 37 | MEASURE_SCRIPT = ROOT / "scripts" / "measure-persistence-backlog.py" |
| 38 | BUDGET_PATH = ROOT / "scripts" / "persistence-backlog-budget.json" |
| 39 | BASELINE_RECEIPT_PATH = ROOT / "scripts" / "persistence-backlog-baseline-receipt.json" |
| 40 | BASELINE_RECEIPT_REFERENCE = "scripts/persistence-backlog-baseline-receipt.json" |
| 41 | RECEIPT_KIND = "codewhale.persistence_backlog_receipt" |
| 42 | BUDGET_KIND = "codewhale.persistence_backlog_budget" |
| 43 | SCHEMA_VERSION = 2 |
| 44 | |
| 45 | FIXTURE = { |
| 46 | "fixture_id": "paused-production-channel-session-snapshot-v1", |
| 47 | "request_variant": "session_snapshot", |
| 48 | "payload_estimator": "retained-saved-session-json-bytes-v1", |
| 49 | "paused_consumer": True, |
| 50 | "requests_attempted": 128, |
| 51 | "content_bytes_per_request": 64 * 1024, |
| 52 | "single_session_id": True, |
| 53 | "expected_applied_version": 127, |
| 54 | } |
| 55 | |
| 56 | REQUIRED_RECEIPT_FIELDS = ( |
| 57 | "document_kind", |
| 58 | "schema_version", |
| 59 | "source_sha", |
| 60 | "source_dirty", |
| 61 | "rustc_version", |
| 62 | "cargo_version", |
| 63 | "build_profile", |
| 64 | "sample_count", |
| 65 | "fixture_id", |
| 66 | "platform", |
| 67 | "request_variant", |
| 68 | "payload_estimator", |
| 69 | "paused_consumer", |
| 70 | "requests_attempted", |
| 71 | "content_bytes_per_request", |
| 72 | "single_session_id", |
| 73 | "expected_applied_version", |
| 74 | "accepted_requests", |
| 75 | "retained_queued_requests", |
| 76 | "estimated_retained_payload_bytes", |
| 77 | "applied_version", |
| 78 | "final_version_applied", |
| 79 | "enqueue_elapsed_ns", |
| 80 | "rss_supported", |
| 81 | "rss_before_bytes", |
| 82 | "rss_during_bytes", |
| 83 | "rss_after_bytes", |
| 84 | "rss_during_delta_bytes", |
| 85 | "rss_after_delta_bytes", |
| 86 | "limitations", |
| 87 | ) |
| 88 | |
| 89 | CEILING_FIELDS = ( |
| 90 | "retained_queued_requests", |
| 91 | "estimated_retained_payload_bytes", |
| 92 | "enqueue_elapsed_ns", |
| 93 | "rss_during_delta_bytes", |
| 94 | "rss_after_delta_bytes", |
| 95 | ) |
| 96 | RSS_SAMPLE_FIELDS = ("rss_before_bytes", "rss_during_bytes", "rss_after_bytes") |
| 97 | RSS_DELTA_FIELDS = ("rss_during_delta_bytes", "rss_after_delta_bytes") |
| 98 | TIMING_FIELD = "enqueue_elapsed_ns" |
| 99 | TIMING_SAMPLES = 5 |
| 100 | SUPPORTED_PLATFORMS = {"linux", "macos", "windows"} |
| 101 | SOURCE_SHA_PATTERN = re.compile(r"[0-9a-f]{40}") |
| 102 | |
| 103 | |
| 104 | class PersistenceBacklogError(ValueError): |
| 105 | """A receipt or budget broke the measurement contract.""" |
| 106 | |
| 107 | |
| 108 | def load_json(path: Path, label: str) -> dict[str, Any]: |
| 109 | try: |
| 110 | value = json.loads(path.read_text(encoding="utf-8")) |
| 111 | except (OSError, json.JSONDecodeError) as error: |
| 112 | raise PersistenceBacklogError(f"invalid {label} {path}: {error}") from error |
| 113 | if not isinstance(value, dict): |
| 114 | raise PersistenceBacklogError(f"{label} must be a JSON object") |
| 115 | return value |
| 116 | |
| 117 | |
| 118 | def non_negative_integer(value: Any, field: str) -> int: |
| 119 | if isinstance(value, bool) or not isinstance(value, int) or value < 0: |
| 120 | raise PersistenceBacklogError(f"{field} must be a non-negative integer") |
| 121 | return value |
| 122 | |
| 123 | |
| 124 | def validate_frozen_field(field: str, value: Any, expected: Any) -> None: |
| 125 | if type(value) is not type(expected) or value != expected: |
| 126 | raise PersistenceBacklogError( |
| 127 | f"receipt {field} must remain {expected!r}, got {value!r}" |
| 128 | ) |
| 129 | |
| 130 | |
| 131 | def current_source_identity() -> dict[str, Any]: |
| 132 | def run(command: list[str]) -> str: |
| 133 | result = subprocess.run( |
| 134 | command, |
| 135 | cwd=ROOT, |
| 136 | text=True, |
| 137 | capture_output=True, |
| 138 | check=False, |
| 139 | ) |
| 140 | if result.returncode != 0: |
| 141 | raise PersistenceBacklogError( |
| 142 | f"source provenance command failed: {' '.join(command)}" |
| 143 | ) |
| 144 | return result.stdout.strip() |
| 145 | |
| 146 | return { |
| 147 | "source_sha": run(["git", "rev-parse", "HEAD"]), |
| 148 | "source_dirty": bool( |
| 149 | run(["git", "status", "--porcelain", "--untracked-files=normal"]) |
| 150 | ), |
| 151 | "rustc_version": run(["rustc", "--version"]), |
| 152 | "cargo_version": run(["cargo", "--version"]), |
| 153 | "build_profile": "test", |
| 154 | "sample_count": 1, |
| 155 | } |
| 156 | |
| 157 | |
| 158 | def validate_receipt( |
| 159 | receipt: dict[str, Any], |
| 160 | *, |
| 161 | expected_source: dict[str, Any] | None = None, |
| 162 | require_clean_source: bool = False, |
| 163 | ) -> None: |
| 164 | missing = [field for field in REQUIRED_RECEIPT_FIELDS if field not in receipt] |
| 165 | if missing: |
| 166 | raise PersistenceBacklogError( |
| 167 | "receipt missing required field(s): " + ", ".join(missing) |
| 168 | ) |
| 169 | if receipt["document_kind"] != RECEIPT_KIND: |
| 170 | raise PersistenceBacklogError(f"receipt document_kind must be {RECEIPT_KIND}") |
| 171 | if receipt["schema_version"] != SCHEMA_VERSION: |
| 172 | raise PersistenceBacklogError("receipt schema_version changed") |
| 173 | for field, expected in FIXTURE.items(): |
| 174 | validate_frozen_field(field, receipt[field], expected) |
| 175 | if not isinstance(receipt["source_sha"], str) or not SOURCE_SHA_PATTERN.fullmatch( |
| 176 | receipt["source_sha"] |
| 177 | ): |
| 178 | raise PersistenceBacklogError("receipt source_sha must be an exact lowercase Git SHA") |
| 179 | if type(receipt["source_dirty"]) is not bool: |
| 180 | raise PersistenceBacklogError("receipt source_dirty must be boolean") |
| 181 | for field, prefix in (("rustc_version", "rustc "), ("cargo_version", "cargo ")): |
| 182 | if not isinstance(receipt[field], str) or not receipt[field].startswith(prefix): |
| 183 | raise PersistenceBacklogError(f"receipt {field} must be a version string") |
| 184 | validate_frozen_field("build_profile", receipt["build_profile"], "test") |
| 185 | validate_frozen_field("sample_count", receipt["sample_count"], 1) |
| 186 | if expected_source is not None: |
| 187 | for field in ( |
| 188 | "source_sha", |
| 189 | "source_dirty", |
| 190 | "rustc_version", |
| 191 | "cargo_version", |
| 192 | "build_profile", |
| 193 | "sample_count", |
| 194 | ): |
| 195 | if receipt[field] != expected_source[field]: |
| 196 | raise PersistenceBacklogError( |
| 197 | f"receipt {field} does not match the checked source" |
| 198 | ) |
| 199 | if require_clean_source and receipt["source_dirty"]: |
| 200 | raise PersistenceBacklogError("persistence measurement source tree is dirty") |
| 201 | platform = receipt["platform"] |
| 202 | if not isinstance(platform, str) or platform not in SUPPORTED_PLATFORMS: |
| 203 | raise PersistenceBacklogError("receipt platform is unsupported") |
| 204 | |
| 205 | attempted = non_negative_integer(receipt["requests_attempted"], "requests_attempted") |
| 206 | accepted = non_negative_integer(receipt["accepted_requests"], "accepted_requests") |
| 207 | if accepted != attempted: |
| 208 | raise PersistenceBacklogError( |
| 209 | "accepted_requests must equal requests_attempted; sender rejection is not backlog improvement" |
| 210 | ) |
| 211 | retained = non_negative_integer( |
| 212 | receipt["retained_queued_requests"], "retained_queued_requests" |
| 213 | ) |
| 214 | if retained > accepted: |
| 215 | raise PersistenceBacklogError("retained_queued_requests exceeds accepted_requests") |
| 216 | for field in ("estimated_retained_payload_bytes", "enqueue_elapsed_ns"): |
| 217 | non_negative_integer(receipt[field], field) |
| 218 | if retained == 0 or receipt["estimated_retained_payload_bytes"] == 0: |
| 219 | raise PersistenceBacklogError( |
| 220 | "the paused channel must retain the newest request and its payload" |
| 221 | ) |
| 222 | minimum_payload_bytes = retained * FIXTURE["content_bytes_per_request"] |
| 223 | if receipt["estimated_retained_payload_bytes"] < minimum_payload_bytes: |
| 224 | raise PersistenceBacklogError( |
| 225 | "estimated_retained_payload_bytes is smaller than the frozen retained content" |
| 226 | ) |
| 227 | applied = non_negative_integer( |
| 228 | receipt["applied_version"], "applied_version" |
| 229 | ) |
| 230 | if applied != FIXTURE["expected_applied_version"]: |
| 231 | raise PersistenceBacklogError("applied_version is not the final sent version") |
| 232 | if receipt["final_version_applied"] is not True: |
| 233 | raise PersistenceBacklogError("final_version_applied must be true") |
| 234 | |
| 235 | limitations = receipt["limitations"] |
| 236 | if not isinstance(limitations, list) or not limitations or not all( |
| 237 | isinstance(item, str) and item for item in limitations |
| 238 | ): |
| 239 | raise PersistenceBacklogError("limitations must be a non-empty string array") |
| 240 | |
| 241 | if not isinstance(receipt["rss_supported"], bool): |
| 242 | raise PersistenceBacklogError("rss_supported must be boolean") |
| 243 | if receipt["rss_supported"] != (platform == "macos"): |
| 244 | raise PersistenceBacklogError( |
| 245 | "rss_supported must be true exactly on the macOS measurement lane" |
| 246 | ) |
| 247 | rss_fields = RSS_SAMPLE_FIELDS + RSS_DELTA_FIELDS |
| 248 | if receipt["rss_supported"]: |
| 249 | for field in rss_fields: |
| 250 | non_negative_integer(receipt[field], field) |
| 251 | before = receipt["rss_before_bytes"] |
| 252 | if receipt["rss_during_delta_bytes"] != max( |
| 253 | 0, receipt["rss_during_bytes"] - before |
| 254 | ): |
| 255 | raise PersistenceBacklogError("rss_during_delta_bytes is inconsistent") |
| 256 | if receipt["rss_after_delta_bytes"] != max( |
| 257 | 0, receipt["rss_after_bytes"] - before |
| 258 | ): |
| 259 | raise PersistenceBacklogError("rss_after_delta_bytes is inconsistent") |
| 260 | elif any(receipt[field] is not None for field in rss_fields): |
| 261 | raise PersistenceBacklogError("unsupported RSS fields must be null") |
| 262 | |
| 263 | |
| 264 | def validate_budget(budget: dict[str, Any]) -> None: |
| 265 | if budget.get("document_kind") != BUDGET_KIND: |
| 266 | raise PersistenceBacklogError(f"budget document_kind must be {BUDGET_KIND}") |
| 267 | if budget.get("schema_version") != SCHEMA_VERSION: |
| 268 | raise PersistenceBacklogError("budget schema_version changed") |
| 269 | fixture = budget.get("fixture") |
| 270 | if not isinstance(fixture, dict) or set(fixture) != set(FIXTURE): |
| 271 | raise PersistenceBacklogError("budget fixture no longer matches the frozen workload") |
| 272 | for field, expected in FIXTURE.items(): |
| 273 | if type(fixture[field]) is not type(expected) or fixture[field] != expected: |
| 274 | raise PersistenceBacklogError( |
| 275 | f"budget fixture.{field} must remain {expected!r}" |
| 276 | ) |
| 277 | if budget.get("baseline_receipt") != BASELINE_RECEIPT_REFERENCE: |
| 278 | raise PersistenceBacklogError("budget baseline_receipt path changed") |
| 279 | ceilings = budget.get("ceilings") |
| 280 | baseline = budget.get("baseline_observation") |
| 281 | if not isinstance(ceilings, dict) or not isinstance(baseline, dict): |
| 282 | raise PersistenceBacklogError("budget needs ceilings and baseline_observation objects") |
| 283 | for field in CEILING_FIELDS: |
| 284 | ceiling = non_negative_integer(ceilings.get(field), f"ceilings.{field}") |
| 285 | observed = non_negative_integer( |
| 286 | baseline.get(field), f"baseline_observation.{field}" |
| 287 | ) |
| 288 | if observed > ceiling: |
| 289 | raise PersistenceBacklogError( |
| 290 | f"baseline_observation.{field} exceeds its ceiling" |
| 291 | ) |
| 292 | baseline_accepted = non_negative_integer( |
| 293 | baseline.get("accepted_requests"), "baseline_observation.accepted_requests" |
| 294 | ) |
| 295 | if baseline_accepted != FIXTURE["requests_attempted"]: |
| 296 | raise PersistenceBacklogError( |
| 297 | "baseline_observation.accepted_requests must equal requests_attempted" |
| 298 | ) |
| 299 | baseline_applied = non_negative_integer( |
| 300 | baseline.get("applied_version"), "baseline_observation.applied_version" |
| 301 | ) |
| 302 | if baseline_applied != FIXTURE["expected_applied_version"]: |
| 303 | raise PersistenceBacklogError( |
| 304 | "baseline_observation.applied_version must be the final sent version" |
| 305 | ) |
| 306 | baseline_retained = baseline["retained_queued_requests"] |
| 307 | baseline_payload = baseline["estimated_retained_payload_bytes"] |
| 308 | if baseline_retained == 0 or baseline_payload == 0: |
| 309 | raise PersistenceBacklogError( |
| 310 | "baseline_observation must retain the final request and payload" |
| 311 | ) |
| 312 | if baseline_retained > baseline_accepted: |
| 313 | raise PersistenceBacklogError( |
| 314 | "baseline_observation.retained_queued_requests exceeds accepted_requests" |
| 315 | ) |
| 316 | if baseline_payload < baseline_retained * FIXTURE["content_bytes_per_request"]: |
| 317 | raise PersistenceBacklogError( |
| 318 | "baseline_observation payload is smaller than frozen retained content" |
| 319 | ) |
| 320 | provenance = baseline.get("provenance") |
| 321 | if not isinstance(provenance, dict): |
| 322 | raise PersistenceBacklogError("baseline_observation needs provenance") |
| 323 | if provenance.get("platform") != "macos": |
| 324 | raise PersistenceBacklogError("baseline provenance platform must be macos") |
| 325 | if not isinstance(provenance.get("source_sha"), str) or not SOURCE_SHA_PATTERN.fullmatch( |
| 326 | provenance["source_sha"] |
| 327 | ): |
| 328 | raise PersistenceBacklogError("baseline provenance needs an exact source SHA") |
| 329 | if provenance.get("source_dirty") is not False: |
| 330 | raise PersistenceBacklogError("baseline provenance must identify a clean source tree") |
| 331 | for field, prefix in (("rustc_version", "rustc "), ("cargo_version", "cargo ")): |
| 332 | if not isinstance(provenance.get(field), str) or not provenance[field].startswith(prefix): |
| 333 | raise PersistenceBacklogError(f"baseline provenance needs {field}") |
| 334 | if provenance.get("build_profile") != "test" or not ( |
| 335 | type(provenance.get("sample_count")) is int |
| 336 | and provenance["sample_count"] == 1 |
| 337 | ): |
| 338 | raise PersistenceBacklogError("baseline provenance build profile/sample count changed") |
| 339 | |
| 340 | |
| 341 | def validate_baseline_receipt( |
| 342 | budget: dict[str, Any], baseline_receipt: dict[str, Any] |
| 343 | ) -> None: |
| 344 | validate_receipt(baseline_receipt, require_clean_source=True) |
| 345 | baseline = budget["baseline_observation"] |
| 346 | for field in ("accepted_requests", "applied_version", *CEILING_FIELDS): |
| 347 | if baseline_receipt[field] != baseline[field]: |
| 348 | raise PersistenceBacklogError( |
| 349 | f"baseline receipt {field} does not match baseline_observation" |
| 350 | ) |
| 351 | provenance = baseline["provenance"] |
| 352 | for field in ( |
| 353 | "platform", |
| 354 | "source_sha", |
| 355 | "source_dirty", |
| 356 | "rustc_version", |
| 357 | "cargo_version", |
| 358 | "build_profile", |
| 359 | "sample_count", |
| 360 | ): |
| 361 | if baseline_receipt[field] != provenance[field]: |
| 362 | raise PersistenceBacklogError( |
| 363 | f"baseline receipt {field} does not match baseline provenance" |
| 364 | ) |
| 365 | |
| 366 | |
| 367 | def compare( |
| 368 | receipt: dict[str, Any], |
| 369 | budget: dict[str, Any], |
| 370 | *, |
| 371 | expected_source: dict[str, Any] | None = None, |
| 372 | require_clean_source: bool = False, |
| 373 | ) -> tuple[list[tuple[str, int, int]], list[tuple[str, int, int]]]: |
| 374 | validate_receipt( |
| 375 | receipt, |
| 376 | expected_source=expected_source, |
| 377 | require_clean_source=require_clean_source, |
| 378 | ) |
| 379 | validate_budget(budget) |
| 380 | increases: list[tuple[str, int, int]] = [] |
| 381 | decreases: list[tuple[str, int, int]] = [] |
| 382 | for field in CEILING_FIELDS: |
| 383 | if field in RSS_DELTA_FIELDS and not receipt["rss_supported"]: |
| 384 | continue |
| 385 | current = receipt[field] |
| 386 | ceiling = budget["ceilings"][field] |
| 387 | if current > ceiling: |
| 388 | increases.append((field, current, ceiling)) |
| 389 | elif current < ceiling: |
| 390 | decreases.append((field, current, ceiling)) |
| 391 | return increases, decreases |
| 392 | |
| 393 | |
| 394 | def compare_samples( |
| 395 | receipts: list[dict[str, Any]], |
| 396 | budget: dict[str, Any], |
| 397 | *, |
| 398 | expected_source: dict[str, Any] | None = None, |
| 399 | require_clean_source: bool = False, |
| 400 | ) -> tuple[list[tuple[str, int, int]], list[tuple[str, int, int]]]: |
| 401 | """Judge several receipts of one source as a single measurement. |
| 402 | |
| 403 | Each receipt is validated in full. The timing field is the fastest sample; |
| 404 | every other ceiling field is the worst sample, so no sample may exceed it. |
| 405 | With one receipt this is exactly ``compare``. |
| 406 | """ |
| 407 | if not receipts: |
| 408 | raise PersistenceBacklogError("no measurement receipts to compare") |
| 409 | for receipt in receipts: |
| 410 | compare( |
| 411 | receipt, |
| 412 | budget, |
| 413 | expected_source=expected_source, |
| 414 | require_clean_source=require_clean_source, |
| 415 | ) |
| 416 | increases: list[tuple[str, int, int]] = [] |
| 417 | decreases: list[tuple[str, int, int]] = [] |
| 418 | for field in CEILING_FIELDS: |
| 419 | values = [ |
| 420 | receipt[field] |
| 421 | for receipt in receipts |
| 422 | if not (field in RSS_DELTA_FIELDS and not receipt["rss_supported"]) |
| 423 | ] |
| 424 | if not values: |
| 425 | continue |
| 426 | current = min(values) if field == TIMING_FIELD else max(values) |
| 427 | ceiling = budget["ceilings"][field] |
| 428 | if current > ceiling: |
| 429 | increases.append((field, current, ceiling)) |
| 430 | elif current < ceiling: |
| 431 | decreases.append((field, current, ceiling)) |
| 432 | return increases, decreases |
| 433 | |
| 434 | |
| 435 | def measure_samples(count: int = TIMING_SAMPLES) -> list[dict[str, Any]]: |
| 436 | """Take ``count`` fresh receipts; the test binary is built by the first.""" |
| 437 | receipts = [measure() for _ in range(count)] |
| 438 | timings = [receipt.get(TIMING_FIELD) for receipt in receipts] |
| 439 | print(f"[persistence-backlog-budget] {TIMING_FIELD} samples: {timings}") |
| 440 | return receipts |
| 441 | |
| 442 | |
| 443 | def measure() -> dict[str, Any]: |
| 444 | env = os.environ.copy() |
| 445 | env["CARGO_NET_OFFLINE"] = "true" |
| 446 | result = subprocess.run( |
| 447 | [sys.executable, str(MEASURE_SCRIPT)], |
| 448 | cwd=ROOT, |
| 449 | env=env, |
| 450 | text=True, |
| 451 | capture_output=True, |
| 452 | check=False, |
| 453 | ) |
| 454 | sys.stderr.write(result.stderr) |
| 455 | if result.returncode != 0: |
| 456 | sys.stdout.write(result.stdout) |
| 457 | raise PersistenceBacklogError("measurement command failed") |
| 458 | try: |
| 459 | receipt = json.loads(result.stdout) |
| 460 | except json.JSONDecodeError as error: |
| 461 | raise PersistenceBacklogError(f"measurement emitted invalid JSON: {error}") from error |
| 462 | if not isinstance(receipt, dict): |
| 463 | raise PersistenceBacklogError("measurement receipt must be an object") |
| 464 | return receipt |
| 465 | |
| 466 | |
| 467 | def update_command(receipt_path: Path | None, budget_path: Path) -> str: |
| 468 | parts = ["python3", "scripts/check-persistence-backlog-budget.py"] |
| 469 | if receipt_path is not None: |
| 470 | parts.extend(["--receipt", str(receipt_path)]) |
| 471 | if budget_path != BUDGET_PATH: |
| 472 | parts.extend(["--budget", str(budget_path)]) |
| 473 | parts.append("--update") |
| 474 | return " ".join(parts) |
| 475 | |
| 476 | |
| 477 | def raise_ceilings( |
| 478 | budget: dict[str, Any], increases: list[tuple[str, int, int]] |
| 479 | ) -> dict[str, Any]: |
| 480 | """Return a copy of ``budget`` with each exceeded ceiling set to its measurement.""" |
| 481 | updated = json.loads(json.dumps(budget)) |
| 482 | for field, current, _ceiling in increases: |
| 483 | updated["ceilings"][field] = current |
| 484 | validate_budget(updated) |
| 485 | return updated |
| 486 | |
| 487 | |
| 488 | def main() -> int: |
| 489 | parser = argparse.ArgumentParser(description=__doc__) |
| 490 | parser.add_argument("--receipt", type=Path, help="check an existing receipt") |
| 491 | parser.add_argument("--budget", type=Path, default=BUDGET_PATH) |
| 492 | parser.add_argument( |
| 493 | "--update", |
| 494 | action="store_true", |
| 495 | help="raise exceeded ceilings to the measured values (never lowers one)", |
| 496 | ) |
| 497 | args = parser.parse_args() |
| 498 | try: |
| 499 | expected_source = current_source_identity() |
| 500 | receipts = ( |
| 501 | [load_json(args.receipt, "receipt")] if args.receipt else measure_samples() |
| 502 | ) |
| 503 | budget = load_json(args.budget, "budget") |
| 504 | baseline_receipt = load_json(BASELINE_RECEIPT_PATH, "baseline receipt") |
| 505 | validate_baseline_receipt(budget, baseline_receipt) |
| 506 | increases, decreases = compare_samples( |
| 507 | receipts, |
| 508 | budget, |
| 509 | expected_source=expected_source, |
| 510 | # An update runs while the author is mid-change; the measurement |
| 511 | # still names its exact SHA and dirty bit, so only the enforcing |
| 512 | # check insists on a clean tree. |
| 513 | require_clean_source=not args.update, |
| 514 | ) |
| 515 | except PersistenceBacklogError as error: |
| 516 | print(f"[persistence-backlog-budget] ERROR: {error}", file=sys.stderr) |
| 517 | return 2 |
| 518 | if args.update: |
| 519 | if not increases: |
| 520 | print( |
| 521 | "[persistence-backlog-budget] --update: no ceiling exceeded; " |
| 522 | f"{args.budget} left unchanged" |
| 523 | ) |
| 524 | return 0 |
| 525 | try: |
| 526 | updated = raise_ceilings(budget, increases) |
| 527 | args.budget.write_text(json.dumps(updated, indent=2) + "\n", encoding="utf-8") |
| 528 | except (OSError, PersistenceBacklogError) as error: |
| 529 | print( |
| 530 | f"[persistence-backlog-budget] ERROR: failed to update budget: {error}", |
| 531 | file=sys.stderr, |
| 532 | ) |
| 533 | return 2 |
| 534 | for field, current, ceiling in increases: |
| 535 | print(f"[persistence-backlog-budget] raised {field}: {ceiling} -> {current}") |
| 536 | print( |
| 537 | f"[persistence-backlog-budget] wrote {args.budget}; say why in the PR " |
| 538 | "description, or add a dated _rebaseline note to the budget." |
| 539 | ) |
| 540 | return 0 |
| 541 | if increases: |
| 542 | for field, current, ceiling in increases: |
| 543 | print( |
| 544 | f"[persistence-backlog-budget] FAIL: {field}={current} exceeds {ceiling}", |
| 545 | file=sys.stderr, |
| 546 | ) |
| 547 | print( |
| 548 | "\nShrink the retained backlog, or if the growth is intended land the new " |
| 549 | f"ceiling in this PR:\n {update_command(args.receipt, args.budget)}", |
| 550 | file=sys.stderr, |
| 551 | ) |
| 552 | return 1 |
| 553 | print("[persistence-backlog-budget] PASS: one-way ceilings respected") |
| 554 | for field, current, ceiling in decreases: |
| 555 | print(f" can tighten {field}: {current} < {ceiling}") |
| 556 | return 0 |
| 557 | |
| 558 | |
| 559 | if __name__ == "__main__": |
| 560 | raise SystemExit(main()) |
| 561 |