Download simulation_modules_v2/mars_daemon.py from fabricioslv/mars-monoculture-data: direct link, hf CLI and curl.
- Browser
- Download file 29.6 kB
-
https://huggingface.co/datasets/fabricioslv/mars-monoculture-data/resolve/main/simulation_modules_v2/mars_daemon.py
- Command line
-
hf download hf://datasets/fabricioslv/mars-monoculture-data/simulation_modules_v2/mars_daemon.py
-
curl -L -o mars_daemon.py https://huggingface.co/datasets/fabricioslv/mars-monoculture-data/resolve/main/simulation_modules_v2/mars_daemon.py
29.6 kB
| """Mars Daemon — servidor autonomo na VM do Colab com checkpoint soberano. | |
| Pedido do operador (2026-09-28): "o daemon la no Colab nao pode ficar nessa | |
| execucao por horas, autonomamente? ele processa e de tempos faz checkpoint | |
| para o HuggingFace... fica ate 12-24h no Colab Pro. E aqui tambem mandando | |
| dados — synthesis, gap-autowatch — para la cruzar." | |
| Arquitetura: | |
| OmniMind local --(mars_bridge: publish)--> HF inbox_local/ --+ | |
| v | |
| MARS DAEMON (Colab VM) | |
| loop de ciclos ~12-24h | |
| checkpoint -> HF a cada N s | |
| | | |
| OmniMind local <--(mars_bridge: consume)-- HF inbox_colab/ <--+ | |
| O HF `mars-monoculture-data` e o BARRAMENTO bidirecional: | |
| inbox_local/ — payloads enviados pelo OmniMind (synthesis, gap reports) | |
| inbox_colab/ — respostas/analises produzidas pelo daemon | |
| daemon_state/ — checkpoint soberano (ciclo, RNG, ultimos resultados) | |
| RESILIENCIA: Colab desconecta ~12-24h. O daemon checkpointa estado completo | |
| a cada checkpoint_every_s; ao restart, restaura do HF e continua do ciclo | |
| exato. Nada se perde. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import os | |
| import time | |
| import random | |
| from dataclasses import dataclass, field | |
| from typing import Dict, List, Optional, Callable | |
| from concurrent.futures import ThreadPoolExecutor | |
| try: | |
| from src.agriculture.mars_unified_simulator import StationUnifiedSimulator | |
| except ImportError: | |
| from mars_unified_simulator import StationUnifiedSimulator | |
| class DaemonCheckpoint: | |
| """Estado soberano do daemon — persistido ao HF para sobreviver desconexao.""" | |
| cycle: int = 0 | |
| started_ts: float = 0.0 | |
| rng_state: tuple | None = None | |
| last_results: Dict = field(default_factory=dict) | |
| processed_inbox: List[str] = field(default_factory=list) | |
| uptime_s: float = 0.0 | |
| station_snapshot: Dict = field(default_factory=dict) | |
| def to_dict(self) -> Dict: | |
| return {"writer": "colab_daemon", "cycle": self.cycle, | |
| "started_ts": self.started_ts, | |
| "rng_state": self.rng_state, "last_results": self.last_results, | |
| "processed_inbox": self.processed_inbox, "uptime_s": self.uptime_s, | |
| "station_snapshot": self.station_snapshot} | |
| def from_dict(cls, d: Dict) -> "DaemonCheckpoint": | |
| return cls(cycle=d.get("cycle", 0), started_ts=d.get("started_ts", 0.0), | |
| rng_state=tuple(d["rng_state"]) if d.get("rng_state") else None, | |
| last_results=d.get("last_results", {}), | |
| processed_inbox=d.get("processed_inbox", []), | |
| uptime_s=d.get("uptime_s", 0.0), | |
| station_snapshot=d.get("station_snapshot", {})) | |
| class _HFBus: | |
| """Barramento HF: lista/lea/grava payloads. | |
| RATE LIMIT (2026-09-28): upload_file = 1 commit HF; o daemon escreve | |
| centenas (checkpoint, job_queue, job_results, inbox) e esgota os | |
| 256 commits/hora. Por isso write() BUFFERIZA em memoria local e | |
| flush() sobe tudo num unico upload_folder -> 1 commit por ciclo. | |
| """ | |
| def __init__(self, api=None, repo: str = "fabricioslv/mars-monoculture-data"): | |
| self.api = api | |
| self.repo = repo | |
| self._mem: Dict[str, str] = {} | |
| self._pending: Dict[str, Dict] = {} # buffer p/ flush em batch | |
| self._files_cache: List[str] = [] # anti-429: listagem cacheada | |
| self._files_ts: float = 0.0 | |
| def list_files(self, ttl_s: float = 60.0) -> List[str]: | |
| """list_repo_files cacheado — cada chamada crua e um GET na API do HF | |
| e o daemon lista varias vezes por ciclo (inbox + queue + reads). | |
| 429s observados (2026-09-28): cache de 60 s reduz chamadas ~10x.""" | |
| if not self.api: | |
| return sorted(self._mem) | |
| if time.time() - self._files_ts > ttl_s: | |
| try: | |
| self._files_cache = self.api.list_repo_files( | |
| self.repo, repo_type="dataset") | |
| self._files_ts = time.time() | |
| except Exception: | |
| pass # em 429, usa o cache velho | |
| return list(self._files_cache) | |
| def list_inbox(self, direction: str = "local") -> List[str]: | |
| if self.api: | |
| return sorted(f for f in self.list_files() | |
| if f.startswith(f"inbox_{direction}/")) | |
| return sorted(f for f in self._mem if f.startswith(f"inbox_{direction}/")) | |
| def read(self, path: str) -> Optional[Dict]: | |
| if self.api: | |
| if path in self._pending: # buffer antes de subir | |
| return self._pending[path] | |
| if path not in self.list_files(): | |
| return None | |
| from huggingface_hub import hf_hub_download | |
| try: | |
| p = hf_hub_download(repo_id=self.repo, repo_type="dataset", | |
| filename=path) | |
| except Exception: | |
| return None | |
| return json.load(open(p)) | |
| return json.loads(self._mem[path]) if path in self._mem else None | |
| def write(self, path: str, payload: Dict) -> None: | |
| if self.api: | |
| self._pending[path] = payload # bufferiza — 1 commit/flush | |
| else: | |
| self._mem[path] = json.dumps(payload) | |
| def flush(self) -> int: | |
| """Sobe todos os writes bufferizados num unico commit (upload_folder).""" | |
| if not self.api or not self._pending: | |
| return 0 | |
| import os, tempfile | |
| n = len(self._pending) | |
| with tempfile.TemporaryDirectory() as td: | |
| for path, payload in self._pending.items(): | |
| fp = os.path.join(td, path) | |
| os.makedirs(os.path.dirname(fp), exist_ok=True) | |
| json.dump(payload, open(fp, "w")) | |
| self.api.upload_folder(repo_id=self.repo, repo_type="dataset", | |
| folder_path=td, path_in_repo="") | |
| for path in self._pending: # escritas entram no cache | |
| if path not in self._files_cache: # sem forcar refresh | |
| self._files_cache.append(path) | |
| self._pending.clear() | |
| return n | |
| # ============ Fila de trabalhos (aproveita os N workers do Colab Pro) ============ | |
| class Job: | |
| """Um trabalho enfileirado para o daemon executar com dados reais.""" | |
| job_id: str | |
| kind: str # mesh_series | synthesis | heavy_sim | classify | |
| payload: Dict | |
| status: str = "queued" # queued | running | done | failed | |
| result: Optional[Dict] = None | |
| submitted_ts: float = 0.0 | |
| finished_ts: float = 0.0 | |
| class JobQueue: | |
| """Fila persistente de jobs — no HF para sobreviver, em memoria p/ testes. | |
| O daemon despacha para N workers (Colab Pro: 8). Cada job grava resultado | |
| em job_results/{id}.json — o OmniMind coleta pela bridge. | |
| """ | |
| def __init__(self, bus: _HFBus): | |
| self.bus = bus | |
| self._local: Dict[str, Job] = {} # cache local (a fila viva) | |
| def submit(self, job: Job) -> str: | |
| job.submitted_ts = time.time() | |
| self._local[job.job_id] = job | |
| self.bus.write(f"job_queue/{job.job_id}.json", | |
| {"job_id": job.job_id, "kind": job.kind, | |
| "payload": job.payload, "status": "queued", | |
| "submitted_ts": job.submitted_ts}) | |
| return job.job_id | |
| def next_queued(self) -> Optional[Job]: | |
| for j in self._local.values(): | |
| if j.status == "queued": | |
| return j | |
| return None | |
| def mark(self, job_id: str, status: str, result: Optional[Dict] = None) -> None: | |
| j = self._local.get(job_id) | |
| if j is None: | |
| return | |
| j.status = status | |
| j.result = result | |
| j.finished_ts = time.time() | |
| # atualiza o job_queue/ tambem — assim pull_remote_queue nao re-puxa | |
| self.bus.write(f"job_queue/{job_id}.json", | |
| {"job_id": job_id, "kind": j.kind, "payload": j.payload, | |
| "status": status, "submitted_ts": j.submitted_ts}) | |
| # resultado vai p/ job_results/ — a bridge local coleta | |
| self.bus.write(f"job_results/{job_id}.json", | |
| {"job_id": job_id, "kind": j.kind, "status": status, | |
| "result": result, "finished_ts": j.finished_ts}) | |
| def counts(self) -> Dict[str, int]: | |
| out: Dict[str, int] = {} | |
| for j in self._local.values(): | |
| out[j.status] = out.get(j.status, 0) + 1 | |
| return out | |
| def _deep_tuple(o): | |
| """JSON serializa tuplas como listas — reconverte recursivamente.""" | |
| return tuple(_deep_tuple(x) for x in o) if isinstance(o, (list, tuple)) else o | |
| def default_worker(payload: Dict) -> Dict: | |
| """Worker padrao — trata todos os kinds que a estacao conhece. | |
| mesh_series -> malha cross-layer completa | |
| classify -> SulfateVeinClassifier (veio/acido/lixivia) | |
| synthesis -> registra no gap-watch e cruza | |
| outros -> ack | |
| """ | |
| kind = payload.get("kind", "data") | |
| body = payload.get("payload", payload) | |
| if kind == "mesh_series" and isinstance(body.get("series"), dict): | |
| try: | |
| from mars_cross_layer import MarsCrossLayer | |
| except ImportError: | |
| from src.agriculture.mars_cross_layer import MarsCrossLayer | |
| out = MarsCrossLayer().build_mesh( | |
| body["series"], bridges=MarsCrossLayer.STANDARD_BRIDGES) | |
| return {"kind": "mesh_result", "n_edges": len(out["edges"]), | |
| "real_edges": [{"a": e["a"], "b": e["b"], "corr": e["corr"], | |
| "diff": e.get("corr_diff", 0)} | |
| for e in out["edges"] if not e.get("trend_artifact")], | |
| "plausible_bridges": [b["bridge"] for b in out["bridges"] | |
| if b["plausible"]]} | |
| if kind == "classify" and isinstance(body.get("mineralogy"), dict): | |
| try: | |
| from regolith_processor import SulfateVeinClassifier | |
| except ImportError: | |
| from src.agriculture.regolith_processor import SulfateVeinClassifier | |
| r = SulfateVeinClassifier().classify(body["mineralogy"]) | |
| return {"kind": "classify_result", "sample": body.get("sample"), **r} | |
| if kind == "station_forecast": | |
| # projeta stocks N sols a frente por deltas da telemetria recente | |
| stocks = body.get("stocks", {}) or {} | |
| telem = body.get("recent_telemetry", []) or [] | |
| horizon = int(body.get("horizon_sols", 30)) | |
| deltas: Dict[str, float] = {} | |
| if len(telem) >= 2: | |
| prev, cur = telem[-2].get("stocks", {}), telem[-1].get("stocks", {}) | |
| n = max(1, len(telem) - 1) | |
| for k in cur: | |
| if isinstance(cur.get(k), (int, float)) and isinstance(prev.get(k), (int, float)): | |
| first = telem[0].get("stocks", {}).get(k, prev.get(k, 0)) | |
| deltas[k] = (cur[k] - first) / n | |
| proj = {k: round(stocks.get(k, 0) + deltas.get(k, 0) * horizon, 3) | |
| for k in stocks} | |
| return {"kind": "station_forecast_result", "horizon_sols": horizon, | |
| "projected_stocks": proj, | |
| "depleting": [k for k, v in proj.items() | |
| if isinstance(v, (int, float)) and v < 0]} | |
| if kind == "synthesis_probe": | |
| # v21: aceita stocks aninhado OU campos flat; correla nivel E | |
| # 1a-diferenca (detrend) — aresta real exige sinal no fluxo, nao na rampa. | |
| import math as _m | |
| def _corr(x, y): | |
| n = len(x); mx, my = sum(x)/n, sum(y)/n | |
| sx = _m.sqrt(sum((v-mx)**2 for v in x)); sy = _m.sqrt(sum((v-my)**2 for v in y)) | |
| if sx < 1e-12 or sy < 1e-12: return 0.0 | |
| return sum((a-mx)*(b-my) for a, b in zip(x, y)) / (sx*sy) | |
| def _d1(s): return [s[i+1]-s[i] for i in range(len(s)-1)] | |
| telem = body.get("telemetry", []) or [] | |
| series = {} | |
| for t in telem: | |
| items = t.get("stocks") or { | |
| k: v for k, v in t.items() | |
| if isinstance(v, (int, float)) and k not in ("sol", "cycle", "synod")} | |
| for k, v in items.items(): | |
| series.setdefault(k, []).append(float(v)) | |
| series = {k: v for k, v in series.items() if len(v) >= 6} | |
| if not series: | |
| return {"kind": "synthesis_probe_result", "edges": [], "note": "insuficiente"} | |
| keys = sorted(series) | |
| real, trend_only = [], [] | |
| for i in range(len(keys)): | |
| for j in range(i+1, len(keys)): | |
| a, b = keys[i], keys[j] | |
| lvl = _corr(series[a], series[b]) | |
| da, db = _d1(series[a]), _d1(series[b]) | |
| dc = _corr(da, db) | |
| lag1 = _corr(da[:-1], db[1:]) if len(da) > 2 else 0.0 | |
| if abs(dc) >= 0.7 or abs(lag1) >= 0.7: | |
| real.append({"a": a, "b": b, "corr_diff": round(dc, 4), | |
| "lag1": round(lag1, 4), "corr_level": round(lvl, 4)}) | |
| elif abs(lvl) >= 0.9: | |
| trend_only.append({"a": a, "b": b, "corr_level": round(lvl, 4), | |
| "corr_diff": round(dc, 4)}) | |
| return {"kind": "synthesis_probe_result", | |
| "n_series": len(series), "n_points": len(telem), | |
| "real_edges": sorted(real, key=lambda e: -max(abs(e["corr_diff"]), abs(e["lag1"])))[:15], | |
| "trend_only": trend_only[:15], | |
| "note": "v21 detrend: corr_diff=1a-dif, corr_level=nivel, lag1=a lidera b"} | |
| if kind == "o2_batch_plan": | |
| clo4 = float(body.get("perchlorate_kg", 0) or 0) | |
| # rendimento nominal usado pelo simulador: ~0.45 kg O2 por kg ClO4 | |
| batch = min(clo4, 100.0) | |
| return {"kind": "o2_batch_plan_result", | |
| "batch_perchlorate_kg": batch, | |
| "expected_o2_kg": round(batch * 0.45, 2), | |
| "o2_stock_kg": body.get("o2_kg", 0), | |
| "note": "batelada limitada a 100kg ClO4 por seguranca termica"} | |
| if kind == "survey_next_site": | |
| uh = body.get("unit_health", []) or [] | |
| return {"kind": "survey_next_site_result", | |
| "fleet_ready": len(uh), "min_health": min(uh) if uh else None, | |
| "spare_parts_kg": body.get("spare_parts_kg", 0), | |
| "recommendation": "avancar prospeccao no anel sul" } | |
| if kind == "body_maintenance_scan": | |
| layers = body.get("layers", {}) or {} | |
| ranked = sorted(layers.items(), key=lambda kv: -(kv[1].get("wear", 0))) | |
| return {"kind": "body_maintenance_scan_result", | |
| "body_integrity": body.get("body_integrity"), | |
| "maintenance_order": [n for n, _ in ranked], | |
| "worst_wear": ranked[0][1].get("wear") if ranked else None} | |
| if kind == "crop_logistics_plan": | |
| total = (body.get("potatoes_kg", 0) or 0) + (body.get("wheat_kg", 0) or 0) | |
| return {"kind": "crop_logistics_plan_result", | |
| "harvestable_kg": total, "era": body.get("era"), | |
| "note": "priorizar secagem p/ reserva estrategica"} | |
| if kind == "synthesis": | |
| return {"kind": "synthesis_logged", "received": body.get("synthesis"), | |
| "note": "registrado p/ cruzamento futuro"} | |
| return {"kind": "ack", "received": kind} | |
| class MarsDaemon: | |
| """O servidor autonomo que vive na VM do Colab. | |
| Cada ciclo: (1) puxa inbox_local/ novos do OmniMind, (2) roda o trabalho | |
| (malha/sintese/simulacao), (3) grava respostas em inbox_colab/, | |
| (4) checkpointa ao HF se passou o intervalo. | |
| """ | |
| budget_hours: float = 11.5 | |
| checkpoint_every_s: float = 300.0 | |
| bus: _HFBus = field(default_factory=_HFBus) | |
| state: DaemonCheckpoint = field(default_factory=DaemonCheckpoint) | |
| worker: Optional[Callable[[Dict], Dict]] = None # funcao de trabalho | |
| n_workers: int = 8 # Colab Pro: 8 vCPUs | |
| # ---- autodespacho por capacidade (v19): a estacao propoe trabalho p/ si ---- | |
| # Pedido do operador (2026-10-05): a estacao deve submeter jobs/atividades | |
| # pela capacidade que tem — nao so CPU, mas energia, frota ociosa, stocks, | |
| # gaps de dados. Quando sobra, ela dispara analises p/ si mesma. | |
| self_dispatch_every_cycles: int = 25 # avalia a cada N ciclos | |
| self_dispatch_max_per_eval: int = 3 # cap de self-jobs por avaliacao | |
| self_dispatch_cooldown_s: float = 1800.0 # 30 min entre jobs do mesmo kind | |
| _dispatch_last_ts: Dict[str, float] = field(default_factory=dict) | |
| queue: JobQueue = field(init=False) | |
| simulator: StationUnifiedSimulator = field(default_factory=StationUnifiedSimulator) | |
| STATE_PATH = "daemon_state/checkpoint_colab.json" | |
| # legado: caminho antigo compartilhado com o kernel Kaggle (colisao de | |
| # schema — o Kaggle grava station_telemetry no mesmo path) | |
| LEGACY_STATE_PATH = "daemon_state/mars_daemon_checkpoint.json" | |
| def __post_init__(self): | |
| self.queue = JobQueue(self.bus) | |
| # ---- checkpoint soberano ---- | |
| def save_checkpoint(self) -> None: | |
| self.state.rng_state = random.getstate() | |
| self.state.station_snapshot = self.simulator.snapshot() | |
| self.bus.write(self.STATE_PATH, self.state.to_dict()) | |
| self.bus.flush() # checkpoint = ponto de persistencia (1 commit) | |
| def restore_checkpoint(self) -> bool: | |
| d = self.bus.read(self.STATE_PATH) | |
| if d is None: | |
| d = self.bus.read(self.LEGACY_STATE_PATH) | |
| # rejeita checkpoint de outro escritor (Kaggle grava outro schema | |
| # no path legado — restaurar isso misturaria contadores) | |
| if not isinstance(d, dict) or ("rng_state" not in d and "station_snapshot" not in d): | |
| return False | |
| self.state = DaemonCheckpoint.from_dict(d) | |
| if self.state.rng_state: | |
| random.setstate(_deep_tuple(self.state.rng_state)) | |
| if self.state.station_snapshot: | |
| self.simulator.restore_from_snapshot(self.state.station_snapshot) | |
| return True | |
| # ---- um ciclo de trabalho ---- | |
| def run_cycle(self) -> Dict: | |
| st = self.state | |
| st.cycle += 1 | |
| # 1. Avanço da estação no simulador unificado (pontua níveis e produção) | |
| station_step = self.simulator.step() | |
| st.station_snapshot = self.simulator.snapshot() | |
| inbox_new = [f for f in self.bus.list_inbox("local") | |
| if f not in st.processed_inbox] | |
| results = {"cycle": st.cycle, "inbox_consumed": [], "outputs": {}, "station": station_step} | |
| for path in inbox_new: | |
| payload = self.bus.read(path) | |
| if payload is None: | |
| continue | |
| # o trabalho: cruza o payload com o estado (worker injetavel) | |
| out = (self.worker or default_worker)(payload) | |
| resp_path = path.replace("inbox_local/", "inbox_colab/") | |
| self.bus.write(resp_path, {"in_response_to": path, | |
| "cycle": st.cycle, "result": out}) | |
| results["inbox_consumed"].append(path) | |
| st.processed_inbox.append(path) | |
| # puxa jobs remotos submetidos pela bridge e drena em paralelo | |
| self.pull_remote_queue() | |
| # autodespacho (v19): com folga holistica, a estacao submete trabalho p/ si | |
| results["self_dispatch"] = self.capacity_autodispatch() | |
| results["queue"] = self.drain_queue() | |
| # flush oportuno se o buffer encheu (protege rate limit 256 commits/h) | |
| if len(self.bus._pending) >= 20: | |
| self.bus.flush() | |
| st.last_results = results | |
| return results | |
| # ---- despacho da fila em paralelo (8 workers do Colab Pro) ---- | |
| def submit_job(self, kind: str, payload: Dict, job_id: Optional[str] = None) -> str: | |
| import uuid | |
| job_id = job_id or f"{kind}_{int(time.time()*1000)}_{uuid.uuid4().hex[:6]}" | |
| return self.queue.submit(Job(job_id=job_id, kind=kind, payload=payload)) | |
| def pull_remote_queue(self) -> int: | |
| """Importa jobs do HF job_queue/ que ainda nao estao na fila local.""" | |
| pulled = 0 | |
| for path in self._list_prefix("job_queue/"): | |
| d = self.bus.read(path) | |
| if not d or d.get("status") != "queued": | |
| continue | |
| jid = d.get("job_id", path.split("/")[-1].replace(".json", "")) | |
| local = self.queue._local.get(jid) | |
| if local is not None and local.status in ("running", "done", "failed"): | |
| continue # ja despachado nesta sessao | |
| if local is None: | |
| self.queue._local[jid] = Job(job_id=jid, kind=d.get("kind", "job"), | |
| payload=d.get("payload", {}), | |
| submitted_ts=d.get("submitted_ts", 0)) | |
| pulled += 1 | |
| return pulled | |
| def _list_prefix(self, prefix: str) -> List[str]: | |
| return sorted(f for f in self.bus.list_files() if f.startswith(prefix)) | |
| def drain_queue(self) -> Dict[str, int]: | |
| """Executa todos os jobs queued em paralelo no pool de n_workers.""" | |
| queued = [j for j in self.queue._local.values() if j.status == "queued"] | |
| if not queued: | |
| return {"dispatched": 0} | |
| def _run(j: Job) -> None: | |
| self.queue.mark(j.job_id, "running") | |
| try: | |
| self.queue.mark(j.job_id, "done", | |
| (self.worker or default_worker)(j.payload)) | |
| except Exception as e: | |
| self.queue.mark(j.job_id, "failed", {"error": str(e)}) | |
| with ThreadPoolExecutor(max_workers=self.n_workers) as ex: | |
| list(ex.map(_run, queued)) | |
| return {"dispatched": len(queued), **self.queue.counts()} | |
| # ---- autodespacho por capacidade: a estacao trabalha nela mesma ---- | |
| def _compute_slack(self) -> Dict: | |
| """Folga computacional: fila drenada + carga baixa na VM.""" | |
| queued = sum(1 for j in self.queue._local.values() if j.status == "queued") | |
| running = sum(1 for j in self.queue._local.values() if j.status == "running") | |
| try: | |
| load1 = os.getloadavg()[0] | |
| except (OSError, AttributeError): | |
| load1 = 0.0 | |
| return {"queued": queued, "running": running, "load1": load1, | |
| "compute_idle": queued < self.n_workers | |
| and load1 < self.n_workers * 0.6} | |
| def _capacity_rules(self, snap: Dict) -> List[Dict]: | |
| """Tabela de capacidade holistica -> job autogerado. | |
| Cada regra: kind, ok(), payload(), heavy(bool so com compute_idle). | |
| Fallback-safe: .get() em todo campo — snapshot evolui entre versoes. | |
| """ | |
| stocks = snap.get("stocks", {}) or {} | |
| fleet = snap.get("fleet_state", {}) or {} | |
| telem = snap.get("recent_telemetry", []) or snap.get("recent_history", []) | |
| unit_health = fleet.get("unit_health", []) or [] | |
| sol = snap.get("sol", 0) | |
| era = snap.get("era", "?") | |
| return [ | |
| # previsao de horizonte: a estacao sempre ganha projetando a si mesma | |
| {"kind": "station_forecast", "heavy": False, | |
| "ok": lambda: len(telem) >= 5, | |
| "payload": lambda: {"kind": "station_forecast", | |
| "horizon_sols": 30, "stocks": stocks, | |
| "sol": sol, "era": era, | |
| "recent_telemetry": telem[-10:]}}, | |
| # malha cross-layer sobre telemetria recente — o "moe autocuacht" | |
| # analogico: cruzar series reais da propria estacao p/ sintese nova | |
| {"kind": "synthesis_probe", "heavy": True, | |
| "ok": lambda: len(telem) >= 8, | |
| "payload": lambda: {"kind": "synthesis_probe", | |
| "telemetry": telem[-20:], | |
| "sol": sol, "era": era}}, | |
| # batelada de oxigenio: estoque de perclorato justifica planejar | |
| {"kind": "o2_batch_plan", "heavy": False, | |
| "ok": lambda: stocks.get("perchlorate_kg", 0) > 50.0, | |
| "payload": lambda: {"kind": "o2_batch_plan", | |
| "perchlorate_kg": stocks.get("perchlorate_kg", 0), | |
| "o2_kg": stocks.get("o2_kg", 0), | |
| "water_l": stocks.get("water_l", 0)}}, | |
| # frota ociosa/sadia: prospeccao adiantada do proximo sitio | |
| {"kind": "survey_next_site", "heavy": False, | |
| "ok": lambda: (len(unit_health) >= 1 | |
| and min(unit_health) > 0.6 | |
| and fleet.get("spare_parts_kg", 0) > 20.0), | |
| "payload": lambda: {"kind": "survey_next_site", | |
| "unit_health": unit_health, | |
| "spare_parts_kg": fleet.get("spare_parts_kg", 0), | |
| "sol": sol}}, | |
| # manutencao do corpo: integridade abaixo de 90% gera plano | |
| {"kind": "body_maintenance_scan", "heavy": False, | |
| "ok": lambda: snap.get("body_integrity", 1.0) < 0.90, | |
| "payload": lambda: {"kind": "body_maintenance_scan", | |
| "body_integrity": snap.get("body_integrity", 1.0), | |
| "layers": (snap.get("body_state", {}) | |
| .get("layers", {}))}}, | |
| # logistica de colheita: graos/tuberculos em volume | |
| {"kind": "crop_logistics_plan", "heavy": False, | |
| "ok": lambda: (stocks.get("potatoes_kg", 0) | |
| + stocks.get("wheat_kg", 0)) > 800.0, | |
| "payload": lambda: {"kind": "crop_logistics_plan", | |
| "potatoes_kg": stocks.get("potatoes_kg", 0), | |
| "wheat_kg": stocks.get("wheat_kg", 0), | |
| "era": era}}, | |
| ] | |
| def capacity_autodispatch(self) -> Dict: | |
| """Com folga holistica, submete ate self_dispatch_max_per_eval jobs. | |
| Guardas: avalia so a cada self_dispatch_every_cycles ciclos; nunca se a | |
| fila ja tem >= n_workers itens (remotos nunca ficam para tras); cooldown | |
| por kind evita re-submissao do mesmo tipo em rajada; sem duplicata de | |
| kind queued/running. | |
| """ | |
| st = self.state | |
| if st.cycle % self.self_dispatch_every_cycles != 0: | |
| return {"evaluated": False} | |
| slack = self._compute_slack() | |
| if slack["queued"] >= self.n_workers: | |
| return {"evaluated": True, "skipped": "queue_full", | |
| **{k: slack[k] for k in ("queued", "running", "load1")}} | |
| snap = st.station_snapshot or self.simulator.snapshot() | |
| now = time.time() | |
| submitted = [] | |
| for rule in self._capacity_rules(snap): | |
| if len(submitted) >= self.self_dispatch_max_per_eval: | |
| break | |
| if rule["heavy"] and not slack["compute_idle"]: | |
| continue # pesado so com folga real | |
| try: | |
| ok = rule["ok"]() | |
| except Exception: | |
| ok = False | |
| if not ok: | |
| continue | |
| last = self._dispatch_last_ts.get(rule["kind"], 0.0) | |
| if now - last < self.self_dispatch_cooldown_s: | |
| continue # cooldown por kind | |
| dup = any(j.kind == rule["kind"] and j.status in ("queued", "running") | |
| for j in self.queue._local.values()) | |
| if dup: | |
| continue | |
| jid = self.submit_job(rule["kind"], rule["payload"]()) | |
| self._dispatch_last_ts[rule["kind"]] = now | |
| submitted.append(jid) | |
| return {"evaluated": True, "submitted": submitted, | |
| **{k: slack[k] for k in ("queued", "running", "load1")}} | |
| # ---- loop soberano ---- | |
| def run(self, max_cycles: Optional[int] = None) -> DaemonCheckpoint: | |
| """Loop de ~budget_hours com checkpoint periodico. Retoma se restart. | |
| BUG (2026-09-28): elapsed media started_ts+uptime_s RESTAURADOS — | |
| budget cumulativo esgotado fazia o daemon sair no 1o ciclo apos | |
| restart do kernel. Corrigido: budget e POR SESSAO (session_start | |
| local); uptime_s segue acumulando so como telemetria historica.""" | |
| self.restore_checkpoint() | |
| session_start = time.time() | |
| self.state.started_ts = session_start # ancora desta sessao | |
| last_ckpt = session_start | |
| budget_s = self.budget_hours * 3600 | |
| while True: | |
| if max_cycles and self.state.cycle >= max_cycles: | |
| break | |
| if time.time() - session_start >= budget_s: | |
| break | |
| self.run_cycle() | |
| if time.time() - last_ckpt >= self.checkpoint_every_s: | |
| self.save_checkpoint() | |
| last_ckpt = time.time() | |
| self.state.uptime_s += time.time() - session_start | |
| self.save_checkpoint() # checkpoint final — sobrevive a desconexao | |
| return self.state | |