Files
floop/code/run_app.py
onibot d384a10a8d feat: flight recorder — events.jsonl for post-mortem debugging
Owner ruling (26/10): 'vull poder fer com un debug amb l'IDE de
programació, però a posteriori de l'execució' — see WHERE inside which
expert we are at every moment, and the input/output of every component,
LLM or not. This is the recorder half (PR A of the observability plan).

- floop/recorder.py: append-only JSONL, one event per line. LAWS:
  never breaks a run (emitting is swallowed; no run dir = TOTAL no-op,
  no buffer, no counters); every line self-describing (seq, ts, run_ts,
  event, payload); in/out carry structured data, the exact prompt text
  stays in prompts/NN-stage.txt (events stay small).
- Wired via RunStreams (every component already had streams):
  comp.start/comp.out (machine stages INIT/ROUTE/EXPERT/ANSWER/FINAL),
  state, llm.done (stage, dur_s, call_seq, prompt file link — from the
  dspy callback), run.final.
- Knowledge pipeline components (floop-internal nodes, not LLMs):
  probe.done (seeds, rows, tau, semantic adds), claims.done (the claim
  list), type.done (claim -> typed fact, one per claim as ruled),
  fact.merged / fact.rejected (one per fact — _ingest_candidate is
  called per fact; verdict + reason + page), prover.done (dsl, verdict:
  invalid_dsl/no_closed_path/closed/ambiguous, bindings), kg.snapshot
  (once at run end: every edge with temporal window + last_touch from
  this run's merge events).
- kg_snapshot(): rows annotated with their last-touch event (owner:
  'cada fila del kg podria tenir anotat quan s'afegeix o edita').

Live-checked: baseline run writes real events (comp.start, llm.done
dur_s=17.35, comp.out '4'). TDD: recorder 3/3; suite 31 files green.

Next (PR B): floop-inspect — the HTML debugger reading events.jsonl
(timeline Gantt, KG view, facts table, probe view).
2026-10-27 07:42:23 +01:00

175 lines
8.0 KiB
Python

#!/usr/bin/env python3
"""Run the floop draft on a question.
uv run run_app.py "Per què el cel és blau?" # log only
uv run run_app.py --verbose "Per què el cel és blau?" # + thinking on screen
uv run run_app.py --baseline "Per què el cel és blau?" # raw LLM, one call (A/B comparison)
uv run run_app.py --no-cache "..." # dspy response cache OFF for this run
FLOOP_LM=ollama-cloud uv run run_app.py "..."
Always: runs/<ts>-<slug>/run.log written with flush -> `tail -f` it from another
terminal. With --verbose, the "thinking" stream (the future floop-as-LLM thinking
output — a subset of the log) also prints to the screen, flushed.
"""
from __future__ import annotations
import sys
import time
from pathlib import Path
import yaml
sys.path.insert(0, str(Path(__file__).resolve().parent))
from floop.llm import configure_lm, install_prompt_log # noqa: E402
from floop.machine import FloopRun, RunReport # noqa: E402
from floop.state import Budget # noqa: E402
from floop.stream import RunStreams # noqa: E402
def run_baseline(question: str, streams: RunStreams) -> str:
"""The A/B control: the raw LM answers in ONE call — no decomposition, no
experts, no evidence. Same LM, same budget unit (1 call) as the loop's init."""
from floop.llm import active_lm
streams.call("BASELINE", f"single raw LM call: {question[:80]}",
think=f"raw LM: {question[:90]}")
t0 = time.time()
raw = active_lm()(messages=[{"role": "user", "content": question}])
first = raw[0] if isinstance(raw, list) else raw.outputs[0]
answer = first["text"] if isinstance(first, dict) and "text" in first else first.get("content") or str(first)
dt = round(time.time() - t0, 1)
streams.output("BASELINE", answer)
streams.log(f"baseline time={dt}s")
return answer
def _assert_local_imports(code_dir: Path) -> None:
"""Abort loudly if floop/knowledge resolve OUTSIDE this repo's tree.
The shared venv carries an editable-install .pth pointing at another
checkout, and a poisoned PYTHONPATH (shim importing knowledge.* first)
pins SUBMODULES to another tree even when the package __path__ lists
this one — a namespace package recomputes __path__ dynamically, so
checking the package proves nothing (run 085457, 25/10: main's pipeline
ran inside the branch worktree with zero signal). Check the FILES the
run actually executes. A wrong import tree invalidates the run; refuse
it, don't log it.
"""
root = str(code_dir.resolve())
for name, relpath in (("floop", "machine.py"), ("floop", "llm.py"),
("knowledge", "expert.py"), ("knowledge", "store.py")):
try:
mod = __import__(f"{name}.{relpath[:-3]}", fromlist=[""])
except ImportError as e: # pragma: no cover — broken install, abort anyway
raise SystemExit(f"ABORT: cannot import {name}.{relpath[:-3]}: {e}")
loaded = str(Path(mod.__file__).resolve())
if not loaded.startswith(root):
raise SystemExit(
f"ABORT: module '{name}.{relpath[:-3]}' resolved outside this repo\n"
f" repo: {root}\n"
f" loaded: {loaded}\n"
"The venv's editable .pth or PYTHONPATH shadows this tree — "
"the run would test the WRONG code. Fix sys.path and retry.")
def main() -> None:
args = sys.argv[1:]
verbose = "--verbose" in args
baseline = "--baseline" in args
no_cache = "--no-cache" in args
args = [a for a in args if a not in ("--verbose", "--baseline", "--no-cache")]
if not args:
print(__doc__)
sys.exit(1)
question = " ".join(args)
code_dir = Path(__file__).resolve().parent
_assert_local_imports(code_dir) # the editable-pth trap: wrong tree = invalid run
cfg = yaml.safe_load((code_dir / "config.yaml").read_text())
b = cfg["budget"]
budget = Budget(max_llm_calls=b["max_llm_calls"], max_depth=b["max_depth"],
max_retries=b["max_retries"], missing_extensions=b["missing_extensions"],
min_child_budget=b["min_child_budget"])
lm_info = configure_lm(no_cache=no_cache)
streams = RunStreams(question, verbose=verbose, runs_dir=code_dir / "runs")
install_prompt_log(streams) # every LM call's exact prompt -> prompts/NN-stage.txt
streams.log(f"lm={lm_info['provider']}/{lm_info['model']} verbose={verbose} "
f"baseline={baseline} no_cache={no_cache} "
f"read_timeout_s={lm_info.get('read_timeout_s')} "
f"num_retries={lm_info.get('num_retries')}")
from floop.llm import signature_overrides
ov = signature_overrides()
if ov:
streams.log(f"signature_overrides: "
+ ", ".join(f"{name}[{', '.join(f'{k}={v}' for k, v in blk.items())}]"
for name, blk in sorted(ov.items())))
if baseline:
answer = run_baseline(question, streams)
streams.close()
print(f"goal: {question}")
print(f"lm: {lm_info['provider']} / {lm_info['model']} | mode=baseline (raw LLM, 1 call)")
print("\nraw LM answer:")
print(answer)
print(f"\nrun log: {streams.run_dir / 'run.log'}")
return
# knowledge expert: real pipeline when enabled, baseline LLM otherwise
knowledge_engine = None
if cfg.get("knowledge", {}).get("enabled", False):
try:
from knowledge.expert import KnowledgeExpert, KnowledgeConfig
from knowledge.store import KnowledgeStore
from floop.engine import KnowledgeEngine, LLMExpertEngine
kcfg = cfg["knowledge"]
kconfig = KnowledgeConfig(
kb_path=str(code_dir / kcfg.get("kb_path", "knowledge_store/kg.sqlite")),
max_articles=kcfg.get("max_articles", 2),
max_search_results=kcfg.get("max_search_results", 4),
max_chunks_extracted=kcfg.get("max_chunks_extracted", 6),
chunk_chars_target=kcfg.get("chunk_chars_target", 32000),
chunk_chars_cap=kcfg.get("chunk_chars_cap", 48000),
extract_mode=kcfg.get("extract_mode", "two_pass"),
)
ke = KnowledgeExpert(config=kconfig, streams=streams)
knowledge_engine = KnowledgeEngine(ke)
streams.log(f"knowledge pipeline enabled (kb={kconfig.kb_path})")
except Exception as e: # noqa: BLE001 — degrade honestly, never die at startup
streams.log(f"knowledge pipeline disabled: {e}")
knowledge_engine = None
try:
report: RunReport = FloopRun(question, budget, streams=streams,
knowledge_engine=knowledge_engine).run()
finally:
# THE FLIGHT RECORDER CLOSE-OUT: the KG snapshot (owner 26/10:
# one snapshot at the end, each row annotated with its last-touch
# event) and the recorder's file handle. Best-effort: the report
# has already been produced; observability never kills a run.
try:
if knowledge_engine is not None and streams is not None:
streams.recorder.emit("kg.snapshot",
kg=knowledge_engine.ke.kg_snapshot())
except Exception: # noqa: BLE001
pass
streams.close()
print(f"goal: {report.goal}")
print(f"lm: {lm_info['provider']} / {lm_info['model']} | llm_calls={report.llm_calls} "
f"engines={report.engine_calls} depth={report.depth} time={report.elapsed_s}s")
if report.notes:
print("notes: " + "; ".join(report.notes))
print("\nquestions:")
for qid, status, text in report.questions:
print(f" {qid} [{status}] {text}")
print("\nevidence:")
for line in report.evidence_rows:
print(f" {line}")
print(f"\nfinal answer [{'VERIFIED' if report.verified else 'UNVERIFIED'}]:")
print(report.final_answer or "(no answer produced)")
print(f"\nrun log: {streams.run_dir / 'run.log'} (tail -f it next time)")
if __name__ == "__main__":
main()