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
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,14 @@ All notable changes to this project are documented here. The format follows

## [Unreleased]

### Added

- `grid_device.py update <name> --model <tag>` and a matching coordinator endpoint
(`POST /api/admin/workers/{id}/model`) to move a device to a different operator-approved
model in place — no new worker token, no new bundle to carry to the device, trust level and
credit history untouched. Previously the only way to change a device's model was
`remove` + `add`, which reissued its token and required transferring a fresh bundle.

### Documentation

- Long-term goal stated in the README and roadmap: a global, federated, community-owned AI
Expand Down
27 changes: 27 additions & 0 deletions coordinator/app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,10 @@ class WorkerIn(BaseModel):
trust_level: Literal["trusted", "community"] = "trusted"


class WorkerModelIn(BaseModel):
model: str = Field(min_length=1, max_length=80, pattern=r"^[A-Za-z0-9_.:-]+$")


class EnrollCodeIn(BaseModel):
ttl_seconds: int = Field(default=3600, ge=60, le=86400)

Expand Down Expand Up @@ -575,6 +579,29 @@ def rotate(worker_id: str):
return {"worker_id": worker_id, "worker_token": token,
"warning": "Worker token shown once. Store securely. Never commit to Git."}

@app.post("/api/admin/workers/{worker_id}/model", dependencies=[Depends(admin)])
def retag(worker_id: str, payload: WorkerModelIn):
"""Move a worker to a different operator-approved model, in place.

Identity, token and credit history are untouched (unlike remove+add) so an operator can
resize a device's model without reissuing its worker token or losing its trust/credit
history. The device's own CAG_MODEL setting lives in its local worker.env, not here — the
operator still has to edit that file on the device and restart it to match.
"""
approved(payload.model)
with database.connect() as db:
db.execute("BEGIN IMMEDIATE")
row = db.execute("SELECT revoked_at FROM workers WHERE id=?", (worker_id,)).fetchone()
if row is None:
db.rollback()
raise HTTPException(404, "Unknown worker")
if row["revoked_at"]:
db.rollback()
raise HTTPException(409, "Worker revoked")
db.execute("UPDATE workers SET model=? WHERE id=?", (payload.model, worker_id))
db.commit()
return {"worker_id": worker_id, "model": payload.model}

@app.post("/api/admin/workers/{worker_id}/settle", dependencies=[Depends(admin)])
def settle(worker_id: str, payload: Settlement):
"""Manually approve provisional demo credits after out-of-band verification.
Expand Down
16 changes: 14 additions & 2 deletions docs/ADD_DEVICE.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ ports. The coordinator itself stays on loopback; nothing is opened on the networ
| Script | Runs on | Purpose |
|---|---|---|
| `scripts/grid_host_setup.sh` | coordinator host, once, `sudo` | user `gridtunnel` (no shell/home), root-owned key file, sshd drop-in limited to this user |
| `scripts/grid_device.py` | coordinator host | `add` / `remove` / `list` devices: worker token + restricted key line + device bundle |
| `scripts/grid_device.py` | coordinator host | `add` / `update` / `remove` / `list` devices: worker token + restricted key line + device bundle |
| `scripts/grid_join.py` | device | `init` key, `check` tunnel, `run` tunnel + worker with reconnect |

## 1. Coordinator host (once)
Expand Down Expand Up @@ -103,14 +103,26 @@ WantedBy=default.target
`systemctl --user daemon-reload && systemctl --user enable --now community-grid` (add
`loginctl enable-linger $USER` to run without being logged in).

## Switch a device's model

```bash
.venv/bin/python scripts/grid_device.py update fedora-laptop --model qwen2.5-coder:7b-instruct
```

Changes only which model this device is approved to serve; the worker token, SSH key and
trust/credit history are untouched, so no new bundle needs to be carried to the device. This
only updates the coordinator-side allowlist entry — on the device itself, edit `CAG_MODEL` in
its `worker.env` to the same tag and restart `grid_join.py run` so the two sides agree again.

## Remove a device

```bash
.venv/bin/python scripts/grid_device.py remove fedora-laptop
```

Removes the key line (new tunnels fail) and revokes the worker token (an already open tunnel can no
longer claim or report jobs).
longer claim or report jobs). Use this instead of `update` when the device itself is changing, not
just its model.

## Tested / not tested

Expand Down
24 changes: 23 additions & 1 deletion scripts/grid_device.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Coordinator-host helper: give one device a worker token and a tunnel-only SSH key.

python scripts/grid_device.py add laptop --pubkey laptop.pub --host <address> --model qwen2.5-coder:1.5b
python scripts/grid_device.py update laptop --model qwen2.5-coder:7b-instruct
python scripts/grid_device.py remove laptop
python scripts/grid_device.py list

Expand Down Expand Up @@ -161,6 +162,19 @@ def add(args, client: httpx.Client, base: str, admin_key: str) -> dict:
return {"device": args.name, "worker_id": worker["id"], "bundle": str(bundle_path)}


def update(args, client: httpx.Client, base: str, admin_key: str) -> dict:
registry = load_registry(args.state)
if args.name not in registry:
raise ValueError(f"Unknown device {args.name!r}")
worker_id = registry[args.name]["worker_id"]
response = client.post(f"{base}/api/admin/workers/{worker_id}/model",
headers={"Authorization": f"Bearer {admin_key}"}, json={"model": args.model})
Comment on lines +170 to +171

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Quiesce the old worker before retagging it

When this runs while the device is still polling with its old CAG_MODEL—the documented sequence edits and restarts it only after this command returns—the coordinator immediately offers it jobs for the new model. worker.client.infer() rejects those jobs because its configured model is still old, and repeated failures can exhaust the three attempts and fail queued jobs. Keep the worker stopped until its local config matches the new model and this update has completed.

Useful? React with 👍 / 👎.

response.raise_for_status()
registry[args.name]["model"] = args.model
save_registry(args.state, registry)
return {"device": args.name, "worker_id": worker_id, "model": args.model}


def remove(args, client: httpx.Client, base: str, admin_key: str) -> dict:
registry = load_registry(args.state)
if args.name not in registry:
Expand Down Expand Up @@ -196,6 +210,10 @@ def main():
adding.add_argument("--trust", choices=["trusted", "community"], default="trusted")
removing = commands.add_parser("remove", help="Remove the tunnel key and revoke the worker token")
removing.add_argument("name")
updating = commands.add_parser(
"update", help="Switch a device to a different operator-approved model, keeping its token")
updating.add_argument("name")
updating.add_argument("--model", required=True, help="New operator-approved model tag for this device")
commands.add_parser("list", help="Show registered devices (no secrets)")
args = parser.parse_args()
if args.command == "list":
Expand All @@ -206,15 +224,19 @@ def main():
sys.exit("Set CAG_ADMIN_KEY or start the coordinator once with scripts/run_coordinator.sh")
args.coordinator_port = httpx.URL(base).port or 8765
args.state.mkdir(parents=True, exist_ok=True, mode=0o700)
actions = {"add": add, "remove": remove, "update": update}
with httpx.Client(timeout=15, trust_env=False) as client:
try:
result = (add if args.command == "add" else remove)(args, client, base, key)
result = actions[args.command](args, client, base, key)
except ValueError as exc:
sys.exit(f"Error: {exc}")
print(json.dumps(result, indent=2))
if args.command == "add":
print("IMPORTANT: The bundle contains the worker token. Move it to the device privately, then delete it here.",
file=sys.stderr)
elif args.command == "update":
print("IMPORTANT: this only changed the server-side allowlist entry. On the device itself, edit "
"CAG_MODEL in worker.env to match and restart grid_join.py run.", file=sys.stderr)


if __name__ == "__main__":
Expand Down
19 changes: 19 additions & 0 deletions tests/test_grid_device.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,25 @@ def fail(path, content):
assert not (args.state / "registry.json").exists()


def test_update_switches_model_and_updates_registry_without_a_new_token(tmp_path):
args, seen = make_args(tmp_path), []
with coordinator(seen) as client:
grid_device.add(args, client, "http://127.0.0.1:8765", "a")
result = grid_device.update(make_args(tmp_path, model="qwen2.5-coder:7b-instruct"), client,
"http://127.0.0.1:8765", "a")
assert result == {"device": "laptop", "worker_id": "w1", "model": "qwen2.5-coder:7b-instruct"}
assert seen[-1] == ("POST", "/api/admin/workers/w1/model", "Bearer a",
{"model": "qwen2.5-coder:7b-instruct"})
assert grid_device.load_registry(args.state)["laptop"] == {
"worker_id": "w1", "model": "qwen2.5-coder:7b-instruct", "trust_level": "trusted"}


def test_update_rejects_unknown_device_without_calling_the_coordinator(tmp_path):
with coordinator([]) as client:
with pytest.raises(ValueError, match="Unknown device"):
grid_device.update(make_args(tmp_path, name="ghost"), client, "http://127.0.0.1:8765", "a")


def test_remove_deletes_key_bundle_and_revokes(tmp_path):
args, seen = make_args(tmp_path), []
with coordinator(seen) as client:
Expand Down
44 changes: 44 additions & 0 deletions tests/test_worker_admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ def revoke(api, worker_id, token=ADMIN):
return api.post(f"/api/admin/workers/{worker_id}/revoke", headers=auth(token))


def retag(api, worker_id, model, token=ADMIN):
return api.post(f"/api/admin/workers/{worker_id}/model", headers=auth(token), json={"model": model})


def test_revoked_worker_token_is_rejected(api):
w = enroll_full(api, "gone")
r = revoke(api, w["id"])
Expand Down Expand Up @@ -74,6 +78,46 @@ def test_rotate_rejects_unknown_and_revoked(api):
assert api.post(f"/api/admin/workers/{w['id']}/rotate", headers=auth(ADMIN)).status_code == 409


def test_retag_switches_which_jobs_the_worker_can_claim(make_api):
api = make_api(allowed_models=("demo-model", "other-model"))
w = enroll_full(api, "switchable")
old_job = submit(api, model="demo-model").json()["id"]
r = retag(api, w["id"], "other-model")
assert r.status_code == 200
assert r.json() == {"worker_id": w["id"], "model": "other-model"}
# Same token still authenticates, but the old-model job is no longer offered to it.
assert api.post("/api/worker/claim", headers=auth(w["worker_token"])).json()["job"] is None
new_job = submit(api, model="other-model").json()["id"]
claimed = api.post("/api/worker/claim", headers=auth(w["worker_token"])).json()["job"]
assert claimed["id"] == new_job and claimed["id"] != old_job


def test_retag_keeps_identity_trust_and_credits_untouched(api):
w = enroll_full(api, "stable-identity")
before = api.get("/api/admin/workers", headers=auth(ADMIN)).json()[0]
retag(api, w["id"], "demo-model") # same model: still exercises the identity-preserving path
after = api.get("/api/admin/workers", headers=auth(ADMIN)).json()[0]
assert after["id"] == before["id"] and after["trust_level"] == before["trust_level"]
assert after["provisional_credits"] == before["provisional_credits"]
# The worker token itself never changed, unlike /rotate.
assert api.post("/api/worker/claim", headers=auth(w["worker_token"])).status_code == 200


def test_retag_rejects_unapproved_model(api):
w = enroll_full(api, "picky")
r = retag(api, w["id"], "some-other-model")
assert r.status_code == 422
assert api.get("/api/admin/workers", headers=auth(ADMIN)).json()[0]["model"] == "demo-model"


def test_retag_rejects_unknown_and_revoked_and_requires_admin(api):
w = enroll_full(api, "retag2")
assert retag(api, "no-such-worker", "demo-model").status_code == 404
assert retag(api, w["id"], "demo-model", token=USER).status_code == 403
revoke(api, w["id"])
assert retag(api, w["id"], "demo-model").status_code == 409


def test_heartbeat_stores_only_known_capability_fields(api):
w = enroll_full(api, "meta")
r = api.post("/api/worker/heartbeat", headers=auth(w["worker_token"]), json={"capabilities": {
Expand Down
Loading