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 — feat(challenge): route production bootstrap and economic-bound writer · CortexLM/hypertrain@3d15495

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • docs
    • network-v2.md
    • operator.md
  • src/hypertrain/challenge
    • app.py
    • store.py
    • trust_v2.py
  • tests/challenge
    • test_production_economics_v2.py
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎docs/network-v2.md‎

Copy file name to clipboardExpand all lines: docs/network-v2.md
+34Lines changed: 34 additions & 0 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,40 @@ No automatic migration is provided; separate operator resolution is required.
166166
Funding uses signed `EscrowLock` via `POST /v2/runs/{run_id}/escrow/lock`, not a
167167
CLI `--bond` flag. Test genesis has pinned nonfinancial origins; production mode
168168
has separate reward authority/issuance bounds and no test-genesis conversion.
169+
170+
Production funding is one coordinator-signed `ProductionBootstrap`, posted as an
171+
`ht/2` envelope to `POST /v2/runs/{run_id}/admin/bootstrap` (admin bearer). The
172+
run's `EconomicsPolicyV2.bootstrap_allocation_hash` pins its owner/units/maturity
173+
list (`genesis_allocation_hash` over `[owner, units, mature_at]`); only
174+
`ledger_mode="production"` may set it, and an unset field is omitted, so earlier
175+
policy digests and run IDs are unchanged. Origins are
176+
`ht-origin-bootstrap-v1|run|allocation_hash|index`. The ledger accepts it once per
177+
run: the same `operation_id` and body replay the stored receipt, the same
178+
`operation_id` with other content answers `OPERATION_CONFLICT`, and any second
179+
bootstrap answers `PRODUCTION_BOOTSTRAP_FORBIDDEN`. It is refused when the inner
180+
authority signature is not `reward_authority` (pinned to `coord_pubkey`), when
181+
the envelope signer is not the coordinator, when the allocation differs from the
182+
pin, when bootstrap plus issued and reserved shadow units would exceed
183+
`max_total_issuance` (`TOTAL_ISSUANCE_BUDGET`; later rewards share the same cap),
184+
when the run has no CUDA qualification (production refuses the CPU backend) and
185+
when the latest beacon round is not BLS-verified (`UNVERIFIED_BEACON`).
186+
Bootstrap units mature on the beacon loop and can be locked or transferred;
187+
like genesis units they are collateral and never pay through `get_weights`.
188+
189+
Production eligibility also needs the run's `economic-bound` record. `POST
190+
/v2/runs/{run_id}/admin/economic-bound` (admin bearer, no body) writes it once,
191+
coordinator-signed, only when the pinned policy satisfies
192+
`q_floor*s_lower*beta*(R_collectible+S_min) >= G_max` in exact ppm integers
193+
(`challenge/trust_v2.py:economic_bound`); otherwise it answers 409 and writes
194+
nothing. The record binds the economics policy hash; later calls return it
195+
unchanged, and a stored record for another policy answers 409.
196+
197+
A test-ledger run published on the production challenge steers real emission:
198+
as soon as its first live round finalizes and its reward matures, those units
199+
enter `get_weights` like any production reward
200+
(`tests/challenge/test_v2_weights_bridge.py::test_v2_matured_reward_reaches_get_weights`).
201+
`ledger_mode="test"` does not keep a run out of on-chain weights; do not host a
202+
test-ledger run on the production challenge unless that emission is intended.
169203
Rewards are issued only through accepted finality, uniquely tracked by origin,
170204
then mature after vesting/dispute conditions. Transfers preserve origin units;
171205
fraud burns collectible exposure rather than redistributing it. Shadow work does
Collapse file

‎docs/operator.md‎

Copy file name to clipboardExpand all lines: docs/operator.md
+1-1Lines changed: 1 addition & 1 deletion
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -202,7 +202,7 @@ uv run --frozen python -m hypertrain.ops.manifest_v2 build \
202202
--exp-round 1000000 --state-dir /tmp/state --out /tmp/out
203203
```
204204

205-
The example's `coord_pubkey`, two auditors, referees, `reward_authority` and relay public key are **placeholder SS58 public identities, not operational keys**. Replace them before a real run; `coord_pubkey` must match the service's K_coord. The example uses a tiny decoder, `ledger_mode="test"`, a pinned genesis allocation hash and one `.test` relay. It creates no dataset, genesis funding or training round. Custom CPU/GPU runs use the same three JSON shapes; provide valid model dimensions and parameter count, an audit budget of `2H`, and the H/step-bound-derived audit lease. Build computes `init_state_hash`; an existing value must match. It also rejects economics whose `reward_authority` differs from `training.coord_pubkey` (`PINNED_AUTHORITIES`) or whose `round_reward_units` differs from `training.budget.epochs_per_round * 1_000_000` (`MANIFEST_REWARD_BUDGET`). The service's configured auditor set must match `training.auditors`; the offline CLI cannot validate that configuration. Building needs the existing `trainer` extra (`uv sync --frozen --extra trainer`); help and example do not.
205+
The example's `coord_pubkey`, two auditors, referees, `reward_authority` and relay public key are **placeholder SS58 public identities, not operational keys**. Replace them before a real run; `coord_pubkey` must match the service's K_coord. The example uses a tiny decoder, `ledger_mode="test"`, a pinned genesis allocation hash and one `.test` relay. It creates no dataset, genesis funding or training round. `example --ledger-mode production` instead writes a production economics policy pinning a placeholder bootstrap allocation (`bootstrap_allocation_hash`, no genesis); funding then uses `POST /v2/runs/{run_id}/admin/bootstrap` and `POST /v2/runs/{run_id}/admin/economic-bound` (see [network-v2.md](network-v2.md)). A test-ledger run hosted on the production challenge steers real emission once its first live reward matures; keep test-mode runs off the production challenge unless that is intended. Custom CPU/GPU runs use the same three JSON shapes; provide valid model dimensions and parameter count, an audit budget of `2H`, and the H/step-bound-derived audit lease. Build computes `init_state_hash`; an existing value must match. It also rejects economics whose `reward_authority` differs from `training.coord_pubkey` (`PINNED_AUTHORITIES`) or whose `round_reward_units` differs from `training.budget.epochs_per_round * 1_000_000` (`MANIFEST_REWARD_BUDGET`). The service's configured auditor set must match `training.auditors`; the offline CLI cannot validate that configuration. Building needs the existing `trainer` extra (`uv sync --frozen --extra trainer`); help and example do not.
206206

207207
The owner seed is an existing private, current-user-owned 0600 file containing 32 raw bytes or 64 hex characters; it is read through the miner's checked loader, never printed or copied. The shared loader strips leading/trailing ASCII whitespace bytes: provide hex for any raw seed whose first or last byte is ASCII whitespace. Choose an expiry drand round later than submission. Both commands require a new or empty output directory. Build writes `manifest.json`, `manifest-envelope.json`, five `policy-<name>.json` files, `relay-registry.json` and `index.json`. The index records `run_id`, `owner_ss58`, six canonical object hashes and hashes of the eight other files; it excludes its own hash.
208208

Collapse file

‎src/hypertrain/challenge/app.py‎

Copy file name to clipboardExpand all lines: src/hypertrain/challenge/app.py
+11Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -570,6 +570,17 @@ async def genesis_v2(run_id: str, request: Request, authorization: Auth = None)
570570
admin(authorization)
571571
return await run(store.for_run(run_id).genesis_v2, run_id, await v2_raw(request))
572572

573+
@app.post("/v2/runs/{run_id}/admin/bootstrap")
574+
async def bootstrap_v2(run_id: str, request: Request, authorization: Auth = None) -> Any:
575+
admin(authorization)
576+
hosted = store.for_run(run_id)
577+
return await run(hosted.production_bootstrap_v2, run_id, await v2_raw(request))
578+
579+
@app.post("/v2/runs/{run_id}/admin/economic-bound")
580+
async def economic_bound_v2(run_id: str, authorization: Auth = None) -> Any:
581+
admin(authorization)
582+
return await run(store.for_run(run_id).economic_bound_v2, run_id)
583+
573584
@app.post("/v2/runs/{run_id}/admin/rounds")
574585
async def open_v2(run_id: str, request: Request, authorization: Auth = None) -> Any:
575586
admin(authorization)
Collapse file

‎src/hypertrain/challenge/store.py‎

Copy file name to clipboardExpand all lines: src/hypertrain/challenge/store.py
+48Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4145,6 +4145,54 @@ def genesis_v2(self, run_id: str, raw: bytes) -> dict[str, JsonValue]:
41454145
)
41464146
return receipt.body()
41474147

4148+
def production_bootstrap_v2(self, run_id: str, raw: bytes) -> dict[str, JsonValue]:
4149+
"""Pinned production issuance; units mature on the beacon loop, never pay out."""
4150+
from hypertrain.protocol.messages_v2 import ProductionBootstrap
4151+
4152+
escrow, admission, _ = self._services(run_id) # production refuses CPU here
4153+
with self._tx():
4154+
admission._beacon(self._now(self._db)) # production requires a BLS-verified round
4155+
model = self._authenticated_v2(run_id, raw, "ProductionBootstrap", self._coord().ss58)
4156+
assert isinstance(model, ProductionBootstrap)
4157+
return escrow.production_bootstrap(model).body()
4158+
4159+
def economic_bound_v2(self, run_id: str) -> dict[str, JsonValue]:
4160+
"""Write the immutable coordinator-signed record only when trust_v2 holds the bound."""
4161+
from hypertrain.challenge.trust_v2 import economic_bound
4162+
from hypertrain.protocol.messages import Receipt
4163+
4164+
escrow, _, _ = self._services(run_id)
4165+
with self._tx():
4166+
row = self._db.execute(
4167+
"SELECT data FROM records_v2 WHERE run_id=? AND kind='economic-bound' AND id='run'",
4168+
(run_id,),
4169+
).fetchone()
4170+
if row is not None:
4171+
stored: dict[str, JsonValue] = json.loads(row[0])
4172+
if stored["economics_policy_hash"] != escrow.manifest.network.economics_policy_hash:
4173+
raise ChallengeError(409, "immutable economic-bound record conflicts")
4174+
return stored
4175+
policy = escrow.policy
4176+
if policy.ledger_mode != "production":
4177+
raise ChallengeError(409, "economic-bound record is production only")
4178+
if not economic_bound(policy):
4179+
raise ChallengeError(409, "economic bound q*s*beta*(R+S)>=G fails")
4180+
evidence: dict[str, JsonValue] = {
4181+
"run_id": run_id,
4182+
"economics_policy_hash": escrow.manifest.network.economics_policy_hash,
4183+
"bound": "q*s*beta*(R+S)>=G",
4184+
}
4185+
now = self._now(self._db)
4186+
receipt = Receipt(
4187+
w=0, commit_hash=sha256_hex(canonicalize(evidence)), received_round=max(now, 1)
4188+
)
4189+
record = {
4190+
**evidence,
4191+
"receipt": envelope_v2.seal(self._coord(), "Receipt", run_id, receipt, NEVER),
4192+
}
4193+
self._put_record_v2(run_id, "economic-bound", "run", record)
4194+
return record
4195+
41484196
def _service_profile_v2(self, run_id: str) -> _ServiceCapacityV1:
41494197
"""Derive the sole admitted tiny shape; never allocate tensors."""
41504198
manifest = self._run_v2(run_id)
Collapse file

‎src/hypertrain/challenge/trust_v2.py‎

Copy file name to clipboardExpand all lines: src/hypertrain/challenge/trust_v2.py
+11Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,17 @@ def audit_floor(
145145
return AuditFloor(min(q, 1_000_000), required, allowed)
146146

147147

148+
def economic_bound(policy: EconomicsPolicyV2) -> bool:
149+
"""Run-level q*s*beta*(R+S)>=G at the pinned audit floor; exact ppm integers."""
150+
return (
151+
policy.q_floor
152+
* policy.s_lower_ppm
153+
* policy.beta_ppm
154+
* (policy.R_collectible_units + policy.S_min_units)
155+
>= policy.G_max_units * 10**18
156+
)
157+
158+
148159
@dataclass(frozen=True, slots=True)
149160
class AuditSelection:
150161
selected: bool
Collapse file

‎tests/challenge/test_production_economics_v2.py‎

Copy file name to clipboard
+183Lines changed: 183 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,183 @@
1+
"""Hosted production bootstrap route and economic-bound record writer."""
2+
3+
from __future__ import annotations
4+
5+
import importlib.util
6+
import json
7+
import sys
8+
from pathlib import Path
9+
10+
import pytest
11+
12+
from hypertrain.challenge.admission_store import AdmissionError
13+
from hypertrain.challenge.store import ChallengeError, ChallengeStore
14+
from hypertrain.data.store import LocalFSStore
15+
from hypertrain.ledger import Params
16+
from hypertrain.protocol.envelope_v2 import UnauthorizedSigner, seal, verify_envelope
17+
from hypertrain.protocol.jcs import canonicalize
18+
from hypertrain.protocol.messages_v2 import DisputePolicyV2, RunManifestV2
19+
20+
_spec = importlib.util.spec_from_file_location(
21+
"production_economics_fixture",
22+
Path(__file__).parents[1] / "ledger/test_production_bootstrap_v2.py",
23+
)
24+
assert _spec is not None and _spec.loader is not None
25+
B = importlib.util.module_from_spec(_spec)
26+
sys.modules[_spec.name] = B
27+
_spec.loader.exec_module(B)
28+
E = B.E
29+
30+
31+
def hosted(tmp_path: Path, monkeypatch, *, cuda: bool, **economics):
32+
"""Production run in a real store; `cuda` stands in for an installed CUDA qualification."""
33+
s = B.pinned(E.setup("production"), **economics)
34+
dispute = DisputePolicyV2(
35+
referees=[E.OTHER.ss58],
36+
max_open=32,
37+
max_transcript_entries=256,
38+
max_entry_bytes=65536,
39+
fanout=2,
40+
max_referee_reassignments=1,
41+
max_referee_cost_units=100,
42+
)
43+
body = s.manifest.body()
44+
body["network"]["dispute_policy_hash"] = dispute.digest()
45+
manifest = RunManifestV2.model_validate(body)
46+
objects = LocalFSStore(tmp_path / "objects")
47+
for policy in (s.policy, s.admission_policy, dispute):
48+
assert objects.put(canonicalize(policy.body())) == policy.digest()
49+
store = ChallengeStore(
50+
tmp_path / "state",
51+
Params("hypertrain", manifest.training.beacon.genesis_time, 300, 1, 1),
52+
E.COORD,
53+
None,
54+
lambda payload: None,
55+
objects,
56+
)
57+
store._db.execute(
58+
"INSERT INTO runs VALUES(?,?,?,'created',NULL)",
59+
(manifest.run_id(), manifest.model_dump_json(), "{}"),
60+
)
61+
if cuda:
62+
monkeypatch.setattr(store, "_backend_v2", lambda m: "cuda")
63+
return store, manifest.run_id()
64+
65+
66+
def beacon(store, number: int, *, bls: bool) -> None:
67+
store._db.execute(
68+
"INSERT INTO beacon VALUES(?,?,?,?)", (number, "aa" * 48, "bb" * 32, int(bls))
69+
)
70+
71+
72+
def signed(run_id: str, signer=E.COORD) -> bytes:
73+
return canonicalize(seal(signer, "ProductionBootstrap", run_id, B.bootstrap(run_id), 10000))
74+
75+
76+
@pytest.fixture
77+
def close():
78+
stores = []
79+
yield stores.append
80+
for store in stores:
81+
store.close_v2_notifications()
82+
store.close()
83+
84+
85+
def issued(store) -> int:
86+
return store._db.execute("SELECT COALESCE(SUM(issued),0) FROM escrow_origins").fetchone()[0]
87+
88+
89+
def test_bootstrap_route_refuses_cpu_backend(tmp_path, monkeypatch, close) -> None:
90+
store, run_id = hosted(tmp_path, monkeypatch, cuda=False)
91+
close(store)
92+
beacon(store, 1, bls=True)
93+
with pytest.raises(ChallengeError, match="production CUDA qualification required"):
94+
store.production_bootstrap_v2(run_id, signed(run_id))
95+
# Refused before any escrow service (or ledger table) exists for the run.
96+
assert store._services_v2 == {}
97+
assert (
98+
store._db.execute("SELECT 1 FROM sqlite_master WHERE name='escrow_origins'").fetchone()
99+
is None
100+
)
101+
102+
103+
def test_bootstrap_route_requires_bls_beacon(tmp_path, monkeypatch, close) -> None:
104+
# Given: an unverified (fixture/HTTP-relayed) latest beacon round.
105+
store, run_id = hosted(tmp_path, monkeypatch, cuda=True)
106+
close(store)
107+
beacon(store, 1, bls=False)
108+
# When / Then
109+
with pytest.raises(AdmissionError, match="UNVERIFIED_BEACON"):
110+
store.production_bootstrap_v2(run_id, signed(run_id))
111+
assert issued(store) == 0
112+
# A BLS-verified round lets the same signed request through, once.
113+
beacon(store, 2, bls=True)
114+
receipt = store.production_bootstrap_v2(run_id, signed(run_id))
115+
assert receipt["ledger_mode"] == "production"
116+
assert issued(store) == 30000
117+
118+
119+
def test_bootstrap_route_rejects_wrong_envelope_signer(tmp_path, monkeypatch, close) -> None:
120+
store, run_id = hosted(tmp_path, monkeypatch, cuda=True)
121+
close(store)
122+
beacon(store, 1, bls=True)
123+
with pytest.raises(UnauthorizedSigner):
124+
store.production_bootstrap_v2(run_id, signed(run_id, E.OTHER))
125+
assert issued(store) == 0
126+
127+
128+
def test_economic_bound_refused_when_bound_false(tmp_path, monkeypatch, close) -> None:
129+
# Given: q*s*beta*(R+S) = 1100 units < G = 1101.
130+
store, run_id = hosted(tmp_path, monkeypatch, cuda=True, G_max_units=1101)
131+
close(store)
132+
beacon(store, 1, bls=True)
133+
_, admission, _ = store._services(run_id)
134+
# When / Then
135+
with pytest.raises(ChallengeError, match="economic bound"):
136+
store.economic_bound_v2(run_id)
137+
assert (
138+
store._db.execute("SELECT COUNT(*) FROM records_v2 WHERE kind='economic-bound'").fetchone()[
139+
0
140+
]
141+
== 0
142+
)
143+
assert admission.conservative_bound() is False
144+
145+
146+
def test_economic_bound_written_once_and_immutable(tmp_path, monkeypatch, close) -> None:
147+
# Given: q*s*beta*(R+S) = 1100 units >= G = 1100 (exact boundary).
148+
store, run_id = hosted(tmp_path, monkeypatch, cuda=True, G_max_units=1100)
149+
close(store)
150+
beacon(store, 1, bls=True)
151+
_, admission, _ = store._services(run_id)
152+
assert admission.conservative_bound() is False
153+
# When
154+
record = store.economic_bound_v2(run_id)
155+
raw = store._db.execute(
156+
"SELECT data FROM records_v2 WHERE kind='economic-bound' AND id='run'"
157+
).fetchone()[0]
158+
# Then: coordinator-signed, admission now sees the bound.
159+
assert record["receipt"]["signer"] == E.COORD.ss58 and verify_envelope(record["receipt"])
160+
assert admission.conservative_bound() is True
161+
# A later call (new beacon, fresh randomized signature possible) never rewrites it.
162+
beacon(store, 2, bls=True)
163+
assert store.economic_bound_v2(run_id) == record
164+
after = store._db.execute(
165+
"SELECT data FROM records_v2 WHERE kind='economic-bound' AND id='run'"
166+
).fetchone()[0]
167+
assert after == raw
168+
# A stored record bound to another policy is a conflict, not silently replaced.
169+
store._db.execute(
170+
"UPDATE records_v2 SET data=json_set(data,'$.economics_policy_hash',?) "
171+
"WHERE kind='economic-bound'",
172+
("ff" * 32,),
173+
)
174+
with pytest.raises(ChallengeError, match="immutable economic-bound"):
175+
store.economic_bound_v2(run_id)
176+
assert (
177+
json.loads(
178+
store._db.execute("SELECT data FROM records_v2 WHERE kind='economic-bound'").fetchone()[
179+
0
180+
]
181+
)["economics_policy_hash"]
182+
== "ff" * 32
183+
)

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.