Spaces:
Sleeping
Sleeping
Commit Β·
79280e2
1
Parent(s): cf9ef2d
feat(audit): Tier 5 deploy-safety (read-only) + selftest_expect for WARN checks
Browse files- audit/core.py +5 -4
- audit/selftest_fixtures.py +135 -0
- audit/tier5_deploy.py +93 -1
audit/core.py
CHANGED
|
@@ -15,12 +15,13 @@ class Result:
|
|
| 15 |
@dataclasses.dataclass
|
| 16 |
class Check:
|
| 17 |
id: str; tier: str; title: str; fn: Callable[[], "Result"]
|
|
|
|
| 18 |
|
| 19 |
CHECKS: list[Check] = []
|
| 20 |
|
| 21 |
-
def register(id: str, tier: str, title: str):
|
| 22 |
def deco(fn):
|
| 23 |
-
CHECKS.append(Check(id, tier, title, fn)); return fn
|
| 24 |
return deco
|
| 25 |
|
| 26 |
TIER_SETS = {
|
|
@@ -85,8 +86,8 @@ def selftest() -> int:
|
|
| 85 |
r = c.fn()
|
| 86 |
except Exception as e:
|
| 87 |
r = Result(c.id, Status.FAIL, f"raised {type(e).__name__}: {e}")
|
| 88 |
-
if r.status is not
|
| 89 |
-
bad.append(f"{c.id}: expected
|
| 90 |
for b in bad: print(f" FAIL {b}")
|
| 91 |
print(f"\n selftest: {len(CHECKS)} checks Β· {len(bad)} not self-verifying")
|
| 92 |
return 1 if bad else 0
|
|
|
|
| 15 |
@dataclasses.dataclass
|
| 16 |
class Check:
|
| 17 |
id: str; tier: str; title: str; fn: Callable[[], "Result"]
|
| 18 |
+
selftest_expect: "Status" = Status.FAIL
|
| 19 |
|
| 20 |
CHECKS: list[Check] = []
|
| 21 |
|
| 22 |
+
def register(id: str, tier: str, title: str, selftest_expect: "Status" = Status.FAIL):
|
| 23 |
def deco(fn):
|
| 24 |
+
CHECKS.append(Check(id, tier, title, fn, selftest_expect)); return fn
|
| 25 |
return deco
|
| 26 |
|
| 27 |
TIER_SETS = {
|
|
|
|
| 86 |
r = c.fn()
|
| 87 |
except Exception as e:
|
| 88 |
r = Result(c.id, Status.FAIL, f"raised {type(e).__name__}: {e}")
|
| 89 |
+
if r.status is not c.selftest_expect:
|
| 90 |
+
bad.append(f"{c.id}: expected {c.selftest_expect.value} on broken fixture, got {r.status.value}")
|
| 91 |
for b in bad: print(f" FAIL {b}")
|
| 92 |
print(f"\n selftest: {len(CHECKS)} checks Β· {len(bad)} not self-verifying")
|
| 93 |
return 1 if bad else 0
|
audit/selftest_fixtures.py
CHANGED
|
@@ -5,6 +5,7 @@ then fully restores in a `finally` so the repo is not left dirty.
|
|
| 5 |
"""
|
| 6 |
from __future__ import annotations
|
| 7 |
import contextlib
|
|
|
|
| 8 |
import os
|
| 9 |
from audit.core import REPO, sh
|
| 10 |
|
|
@@ -461,6 +462,136 @@ def _f_t4_e2e():
|
|
| 461 |
m.sh = orig_sh
|
| 462 |
|
| 463 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 464 |
FIXTURES.update({
|
| 465 |
"T1.1": _f_t1_1,
|
| 466 |
"T1.2": _f_t1_2,
|
|
@@ -482,4 +613,8 @@ FIXTURES.update({
|
|
| 482 |
"T4.4": _f_t4_4,
|
| 483 |
"T4.5": _f_t4_5,
|
| 484 |
"T4.E2E": _f_t4_e2e,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 485 |
})
|
|
|
|
| 5 |
"""
|
| 6 |
from __future__ import annotations
|
| 7 |
import contextlib
|
| 8 |
+
import json
|
| 9 |
import os
|
| 10 |
from audit.core import REPO, sh
|
| 11 |
|
|
|
|
| 462 |
m.sh = orig_sh
|
| 463 |
|
| 464 |
|
| 465 |
+
# ---------------------------------------------------------------------------
|
| 466 |
+
# Tier 5 fixtures.
|
| 467 |
+
#
|
| 468 |
+
# T5.1/T5.2/T5.4 are file/index-on-disk fixtures (the T1βT3 pattern): create an
|
| 469 |
+
# obviously-temporary broken tracked state, yield, then fully restore so the
|
| 470 |
+
# repo is byte-identical afterwards. T5.2 captures the Dockerfile's EXACT bytes
|
| 471 |
+
# BEFORE any mutation and rewrites them UNCONDITIONALLY first in `finally`
|
| 472 |
+
# (the T3.3/main.py critical-integrity pattern) β a corrupted Dockerfile would
|
| 473 |
+
# break the deploy. T5.3 hits the HF Space API, so it monkeypatches the module
|
| 474 |
+
# seam (`tier5_deploy.urllib.request.urlopen`) to return a controlled
|
| 475 |
+
# non-RUNNING runtime; the patch is restored UNCONDITIONALLY in `finally`.
|
| 476 |
+
# T5.3/T5.4's checks carry selftest_expect=Status.WARN, so their fixtures must
|
| 477 |
+
# make the check RETURN Status.WARN (not raise).
|
| 478 |
+
# ---------------------------------------------------------------------------
|
| 479 |
+
|
| 480 |
+
|
| 481 |
+
@contextlib.contextmanager
|
| 482 |
+
def _f_t5_1():
|
| 483 |
+
"""Track _audit_st.parquet as a PLAIN blob (NOT an LFS pointer).
|
| 484 |
+
|
| 485 |
+
`.parquet` is in `.gitattributes` as `filter=lfs`, so a non-pointer
|
| 486 |
+
`.parquet` blob is exactly the "LFS-globbed but stored raw" state HF's
|
| 487 |
+
pre-push hook rejects -> T5.1 FAIL. We add it with the lfs clean/smudge
|
| 488 |
+
filters neutralised so git stores the raw bytes instead of a pointer, then
|
| 489 |
+
assert it is NOT in `git lfs ls-files`. Restored via `git rm --cached` +
|
| 490 |
+
unlink so the repo is byte-identical after.
|
| 491 |
+
"""
|
| 492 |
+
rel = "_audit_st.parquet"
|
| 493 |
+
f = REPO / rel
|
| 494 |
+
f.write_bytes(b"PAR1_audit_selftest_not_a_pointer_PAR1\n")
|
| 495 |
+
# Empty ALL lfs filters (clean/smudge/process) and drop the `required`
|
| 496 |
+
# guard so `git add` stores the raw bytes instead of running the LFS
|
| 497 |
+
# clean filter (which, if only partially neutralised, aborts the add and
|
| 498 |
+
# silently leaves nothing staged β a false-PASS for T5.1).
|
| 499 |
+
sh(["git",
|
| 500 |
+
"-c", "filter.lfs.clean=",
|
| 501 |
+
"-c", "filter.lfs.smudge=",
|
| 502 |
+
"-c", "filter.lfs.process=",
|
| 503 |
+
"-c", "filter.lfs.required=false",
|
| 504 |
+
"add", "-f", rel])
|
| 505 |
+
# Sanity: it must be tracked AND NOT an LFS pointer for the fixture valid.
|
| 506 |
+
tracked = sh(["git", "ls-files"]).stdout.split()
|
| 507 |
+
tracked_lfs = sh(["git", "lfs", "ls-files", "-n"]).stdout.split()
|
| 508 |
+
if rel not in tracked or rel in tracked_lfs:
|
| 509 |
+
sh(["git", "rm", "--cached", "-qf", rel])
|
| 510 |
+
if f.exists():
|
| 511 |
+
f.unlink()
|
| 512 |
+
raise RuntimeError(
|
| 513 |
+
"T5.1 fixture: _audit_st.parquet not staged as a plain blob "
|
| 514 |
+
f"(tracked={rel in tracked} lfs={rel in tracked_lfs})")
|
| 515 |
+
try:
|
| 516 |
+
yield
|
| 517 |
+
finally:
|
| 518 |
+
# staged content differs from HEAD (file is new) -> needs -f.
|
| 519 |
+
sh(["git", "rm", "--cached", "-qf", rel])
|
| 520 |
+
if f.exists():
|
| 521 |
+
f.unlink()
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
@contextlib.contextmanager
|
| 525 |
+
def _f_t5_2():
|
| 526 |
+
"""Append a `COPY <nonexistent> ./x` line to Dockerfile so T5.2 FAILs.
|
| 527 |
+
|
| 528 |
+
The Dockerfile's EXACT original bytes are captured BEFORE any mutation and
|
| 529 |
+
written back UNCONDITIONALLY as the FIRST statement in `finally` (even if
|
| 530 |
+
the check raises mid-way) β a corrupted Dockerfile is a deploy disaster, so
|
| 531 |
+
the restore is the verbatim captured bytes, not a re-render.
|
| 532 |
+
"""
|
| 533 |
+
df = REPO / "Dockerfile"
|
| 534 |
+
original_bytes = df.read_bytes() # capture EXACT bytes first
|
| 535 |
+
try:
|
| 536 |
+
df.write_bytes(
|
| 537 |
+
original_bytes
|
| 538 |
+
+ b"\nCOPY _audit_st_nonexistent_dir ./x\n"
|
| 539 |
+
)
|
| 540 |
+
yield
|
| 541 |
+
finally:
|
| 542 |
+
# Restore Dockerfile byte-for-byte, unconditionally, FIRST.
|
| 543 |
+
df.write_bytes(original_bytes)
|
| 544 |
+
|
| 545 |
+
|
| 546 |
+
@contextlib.contextmanager
|
| 547 |
+
def _f_t5_3():
|
| 548 |
+
"""Patch tier5_deploy.urllib.request.urlopen so SPACE_API runtime.stage is
|
| 549 |
+
BUILDING (not RUNNING) -> T5.3 returns Status.WARN.
|
| 550 |
+
|
| 551 |
+
The patched urlopen is captured BEFORE the yield and restored
|
| 552 |
+
UNCONDITIONALLY in `finally`. No repo files are touched.
|
| 553 |
+
"""
|
| 554 |
+
import io
|
| 555 |
+
import audit.tier5_deploy as m
|
| 556 |
+
orig_urlopen = m.urllib.request.urlopen
|
| 557 |
+
payload = json.dumps({"runtime": {"stage": "BUILDING", "sha": "deadbeefcafe0000"}})
|
| 558 |
+
|
| 559 |
+
def _fake_urlopen(url, *a, **k):
|
| 560 |
+
# Only intercept the HF Space API call; anything else is unexpected
|
| 561 |
+
# here (the BUILDING branch returns before any LIVE smoke fetch).
|
| 562 |
+
return io.BytesIO(payload.encode())
|
| 563 |
+
|
| 564 |
+
m.urllib.request.urlopen = _fake_urlopen
|
| 565 |
+
try:
|
| 566 |
+
yield
|
| 567 |
+
finally:
|
| 568 |
+
m.urllib.request.urlopen = orig_urlopen
|
| 569 |
+
|
| 570 |
+
|
| 571 |
+
@contextlib.contextmanager
|
| 572 |
+
def _f_t5_4():
|
| 573 |
+
"""Track 70-docs/_audit_st_stale.md containing both `Status | Live` and
|
| 574 |
+
`orchestrator.py` so T5.4's stale-present-state-doc tripwire -> WARN.
|
| 575 |
+
|
| 576 |
+
Restored via `git rm --cached` + unlink so the repo is byte-identical
|
| 577 |
+
after.
|
| 578 |
+
"""
|
| 579 |
+
rel = "70-docs/_audit_st_stale.md"
|
| 580 |
+
f = REPO / rel
|
| 581 |
+
f.parent.mkdir(parents=True, exist_ok=True)
|
| 582 |
+
f.write_text(
|
| 583 |
+
"| Status | Live |\n\nReferences backend/orchestrator.py here.\n",
|
| 584 |
+
encoding="utf-8",
|
| 585 |
+
)
|
| 586 |
+
sh(["git", "add", "-f", rel])
|
| 587 |
+
try:
|
| 588 |
+
yield
|
| 589 |
+
finally:
|
| 590 |
+
sh(["git", "rm", "--cached", "-q", rel])
|
| 591 |
+
if f.exists():
|
| 592 |
+
f.unlink()
|
| 593 |
+
|
| 594 |
+
|
| 595 |
FIXTURES.update({
|
| 596 |
"T1.1": _f_t1_1,
|
| 597 |
"T1.2": _f_t1_2,
|
|
|
|
| 613 |
"T4.4": _f_t4_4,
|
| 614 |
"T4.5": _f_t4_5,
|
| 615 |
"T4.E2E": _f_t4_e2e,
|
| 616 |
+
"T5.1": _f_t5_1,
|
| 617 |
+
"T5.2": _f_t5_2,
|
| 618 |
+
"T5.3": _f_t5_3,
|
| 619 |
+
"T5.4": _f_t5_4,
|
| 620 |
})
|
audit/tier5_deploy.py
CHANGED
|
@@ -1 +1,93 @@
|
|
| 1 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tier 5 β deploy safety. READ-ONLY vs production (HTTP GET + git ls-remote
|
| 2 |
+
+ local git only). NEVER pushes or mutates anything."""
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
import fnmatch, json, urllib.request
|
| 5 |
+
from audit.core import register, Result, Status, REPO, git, sh
|
| 6 |
+
|
| 7 |
+
SPACE_API = "https://huggingface.co/api/spaces/rohitsar567/InsuranceBot"
|
| 8 |
+
LIVE = "https://rohitsar567-insurancebot.hf.space"
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@register("T5.1", "deploy", "LFS pre-push validation (HF hook simulation)")
|
| 12 |
+
def t5_1() -> Result:
|
| 13 |
+
ga = (REPO / ".gitattributes").read_text(encoding="utf-8", errors="replace")
|
| 14 |
+
globs = [l.split()[0] for l in ga.splitlines()
|
| 15 |
+
if "filter=lfs" in l and l.strip() and not l.startswith("#")]
|
| 16 |
+
lfs = set(sh(["git", "lfs", "ls-files", "-n"]).stdout.split())
|
| 17 |
+
bad = [p for p in git("ls-files").splitlines()
|
| 18 |
+
if any(fnmatch.fnmatch(p, g) for g in globs) and p not in lfs]
|
| 19 |
+
return (Result("T5.1", Status.FAIL, f"non-LFS but LFS-globbed (HF would reject): {bad[:6]}",
|
| 20 |
+
"git rm --cached + re-add so they store as LFS pointers")
|
| 21 |
+
if bad else Result("T5.1", Status.PASS, "all LFS-pattern files are pointers"))
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@register("T5.2", "deploy", "Dockerfile coherence")
|
| 25 |
+
def t5_2() -> Result:
|
| 26 |
+
df = (REPO / "Dockerfile").read_text(encoding="utf-8", errors="replace")
|
| 27 |
+
missing = []
|
| 28 |
+
for ln in df.splitlines():
|
| 29 |
+
s = ln.strip()
|
| 30 |
+
if s.startswith("COPY ") and not s.startswith("COPY --from"):
|
| 31 |
+
parts = s.split()
|
| 32 |
+
if len(parts) >= 3:
|
| 33 |
+
src = parts[1]
|
| 34 |
+
if src not in (".",) and "*" not in src and not (REPO / src).exists():
|
| 35 |
+
missing.append(src)
|
| 36 |
+
collide = [p for p in git("ls-files").splitlines()
|
| 37 |
+
if p in ("rag/corpus", "rag/extracted", "rag/vectors")]
|
| 38 |
+
if missing or collide:
|
| 39 |
+
return Result("T5.2", Status.FAIL,
|
| 40 |
+
f"COPY src missing: {missing}; dataset-hydration collide: {collide}",
|
| 41 |
+
"fix the COPY source path / untrack rag/corpus|extracted|vectors")
|
| 42 |
+
return Result("T5.2", Status.PASS, "COPY paths exist; no hydration collision")
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@register("T5.3", "deploy", "deployed sha matches local (guarded)", selftest_expect=Status.WARN)
|
| 46 |
+
def t5_3() -> Result:
|
| 47 |
+
head = git("rev-parse", "HEAD")[:12]
|
| 48 |
+
o = sh(["git", "ls-remote", "origin", "-h", "refs/heads/main"]).stdout.split()
|
| 49 |
+
origin_sha = o[0][:12] if o else ""
|
| 50 |
+
try:
|
| 51 |
+
rt = json.load(urllib.request.urlopen(SPACE_API, timeout=20)).get("runtime", {})
|
| 52 |
+
except Exception as e:
|
| 53 |
+
return Result("T5.3", Status.SKIP, f"no network/HF API: {e}", "run with network to verify deploy")
|
| 54 |
+
stage = rt.get("stage")
|
| 55 |
+
live_sha = (rt.get("sha") or "")[:12]
|
| 56 |
+
if stage != "RUNNING":
|
| 57 |
+
return Result("T5.3", Status.WARN, f"Space stage={stage} sha={live_sha}",
|
| 58 |
+
"wait for build / inspect HF build log")
|
| 59 |
+
if origin_sha and live_sha and live_sha != origin_sha:
|
| 60 |
+
return Result("T5.3", Status.WARN,
|
| 61 |
+
f"live sha {live_sha} != origin/main {origin_sha} (Space lagging build / LFS silent-fail?)",
|
| 62 |
+
"verify the Space actually rebuilt; never trust 'RUNNING' alone")
|
| 63 |
+
if origin_sha and origin_sha != head:
|
| 64 |
+
return Result("T5.3", Status.WARN,
|
| 65 |
+
f"local HEAD {head} not pushed (origin/main={origin_sha} is live)",
|
| 66 |
+
"expected if deploy is deliberately deferred; push when ready")
|
| 67 |
+
try:
|
| 68 |
+
h = urllib.request.urlopen(f"{LIVE}/api/health", timeout=20).read(200).decode()
|
| 69 |
+
logo = urllib.request.urlopen(f"{LIVE}/insurer-logos/oriental-insurance.png", timeout=20)
|
| 70 |
+
ok = '"status":"ok"' in h and logo.headers.get_content_type() == "image/png"
|
| 71 |
+
return (Result("T5.3", Status.PASS, f"sha {live_sha} live; health ok; LFS logo image/png")
|
| 72 |
+
if ok else Result("T5.3", Status.FAIL, f"live unhealthy: {h[:80]}", "investigate live deploy"))
|
| 73 |
+
except Exception as e:
|
| 74 |
+
return Result("T5.3", Status.WARN, f"live smoke unreachable: {e}", "retry with network")
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
@register("T5.4", "deploy", "standing tripwires (bloat/disk/stale-docs)", selftest_expect=Status.WARN)
|
| 78 |
+
def t5_4() -> Result:
|
| 79 |
+
warns = []
|
| 80 |
+
bloat = sh(["bash", "-lc",
|
| 81 |
+
"find rag -name link_lists.bin -size +200M 2>/dev/null | head -3; "
|
| 82 |
+
"du -sm rag/_hf_dataset_backup 2>/dev/null | awk '$1>20000{print $0\" MB\"}'"]).stdout.strip()
|
| 83 |
+
if bloat:
|
| 84 |
+
warns.append(f"chroma/backup bloat: {bloat[:160]}")
|
| 85 |
+
free = sh(["bash", "-lc", "df -m . | tail -1 | awk '{print $4}'"]).stdout.strip()
|
| 86 |
+
if free.isdigit() and int(free) < 2000:
|
| 87 |
+
warns.append(f"low disk: {free} MB free")
|
| 88 |
+
stale = sh(["bash", "-lc",
|
| 89 |
+
"grep -rl 'Status | Live' 70-docs 2>/dev/null | xargs -r grep -l 'orchestrator.py' 2>/dev/null | head -3"]).stdout.strip()
|
| 90 |
+
if stale:
|
| 91 |
+
warns.append(f"stale present-state docs: {stale.splitlines()[:3]}")
|
| 92 |
+
return (Result("T5.4", Status.WARN, " | ".join(warns), "address the flagged tripwire")
|
| 93 |
+
if warns else Result("T5.4", Status.PASS, "no bloat/disk/stale-doc tripwire"))
|