GeezerVison is showing github.com — fix(challenge): re-check for an accepted receipt before writing a sec… · CortexLM/hypertrain@dc5f25f
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: src/hypertrain/challenge/store.py +28-13Lines changed: 28 additions & 13 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -9929,6 +9929,25 @@ def upload_grant_v2( | 9929 | 9929 | self._put_record_v2(run_id, "chunk-manifest", grant.digest(), chunk.body()) | 9930 | 9930 | return signed | 9931 | 9931 |
| | 9932 | + def _accepted_receipt_v2( | | 9933 | + self, run_id: str, w: int, hotkey: str, receipt_hash: str | | 9934 | + ) -> dict[str, Any] | None: | | 9935 | + """Stored acceptance of receipt_hash for (w, hotkey); 409 if another was accepted.""" | | 9936 | + accepted: list[dict[str, Any]] = [ | | 9937 | + json.loads(stored) | | 9938 | + for (stored,) in self._db.execute( | | 9939 | + "SELECT data FROM records_v2 WHERE run_id=? AND kind='master-acceptance' " | | 9940 | + "AND json_extract(data,'$.body.w')=? AND json_extract(data,'$.body.hotkey')=?", | | 9941 | + (run_id, w, hotkey), | | 9942 | + ) | | 9943 | + ] | | 9944 | + for stored in accepted: | | 9945 | + if stored["body"]["receipt_hash"] == receipt_hash: | | 9946 | + return stored | | 9947 | + if accepted: | | 9948 | + raise ChallengeError(409, "RELAY_RECEIPT_CONFLICT") | | 9949 | + return None | | 9950 | + | 9932 | 9951 | async def relay_receipt_v2(self, raw: bytes, client: Any) -> dict[str, Any]: | 9933 | 9952 | import base64 | 9934 | 9953 |
| @@ -9961,19 +9980,10 @@ async def relay_receipt_v2(self, raw: bytes, client: Any) -> dict[str, Any]: | 9961 | 9980 | ) | 9962 | 9981 | # A rerun must not challenge the relay again: it refuses a second live | 9963 | 9982 | # retrieval of the same object, and the first acceptance is authoritative. | 9964 | | - accepted: list[dict[str, Any]] = [ | 9965 | | - json.loads(stored) | 9966 | | - for (stored,) in self._db.execute( | 9967 | | - "SELECT data FROM records_v2 WHERE run_id=? AND kind='master-acceptance' " | 9968 | | - "AND json_extract(data,'$.body.w')=? AND json_extract(data,'$.body.hotkey')=?", | 9969 | | - (run_id, grant.w, grant.hotkey), | 9970 | | - ) | 9971 | | - ] | 9972 | | - for stored in accepted: | 9973 | | - if stored["body"]["receipt_hash"] == receipt.digest(): | 9974 | | - return stored | 9975 | | - if accepted: | 9976 | | - raise ChallengeError(409, "RELAY_RECEIPT_CONFLICT") | | 9983 | + if ( | | 9984 | + stored := self._accepted_receipt_v2(run_id, grant.w, grant.hotkey, receipt.digest()) | | 9985 | + ) is not None: | | 9986 | + return stored | 9977 | 9987 | assignment = self._record_v2(run_id, "relay-assignment", f"{grant.w}:{grant.hotkey}")[ | 9978 | 9988 | "body" | 9979 | 9989 | ] | @@ -10023,6 +10033,11 @@ async def relay_receipt_v2(self, raw: bytes, client: Any) -> dict[str, Any]: | 10023 | 10033 | 502, f"relay refused master retrieval: HTTP {exc.response.status_code}" | 10024 | 10034 | ) from exc | 10025 | 10035 | with self._tx(): | | 10036 | + # A concurrent submission may have been accepted while this one awaited the relay. | | 10037 | + if ( | | 10038 | + stored := self._accepted_receipt_v2(run_id, grant.w, grant.hotkey, receipt.digest()) | | 10039 | + ) is not None: | | 10040 | + return stored | 10026 | 10041 | current = self._fresh_v2( | 10027 | 10042 | manifest, f"relay-accept:{receipt.digest()}:{self._now(self._db)}" | 10028 | 10043 | ) | |
Collapse file Copy file name to clipboardExpand all lines: tests/challenge/test_relay_receipt_idempotent.py +89Lines changed: 89 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 10 | 10 | import httpx | 11 | 11 | import pytest | 12 | 12 |
| | 13 | +from hypertrain.challenge.store import ChallengeError | 13 | 14 | from hypertrain.data.store import LocalFSStore | 14 | 15 | from hypertrain.data.stream_store import StreamStore | 15 | 16 | from hypertrain.protocol import envelope_v2, relay_envelope | 16 | 17 | from hypertrain.protocol.hashing import sha256_hex | 17 | 18 | from hypertrain.protocol.jcs import canonicalize | 18 | 19 | from hypertrain.protocol.relay_messages import ( | | 20 | + MasterAcceptanceV2, | 19 | 21 | RelayAssignment, | 20 | 22 | RelayNetworkManifest, | 21 | 23 | RelayReceipt, | @@ -241,3 +243,90 @@ def test_relay_400_on_retrieval_is_a_clean_error_not_500(network, uploaded): | 241 | 243 | assert refused.status_code == 502, refused.text | 242 | 244 | assert "400" in refused.json()["detail"] | 243 | 245 | assert count(network, "master-acceptance") == 0 | | 246 | + | | 247 | + | | 248 | +def race(network, monkeypatch, receipt, finish_a): | | 249 | + """B passes the first transaction and the relay; A is accepted before B writes.""" | | 250 | + from hypertrain.relay.client import RelayClient | | 251 | + | | 252 | + real = RelayClient.retrieval | | 253 | + pending = [finish_a] | | 254 | + | | 255 | + async def retrieval(self, *args, **kwargs): | | 256 | + response = await real(self, *args, **kwargs) | | 257 | + if pending: | | 258 | + await pending.pop()() | | 259 | + return response | | 260 | + | | 261 | + monkeypatch.setattr(RelayClient, "retrieval", retrieval) | | 262 | + store = network.store.for_run(network.manifest.run_id()) | | 263 | + | | 264 | + async def b(): | | 265 | + async with httpx.AsyncClient() as client: | | 266 | + try: | | 267 | + return await store.relay_receipt_v2( | | 268 | + canonicalize(receipt.model_dump(mode="json")), client | | 269 | + ) | | 270 | + except ChallengeError as exc: | | 271 | + return exc | | 272 | + | | 273 | + outcome = anyio.run(b) | | 274 | + assert not pending | | 275 | + return outcome | | 276 | + | | 277 | + | | 278 | +def test_second_transaction_does_not_write_a_second_acceptance_same_receipt( | | 279 | + network, uploaded, monkeypatch | | 280 | +): | | 281 | + _, _, receipt = uploaded | | 282 | + store = network.store.for_run(network.manifest.run_id()) | | 283 | + start = store._now(store._db) | | 284 | + accepted = [] | | 285 | + | | 286 | + async def finish_a(): | | 287 | + # A arrives after B's relay challenge expired and is accepted one beacon before B writes. | | 288 | + network.push(start + 11) | | 289 | + async with httpx.AsyncClient() as client: | | 290 | + accepted.append( | | 291 | + await store.relay_receipt_v2(canonicalize(receipt.model_dump(mode="json")), client) | | 292 | + ) | | 293 | + network.push(start + 12) | | 294 | + | | 295 | + outcome = race(network, monkeypatch, receipt, finish_a) | | 296 | + assert count(network, "master-acceptance") == 1 | | 297 | + assert outcome == accepted[0] | | 298 | + | | 299 | + | | 300 | +def test_second_transaction_conflicts_with_acceptance_of_another_receipt( | | 301 | + network, uploaded, monkeypatch | | 302 | +): | | 303 | + _, grant, receipt = uploaded | | 304 | + run_id = network.manifest.run_id() | | 305 | + store = network.store.for_run(run_id) | | 306 | + other = RelayReceipt.model_validate(receipt.body).model_copy( | | 307 | + update={"received_drand": RelayReceipt.model_validate(receipt.body).received_drand + 1} | | 308 | + ) | | 309 | + | | 310 | + async def finish_a(): | | 311 | + # The real relay only serves its own receipt, so A's acceptance is written as A would. | | 312 | + acceptance = MasterAcceptanceV2( | | 313 | + w=grant.w, | | 314 | + hotkey=grant.hotkey, | | 315 | + delta_hash=grant.delta_hash, | | 316 | + receipt_hash=other.digest(), | | 317 | + received_drand=store._now(store._db), | | 318 | + ) | | 319 | + with store._tx(): | | 320 | + store._put_record_v2( | | 321 | + run_id, | | 322 | + "master-acceptance", | | 323 | + acceptance.digest(), | | 324 | + relay_envelope.seal( | | 325 | + COORD, "MasterAcceptanceV2", run_id, acceptance, grant.retain_until | | 326 | + ), | | 327 | + ) | | 328 | + | | 329 | + outcome = race(network, monkeypatch, receipt, finish_a) | | 330 | + assert count(network, "master-acceptance") == 1 | | 331 | + assert isinstance(outcome, ChallengeError) | | 332 | + assert (outcome.status, outcome.detail) == (409, "RELAY_RECEIPT_CONFLICT") |
|