cswap-pin 0.1.330__tar.gz → 0.1.332__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. {cswap_pin-0.1.330 → cswap_pin-0.1.332}/PKG-INFO +12 -1
  2. {cswap_pin-0.1.330 → cswap_pin-0.1.332}/README.md +11 -0
  3. {cswap_pin-0.1.330 → cswap_pin-0.1.332}/pyproject.toml +1 -1
  4. {cswap_pin-0.1.330 → cswap_pin-0.1.332}/src/cswap_pin/proxy.py +108 -47
  5. {cswap_pin-0.1.330 → cswap_pin-0.1.332}/tests/test_proxy.py +50 -22
  6. {cswap_pin-0.1.330 → cswap_pin-0.1.332}/tests/test_proxy_server.py +286 -11
  7. {cswap_pin-0.1.330 → cswap_pin-0.1.332}/uv.lock +1 -1
  8. {cswap_pin-0.1.330 → cswap_pin-0.1.332}/.githooks/pre-push +0 -0
  9. {cswap_pin-0.1.330 → cswap_pin-0.1.332}/.github/workflows/ci.yml +0 -0
  10. {cswap_pin-0.1.330 → cswap_pin-0.1.332}/.github/workflows/publish.yml +0 -0
  11. {cswap_pin-0.1.330 → cswap_pin-0.1.332}/.github/workflows/tag-on-version-bump.yml +0 -0
  12. {cswap_pin-0.1.330 → cswap_pin-0.1.332}/.gitignore +0 -0
  13. {cswap_pin-0.1.330 → cswap_pin-0.1.332}/src/cswap_pin/__init__.py +0 -0
  14. {cswap_pin-0.1.330 → cswap_pin-0.1.332}/src/cswap_pin/_host.py +0 -0
  15. {cswap_pin-0.1.330 → cswap_pin-0.1.332}/tests/conftest.py +0 -0
  16. {cswap_pin-0.1.330 → cswap_pin-0.1.332}/tests/leakwatch.py +0 -0
  17. {cswap_pin-0.1.330 → cswap_pin-0.1.332}/tests/models/at_limit_conversion.pict +0 -0
  18. {cswap_pin-0.1.330 → cswap_pin-0.1.332}/tests/models/at_limit_conversion.tsv +0 -0
  19. {cswap_pin-0.1.330 → cswap_pin-0.1.332}/tests/test_meta.py +0 -0
  20. {cswap_pin-0.1.330 → cswap_pin-0.1.332}/tests/test_packaging.py +0 -0
  21. {cswap_pin-0.1.330 → cswap_pin-0.1.332}/tests/test_pin_run.py +0 -0
  22. {cswap_pin-0.1.330 → cswap_pin-0.1.332}/tests/test_publish_guard.py +0 -0
  23. {cswap_pin-0.1.330 → cswap_pin-0.1.332}/tests/test_session_name_adopt.py +0 -0
  24. {cswap_pin-0.1.330 → cswap_pin-0.1.332}/tools/thread_probe.py +0 -0
  25. {cswap_pin-0.1.330 → cswap_pin-0.1.332}/tools/upgrade_probe.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: cswap-pin
3
- Version: 0.1.330
3
+ Version: 0.1.332
4
4
  Summary: Keep Claude Code's Remote Control and Artifacts on one account while inference follows cswap's account swap
5
5
  Project-URL: Homepage, https://github.com/codeslake/cswap-pin
6
6
  Project-URL: Repository, https://github.com/codeslake/cswap-pin
@@ -1001,6 +1001,17 @@ Connections are multiplexed on one selector instead. Measured with
1001
1001
  A ceiling was tried first and removed: it turns the 257th retry into a
1002
1002
  refused connection and leaves the coupling in place.
1003
1003
 
1004
+ One ceiling is back, for a different resource. A fan-out of tunnels to hosts
1005
+ that are not Anthropic's (an agent's 48 parallel bulk transfers, measured at
1006
+ ~500 tunnels) used every fd the egress hop had, and Claude's own `/v1/messages`
1007
+ CONNECTs through the same hop got `502`. So at most 256 blind tunnels to other
1008
+ hosts are open at once; the 257th waits 2 s for a slot, then gets the same
1009
+ `503` with `Retry-After: 2` as a dead hop, and nothing else is counted:
1010
+ `anthropic.com`, `claude.ai`, `claude.com` and `claudeusercontent.com` (and
1011
+ their subdomains) are never capped. It bounds the hop's fds, not threads, so
1012
+ the coupling above stays gone. `thread_probe.py` tunnels to `127.0.0.1`, so its
1013
+ 300 row now tops out at 256.
1014
+
1004
1015
  ### Asking for a specific port
1005
1016
 
1006
1017
  ```bash
@@ -978,6 +978,17 @@ Connections are multiplexed on one selector instead. Measured with
978
978
  A ceiling was tried first and removed: it turns the 257th retry into a
979
979
  refused connection and leaves the coupling in place.
980
980
 
981
+ One ceiling is back, for a different resource. A fan-out of tunnels to hosts
982
+ that are not Anthropic's (an agent's 48 parallel bulk transfers, measured at
983
+ ~500 tunnels) used every fd the egress hop had, and Claude's own `/v1/messages`
984
+ CONNECTs through the same hop got `502`. So at most 256 blind tunnels to other
985
+ hosts are open at once; the 257th waits 2 s for a slot, then gets the same
986
+ `503` with `Retry-After: 2` as a dead hop, and nothing else is counted:
987
+ `anthropic.com`, `claude.ai`, `claude.com` and `claudeusercontent.com` (and
988
+ their subdomains) are never capped. It bounds the hop's fds, not threads, so
989
+ the coupling above stays gone. `thread_probe.py` tunnels to `127.0.0.1`, so its
990
+ 300 row now tops out at 256.
991
+
981
992
  ### Asking for a specific port
982
993
 
983
994
  ```bash
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "cswap-pin"
3
- version = "0.1.330"
3
+ version = "0.1.332"
4
4
  description = "Keep Claude Code's Remote Control and Artifacts on one account while inference follows cswap's account swap"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.10"
@@ -2309,10 +2309,12 @@ def wire_global_config(port: int | None, ca_path: Path | None,
2309
2309
  so this touches nothing new: not ``settings.json`` (Claude Code's own),
2310
2310
  not a shell rc, not a shim on PATH.
2311
2311
 
2312
- Only keys THIS function wrote are ever modified, tracked by name in
2313
- ``_WIRE_MARK``. A proxy the user (or their launcher) set themselves is
2314
- left exactly as found, and clearing the pin restores it rather than
2315
- deleting it — the ordering matters, because the env block is applied on
2312
+ Only the keys THIS function writes are ever modified, tracked by name in
2313
+ ``_WIRE_MARK``. A value already under one of those names (a proxy the user
2314
+ or their launcher set, or an unmarked ``CSWAP_PIN_PORT`` block) is
2315
+ REPLACED, not left as found: it is displaced into ``_WIRE_MARK``Saved, and
2316
+ clearing the pin restores it rather than deleting it — the ordering
2317
+ matters, because the env block is applied on
2316
2318
  top of the process environment and would otherwise silently displace a
2317
2319
  wrapper's own proxy.
2318
2320
 
@@ -9865,7 +9867,9 @@ def ensure_wired_to(port: int, certdir: Path) -> bool:
9865
9867
  that one. Measured 2026-09-24: a throwaway daemon on a spare certdir
9866
9868
  under the same ``$HOME`` rewired the shared ``.claude.json`` away from
9867
9869
  the live pin four times in one day. A wiring naming a DEAD port (or
9868
- nothing) is still corrected, exactly as before.
9870
+ nothing) is still corrected, exactly as before, and that includes a
9871
+ ``CSWAP_PIN_PORT`` block the pin never marked: its values are displaced
9872
+ into the receipt's ``Saved`` and an unwire hands them back.
9869
9873
 
9870
9874
  ONLY WHILE A PIN RECORD EXISTS. `cswap pin --clear` drops the record and
9871
9875
  the wiring and leaves this daemon serving the sessions it holds; a
@@ -15327,6 +15331,12 @@ def wire_env(
15327
15331
  UPSTREAM_HOST = "api.anthropic.com"
15328
15332
  UPSTREAM_PORT = 443
15329
15333
 
15334
+ # ~500 parallel bulk tunnels to other hosts took every fd the hop had and
15335
+ # /v1/messages got 502; 256 at 2 fds each leaves a 1024-nofile hop room for the API.
15336
+ _BLIND_TUNNEL_CAP = 256
15337
+ _UNCAPPED_DOMAINS = ("anthropic.com", "claude.ai", "claude.com",
15338
+ "claudeusercontent.com")
15339
+
15330
15340
 
15331
15341
  def _config_home_for_policy() -> Path:
15332
15342
  """Where Claude Code keeps `policy-limits.json`. A seam, so a test can
@@ -15804,6 +15814,7 @@ class PinProxy:
15804
15814
  # its own thread, so a thread-local keeps one upstream per client.
15805
15815
  self._local = threading.local()
15806
15816
  self._conn_seq = itertools.count(1)
15817
+ self._tunnel_slots = threading.BoundedSemaphore(_BLIND_TUNNEL_CAP)
15807
15818
  # Clients connected right now, in `_open_conns` — the daemon's own
15808
15819
  # record, because the /proc-based probe is Linux-only and its None
15809
15820
  # reads as "idle" on the machines that cannot answer (see
@@ -19519,7 +19530,7 @@ class PinProxy:
19519
19530
  # auto-updater.
19520
19531
  host = target.rsplit(":", 1)[0]
19521
19532
  if host != UPSTREAM_HOST:
19522
- return self._blind_tunnel(target, conn)
19533
+ return self._capped_tunnel(target, conn)
19523
19534
  return self._mitm(conn)
19524
19535
  if len(parts) >= 2 and parts[1].startswith("/health"):
19525
19536
  # Local health probe (origin-form GET /health to our own port).
@@ -19881,15 +19892,17 @@ class PinProxy:
19881
19892
  code_watch_beat = getattr(self, "_code_watch_beat", None)
19882
19893
  # READ NOW, never remembered from start: this is how a rollout verifies
19883
19894
  # the fd limit `_raise_nofile_soft_limit` set (it cannot be read from
19884
- # outside the process on a Mac). `null` for unlimited or an unreadable
19885
- # limit, which is not zero. Never raises: this is the liveness probe.
19895
+ # outside the process on a Mac). A number for a finite limit,
19896
+ # "unlimited" for RLIM_INFINITY (the word daemon.log's `nofile before`
19897
+ # line uses), `null` ONLY for a limit that could not be read.
19898
+ # Never raises: this is the liveness probe.
19886
19899
  try:
19887
19900
  import resource # POSIX only
19888
19901
 
19889
19902
  nofile_soft, nofile_hard = (
19890
- None if n == resource.RLIM_INFINITY else n
19903
+ "unlimited" if n == resource.RLIM_INFINITY else n
19891
19904
  for n in resource.getrlimit(resource.RLIMIT_NOFILE))
19892
- except (OSError, ValueError):
19905
+ except (ImportError, OSError, ValueError):
19893
19906
  nofile_soft = nofile_hard = None
19894
19907
  body = json.dumps(
19895
19908
  {"pin_proxy": True, "port": self.port, "chain": chain,
@@ -21732,7 +21745,47 @@ class PinProxy:
21732
21745
  self._debug = _append_capped(
21733
21746
  debug_path, text, self._debug, cap=_TRACE_MAX_BYTES)
21734
21747
 
21735
- def _blind_tunnel(self, target: str, conn: socket.socket) -> None:
21748
+ def _capped_tunnel(self, target: str, conn: socket.socket) -> None:
21749
+ host = target.rpartition(":")[0].lower().rstrip(".")
21750
+ if any(host == d or host.endswith("." + d) for d in _UNCAPPED_DOMAINS):
21751
+ return self._blind_tunnel(target, conn, lambda: None)
21752
+ if not self._tunnel_slots.acquire(timeout=2):
21753
+ now = time.monotonic()
21754
+ last = getattr(self, "_tunnel_capped_at", None)
21755
+ if last is None or now - last >= _BUSY_REPORT_COOLDOWN_S:
21756
+ self._tunnel_capped_at = now
21757
+ _log_lifecycle(
21758
+ f"CONNECT {target} refused (503): {_BLIND_TUNNEL_CAP} "
21759
+ "tunnels to other hosts are open, the rest of the hop is "
21760
+ "kept for the API")
21761
+ self._refuse_tunnel(conn)
21762
+ return
21763
+ slot = [self._tunnel_slots] # popped by whoever gives it back: once
21764
+
21765
+ def give() -> None:
21766
+ with contextlib.suppress(IndexError):
21767
+ slot.pop().release()
21768
+
21769
+ detached = False
21770
+ try:
21771
+ detached = self._blind_tunnel(target, conn, give)
21772
+ return detached
21773
+ finally:
21774
+ if not detached:
21775
+ give()
21776
+
21777
+ @staticmethod
21778
+ def _refuse_tunnel(conn: socket.socket) -> None:
21779
+ try:
21780
+ conn.sendall(
21781
+ b"HTTP/1.1 503 Service Unavailable\r\nRetry-After: 2\r\n"
21782
+ b"Content-Length: 0\r\nConnection: close\r\n\r\n"
21783
+ )
21784
+ except OSError:
21785
+ pass
21786
+ conn.close()
21787
+
21788
+ def _blind_tunnel(self, target: str, conn: socket.socket, give) -> None:
21736
21789
  host, _, port_s = target.rpartition(":")
21737
21790
  port = int(port_s) if port_s else 443
21738
21791
  # Trace the tunnel too. Remote Control receives over a WebSocket to the
@@ -21822,14 +21875,7 @@ class PinProxy:
21822
21875
  # at the CONNECT path Remote Control's WebSocket takes.
21823
21876
  if candidates and not _direct_allowed():
21824
21877
  self._note_egress_refused()
21825
- try:
21826
- conn.sendall(
21827
- b"HTTP/1.1 503 Service Unavailable\r\nRetry-After: 2\r\n"
21828
- b"Content-Length: 0\r\nConnection: close\r\n\r\n"
21829
- )
21830
- except OSError:
21831
- pass
21832
- conn.close()
21878
+ self._refuse_tunnel(conn)
21833
21879
  return
21834
21880
  try:
21835
21881
  up = socket.create_connection((host, port), timeout=15)
@@ -21860,6 +21906,7 @@ class PinProxy:
21860
21906
  def _release_tunnel():
21861
21907
  if release:
21862
21908
  release()
21909
+ give()
21863
21910
 
21864
21911
  # DETACHED: nothing after the 200 is ours to parse, so the thread that
21865
21912
  # built the tunnel has no work left. It hands the pair to the shared
@@ -22256,7 +22303,13 @@ def _hop_recently_failed() -> bool:
22256
22303
  _STREAM_ROUTE = re.compile(r"/v1/code/sessions/([^/?]+)/worker/events/stream")
22257
22304
  _WORKER_ROUTE = re.compile(r"/v1/code/sessions/([^/?]+)/worker")
22258
22305
  _worker_alive: dict[str, float] = {}
22306
+ #: When each session's stamp was last WRITTEN to the file, apart from when it
22307
+ #: was last SEEN above. The throttle needs the former: measured against the
22308
+ #: latter, a bridge asking every <=`_ALIVE_WRITE_EVERY` seconds refreshed the
22309
+ #: very clock it was throttled by and never reached the file.
22310
+ _worker_alive_written: dict[str, float] = {}
22259
22311
  _worker_alive_lock = threading.Lock()
22312
+ _alive_file_lock = threading.Lock()
22260
22313
  #: WHERE THE EVIDENCE LIVES, AND IT CANNOT BE THIS PROCESS'S MEMORY. A
22261
22314
  #: long-held stream stays with the DEPARTING daemon for the whole drain while
22262
22315
  #: its session's heartbeats move to the successor, so the process holding the
@@ -22318,7 +22371,6 @@ def _note_worker_status(path: str | None, status_line: bytes,
22318
22371
  return
22319
22372
  sid, now = m.group(1), time.time()
22320
22373
  with _worker_alive_lock:
22321
- last = _worker_alive.get(sid, 0.0)
22322
22374
  _worker_alive[sid] = now
22323
22375
  if len(_worker_alive) > 256:
22324
22376
  # One entry per session this daemon has ever relayed for, so it
@@ -22327,37 +22379,46 @@ def _note_worker_status(path: str | None, status_line: bytes,
22327
22379
  for k, seen in list(_worker_alive.items()):
22328
22380
  if now - seen > _STREAM_LIVE_SECONDS:
22329
22381
  del _worker_alive[k]
22330
- if now - last < _ALIVE_WRITE_EVERY:
22382
+ _worker_alive_written.pop(k, None)
22383
+ # `0 <=`: a written stamp from the FUTURE (the wall clock stepped back)
22384
+ # must not throttle, or the file stays still until the clock catches up.
22385
+ if 0 <= now - _worker_alive_written.get(sid, 0.0) < _ALIVE_WRITE_EVERY:
22331
22386
  return
22387
+ _worker_alive_written[sid] = now
22332
22388
  p = _alive_path(certdir)
22333
22389
  if p is None:
22334
22390
  return
22335
- shared = _alive_load(certdir)
22336
- # THE WRITER'S OWN PID IS PART OF THE KEY, not the value -- a value has
22337
- # to stay a bare number or the filter two lines down (every OTHER
22338
- # writer's read-modify-write, not just this one) drops the entry on its
22339
- # very next pass. See `_worker_alive_age`, the reader this exists for.
22340
- #
22341
- # BOTH SHAPES, DURING THE ROLLOUT HANDOVER. A DEPLOYED release still
22342
- # reads the bare `shared.get(sid)` -- a draining OLD daemon running that
22343
- # code cannot see a successor's `sid@pid`-only stamp, and after
22344
- # `_STREAM_LIVE_SECONDS` a spurious stream 404 passes through and ends
22345
- # the session. `_stream_404_is_spurious` here already accepts either
22346
- # shape; the bare key is for the reader this process has not upgraded
22347
- # past yet.
22348
- shared[sid] = now
22349
- shared[f"{sid}@{os.getpid()}"] = now
22350
- # MERGED, NOT OVERWRITTEN: the departing daemon and its successor both
22351
- # write here. A lost update costs one entry and fails toward "no
22352
- # evidence", which is the direction that lets the 404 through.
22353
- shared = {k: v for k, v in shared.items()
22354
- if isinstance(v, (int, float)) and now - v <= _STREAM_LIVE_SECONDS}
22355
- try:
22356
- tmp = p.with_name(p.name + f".{os.getpid()}.tmp")
22357
- tmp.write_text(json.dumps(shared))
22358
- os.replace(tmp, p) # atomic, so a reader never sees a torn file
22359
- except OSError:
22360
- pass
22391
+ # ONE READ-MERGE-WRITE AT A TIME PER PROCESS: relay threads shared one temp
22392
+ # name, so two writers tore the file (reads as `{}`, "no evidence") or merged
22393
+ # into a stale read and dropped a stamp. Not `_worker_alive_lock`: this holds
22394
+ # across disk I/O, which must not stall the in-memory check on every route.
22395
+ with _alive_file_lock:
22396
+ shared = _alive_load(certdir)
22397
+ # THE WRITER'S OWN PID IS PART OF THE KEY, not the value -- a value has
22398
+ # to stay a bare number or the filter two lines down (every OTHER
22399
+ # writer's read-modify-write, not just this one) drops the entry on its
22400
+ # very next pass. See `_worker_alive_age`, the reader this exists for.
22401
+ #
22402
+ # BOTH SHAPES, DURING THE ROLLOUT HANDOVER. A DEPLOYED release still
22403
+ # reads the bare `shared.get(sid)` -- a draining OLD daemon running that
22404
+ # code cannot see a successor's `sid@pid`-only stamp, and after
22405
+ # `_STREAM_LIVE_SECONDS` a spurious stream 404 passes through and ends
22406
+ # the session. `_stream_404_is_spurious` here already accepts either
22407
+ # shape; the bare key is for the reader this process has not upgraded
22408
+ # past yet.
22409
+ shared[sid] = now
22410
+ shared[f"{sid}@{os.getpid()}"] = now
22411
+ # MERGED, NOT OVERWRITTEN: the departing daemon and its successor both
22412
+ # write here. A lost update costs one entry and fails toward "no
22413
+ # evidence", which is the direction that lets the 404 through.
22414
+ shared = {k: v for k, v in shared.items()
22415
+ if isinstance(v, (int, float)) and now - v <= _STREAM_LIVE_SECONDS}
22416
+ try:
22417
+ tmp = p.with_name(p.name + f".{os.getpid()}.tmp")
22418
+ tmp.write_text(json.dumps(shared))
22419
+ os.replace(tmp, p) # atomic, so a reader never sees a torn file
22420
+ except OSError:
22421
+ pass
22361
22422
 
22362
22423
 
22363
22424
  def _stream_404_is_spurious(path: str | None, certdir=None) -> bool:
@@ -20608,31 +20608,63 @@ class TestTheDaemonWatchesItsOwnCode:
20608
20608
  finally:
20609
20609
  hold.close()
20610
20610
 
20611
- def case_CONTROL_a_block_the_pin_did_not_write_is_left_alone(
20611
+ def case_an_UNMARKED_block_naming_a_DEAD_port_is_rewired_and_unwire_hands_its_values_back(
20612
20612
  self, tmp_path, monkeypatch
20613
20613
  ):
20614
- """The repair is scoped to the pin's own keys, and must stay scoped.
20615
-
20616
- `wire_global_config` modifies only what `_WIRE_MARK` records, so a
20617
- `CSWAP_PIN_PORT` some launcher or person set is not ours to correct --
20618
- and a serving daemon calling into it must not become the exception.
20619
- Found by seeding the case above with an unmarked block by hand, which
20620
- reported a repair failure over code keeping this promise.
20614
+ """`ensure_wired_to` corrects an `env` block the pin never wrote, and
20615
+ loses nothing doing so (e0d4e44).
20616
+
20617
+ `wire_global_config` treats a value under one of its own key names as
20618
+ displaced whoever put it there: it lands in the receipt's `Saved` and
20619
+ an unwire hands it back. So the repair is NOT scoped to a block the
20620
+ pin marked, and this case pins the contract that replaced the old
20621
+ "left alone" one.
20622
+
20623
+ THE DEAD PORT IS HELD, NOT PICKED. This case used to seed a fixed
20624
+ 41111 and was green only while the daemon could reclaim it
20625
+ (`wanted_port` falls back to the port the config names): on a box
20626
+ where something already held 41111 the daemon served elsewhere and
20627
+ the rewire ran. A bound, never-listening socket is a port the daemon
20628
+ cannot take and nobody answers on, whatever else the host runs.
20621
20629
  """
20630
+ import socket
20631
+
20622
20632
  import claude_swap.paths as paths
20623
20633
  from cswap_pin import proxy as pin_proxy
20624
20634
 
20635
+ hold = socket.socket()
20636
+ hold.bind(("127.0.0.1", 0))
20637
+ dead = hold.getsockname()[1]
20638
+ seed = {"CSWAP_PIN_PORT": str(dead),
20639
+ "HTTPS_PROXY": "http://launcher.example:3128"}
20625
20640
  # A PIN RECORD: a daemon wires only while one exists.
20626
20641
  pin_proxy.save_pin(tmp_path, "a@b.c", "org")
20627
- certdir, cfg, _ = self._live_daemon(
20628
- tmp_path, monkeypatch, paths,
20629
- cfg_text=json.dumps({"env": {"CSWAP_PIN_PORT": "41111"}}))
20630
20642
  try:
20631
- assert pin_proxy._wired_port() == 41111, (
20632
- "a daemon start rewrote an env block the pin never wrote",
20633
- cfg.read_text())
20643
+ certdir, cfg, _ = self._live_daemon(
20644
+ tmp_path, monkeypatch, paths,
20645
+ cfg_text=json.dumps({"env": seed}))
20646
+ try:
20647
+ st = pin_proxy.read_daemon_state(certdir)
20648
+ assert st["port"] != dead, (
20649
+ "premise: the daemon bound the held port, so nothing was "
20650
+ "wrong for it to repair", st)
20651
+ assert pin_proxy._wired_port() == st["port"], (
20652
+ "an unmarked block naming a dead port was left in place",
20653
+ cfg.read_text())
20654
+ saved = pin_proxy._read_ledger(
20655
+ cfg, json.loads(cfg.read_text())
20656
+ )[f"{pin_proxy._WIRE_MARK}Saved"]
20657
+ assert saved == seed, (
20658
+ "the displaced values were not recorded for the unwire",
20659
+ saved)
20660
+ assert pin_proxy.wire_global_config(None, None)
20661
+ assert json.loads(cfg.read_text())["env"] == seed, (
20662
+ "unwire did not hand the unmarked values back",
20663
+ cfg.read_text())
20664
+ finally:
20665
+ self._stop_live()
20634
20666
  finally:
20635
- self._stop_live()
20667
+ hold.close()
20636
20668
 
20637
20669
  def _live_daemon(self, tmp_path, monkeypatch, paths, stale_port=None,
20638
20670
  cfg_text="{}"):
@@ -20651,13 +20683,9 @@ class TestTheDaemonWatchesItsOwnCode:
20651
20683
  cfg = tmp_path / ".claude.json"
20652
20684
  cfg.write_text(cfg_text)
20653
20685
  monkeypatch.setattr(paths, "get_global_config_path", lambda: cfg)
20654
- # THE REAL WRITER, never a hand-built block. `wire_global_config`
20655
- # only ever modifies keys it recorded in `_WIRE_MARK`, so an
20656
- # approximation of its output without that mark is a config it is
20657
- # required to leave alone -- a seed that tests the opposite of what it
20658
- # was written for. Measured: a hand-built `{"env": {"CSWAP_PIN_PORT":
20659
- # "41111"}}` made this harness report a repair failure over code doing
20660
- # exactly what it promises.
20686
+ # THE REAL WRITER for a MARKED stale wiring, so the receipt exists as
20687
+ # a live pin leaves it. An UNMARKED block is rewired too (its values
20688
+ # land in `Saved`); `cfg_text` seeds that case.
20661
20689
  if stale_port is not None:
20662
20690
  pin_proxy.wire_global_config(stale_port, certdir / "ca.pem")
20663
20691
  assert pin_proxy._wired_port() == stale_port, cfg.read_text()
@@ -2287,11 +2287,17 @@ class _StallingHop:
2287
2287
  else a canned 200. ``reached`` is set when the request head arrived;
2288
2288
  ``cut`` when the pin's side of that leg ended (EOF or reset), which is how
2289
2289
  a case sees the hop leg closed. ``reply`` (with ``delay=None``) is sent
2290
- first and then nothing: a reply head and part of a body, then silence."""
2290
+ first and then nothing: a reply head and part of a body, then silence.
2291
+ ``max_conns`` makes it a hop out of fds: past that many live connections a
2292
+ request is answered 502. ``hold_rest``: a CONNECT for anything but
2293
+ ``target`` is answered 200 and then held silent."""
2291
2294
 
2292
2295
  def __init__(self, delay: "float | None" = None, target=None,
2293
- reply: bytes = b""):
2296
+ reply: bytes = b"", max_conns: "int | None" = None,
2297
+ hold_rest: bool = False):
2294
2298
  self._delay, self._target, self._reply = delay, target, reply
2299
+ self._budget = max_conns and threading.BoundedSemaphore(max_conns)
2300
+ self._hold_rest = hold_rest
2295
2301
  self.reached, self.cut = threading.Event(), threading.Event()
2296
2302
  self._conns: list = []
2297
2303
  self._srv = socket.socket()
@@ -2315,6 +2321,7 @@ class _StallingHop:
2315
2321
  def _serve(self, conn):
2316
2322
  import select
2317
2323
 
2324
+ counted = False
2318
2325
  try:
2319
2326
  head = b""
2320
2327
  while b"\r\n\r\n" not in head:
@@ -2323,10 +2330,18 @@ class _StallingHop:
2323
2330
  return
2324
2331
  head += chunk
2325
2332
  self.reached.set()
2333
+ if self._budget:
2334
+ counted = self._budget.acquire(blocking=False)
2335
+ if not counted:
2336
+ conn.sendall(b"HTTP/1.1 502 Bad Gateway\r\n"
2337
+ b"Content-Length: 0\r\n\r\n")
2338
+ return
2326
2339
  connect = head.startswith(b"CONNECT")
2327
2340
  if connect:
2328
2341
  conn.sendall(b"HTTP/1.1 200 Connection Established\r\n\r\n")
2329
- if self._delay is None:
2342
+ held = self._hold_rest and (
2343
+ f"{self._target[0]}:{self._target[1]}".encode() not in head)
2344
+ if self._delay is None or held:
2330
2345
  if self._reply:
2331
2346
  conn.sendall(self._reply)
2332
2347
  while conn.recv(65536):
@@ -2350,6 +2365,8 @@ class _StallingHop:
2350
2365
  except OSError:
2351
2366
  pass
2352
2367
  finally:
2368
+ if counted:
2369
+ self._budget.release()
2353
2370
  self.cut.set()
2354
2371
 
2355
2372
  def stop(self):
@@ -2745,6 +2762,160 @@ class TestAClientThatHangsUpOnASilentHop:
2745
2762
  self._assert_let_go(late, lambda: True)
2746
2763
 
2747
2764
 
2765
+ class TestTunnelsToOtherHostsCannotTakeTheWholeHop:
2766
+ """T2031. A tunnel fan-out to hosts that are not Anthropic's (one agent's
2767
+ parallel bulk transfers, measured at ~500 tunnels) used every fd the hop
2768
+ had, and Claude's own /v1/messages CONNECTs through the same hop got 502.
2769
+ The pin caps what the other hosts may hold; Anthropic's domains are never
2770
+ counted. The hop here is out of fds past 5 live connections, the cap is 3."""
2771
+
2772
+ def test_all(self, request, tmp_path_factory):
2773
+ run_cases(self, request, tmp_path_factory)
2774
+
2775
+ @staticmethod
2776
+ def _pin(certdir, monkeypatch, hop, upstream_port=9, cap=3):
2777
+ from cswap_pin import proxy as pin_proxy
2778
+ from cswap_pin.proxy import PinProxy
2779
+
2780
+ monkeypatch.setattr(pin_proxy, "_BLIND_TUNNEL_CAP", cap)
2781
+ monkeypatch.setattr(pin_proxy, "_CHAIN_HEAL_GRACE_S", 0.2)
2782
+ monkeypatch.setattr(pin_proxy, "_CHAIN_HEAL_POLL_S", 0.05)
2783
+ monkeypatch.delenv("CSWAP_PIN_ALLOW_DIRECT", raising=False)
2784
+ proxy = PinProxy(certdir=certdir, pin_token_provider=lambda: None,
2785
+ upstream=("127.0.0.1", upstream_port),
2786
+ chain_proxy=("127.0.0.1", hop.port))
2787
+ assert proxy._chain_candidates(), "premise: this host has a chain"
2788
+ proxy.start()
2789
+ return proxy, proxy._tunnel_slots
2790
+
2791
+ @staticmethod
2792
+ def _open(proxy, hosts):
2793
+ """CONNECT to every host through the pin at once. The open sockets and
2794
+ the status code each got, in order."""
2795
+ socks = []
2796
+ for host in hosts:
2797
+ s = socket.create_connection(("127.0.0.1", proxy.port), timeout=10)
2798
+ s.sendall(f"CONNECT {host}:443 HTTP/1.1\r\nHost: {host}:443\r\n\r\n"
2799
+ .encode())
2800
+ socks.append(s)
2801
+ codes = []
2802
+ for s in socks:
2803
+ head = b""
2804
+ while b"\r\n\r\n" not in head:
2805
+ chunk = s.recv(4096)
2806
+ if not chunk:
2807
+ break
2808
+ head += chunk
2809
+ codes.append(head.split(b"\r\n")[0].decode().split(" ")[1])
2810
+ return socks, codes
2811
+
2812
+ def case_a_flood_to_other_hosts_leaves_the_hop_room_for_the_api(
2813
+ self, certdir, monkeypatch):
2814
+ upstream = _FakeUpstream(certdir)
2815
+ hop = _StallingHop(delay=0.0, target=("127.0.0.1", upstream.port),
2816
+ max_conns=5, hold_rest=True)
2817
+ proxy, _ = self._pin(certdir, monkeypatch, hop, upstream.port)
2818
+ socks = []
2819
+ try:
2820
+ socks, codes = self._open(
2821
+ proxy, [f"bulk{i}.example.test" for i in range(8)])
2822
+ api = _request_through_proxy(
2823
+ proxy.port, certdir / "ca.pem", "/v1/messages", bearer="t")
2824
+ assert api == 200, (
2825
+ f"the hop's fds went to the other hosts' tunnels, so the API "
2826
+ f"request got {api}; the tunnels answered {codes}")
2827
+ assert sorted(codes) == ["200"] * 3 + ["503"] * 5, (
2828
+ f"3 tunnels fit the cap and 5 are refused with a 503: {codes}")
2829
+ finally:
2830
+ for s in socks:
2831
+ s.close()
2832
+ hop.stop()
2833
+ proxy.stop()
2834
+ upstream.stop()
2835
+
2836
+ def case_anthropic_domains_are_never_capped(self, certdir, monkeypatch):
2837
+ hop = _StallingHop(delay=0.0, target=("127.0.0.1", 9), hold_rest=True)
2838
+ proxy, _ = self._pin(certdir, monkeypatch, hop)
2839
+ socks = []
2840
+ try:
2841
+ socks, codes = self._open(
2842
+ proxy, [f"bulk{i}.example.test" for i in range(3)])
2843
+ assert codes == ["200"] * 3, f"premise: the cap is full: {codes}"
2844
+ more, codes = self._open(proxy, [
2845
+ "bridge.claudeusercontent.com", "downloads.claude.ai",
2846
+ "claude.com", "Statsig.Anthropic.COM",
2847
+ # Lookalikes: a suffix match must stop at the dot.
2848
+ "notclaude.ai", "evilanthropic.com"])
2849
+ socks += more
2850
+ assert codes == ["200"] * 4 + ["503"] * 2, codes
2851
+ finally:
2852
+ for s in socks:
2853
+ s.close()
2854
+ hop.stop()
2855
+ proxy.stop()
2856
+
2857
+ def case_slots_come_back_when_tunnels_end_or_are_refused(
2858
+ self, certdir, monkeypatch):
2859
+ # A hop that fits ONE tunnel: the other two are refused by the hop,
2860
+ # which is an exit that never reaches the pump.
2861
+ hop = _StallingHop(delay=0.0, target=("127.0.0.1", 9), max_conns=1,
2862
+ hold_rest=True)
2863
+ proxy, slots = self._pin(certdir, monkeypatch, hop)
2864
+ socks = []
2865
+ try:
2866
+ socks, codes = self._open(
2867
+ proxy, [f"bulk{i}.example.test" for i in range(3)])
2868
+ assert sorted(codes) == ["200", "503", "503"], codes
2869
+ for s in socks:
2870
+ s.close()
2871
+
2872
+ def free():
2873
+ n = 0
2874
+ while slots.acquire(blocking=False):
2875
+ n += 1
2876
+ for _ in range(n):
2877
+ slots.release()
2878
+ return n
2879
+
2880
+ deadline = time.monotonic() + 5
2881
+ while free() < 3 and time.monotonic() < deadline:
2882
+ time.sleep(0.05)
2883
+ assert free() == 3, "a slot never came back"
2884
+ finally:
2885
+ hop.stop()
2886
+ proxy.stop()
2887
+
2888
+ def case_a_slot_is_given_back_exactly_once(self, certdir, monkeypatch):
2889
+ """BoundedSemaphore raises only past its initial value, so a second
2890
+ give while another tunnel still holds a slot would silently grow the
2891
+ cap. The pump closes a pair once, but nothing here relies on that."""
2892
+ from cswap_pin import proxy as pin_proxy
2893
+
2894
+ hop = _StallingHop(delay=0.0, target=("127.0.0.1", 9))
2895
+ proxy, slots = self._pin(certdir, monkeypatch, hop, cap=2)
2896
+ closed = threading.Event()
2897
+
2898
+ def closes_twice(a, b, on_close=None, kind="bridge"):
2899
+ on_close()
2900
+ on_close()
2901
+ closed.set()
2902
+
2903
+ monkeypatch.setattr(pin_proxy, "_pump_detached", closes_twice)
2904
+ assert slots.acquire(blocking=False), "premise: another tunnel's slot"
2905
+ socks = []
2906
+ try:
2907
+ socks, codes = self._open(proxy, ["bulk.example.test"])
2908
+ assert codes == ["200"] and closed.wait(5), codes
2909
+ assert slots.acquire(blocking=False), "the slot was not given back"
2910
+ assert not slots.acquire(blocking=False), (
2911
+ "a second give grew the cap past the other tunnel's slot")
2912
+ finally:
2913
+ for s in socks:
2914
+ s.close()
2915
+ hop.stop()
2916
+ proxy.stop()
2917
+
2918
+
2748
2919
  class TestPinTimeHopTrust:
2749
2920
  """T1612: `cswap pin N` makes ONE CONNECT to the API host through the
2750
2921
  recorded hop, with the trust the daemon will use, and names the fix when
@@ -7997,11 +8168,14 @@ class TestHealthEndpoint:
7997
8168
  def case_health_carries_the_live_nofile_limits(self, certdir, monkeypatch):
7998
8169
  """`nofile_soft` / `nofile_hard` are RLIMIT_NOFILE read at REQUEST time:
7999
8170
  a rollout verifies the daemon's fd limit from outside with it (no
8000
- psutil, `launchctl procinfo` needs root). Null is unlimited or an
8001
- unreadable limit, never zero."""
8171
+ psutil, `launchctl procinfo` needs root). A number is a finite limit,
8172
+ "unlimited" is RLIM_INFINITY (the word daemon.log's `nofile before`
8173
+ line uses), and null is ONLY a limit that could not be read: an
8174
+ unlimited hard limit must not read as "could not read"."""
8002
8175
  import http.client
8003
8176
  import json as _json
8004
8177
  import resource
8178
+ import sys
8005
8179
 
8006
8180
  from cswap_pin.proxy import PinProxy
8007
8181
 
@@ -8020,15 +8194,28 @@ class TestHealthEndpoint:
8020
8194
  soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE)
8021
8195
  got = _payload(proxy)
8022
8196
  assert got["nofile_soft"] == (
8023
- None if soft == resource.RLIM_INFINITY else soft)
8197
+ "unlimited" if soft == resource.RLIM_INFINITY else soft)
8024
8198
  assert got["nofile_hard"] == (
8025
- None if hard == resource.RLIM_INFINITY else hard)
8199
+ "unlimited" if hard == resource.RLIM_INFINITY else hard)
8200
+
8201
+ def _unreadable(which):
8202
+ raise OSError("getrlimit refused")
8203
+
8026
8204
  # Read per request, not remembered from start: the control a
8027
8205
  # cached field fails.
8028
- monkeypatch.setattr(resource, "getrlimit",
8029
- lambda w: (777, resource.RLIM_INFINITY))
8206
+ for fake, want in (
8207
+ (lambda w: (777, 4096), (777, 4096)),
8208
+ (lambda w: (777, resource.RLIM_INFINITY), (777, "unlimited")),
8209
+ (_unreadable, (None, None)),
8210
+ ):
8211
+ monkeypatch.setattr(resource, "getrlimit", fake)
8212
+ got = _payload(proxy)
8213
+ assert (got["nofile_soft"], got["nofile_hard"]) == want
8214
+ # No `resource` module at all (non-POSIX): null, and /health,
8215
+ # the liveness probe, still answers.
8216
+ monkeypatch.setitem(sys.modules, "resource", None)
8030
8217
  got = _payload(proxy)
8031
- assert (got["nofile_soft"], got["nofile_hard"]) == (777, None)
8218
+ assert (got["nofile_soft"], got["nofile_hard"]) == (None, None)
8032
8219
  finally:
8033
8220
  proxy.stop()
8034
8221
 
@@ -14677,7 +14864,7 @@ class TestDrainReportsWhatItCut:
14677
14864
 
14678
14865
  proxy._local.conn = conn
14679
14866
  proxy._local.release = lambda: None
14680
- proxy._blind_tunnel(target, conn)
14867
+ proxy._capped_tunnel(target, conn)
14681
14868
  accepted.append(srv.accept()[0])
14682
14869
 
14683
14870
  assert proxy.inflight_requests() == 0, (
@@ -22112,6 +22299,7 @@ class TestTheEvidenceSurvivesAHandover:
22112
22299
  from cswap_pin import proxy as pp
22113
22300
  with pp._worker_alive_lock:
22114
22301
  pp._worker_alive.clear()
22302
+ pp._worker_alive_written.clear()
22115
22303
 
22116
22304
  @staticmethod
22117
22305
  def _relay(path, status, certdir):
@@ -22224,6 +22412,93 @@ class TestTheEvidenceSurvivesAHandover:
22224
22412
  f"nothing: {pp._alive_load(certdir)!r}")
22225
22413
  assert abs(bare - _t.time()) < 60, f"stale bare stamp: {bare}"
22226
22414
 
22415
+ def _stamp_ages(self, certdir, monkeypatch, times):
22416
+ """One 2xx worker request at each fake wall-clock instant in `times`,
22417
+ returning the age the Rule 0 census reads (`_worker_alive_age`, the
22418
+ FILE's newest stamp for this pid) right after each."""
22419
+ import os
22420
+ import time as _t
22421
+ import types
22422
+ from cswap_pin import proxy as pp
22423
+ self._cold()
22424
+ now = [0.0]
22425
+ monkeypatch.setattr(pp, "time", types.SimpleNamespace(
22426
+ time=lambda: now[0], monotonic=_t.monotonic))
22427
+ ages = []
22428
+ for now[0] in times:
22429
+ pp._note_worker_status(self.BEAT, b"HTTP/1.1 200 OK", certdir)
22430
+ ages.append(pp._worker_alive_age(certdir, os.getpid()))
22431
+ return ages
22432
+
22433
+ def case_a_bridge_requesting_every_5s_keeps_a_fresh_file_stamp(
22434
+ self, certdir, monkeypatch):
22435
+ """THE THROTTLE MEASURED LAST SEEN, NOT LAST WRITTEN. A bridge asking
22436
+ every <=10 s kept refreshing the clock the throttle compared against,
22437
+ so the file stamp aged 0, 25, 85, 145 s while the session was live and
22438
+ the census called a live bridge LOST."""
22439
+ ages = self._stamp_ages(
22440
+ certdir, monkeypatch, [1e6 + t for t in range(0, 61, 5)])
22441
+ assert max(ages) < 15, ages
22442
+
22443
+ def case_CONTROL_a_12s_cadence_writes_every_request(
22444
+ self, certdir, monkeypatch):
22445
+ ages = self._stamp_ages(
22446
+ certdir, monkeypatch, [1e6 + t for t in range(0, 61, 12)])
22447
+ assert set(ages) == {0.0}, ages
22448
+
22449
+ def case_a_wall_clock_stepped_back_does_not_silence_the_file(
22450
+ self, certdir, monkeypatch):
22451
+ """A last-written stamp from the FUTURE must not throttle: unlike the
22452
+ last-seen one it is not rewritten by every request, so one backward
22453
+ step would hold the file still until the clock caught up."""
22454
+ ages = self._stamp_ages(certdir, monkeypatch, [2000.0, 1000.0])
22455
+ assert ages == [0.0, 0.0], ages
22456
+
22457
+ def case_the_written_map_is_evicted_with_the_seen_map(self, certdir):
22458
+ from cswap_pin import proxy as pp
22459
+ self._cold()
22460
+ stale = __import__("time").time() - 3 * pp._STREAM_LIVE_SECONDS
22461
+ with pp._worker_alive_lock:
22462
+ for i in range(300):
22463
+ pp._worker_alive[f"cse_old{i}"] = stale
22464
+ pp._worker_alive_written[f"cse_old{i}"] = stale
22465
+ pp._note_worker_status(self.BEAT, b"HTTP/1.1 200 OK", certdir)
22466
+ assert set(pp._worker_alive_written) == {self.SID} == set(
22467
+ pp._worker_alive), (len(pp._worker_alive_written),
22468
+ len(pp._worker_alive))
22469
+
22470
+ def case_concurrent_stampers_never_tear_the_file_or_lose_a_stamp(
22471
+ self, certdir):
22472
+ """EVERY RELAY THREAD WRITES THIS FILE. One shared temp name let two
22473
+ writers truncate each other's bytes before `os.replace` (a torn file, or
22474
+ an ENOENT swallowed as "no write"), and the unlocked read-merge-write
22475
+ dropped whichever stamp merged into the staler read. Either one reads
22476
+ back as "no evidence", the answer that lets a real stream 404 through.
22477
+ Fresh sids every round, so a stamp lost in round r is never re-written
22478
+ and stays missing at the end; a barrier makes each round a collision."""
22479
+ import json
22480
+ import threading
22481
+ from cswap_pin import proxy as pp
22482
+ self._cold()
22483
+ threads, rounds = 8, 60
22484
+ gate = threading.Barrier(threads)
22485
+ sids = [f"cse_race{t:02d}r{r:03d}" for t in range(threads)
22486
+ for r in range(rounds)]
22487
+
22488
+ def stamp(t):
22489
+ for r in range(rounds):
22490
+ gate.wait()
22491
+ pp._note_worker_status(
22492
+ f"/v1/code/sessions/cse_race{t:02d}r{r:03d}/worker/heartbeat",
22493
+ b"HTTP/1.1 200 OK", certdir)
22494
+
22495
+ ts = [threading.Thread(target=stamp, args=(t,)) for t in range(threads)]
22496
+ for t in ts: t.start()
22497
+ for t in ts: t.join()
22498
+ got = json.loads(pp._alive_path(certdir).read_text())
22499
+ missing = [s for s in sids if s not in got]
22500
+ assert not missing, f"{len(missing)}/{len(sids)} stamps lost: {missing[:3]}"
22501
+
22227
22502
  def case_a_fresh_bare_key_from_an_older_writer_still_spares_the_404(
22228
22503
  self, certdir):
22229
22504
  """The `k == sid` branch in `_stream_404_is_spurious`, untested until
@@ -180,7 +180,7 @@ wheels = [
180
180
 
181
181
  [[package]]
182
182
  name = "cswap-pin"
183
- version = "0.1.330"
183
+ version = "0.1.332"
184
184
  source = { editable = "." }
185
185
  dependencies = [
186
186
  { name = "cryptography" },
File without changes