Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .agents/skills/manage-ci/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,10 @@ contract; no downstream product's workflow topology applies here.
- Ordinary tests are offline. Model admission is explicit and digest-bound.
GPU qualification requires a real matching device; missing fixtures, devices,
capacity, or evidence fail or queue, never become passing skips.
Split qualification must bind readiness and acknowledged completion to its
own JY formation/source/model/profile/role/attempt identities. Require both
members' receipts and overlapping successful execution on the distinct
reserved nodes; a listening port or a leader-only pass is insufficient.
- Split admission is established by actual native stage plans, tensor closures,
activation frontiers, artifact identities and backend compatibility. Qualification
records exact tested configurations. There is no architecture certification
Expand Down
21 changes: 21 additions & 0 deletions ci/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,27 @@ its 60-second grace. This execution clock starts once and never resets on
later status polls or when the other split member starts. The Actions job
allows 130 minutes in total, leaving nine minutes for setup, evidence and
cleanup. Nightly/release total deadlines and native lease budgets are unchanged.
Split readiness uses a control listener on each reserved machine, bound to the
JY formation, source SHA, model, profile, role and native attempt ID. The leader
waits for its own worker's ready response; an unrelated stage listener cannot
satisfy readiness. The worker joins the serving child's Linux `/proc/PID/fd`
socket inodes with its TCP LISTEN table to verify ownership of the exact stage
endpoint, as well as requiring a live child and reachable port. A port taken
by another process during model loading cannot make it ready. This uses the
existing same-user process visibility; no tracing subscriber is required.
Leader control is already served during the longer nightly/release numerical
checks, so the worker can identify it without waiting for those checks to end.
Existing data/control listeners cause failure rather than
being reused or killed. The worker must acknowledge the leader's completion
before either writes passing peer evidence. Missing peers and acknowledgements
fail within the existing native lease; this does not change JY scheduling.
The protected controller requires both formation members to succeed on their
distinct reserved nodes with overlapping execution windows and matching
two-way `split-peer.json` evidence. It checks the leader's `qualification.json`
and worker's peer receipt before accepting the split, independently of optional
throughput reporting. These identities are diagnostic provenance, not secrets.
Older split receipts without this evidence cannot qualify a new run; update the
candidate harness from main before rerunning qualification.
Branch PRs retain
same-repository/collaborator admission; forks use the approved
controller above. Both retain a fresh-head check and all seven GPU smoke
Expand Down
3 changes: 3 additions & 0 deletions ci/automation.just
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ inference-contracts:
@PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_streaming.py
@PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_build.py
@PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_deadlines.py
@PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_peer.py
@PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_socket.py
@PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_peer_evidence.py
@PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_contracts.py
@PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/inference_probe.py
@PYTHONPATH=scripts "{{ automation_python }}" scripts/tests/jy_read_recovery.py
Expand Down
3 changes: 3 additions & 0 deletions scripts/inference-dispatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from lib.ci_process import cancel_on_signal
from lib.inference_ladder import plan
from lib.inference_logs import NativeLogs
from lib.inference_peer_evidence import verify_split_peer
from lib.inference_nightly_metrics import collect_nightly
from lib.inference_throughput import collect
from lib.jy_qualification import Pilot, placement
Expand Down Expand Up @@ -171,6 +172,8 @@ def dispatch(pilot, profile, sha, output, configuration, collect_public=False):
write_json(output / f"{identity}-launch.json", launched)
job = wait(pilot, handle, identity, sha, output, deadline,
execution_seconds=1860 if profile == "pr" else None)
if mode == "split":
verify_split_peer(pilot, job, row, sha, profile, output)
if collect_public:
collect_nightly(pilot, job, row, sha, output, model_key, profile)
elif profile == "pr":
Expand Down
65 changes: 25 additions & 40 deletions scripts/inference-execute.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@
import os
import platform
import shutil
import socket
import subprocess
import sys
import tempfile
import time
from pathlib import Path
from contextlib import nullcontext

from lib.ci_artifacts import read_json, write_json
from lib.ci_process import cancel_on_signal, capture, command, start, stop
Expand All @@ -22,6 +22,7 @@
from lib.inference_ladder import plan
from lib.inference_admission import split_admissions_digest
from lib.inference_probe import measure
from lib.inference_peer import PeerControl, port_available


def authority():
Expand Down Expand Up @@ -71,17 +72,7 @@ def address(ip, port):
args = ["--config", str(local), "--stage-transport", "binary"]
if worker:
args.append("--worker-only")
else:
deadline = time.monotonic() + 900
while True:
try:
with socket.create_connection((str(follower), 9401), timeout=1):
break
except OSError:
if time.monotonic() >= deadline:
raise RuntimeError("split worker listener did not become ready")
time.sleep(1)
return args, "http://" + address(leader, 9912)
return args


def wait_for(server, url, seconds, poll, check):
Expand All @@ -98,25 +89,6 @@ def wait_for(server, url, seconds, poll, check):
raise RuntimeError("inference server or split leader timed out")


def acknowledge_worker():
with socket.socket() as listener:
listener.bind(("0.0.0.0", 9912))
listener.listen(1)
listener.settimeout(60)
try:
connection, _ = listener.accept()
except socket.timeout:
return
with connection:
connection.settimeout(2)
try:
connection.recv(1024)
except OSError:
pass
body = b"qualification-complete"
connection.sendall(b"HTTP/1.1 200 OK\r\nContent-Length: 22\r\nConnection: close\r\n\r\n" + body)


def execute(profile, key, mode):
sha, gpu = authority()
result = plan(profile, sha)
Expand All @@ -134,27 +106,38 @@ def execute(profile, key, mode):
model = admit(key, inputs)
coordinate = f'{inputs["repo"]}@{inputs["revision"]}'
context = 4096 if profile == "pr" else 65536
if not worker and profile != "pr":
numerical(model, coordinate, inputs, output)
args = ["target/debug/skippy", "--debug", "serve", "--startup-timeout-secs", "300"]
if not worker:
args += ["--speculative-strategy", "disabled", "--generation-concurrency", "1"]
control = None
if mode == "split":
split_args, control = prepare_split(model, coordinate, profile, context, output, worker)
args += split_args
args += prepare_split(model, coordinate, profile, context, output, worker)
else:
args += [
"--ctx-size", str(context), "--n-gpu-layers", "999", "--bind-addr", "127.0.0.1:9337",
"--model-path", str(model), "--model-id", coordinate,
]
log = output / "server.log"
with log.open("wb") as stream:
peer_context = PeerControl.from_environment(sha, key, profile) if mode == "split" else nullcontext()
with log.open("wb") as stream, peer_context as peer:
# Keep formation identity observable while the leader runs longer
# nightly/release numerical checks, before starting its serving child.
if not worker and profile != "pr":
numerical(model, coordinate, inputs, output)
if peer is not None:
peer.await_peer(None if worker else "ready")
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
if worker:
# A ready control response must describe our own new listener.
port_available(peer.host, 9401)
if not worker:
port_available("127.0.0.1", 9337)
server = start(args, stdin=subprocess.DEVNULL, stdout=stream, stderr=stream)
try:
if worker:
wait_for(server, control, 18000, 5, lambda body: body == "qualification-complete")
peer.worker_ready(server, read_json(output / "stage.json"))
peer.await_peer("complete", server, seconds=18000)
offload(log)
peer.acknowledge()
peer.save(output)
return
wait_for(server, ENDPOINT + "/v1/models", 900, 2, lambda _body: True)
offload(log)
Expand All @@ -167,16 +150,18 @@ def execute(profile, key, mode):
performance(profile, coordinate, context, output, inputs)
scope = ("native chain parity, state handoff, deterministic endpoint repeat; "
"not an independent implementation reference")
if peer is not None:
peer.complete(server)
peer.save(output)
write_json(output / "qualification.json", {
"source_sha": sha, "model": key, "mode": mode, "profile": profile, "status": "passed",
"performance_claim": result["performance_claim"], "gpu": gpu, "layers": inputs["layers"],
"artifact_manifest_sha256": input_hashes()["model_manifest_sha256"],
"correctness_scope": scope,
"split_peer": peer.proof() if peer is not None else None,
"split_admissions_sha256": (split_admissions_digest(read_json(output / "split-admissions.json"))
if mode == "split" else None),
})
if mode == "split":
acknowledge_worker()
finally:
stop(server)

Expand Down
191 changes: 191 additions & 0 deletions scripts/lib/inference_peer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
"""Bind split readiness and completion to the actual JY formation attempts."""

import ipaddress
import json
import os
import re
import socket
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.error import URLError
from urllib.request import ProxyHandler, Request, build_opener

from .ci_artifacts import write_json
from .inference_socket import owns_listener


def port_available(host, port):
family = socket.AF_INET6 if ipaddress.ip_address(host).version == 6 else socket.AF_INET
with socket.socket(family) as listener:
listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listener.bind((host, port))


class PeerControl:
def __init__(self, identity, host, peer_url, *, port=9912):
self.identity = identity
self.expected = {k: v for k, v in identity.items() if k != "run_id"}
self.expected["role"] = "worker" if identity["role"] == "leader" else "leader"
self.host, self.peer_url, self.port = host, peer_url, port
self.peer = None
self.phase = "starting"
self.ack = threading.Event()
self.completed = False
self.opener = build_opener(ProxyHandler({}))

@classmethod
def from_environment(cls, sha, model, profile):
formation, run, role = (os.environ[name] for name in
("JIANYANG_FORMATION_ID", "JIANYANG_RUN_ID", "JIANYANG_ROLE"))
if (not re.fullmatch(r"frm_[A-Za-z0-9_]+", formation)
or not re.fullmatch(r"run_[A-Za-z0-9_]+", run) or role not in {"leader", "worker"}):
raise ValueError("split qualification requires a JY formation and attempt identity")
peers = json.loads(os.environ["JIANYANG_PEERS"])
if len(peers) != 2 or {p["role"] for p in peers} != {"leader", "worker"}:
raise ValueError("split qualification requires exactly two peer roles")
hosts = {p["role"]: ipaddress.ip_address(p["host"]) for p in peers}
remote = hosts["worker" if role == "leader" else "leader"]
address = f"[{remote}]" if remote.version == 6 else str(remote)
return cls({"formation_id": formation, "run_id": run, "source_sha": sha,
"model": model, "profile": profile, "role": role},
str(hosts[role]), f"http://{address}:9912")

def __enter__(self):
control = self

class Handler(BaseHTTPRequestHandler):
def setup(self):
super().setup()
self.connection.settimeout(2)

def log_message(self, *_args):
pass

def respond(self, status):
body = json.dumps({"identity": control.identity, "phase": control.phase}).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
self.wfile.flush()

def do_GET(self):
self.respond(200 if self.path == "/" else 404)

def do_POST(self):
try:
size = int(self.headers.get("Content-Length", "0"))
if not 0 < size <= 4096:
raise ValueError("invalid acknowledgement size")
identity = json.loads(self.rfile.read(size))
valid = (self.path == "/ack" and control.identity["role"] == "leader"
and control.phase == "complete" and control.peer is not None
and identity == control.peer)
self.respond(200 if valid else 409)
if valid:
# Finish the response before allowing the leader to close.
control.ack.set()
except (OSError, ValueError):
self.respond(400)

class Server(ThreadingHTTPServer):
address_family = socket.AF_INET6 if ipaddress.ip_address(control.host).version == 6 else socket.AF_INET
daemon_threads = True

self.server = Server((self.host, self.port), Handler)
self.port = self.server.server_address[1]
self.thread = threading.Thread(target=self.server.serve_forever, kwargs={"poll_interval": 0.1}, daemon=True)
self.thread.start()
return self

def __exit__(self, *_args):
self.server.shutdown()
self.server.server_close()
self.thread.join(timeout=5)

def matches(self, identity):
return (isinstance(identity, dict)
and {k: v for k, v in identity.items() if k != "run_id"} == self.expected
and isinstance(identity.get("run_id"), str)
and re.fullmatch(r"run_[A-Za-z0-9_]+", identity["run_id"]) is not None
and (self.peer is None or identity == self.peer))

def request(self, path="/", body=None):
data = json.dumps(body).encode() if body is not None else None
request = Request(self.peer_url + path, data=data,
headers={"Content-Type": "application/json"})
with self.opener.open(request, timeout=2) as response:
payload = response.read(4097)
if len(payload) > 4096:
raise ValueError("split peer response exceeded capture limit")
value = json.loads(payload)
if not isinstance(value, dict) or not self.matches(value.get("identity")):
raise ValueError("split peer formation/source/attempt identity mismatch")
return value

def await_peer(self, phase=None, process=None, *, seconds=900):
deadline = time.monotonic() + seconds
last = "peer absent"
reported = None
while time.monotonic() < deadline:
if process is not None and process.poll() is not None:
raise RuntimeError("split inference server exited; inspect server.log")
try:
value = self.request()
if phase is None or value.get("phase") == phase:
self.peer = value["identity"]
return
last = "peer has not reached " + phase
except (OSError, ValueError, URLError) as error:
last = str(error)
if last != reported:
print("Waiting for split peer: " + last, flush=True)
reported = last
time.sleep(min(1, max(0, deadline - time.monotonic())))
raise RuntimeError("split peer rendezvous timed out: " + last)

def worker_ready(self, process, stage, *, port=9401, seconds=900):
address = f"[{self.host}]:{port}" if ":" in self.host else f"{self.host}:{port}"
if stage["bind_addr"] != address:
raise ValueError("worker stage listener differs from its reserved endpoint")
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
if process.poll() is not None:
raise RuntimeError("split worker exited before readiness; inspect server.log")
if owns_listener(process.pid, self.host, port):
try:
with socket.create_connection((self.host, port), timeout=1):
self.phase = "ready"
return
except OSError:
pass
time.sleep(min(1, max(0, deadline - time.monotonic())))
raise RuntimeError("split worker does not own its bound listener; inspect server.log")

def complete(self, process, *, seconds=60):
if self.peer is None:
raise ValueError("split completion requires a verified peer attempt")
self.phase = "complete"
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
if process.poll() is not None:
raise RuntimeError("split leader exited before completion acknowledgement")
if self.ack.wait(timeout=min(1, deadline - time.monotonic())):
self.completed = True
return
raise RuntimeError("split worker completion acknowledgement timed out")

def acknowledge(self):
if self.request("/ack", self.identity).get("phase") != "complete":
raise ValueError("split leader has not completed qualification")
self.completed = True

def proof(self):
if not self.completed or self.peer is None:
raise ValueError("split peer proof requires acknowledged completion")
return {"local": self.identity, "peer": self.peer, "completion_acknowledged": True}

def save(self, output):
write_json(output / "split-peer.json", self.proof())
Loading
Loading