File size: 6,738 Bytes
72c7148
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
"""Runtime side of the MacJev gate: the ONE place the product builds the gate state and question.

``mac_laya.assistant`` is owned by another work stream and is not edited here; RUNTIME_PATCH.md holds
the ready-to-apply diff that routes ``Assistant.decide_step`` and the planner's ``done`` step through
this module. Training data (``macjev.builders.mac_gate``) builds states with the same
``macjev.mac.view.gate_state`` call, so the deployed input and the training input cannot drift.

What it does
* ``stamped(history)``: copies of the history entries with ``at_unix`` = first time the loop saw them
  (side table; the runtime's own dicts are untouched), so the view can show ``age_s``
  (window snapshots expire after 120 s).
* ``gate_call(engine, goal, observation, action)``: scope-relative view of the FULL history within a
  ~20K-token budget (gate.HISTORY_TOKEN_BUDGET; explicit truncation markers, oldest results dropped last and counted), the gate
  question from ``macjev.mac.gate``, fallback budgets on an input-budget error (never a silent cut),
  and one JSON line per call in ``runs/macjev/gate_log/<date>.jsonl`` (state, question, answer).
* ``goal_done_shadow(engine, goal, observation, action)``: the shadow "goal satisfied?" (noul)
  question when the planner proposes ``done``. The answer is logged only; it never ends a task.
"""
from __future__ import annotations

import collections
import json
import threading
import time
from pathlib import Path
from typing import Any, Callable

from macjev import paths

from . import gate, view

GATE_LOG_DIR = paths.RUNS_V3 / "gate_log"
_lock = threading.Lock()


_RECEIPTS: "collections.OrderedDict[int, tuple[dict, float]]" = collections.OrderedDict()
_MAX_RECEIPTS = 20000


def stamped(history: list, now: float | None = None) -> list:
    """Copies of the history entries with ``at_unix`` = when this module first saw each entry.

    The runtime's own entries are not modified (the planner's input stays byte-identical); receipt
    times are kept in a bounded side table keyed by object identity (the loop appends one result
    and then plans again, so "first seen" is the receipt time to within one step).
    """
    now = time.time() if now is None else now
    out = []
    with _lock:
        for entry in history:
            if not isinstance(entry, dict):
                out.append(entry)
                continue
            if "at_unix" in entry:
                out.append(entry)
                continue
            known = _RECEIPTS.get(id(entry))
            if known is None or known[0] is not entry:
                known = (entry, now)
                _RECEIPTS[id(entry)] = known
                while len(_RECEIPTS) > _MAX_RECEIPTS:
                    _RECEIPTS.popitem(last=False)
            out.append({**entry, "at_unix": known[1]})
    return out


def _counter(engine) -> Callable[[str], int]:
    tok = getattr(engine, "tokenizer", None)
    if tok is not None:
        try:
            tok("probe", add_special_tokens=False)
            return lambda text: len(tok(text, add_special_tokens=False)["input_ids"])
        except Exception:  # pragma: no cover - engine without a HF tokenizer
            pass
    return view.approx_tokens


def _budget_errors() -> tuple:
    errors: list = []
    for module, name in (("mac_laya.model", "InputBudgetError"), ("macjev.render", "InputBudgetError")):
        try:
            errors.append(getattr(__import__(module, fromlist=[name]), name))
        except Exception:  # pragma: no cover - optional engines
            continue
    return tuple(errors) or (ValueError,)


def build_state(goal: str, observation: dict, action: Any, *, budget: int = gate.HISTORY_TOKEN_BUDGET,
                count_tokens: Callable[[str], int] | None = None, now: float | None = None) -> dict:
    return view.gate_state(goal, observation, action, now=time.time() if now is None else now,
                           budget_tokens=budget, count_tokens=count_tokens)


def log_call(record: dict, directory: Path | None = None) -> Path:
    directory = directory or GATE_LOG_DIR
    directory.mkdir(parents=True, exist_ok=True)
    path = directory / (time.strftime("%Y-%m-%d") + ".jsonl")
    line = json.dumps(record, ensure_ascii=False, allow_nan=False, default=str)
    with _lock, path.open("a") as stream:
        stream.write(line + "\n")
    return path


def _ask_engine(engine, goal, observation, action, question, kind, log, log_dir):
    count = _counter(engine)
    errors = _budget_errors()
    for budget in gate.FALLBACK_BUDGETS:
        state = build_state(goal, observation, action, budget=budget, count_tokens=count)
        started = time.monotonic()
        try:
            decision = engine.decide(state, question)
        except errors as error:
            if log:
                log_call({"at_unix": time.time(), "kind": kind, "status": "input_budget_error", "budget": budget,
                          "error": str(error), "view": view.view_meta(state, count)}, log_dir)
            continue
        if log:
            log_call({"at_unix": time.time(), "kind": kind, "status": "ok", "budget": budget, "view_version": gate.VIEW_VERSION,
                      "state": state, "question": question, "answer": decision.get("answer"),
                      "probabilities": decision.get("probabilities"), "model": decision.get("model"),
                      "latency_ms": decision.get("latency_ms", (time.monotonic() - started) * 1000),
                      "view": view.view_meta(state, count)}, log_dir)
        return {**decision, "gate_budget_tokens": budget, "gate_view": view.view_meta(state, count)}
    return None


def gate_call(engine, goal: str, observation: dict, action: dict, *, log: bool = True, log_dir: Path | None = None):
    """execute / inspect / ask for one proposed step; None when even the smallest budget does not fit."""
    return _ask_engine(engine, goal, observation, action, gate.gate_question(), "gate", log, log_dir)


def goal_done_shadow(engine, goal: str, observation: dict, action: dict, *, log_dir: Path | None = None):
    """Shadow question when the planner proposes ``done``: logged only, never returned to the caller's control flow."""
    try:
        decision = _ask_engine(engine, goal, observation, action, gate.goal_done_question(), "goal_done_shadow", True, log_dir)
    except Exception as error:  # the shadow must never break a task
        log_call({"at_unix": time.time(), "kind": "goal_done_shadow", "status": "error", "error": f"{type(error).__name__}: {error}"},
                 log_dir)
        return None
    return None if decision is None else {"answer": decision.get("answer"), "probabilities": decision.get("probabilities")}