diff --git a/CHANGELOG.md b/CHANGELOG.md index 4bca02f..3e7b4f7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,14 @@ All notable changes to this project are documented here. The format follows ## [Unreleased] +### Added + +- `grid_device.py update --model ` 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 diff --git a/coordinator/app/main.py b/coordinator/app/main.py index b864470..6620d8b 100644 --- a/coordinator/app/main.py +++ b/coordinator/app/main.py @@ -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) @@ -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. diff --git a/docs/ADD_DEVICE.md b/docs/ADD_DEVICE.md index 6061d0c..866d166 100644 --- a/docs/ADD_DEVICE.md +++ b/docs/ADD_DEVICE.md @@ -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) @@ -103,6 +103,17 @@ 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 @@ -110,7 +121,8 @@ WantedBy=default.target ``` 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 diff --git a/scripts/grid_device.py b/scripts/grid_device.py index 1b70f48..7e415a6 100644 --- a/scripts/grid_device.py +++ b/scripts/grid_device.py @@ -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
--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 @@ -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}) + 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: @@ -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": @@ -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__": diff --git a/tests/test_grid_device.py b/tests/test_grid_device.py index f064e63..fd5d422 100644 --- a/tests/test_grid_device.py +++ b/tests/test_grid_device.py @@ -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: diff --git a/tests/test_worker_admin.py b/tests/test_worker_admin.py index 6b4a153..e4b22c0 100644 --- a/tests/test_worker_admin.py +++ b/tests/test_worker_admin.py @@ -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"]) @@ -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": {