cswap-pin 0.1.331__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.331 → cswap_pin-0.1.332}/PKG-INFO +1 -1
  2. {cswap_pin-0.1.331 → cswap_pin-0.1.332}/pyproject.toml +1 -1
  3. {cswap_pin-0.1.331 → cswap_pin-0.1.332}/src/cswap_pin/proxy.py +57 -37
  4. {cswap_pin-0.1.331 → cswap_pin-0.1.332}/tests/test_proxy.py +50 -22
  5. {cswap_pin-0.1.331 → cswap_pin-0.1.332}/tests/test_proxy_server.py +111 -7
  6. {cswap_pin-0.1.331 → cswap_pin-0.1.332}/uv.lock +1 -1
  7. {cswap_pin-0.1.331 → cswap_pin-0.1.332}/.githooks/pre-push +0 -0
  8. {cswap_pin-0.1.331 → cswap_pin-0.1.332}/.github/workflows/ci.yml +0 -0
  9. {cswap_pin-0.1.331 → cswap_pin-0.1.332}/.github/workflows/publish.yml +0 -0
  10. {cswap_pin-0.1.331 → cswap_pin-0.1.332}/.github/workflows/tag-on-version-bump.yml +0 -0
  11. {cswap_pin-0.1.331 → cswap_pin-0.1.332}/.gitignore +0 -0
  12. {cswap_pin-0.1.331 → cswap_pin-0.1.332}/README.md +0 -0
  13. {cswap_pin-0.1.331 → cswap_pin-0.1.332}/src/cswap_pin/__init__.py +0 -0
  14. {cswap_pin-0.1.331 → cswap_pin-0.1.332}/src/cswap_pin/_host.py +0 -0
  15. {cswap_pin-0.1.331 → cswap_pin-0.1.332}/tests/conftest.py +0 -0
  16. {cswap_pin-0.1.331 → cswap_pin-0.1.332}/tests/leakwatch.py +0 -0
  17. {cswap_pin-0.1.331 → cswap_pin-0.1.332}/tests/models/at_limit_conversion.pict +0 -0
  18. {cswap_pin-0.1.331 → cswap_pin-0.1.332}/tests/models/at_limit_conversion.tsv +0 -0
  19. {cswap_pin-0.1.331 → cswap_pin-0.1.332}/tests/test_meta.py +0 -0
  20. {cswap_pin-0.1.331 → cswap_pin-0.1.332}/tests/test_packaging.py +0 -0
  21. {cswap_pin-0.1.331 → cswap_pin-0.1.332}/tests/test_pin_run.py +0 -0
  22. {cswap_pin-0.1.331 → cswap_pin-0.1.332}/tests/test_publish_guard.py +0 -0
  23. {cswap_pin-0.1.331 → cswap_pin-0.1.332}/tests/test_session_name_adopt.py +0 -0
  24. {cswap_pin-0.1.331 → cswap_pin-0.1.332}/tools/thread_probe.py +0 -0
  25. {cswap_pin-0.1.331 → 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.331
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
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "cswap-pin"
3
- version = "0.1.331"
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
@@ -19888,15 +19892,17 @@ class PinProxy:
19888
19892
  code_watch_beat = getattr(self, "_code_watch_beat", None)
19889
19893
  # READ NOW, never remembered from start: this is how a rollout verifies
19890
19894
  # the fd limit `_raise_nofile_soft_limit` set (it cannot be read from
19891
- # outside the process on a Mac). `null` for unlimited or an unreadable
19892
- # 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.
19893
19899
  try:
19894
19900
  import resource # POSIX only
19895
19901
 
19896
19902
  nofile_soft, nofile_hard = (
19897
- None if n == resource.RLIM_INFINITY else n
19903
+ "unlimited" if n == resource.RLIM_INFINITY else n
19898
19904
  for n in resource.getrlimit(resource.RLIMIT_NOFILE))
19899
- except (OSError, ValueError):
19905
+ except (ImportError, OSError, ValueError):
19900
19906
  nofile_soft = nofile_hard = None
19901
19907
  body = json.dumps(
19902
19908
  {"pin_proxy": True, "port": self.port, "chain": chain,
@@ -22297,7 +22303,13 @@ def _hop_recently_failed() -> bool:
22297
22303
  _STREAM_ROUTE = re.compile(r"/v1/code/sessions/([^/?]+)/worker/events/stream")
22298
22304
  _WORKER_ROUTE = re.compile(r"/v1/code/sessions/([^/?]+)/worker")
22299
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] = {}
22300
22311
  _worker_alive_lock = threading.Lock()
22312
+ _alive_file_lock = threading.Lock()
22301
22313
  #: WHERE THE EVIDENCE LIVES, AND IT CANNOT BE THIS PROCESS'S MEMORY. A
22302
22314
  #: long-held stream stays with the DEPARTING daemon for the whole drain while
22303
22315
  #: its session's heartbeats move to the successor, so the process holding the
@@ -22359,7 +22371,6 @@ def _note_worker_status(path: str | None, status_line: bytes,
22359
22371
  return
22360
22372
  sid, now = m.group(1), time.time()
22361
22373
  with _worker_alive_lock:
22362
- last = _worker_alive.get(sid, 0.0)
22363
22374
  _worker_alive[sid] = now
22364
22375
  if len(_worker_alive) > 256:
22365
22376
  # One entry per session this daemon has ever relayed for, so it
@@ -22368,37 +22379,46 @@ def _note_worker_status(path: str | None, status_line: bytes,
22368
22379
  for k, seen in list(_worker_alive.items()):
22369
22380
  if now - seen > _STREAM_LIVE_SECONDS:
22370
22381
  del _worker_alive[k]
22371
- 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:
22372
22386
  return
22387
+ _worker_alive_written[sid] = now
22373
22388
  p = _alive_path(certdir)
22374
22389
  if p is None:
22375
22390
  return
22376
- shared = _alive_load(certdir)
22377
- # THE WRITER'S OWN PID IS PART OF THE KEY, not the value -- a value has
22378
- # to stay a bare number or the filter two lines down (every OTHER
22379
- # writer's read-modify-write, not just this one) drops the entry on its
22380
- # very next pass. See `_worker_alive_age`, the reader this exists for.
22381
- #
22382
- # BOTH SHAPES, DURING THE ROLLOUT HANDOVER. A DEPLOYED release still
22383
- # reads the bare `shared.get(sid)` -- a draining OLD daemon running that
22384
- # code cannot see a successor's `sid@pid`-only stamp, and after
22385
- # `_STREAM_LIVE_SECONDS` a spurious stream 404 passes through and ends
22386
- # the session. `_stream_404_is_spurious` here already accepts either
22387
- # shape; the bare key is for the reader this process has not upgraded
22388
- # past yet.
22389
- shared[sid] = now
22390
- shared[f"{sid}@{os.getpid()}"] = now
22391
- # MERGED, NOT OVERWRITTEN: the departing daemon and its successor both
22392
- # write here. A lost update costs one entry and fails toward "no
22393
- # evidence", which is the direction that lets the 404 through.
22394
- shared = {k: v for k, v in shared.items()
22395
- if isinstance(v, (int, float)) and now - v <= _STREAM_LIVE_SECONDS}
22396
- try:
22397
- tmp = p.with_name(p.name + f".{os.getpid()}.tmp")
22398
- tmp.write_text(json.dumps(shared))
22399
- os.replace(tmp, p) # atomic, so a reader never sees a torn file
22400
- except OSError:
22401
- 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
22402
22422
 
22403
22423
 
22404
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()
@@ -8168,11 +8168,14 @@ class TestHealthEndpoint:
8168
8168
  def case_health_carries_the_live_nofile_limits(self, certdir, monkeypatch):
8169
8169
  """`nofile_soft` / `nofile_hard` are RLIMIT_NOFILE read at REQUEST time:
8170
8170
  a rollout verifies the daemon's fd limit from outside with it (no
8171
- psutil, `launchctl procinfo` needs root). Null is unlimited or an
8172
- 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"."""
8173
8175
  import http.client
8174
8176
  import json as _json
8175
8177
  import resource
8178
+ import sys
8176
8179
 
8177
8180
  from cswap_pin.proxy import PinProxy
8178
8181
 
@@ -8191,15 +8194,28 @@ class TestHealthEndpoint:
8191
8194
  soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE)
8192
8195
  got = _payload(proxy)
8193
8196
  assert got["nofile_soft"] == (
8194
- None if soft == resource.RLIM_INFINITY else soft)
8197
+ "unlimited" if soft == resource.RLIM_INFINITY else soft)
8195
8198
  assert got["nofile_hard"] == (
8196
- 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
+
8197
8204
  # Read per request, not remembered from start: the control a
8198
8205
  # cached field fails.
8199
- monkeypatch.setattr(resource, "getrlimit",
8200
- 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)
8201
8217
  got = _payload(proxy)
8202
- assert (got["nofile_soft"], got["nofile_hard"]) == (777, None)
8218
+ assert (got["nofile_soft"], got["nofile_hard"]) == (None, None)
8203
8219
  finally:
8204
8220
  proxy.stop()
8205
8221
 
@@ -22283,6 +22299,7 @@ class TestTheEvidenceSurvivesAHandover:
22283
22299
  from cswap_pin import proxy as pp
22284
22300
  with pp._worker_alive_lock:
22285
22301
  pp._worker_alive.clear()
22302
+ pp._worker_alive_written.clear()
22286
22303
 
22287
22304
  @staticmethod
22288
22305
  def _relay(path, status, certdir):
@@ -22395,6 +22412,93 @@ class TestTheEvidenceSurvivesAHandover:
22395
22412
  f"nothing: {pp._alive_load(certdir)!r}")
22396
22413
  assert abs(bare - _t.time()) < 60, f"stale bare stamp: {bare}"
22397
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
+
22398
22502
  def case_a_fresh_bare_key_from_an_older_writer_still_spares_the_404(
22399
22503
  self, certdir):
22400
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.331"
183
+ version = "0.1.332"
184
184
  source = { editable = "." }
185
185
  dependencies = [
186
186
  { name = "cryptography" },
File without changes
File without changes