|
| 1 | +"""Bind resource requests to real allocation receipts, not unrelated chat history.""" |
| 2 | + |
| 3 | +import json |
| 4 | +import re |
| 5 | +import time |
| 6 | +from pathlib import Path |
| 7 | + |
| 8 | +import requests |
| 9 | + |
| 10 | +from rlm.v100.chat_goals import normalized |
| 11 | +from rlm.v100.common import atomic_json |
| 12 | + |
| 13 | +RESOURCE_TOOLS = { |
| 14 | + "compute_resources", |
| 15 | + "get_plan", |
| 16 | + "mission_evidence", |
| 17 | + "drone_status", |
| 18 | + "propose_compute_trial", |
| 19 | + "compute_trial_status", |
| 20 | + "cancel_compute_trial", |
| 21 | + "schedule_drone", |
| 22 | + "cancel_drone", |
| 23 | + "calculate", |
| 24 | + "goal_learning_status", |
| 25 | +} |
| 26 | + |
| 27 | + |
| 28 | +def instruction(message: str) -> bool: |
| 29 | + text = normalized(message) |
| 30 | + if "?" in text or re.match(r"^(?:czy|jak|why|how|is|are)\b", text): |
| 31 | + return False |
| 32 | + if re.search(r"dashboard|\bhtml\b|pulpit|(?:ustaw|zmien)\w*\s+(?:cel|plan)", text): |
| 33 | + return False |
| 34 | + resource = re.findall(r"\b(?:rtx|windows\w*|cpu|ram\w*|dysk\w*|worker\w*|dron\w*)\b", text) |
| 35 | + return len(set(resource)) >= 2 and bool( |
| 36 | + re.search(r"uzyw|wykorzyst|przydz|deleg|udostep|wspoldziel|shared", text) |
| 37 | + ) |
| 38 | + |
| 39 | + |
| 40 | +def filter_actions(actions: list[dict]) -> tuple[list[dict], list[dict]]: |
| 41 | + allowed = [row for row in actions if row.get("kind") in ("directive", "budget")] |
| 42 | + rejected = [row for row in actions if row not in allowed] |
| 43 | + return allowed, rejected |
| 44 | + |
| 45 | + |
| 46 | +def status(root: Path) -> dict: |
| 47 | + from rlm.v100.common import load_profile |
| 48 | + from rlm.v100.competition import helper_client |
| 49 | + from rlm.v100.distributed_compute import inspect |
| 50 | + from rlm.v100.drones import inspect as drone_status |
| 51 | + from rlm.v100.remote_helper import remote_profile, selected_helper |
| 52 | + |
| 53 | + value = { |
| 54 | + "external_compute": inspect(root), |
| 55 | + "drones": drone_status(root), |
| 56 | + "scope": "Owned job execution only. Windows RAM/disk are worker-local resources, not pooled Debian RAM or shared VRAM. No arbitrary Windows shell is exposed.", |
| 57 | + } |
| 58 | + try: |
| 59 | + profile = load_profile(selected_helper(root), root) |
| 60 | + if not remote_profile(profile): |
| 61 | + raise ValueError("Pinned RTX helper is not configured") |
| 62 | + client = helper_client(profile, root) |
| 63 | + client.timeout = 3 |
| 64 | + loaded = client.remote_request("/api/ps").get("models", []) |
| 65 | + loaded = [m for m in loaded if m.get("digest") == client.model_digest] |
| 66 | + value["helper"] = { |
| 67 | + "reachable": True, |
| 68 | + "pinned_model_loaded": bool(loaded), |
| 69 | + "context": profile["runtime"]["context_window"], |
| 70 | + "batch": client.helper_batch_tokens, |
| 71 | + "active_request_target_percent": client.helper_duty_percent, |
| 72 | + "scope": "Inference/vision helper, request pacing; not a hard GPU utilization/power cap", |
| 73 | + } |
| 74 | + except (OSError, ValueError, RuntimeError, requests.RequestException) as error: |
| 75 | + value["helper"] = {"reachable": False, "error": str(error)[:300]} |
| 76 | + return value |
| 77 | + |
| 78 | + |
| 79 | +def answer(evidence: dict, trace: list[dict], rejected: list[dict]) -> str: |
| 80 | + helper = evidence["helper"] |
| 81 | + external = evidence["external_compute"] |
| 82 | + workers = external.get("workers", []) |
| 83 | + active = [w for w in workers if not w.get("stale", True)] |
| 84 | + text = "RTX helper: " + ( |
| 85 | + "osiągalny, przypięty model załadowany." |
| 86 | + if helper.get("pinned_model_loaded") |
| 87 | + else "brak potwierdzenia załadowanego modelu." |
| 88 | + ) |
| 89 | + text += f"\nWindows CPU: {len(active)} aktualnych workerów. " |
| 90 | + text += "RAM i dysk Windows są używane lokalnie przez workery; nie powiększają RAM ani VRAM Debiana." |
| 91 | + for worker in active: |
| 92 | + text += f"\n{worker.get('name', 'worker')}: {worker.get('phase', 'unknown')}, {worker.get('threads', '?')} wątki, limit RAM {worker.get('ram_limit_gib', '?')} GiB." |
| 93 | + allocations = [ |
| 94 | + row for row in trace if row["tool"] in ("propose_compute_trial", "schedule_drone") |
| 95 | + ] |
| 96 | + for row in allocations: |
| 97 | + result = row["result"] |
| 98 | + text += ( |
| 99 | + "\nZlecenie: " |
| 100 | + + str(result.get("id", "brak ID")) |
| 101 | + + " | " |
| 102 | + + str(result.get("state", result.get("status", "unknown"))) |
| 103 | + ) |
| 104 | + if result.get("error"): |
| 105 | + text += " | " + str(result["error"])[:200] |
| 106 | + if not allocations: |
| 107 | + text += "\nW tej odpowiedzi nie przydzielono nowego zadania. Gotowość workera nie oznacza wykonania." |
| 108 | + if rejected: |
| 109 | + text += "\nOdrzucono działania niezwiązane z przydziałem zasobów. Nie zmieniono nimi planów ani HTML." |
| 110 | + text += "\nZlecenie w kolejce nie potwierdza wykonania, przyspieszenia ani aktualizacji wag." |
| 111 | + return text |
| 112 | + |
| 113 | + |
| 114 | +def repair_completed(root: Path) -> dict: |
| 115 | + """Upgrade-only recovery of misrouted completed resource commands; never overwrite later plans.""" |
| 116 | + from rlm.v100.drones import connect as drone_connect |
| 117 | + from rlm.v100.mission import status as mission_status |
| 118 | + from rlm.v100.mission_chat import connect |
| 119 | + |
| 120 | + if mission_status(root)["running"]: |
| 121 | + raise ValueError("Stop the mission before recovering misrouted chat plans") |
| 122 | + repaired = [] |
| 123 | + with connect(root) as db: |
| 124 | + rows = db.execute("SELECT * FROM requests WHERE state='completed'").fetchall() |
| 125 | + for row in rows: |
| 126 | + if not instruction(row["message"]): |
| 127 | + continue |
| 128 | + response = json.loads(row["response"]) |
| 129 | + _, rejected = filter_actions(response.get("actions", [])) |
| 130 | + if not rejected or response.get("resource_contract"): |
| 131 | + continue |
| 132 | + if not re.fullmatch("[a-f0-9]{32}", row["id"]): |
| 133 | + raise ValueError("Invalid persisted request identity") |
| 134 | + archive = root / "research/state/chat-contract-repairs" / (row["id"] + ".json") |
| 135 | + atomic_json(archive, dict(row)) |
| 136 | + plans_path = root / "research/plans/current.json" |
| 137 | + plans = json.loads(plans_path.read_text()) if plans_path.exists() else {} |
| 138 | + restored = [] |
| 139 | + for receipt in response.get("applied", []): |
| 140 | + horizon, identity = receipt.get("horizon"), receipt.get("id", "") |
| 141 | + if horizon in ("short", "mid") and re.fullmatch("[a-f0-9]{32}", identity): |
| 142 | + if plans.get(horizon, {}).get("id") == identity: |
| 143 | + version = json.loads( |
| 144 | + (root / "research/plans" / (identity + ".json")).read_text() |
| 145 | + ) |
| 146 | + plans[horizon] = version.get("previous") or {} |
| 147 | + restored.append(horizon) |
| 148 | + elif receipt.get("kind") == "desktop": |
| 149 | + with drone_connect(root) as jobs: |
| 150 | + current = jobs.execute( |
| 151 | + "SELECT payload,state FROM jobs WHERE id=?", (identity,) |
| 152 | + ).fetchone() |
| 153 | + payloads = {a["text"] for a in rejected if a.get("kind") == "sandbox"} |
| 154 | + if ( |
| 155 | + current |
| 156 | + and current["state"] == "queued" |
| 157 | + and current["payload"] in payloads |
| 158 | + ): |
| 159 | + jobs.execute( |
| 160 | + "UPDATE jobs SET state='cancelled',updated=? WHERE id=?", |
| 161 | + (time.time(), identity), |
| 162 | + ) |
| 163 | + if restored: |
| 164 | + atomic_json( |
| 165 | + archive.with_name(row["id"] + "-plans-before.json"), |
| 166 | + json.loads(plans_path.read_text()), |
| 167 | + ) |
| 168 | + atomic_json(plans_path, plans) |
| 169 | + db.execute( |
| 170 | + "UPDATE requests SET state='queued',response=NULL,attempts=0,error=NULL,updated=? WHERE id=?", |
| 171 | + (time.time(), row["id"]), |
| 172 | + ) |
| 173 | + repaired.append({"id": row["id"], "restored_plans": restored, "archive": str(archive)}) |
| 174 | + return {"requeued_resource_requests": repaired, "long_term_goal_changed": False} |
0 commit comments