GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix(challenge): re-check for an accepted receipt before writing a sec… · CortexLM/hypertrain@dc5f25f

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • src/hypertrain/challenge
    • store.py
  • tests/challenge
    • test_relay_receipt_idempotent.py
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎src/hypertrain/challenge/store.py‎

Copy file name to clipboardExpand all lines: src/hypertrain/challenge/store.py
+28-13Lines changed: 28 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -9929,6 +9929,25 @@ def upload_grant_v2(
99299929
self._put_record_v2(run_id, "chunk-manifest", grant.digest(), chunk.body())
99309930
return signed
99319931

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+
99329951
async def relay_receipt_v2(self, raw: bytes, client: Any) -> dict[str, Any]:
99339952
import base64
99349953

@@ -9961,19 +9980,10 @@ async def relay_receipt_v2(self, raw: bytes, client: Any) -> dict[str, Any]:
99619980
)
99629981
# A rerun must not challenge the relay again: it refuses a second live
99639982
# 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
99779987
assignment = self._record_v2(run_id, "relay-assignment", f"{grant.w}:{grant.hotkey}")[
99789988
"body"
99799989
]
@@ -10023,6 +10033,11 @@ async def relay_receipt_v2(self, raw: bytes, client: Any) -> dict[str, Any]:
1002310033
502, f"relay refused master retrieval: HTTP {exc.response.status_code}"
1002410034
) from exc
1002510035
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
1002610041
current = self._fresh_v2(
1002710042
manifest, f"relay-accept:{receipt.digest()}:{self._now(self._db)}"
1002810043
)
Collapse file

‎tests/challenge/test_relay_receipt_idempotent.py‎

Copy file name to clipboardExpand all lines: tests/challenge/test_relay_receipt_idempotent.py
+89Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,14 @@
1010
import httpx
1111
import pytest
1212

13+
from hypertrain.challenge.store import ChallengeError
1314
from hypertrain.data.store import LocalFSStore
1415
from hypertrain.data.stream_store import StreamStore
1516
from hypertrain.protocol import envelope_v2, relay_envelope
1617
from hypertrain.protocol.hashing import sha256_hex
1718
from hypertrain.protocol.jcs import canonicalize
1819
from hypertrain.protocol.relay_messages import (
20+
MasterAcceptanceV2,
1921
RelayAssignment,
2022
RelayNetworkManifest,
2123
RelayReceipt,
@@ -241,3 +243,90 @@ def test_relay_400_on_retrieval_is_a_clean_error_not_500(network, uploaded):
241243
assert refused.status_code == 502, refused.text
242244
assert "400" in refused.json()["detail"]
243245
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")

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.