Owner's 27/10 review of the OTel export, four asks, all landed:
1. NAMED IN/OUT PER FUNCTION: fn.done events (fn, in, out) at the
knowledge pipeline's main functions - search (in.query -> out.titles),
fetch, skim, compose, chunk_gate, serve_set, list_ingest, harvest,
promote, check, judge - rendered as spans with in.<arg>/out.<arg>
attributes. "wiki search ('Pedro date take'): [...]" is now
knowledge.search with in.query and out.titles as data.
2. SIGNATURE IN/OUT: the dspy prompt-log callback emits sig.start/sig.done
- the typed fields of every dspy call (in.question, out.entities,
out.facts...). The LLM span and the sig span are one node.
3. CLICKABLE PROMPT: every LLM span carries a child 'prompt' span with
the exact prompt + raw response read from prompts/NN-stage.txt at
export time - retroactive for old runs (the Pedro run re-exports with
128 prompt children).
4. EXPERT NAMES: EXPERT comp spans carry expert= (EXPERT knowledge);
nested spans prefix with the expert (knowledge.search,
knowledge.state, knowledge.TranslateToDSL); each expert exports its
spans under its own OTel service so Jaeger groups by component.
Live-verified end to end: smoke run (glm-5.3-flash) exported while
running - MASK shows in.question -> out.entities [{France, PLACE}],
EXPERT knowledge nests knowledge.TranslateToDSL under service
knowledge; read back via Jaeger's own API. Suite: traces 7/7, all
floop + knowledge test files green (guards/value_clean caught two bugs
in the new emissions before commit: a wrong-scope variable and a
use-before-define; _rec now reads getattr(streams) so __new__ test
fakes survive).
Co-Authored-By: Claude <noreply@anthropic.com>
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).
His diagnosis accepted (26/10): the single-pass EXTRACT's giant typed
JSON array (verbatim quotes + temporal restrictions + sibling orders)
is the output budget behind the 40-minute arithmetic on slow local
models. Two-pass shortens EVERY output:
- Pass 1 ExtractClaims: plain claim strings, coreferences resolved
(entities named, never pronouns) — near-zero format tax.
- Pass 2 TypeClaim: ONE claim -> one typed Fact per call (same Fact
schema the store eats; temporal fields optional, containment-checked
downstream as always). Orders NEVER produced here: one claim at a
time has no siblings — the legacy Fact keeps orders for the
single-pass path and table frags, untouched.
- extract_mode: two_pass (default) | single (legacy) — config-driven,
read from config.yaml's knowledge block by run_app.
- Budget: Pass 1 charges once per chunk; Pass 2 charges once per
claim. Table frags keep the legacy single-pass call.
- Prompt log: CLAIMS/TYPE stage labels added.
TDD: two_pass_extract 5/5 (signatures, coref law, honest empties) +
two_pass_wiring 2/2 (end-to-end on a real store: two_pass ingests
typed facts with windows kept; single-pass control green). Suite: 29
test files green. The router from #26 makes the upcoming
extraction-model swap a pure config edit.
His ask: one general construction door so a signature's model/settings
change by editing config alone — no call-site ifs, now or ever after.
lm[ExtractSignature]: as a config.yaml sibling of lm: (provider:
inherits base_url + transport ceiling; model: builds a dedicated
cached LM; other keys -> per-call lm_kwargs through Predict config,
honored by dspy 3.4.1 _forward_preprocess). predict() is the door: the
13 construction sites swapped mechanically. First block shipped:
ExtractSignature max_tokens=1800 (the 4096 cap was 3x headroom that
only extended the worst case on slow local models — the 40-min
arithmetic). run.log reports active blocks at startup. TDD:
tests/lm_signature_router.py 5/5 (parse, no-block defaults,
settings-only override, dedicated+cached LM, provenance listing).
The bug his log pinned: local EXTRACT died at 2407.3s = 4 attempts x
600s + 7s backoff — dspy's retry loop (default num_retries=3) ran
honestly but every attempt hit the SAME wall: lm15's default read
timeout of 600s (and the silent-ollama proxy in front cuts at its own
READ_TIMEOUT=600 too). Retries can't help when each attempt dies at
the same ceiling — the 27b on a single 3090 legitimately needs
minutes for a long EXTRACT output (his nvidia-smi: 21GB resident,
64k context, ~52% util).
The fix: the ceiling is CONFIG, not code.
- config.yaml: local read_timeout_s=1800 (one honest 30-min attempt),
num_retries=1 (one re-try after a genuine cut, not 3x30min);
ollama-cloud read_timeout_s=300 (glm answers EXTRACT in ~3s),
num_retries=2 (cloud retries are cheap).
- configure_lm forwards read_timeout_s as dspy.LM(timeout=...) —
dspy 3.4.1 routes it to lm15 Timeouts(read/write/pool) — and
num_retries to the retry loop (LMTransportError is retryable).
- run.log first line now reports the ceiling (no more silent 600s
walls — you SEE what will kill a slow call).
- Unset keys -> dspy defaults (600s / retries 3), nothing invented.
Verified on the wire (tests/lm_transport_wire.py): a hang server +
timeout=3 kills the call at 3.1s (not 600s); num_retries=1 gives
exactly 2 attempts (3.2s = 2x1s + backoff). Suite: 21 files green.
Conflict resolutions, the honest way:
- extract/expert gap-step: main's deterministic COMPOSE wins over the
branch's TRANSLATE LLM (main removed it 23/10 with measurement: the
model was putting the ANSWER into retrieval queries). The branch's
_extract_entities contract (question-blind extractor) is fed from
compose's entities.
- tablefrags/semantic tests: restored the branch's adapted versions +
fixed their single-insert sys.path bug (parent.parent resolved to
knowledge/, not code/ — the tests were silently importing MAIN's
expert.py through the venv pth; same class as the run-085457 trap).
The (K5) bug fix (his 24-25/10 session): glm-5.3-flash glues row
citations and glosses onto the judge's value field, killing the ablation
audit silently ("the judge invented it: nothing to ablate") and leaking
LLM prose into typed payloads. Fixed at the judge's output boundary
(_answer_from_rows): trailing-only, marker-anchored cleanup (_clean_value)
that strips the three live citation shapes and survives legitimate
parentheticals ("(PSOE)", "(since 2018)"). The AnswerFromKG value desc
now says what the value must be.
--no-cache CLI flag (his ruling: the dspy disk cache is not a bug, the
default stays; the flag exists for A/B and freshness testing) — builds
dspy.LM with cache=False for the process; verified live: repeated runs
re-run real inference instead of replaying.
Import assert at startup: floop/knowledge SUBMODULE files must resolve
inside this repo's tree. Namespace-package __path__ lies (it recomputes
dynamically and lists every tree), so the check pins the actual module
files (run 085457 was main's pipeline inside the branch worktree, no
signal). Abort loudly, don't log.
His 23/10 weights-tightness audit found the TRANSLATE step composing
search queries from its own knowledge of the entities: 'Pedro Sánchez
2018 investiture President of the Government of Spain' for a term-start
question (the '2018' IS the answer, steered into retrieval from weights),
'Po, Adige, Tiber' proposed as entities for a question that named only
Italy. Measured over every logged TRANSLATE call of runs 22-23/10: 5/10
calls carried untraceable query terms, 6/10 untraceable entity terms.
Probed against real Wikipedia before deciding: queries composed
deterministically from question ∪ evidence put the decisive article at
top-1/2 of the search in 8 of 9 cases — the LLM's world knowledge was
never load-bearing; the search engine's own relevance was. So the step
becomes code (the law: LLMs translate, fixed code composes — and here
nothing is left to translate).
- NEW knowledge/queries.py: compose_queries() + proper_nouns/keywords
(moved here, single source — the expert delegates). Laws: every query
token traces to the question or an evidence row; deterministic; never
empty. Top-N asks slice the FIRST N evidence members by source order
(never dump all members); enumerations with one subject NE get the
list-article shape ('List of rivers of Italy'); sentence-initial
capitals are dropped when other NEs exist ('During', 'Ranked').
- DELETED TranslateSignature + the Predict + the stage map entry;
the gather charges one LLM call less.
- expert.py: COMPOSE at the gather head; the context var (rendered
only for the dead prompt) removed — evidence feeds the probe seeds,
the composer and the guards directly.
- Tests: knowledge/tests/queries.py (12) — the sonde's cases as the
contract, incl. the traceback law over the logged questions.
- DESIGN.md §4 + code/README honest map updated.
Suite 17/17. Live probe (real Wikipedia): rivers/Pedro/France/Po all
fetch the decisive article at top-1.
Implements his design (RESEARCH-semantic-kg.md) on the research branch:
1. EMBEDDINGS (knowledge/embeddings.py): local ollama /api/embed,
nomic-embed-text 768d — the only proven endpoint (ollama.com has
NO embeddings API). Honest failure: EmbedderDown -> lexical probe
fallback, never a dead run.
2. SEMANTIC PROBE: edge_vectors cache in the store (keyed edge_id +
model + text_hash; upsert, last model wins), cosine rank over all
cached edges, tau=0.45 from real calibration (rivers 0.49-0.52 must
pass; cross-question Pedro-vs-rivers 0.35-0.38 must not). Hybrid
_probe: lexical UNION semantic, dedup by eid. EdgeView gains eid.
3. QUESTION-BLIND EXTRACTION: ExtractSignature loses 'question' and
stop_table — it receives ENTITIES only (from TRANSLATE + evidence
+ proper nouns) and transcribes their facts, capped per chunk
(max_facts_per_chunk=12). Facts cache vectors at ingest. The KG
fattens per-entity, reusable across questions (his cacheability
argument).
4. STOP MOVES TO THE SKIM: SkimTableSignature decides per table from
caption+header+row count+first rows (one LLM call per page) BEFORE
any extraction spend; tables that literally name an entity skip the
call. The extractor itself never judges relevance.
VERIFIED: knowledge suite 8/8 (semantic.py new 4/4: lexical-missed edge
surfaced, hybrid dedup, embedder-down degradation, cache upsert;
tablefrags adapted: skim kills tables pre-extract). floop suite 9/9.
Live E2E (glm): semantic probe fires live (+1 lexical-missed edge);
blind extractor ingests 12-fact chunks; Pedro run answers 'himself'
(3rd gov succeeded his 2nd — a reading trap, NOT a retrieval failure;
INIT degraded honestly on garbage); rivers run burned budget on
fan-out ROUTE calls (22x2) — both findings logged as open work on the
research doc, not regressions of this PR.
The model was using its own knowledge of the people in the question
to decide decomposition (his qwen collapsed Pedro Sanchez to ONE
subquestion: 'the question is nearly atomic because I know who he
is'). Structural fix: INIT sees the question's SHAPE, not identity.
- EntityMaskSignature (typed NER proposal): entities as list[NamedEntity]
(name verbatim + kind) — the typed-output law, no string parsing
- apply_mask/restore_mask: DETERMINISTIC code (LLMs propose, code
applies): longest names first, one placeholder per surface text,
typed prefixes PERSON_1/ORGANIZATION_1/..., restore longest-first
(PERSON_10 never eaten by PERSON_1)
- init_decompose: mask -> INIT -> restore in each returned subquestion;
MASK finding no entities OR dying (AdapterParseError) -> passthrough,
never a dead run
- MASK stage in the prompt log (prompts/01-MASK.txt)
VERIFIED: tests/anonymize.py 4/4 (deterministic apply/restore, E2E
mask+restore, no-entity passthrough, mask-death passthrough); suite
15/15. Live E2E (glm-5.3-flash): MASK found exactly Pedro Sanchez
(reasoning explicitly excluded 'President' as a role, not entity);
INIT saw 'Who was the President before PERSON_1?' and returned FOUR
subquestions (identity, office, term start, predecessor) — the shape
split he wanted, plus a 'who is PERSON_1' question; run answers Rajoy
correctly (E1-E4).
OPEN (his question pending): the model now asks WHO the placeholder
is, spending one call per run. Options: (a) keep, (b) desc note that
placeholders are known entities, (c) give INIT the masked question PLUS
the original as context. Not decided — he answers when back.
Two fixes from his 22/10 re-run log, both small and deterministic:
1. THE ABLATION MASK WAS QUOTE-BLINDED (run L: Q1 stayed silent over
the Pedro page that run J flags). The Pedro paragraph interleaves
all three readings in ONE quote ('...Secretary-General ... ninth
president of Socialist International...'), and _carries matched
the picked value by substring over dst OR quote — so masking SI's
support masked the PM/PSOE rows too; round 1 answered UNKNOWN and
the audit died silent. The DST-FIRST LAW: when a row has a
meaningful dst (non-empty, non-numeric) it is the VALUE BEARER and
the mask matches IT; the quote is a fallback only for
empty/numeric dsts. Same law in _carries_target for each round's
surviving value, with one addition: the judge's round value may be
an OFFICE DESCRIPTION ('prime minister of Spain') while the row's
dst is the ENTITY ('Spain') — resolve by reciprocal token
containment, or the loop dies after one alternative.
2. THE ADAPTER RE-ASK WAS INVISIBLE TO THE BUDGET (run L: prompts #9
and #10 were both ANSWER — #10 5 chars shorter, 340s, the
ChatAdapter's JSON-fallback second wire call after a parse
failure; llm_calls said 9/80 while 10 hit the wire). THE METER:
the prompt-log callback already sees every LM call — a second LM
call with NO new module forward between them is the adapter
fallback re-firing inside the same Predict. Count it, log the
line, and charge the budget through a meter hook the machine
wires at construction. A re-ask at the ceiling does not kill the
run (the call already happened). dspy's BEHAVIOUR IS UNTOUCHED —
his call: the fallback stays, it is future self-improvement
signal (which prompts the model formats badly), not a bug.
Tests: knowledge/tests/ablation.py +3 — run-L regression (interleaved
one-paragraph quote flags all three readings), office-description
resolution, numeric-dst quote fallback. tests/reask_meter.py +3 —
fallback detected and charged on the REAL adapter path (custom engine
returning raw text, marker-less first response), separate forwards NOT
flagged (the ablation-rounds shape), ceiling charge survives. Suite
12/12 files green (74 tests). Live smokes: the run-L interleaved-quote
page flags SI+PM+SG through the full pipeline; the run-J
separate-quotes smoke still passes.
Run I ('Who was the President before Pedro Sanchez?'): the INIT LM wrote
its own line numbers as an extra first pipe field ('1 | Who was... |
none | OPEN'), the naive parse took '1' as the subquestion text, ROUTE
classified Q1='1' as numeric, and the machine burned four calls on
garbage before luck produced the answer. Two of the fixes close the same
observability gap that hid the root cause for a day.
1. PARSER (parse_subquestions): shifts the numbered form (>=4 fields
with a bare number first) and drops any text that is a bare number —
a routable question is text, never '1'. Enumerator prefixes ('1.')
inside the text field are stripped. Well-formed lines parse exactly
as before (regression-tested).
2. INIT DEGRADE (machine): init_decompose now returns (subs, raw).
Non-empty raw that parses to nothing = model garbage — degrade to
the ORIGINAL question as one OPEN subquestion (routable, logged,
budget-safe). Empty raw keeps the old law: the question is atomic,
stop and synthesize — never fabricate a subquestion.
3. RAW RESPONSE LOG (the ask behind the ask): prompts/NN-stage.txt now
carries the exact LM response after the prompt. Run I's parsed
'OUTPUT INIT: 1\n2' could not show what the model actually wrote —
the raw text is in the file from now on; the log stays line-based.
Tests: tests/robust_init.py — the numbered form, bare-number drop,
enumerator strip, happy-path regression, the degrade, the atomic stop,
raw-response capture. Suite 59/59. Smoke: the exact run-I transcript
replayed through the real machine (DummyLM) parses to Q1/Q2 real
subquestions and answers Mariano Rajoy.
Run G hung at call 8/80 for minutes with no way to see what was sent.
Reproducing it found TWO root causes, both fixed here:
1. THE 22K TABLE CHUNK WAS A PARSER BUG, not just a size problem. The
world-rivers table marks each data row's leading cell with
'!scope="row"|' (a row-label th); parse_tables flagged any row that
touched a '!' as a header row, so all 227 data rows collapsed into ONE
header of 1,825 cells and zero rows. tables_as_text then flattened
that monster into a single 22,021-char prose chunk. Fix: a row is a
header row only if ALL its cells are '!' cells; mixed rows are data
rows. Live: the world table now parses as 8 cols x 227 rows.
2. NO PROMPT OBSERVABILITY. The log's CALL/OUTPUT lines never carried
what the LM actually received. floop/llm.py now installs a dspy global
callback (PromptLogCallback): every LM call's exact rendered prompt
lands in runs/<ts>/prompts/NN-stage.txt (NN mirrors the budget counter
-- 08-EXTRACT.txt IS call 8/80), plus size/duration lines in run.log.
Stage comes from a module stack (dspy fires on_module_start with a
DIFFERENT call_id than the inner LM call -- verified with DummyLM
probes), not a call_id map.
Plus the design Emili steered (tables reach the extractor as typed
fragments, never prose dumps):
- tables_as_chunks: per-table fragments of <=40 rows, EVERY fragment
repeats header + caption, part i/N markers; the extractor always knows
which table ('troç 2/10') it is reading.
- STOP_TABLE: the extractor may early-skip a table whose subject is
wrong for the question after one fragment; fixed code skips the rest
of THAT table. ExtractSignature teaches the protocol.
- fetch_rich no longer appends the '== Tables ==' enrichment to prose
(the giant chunk's birthplace; also let verify_count cite the table as
'prose'). Tables reach the extract path only as fragments; LIST and
harvest keep reading page.tables directly.
- fragment candidates pass the same containment check against prose +
full table text; LIST answer's table never re-enters extract.
Tests: knowledge/tests/tablefrags.py (fragment generation/render,
STOP_TABLE skipping, fragment extraction with containment, prompt log
files + log lines). Live smoke: world article 10 chunks none >5k; world
table = 6 fragments (max 5,787c); Italy discharge fragment intact
(Po/1540). Full suite 47/47.
Per Emili 2026-10-16: the draft experts are baseline experts - the LLM answers each subquestion directly from its own knowledge (no verification yet; engines replace the baseline path per expert later). ExpertSignature no longer forbids weights-based answers; source_quote now means verbatim from GIVEN evidence, empty when answering from weights. Evidence rows record source: model_weights | given_evidence. --baseline mode: the same LM answers the whole question in ONE raw call - the A/B control against the loop's many small directed calls. Also: pyproject fixed (name floop, hatchling backend, package floop/) - uv_build expected src/ layout; runner docs now uv-first; uv.lock regenerated.