Compare commits
14
Commits
fix/no-claim-cap
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3d541ec8d6 | ||
|
|
4e7229c92c | ||
|
|
72ebe44053 | ||
|
|
bc543459c7 | ||
|
|
77fef0a499 | ||
|
|
12fb3c78b2 | ||
|
|
a007e8da25 | ||
|
|
1af308ae60 | ||
|
|
6ea769b7d1 | ||
|
|
d6c5bed443 | ||
|
|
e365f6d1e8 | ||
|
|
9f2fbd711c | ||
|
|
d384a10a8d | ||
|
|
86af2c968d |
+50
-12
@@ -260,7 +260,7 @@ branches compete for budget, a learned router earns its place (v2).
|
|||||||
becomes data-driven. v1's logs — enriched by meta-level critiques — are v2's training
|
becomes data-driven. v1's logs — enriched by meta-level critiques — are v2's training
|
||||||
data, and the same data feeds prompt optimization and fine-tuning (META.md).
|
data, and the same data feeds prompt optimization and fine-tuning (META.md).
|
||||||
|
|
||||||
## 9-bis. Observability roadmap (future plan): OpenTelemetry
|
## 9-bis. Observability (2026-10-27): OpenTelemetry export, BUILT
|
||||||
|
|
||||||
Today a run's observability is files: `runs/<ts>/run.log` (the line-based technical
|
Today a run's observability is files: `runs/<ts>/run.log` (the line-based technical
|
||||||
superset), `prompts/NN-stage.txt` (every exact rendered prompt + raw response), and the
|
superset), `prompts/NN-stage.txt` (every exact rendered prompt + raw response), and the
|
||||||
@@ -268,19 +268,57 @@ WARNING channel (machine judgements worth a human's eye — the mask seed that
|
|||||||
auto-answered a question, guards refusing ingests, budget starvation). This is complete
|
auto-answered a question, guards refusing ingests, budget starvation). This is complete
|
||||||
but closed: reading it means tailing files.
|
but closed: reading it means tailing files.
|
||||||
|
|
||||||
**Planned, not built:** export the run as **OpenTelemetry** traces/spans so floop is
|
**BUILT (post-mortem half):** the run exports as **OpenTelemetry** traces/spans
|
||||||
observable from the standard tooling that already exists — Jaeger, Grafana Tempo,
|
(`floop/traces.py`), so floop is observable from the standard tooling that already
|
||||||
any OTLP consumer — instead of floop growing its own dashboards. The mapping is
|
exists — Jaeger (running on the agentvps as a docker container), Grafana Tempo, any
|
||||||
natural: one run = one trace; each LLM call, engine step (probe, search, fetch, check,
|
OTLP consumer — instead of floop growing its own dashboards. The mapping is the
|
||||||
merge) and evidence append = one span, carrying the fields the logs carry today
|
natural one: one run = one trace; each LLM call, engine step (probe, search, fetch,
|
||||||
|
check, merge) and evidence append = one span, carrying the fields the logs carry today
|
||||||
(stage, budget tick, duration, prompt-file pointer, verification flags, warnings).
|
(stage, budget tick, duration, prompt-file pointer, verification flags, warnings).
|
||||||
The planned `events.jsonl` (machine-readable event stream) becomes the in-process
|
`events.jsonl` (the flight recorder's machine-readable event stream) is the single
|
||||||
event bus this exporter reads — one schema, two consumers (offline self-analysis in
|
schema with two consumers: offline self-analysis in META.md, and `python -m
|
||||||
META.md, live OTel export). Warnings export as span events first-class, since they are
|
floop.traces <run_dir>` replaying it into Jaeger over OTLP/HTTP after the run — the
|
||||||
the self-improvement signal the lessons bank counts.
|
run itself never touches the network (observability never kills a run). Warnings
|
||||||
|
export as span attributes/events first-class, since they are the self-improvement
|
||||||
|
signal the lessons bank counts.
|
||||||
|
|
||||||
Deferred until the loop hardening is done — building it before v1's shape settles
|
Conventions the exporter keeps:
|
||||||
would instrument a moving target.
|
- Deterministic trace ids (sha of the run dir name) — the same run always maps to
|
||||||
|
the same trace id, so UI links are stable and a re-push finds the same trace.
|
||||||
|
- The root span is named by the run's question and carries the final answer as an
|
||||||
|
attribute; the trace list in Jaeger reads as a list of questions.
|
||||||
|
- Recursive child runs (recursive floop as an expert attendant) write the SAME
|
||||||
|
events.jsonl with their own run_ts; each child-run block becomes its own span
|
||||||
|
nested under the spawning component, so the fractal recursion is visible as
|
||||||
|
nesting, and `seq` restarting is expected (positions, not seq, identify spans).
|
||||||
|
- `ts` is local wall time without a date; the date comes from the run dir name,
|
||||||
|
and a backwards jump means midnight crossed. The clock is only ever fed in
|
||||||
|
emission order — pre-reading a later event poisons the midnight detector.
|
||||||
|
|
||||||
|
Owner's visibility laws (27/10, this PR) — inputs and outputs are data, not
|
||||||
|
prose:
|
||||||
|
- Every pipeline function emits `fn.done` (fn, in, out) with NAMED arguments:
|
||||||
|
in.query / out.titles for the Wikipedia search, in.title / out.{url, chars,
|
||||||
|
tables} for the fetch, in.question / out.{value, confidence} for the judge,
|
||||||
|
compose, skim, chunk_gate, serve_set, list_ingest, harvest, promote, check.
|
||||||
|
- Every dspy call emits `sig.start` (the Signature's input fields, named:
|
||||||
|
in.question, in.entities...) and `sig.done` (the typed output fields:
|
||||||
|
out.entities, out.facts, out.value...) — emitted by the prompt-log callback,
|
||||||
|
which sees the module forward; the LLM span and the sig span are the SAME
|
||||||
|
node (name = stage, attributes carry in.*/out.* plus dur/call_seq/file).
|
||||||
|
- The exact prompt + raw response live in a CHILD `prompt` span of every LLM
|
||||||
|
span, read from the prompts/ file at export time — clickable in Jaeger,
|
||||||
|
works retroactively for old runs.
|
||||||
|
- EXPERT component spans carry the attendant's name (EXPERT knowledge);
|
||||||
|
everything nested inside carries the expert prefix (knowledge.search,
|
||||||
|
knowledge.state, knowledge.TYPE), and each expert exports its spans under
|
||||||
|
its own OTel service (floop / knowledge / ...) so Jaeger groups and colors
|
||||||
|
by component.
|
||||||
|
|
||||||
|
**Still deferred:** the in-process LIVE export (an OTLP exporter listening on the
|
||||||
|
event bus during the run, so Jaeger shows the waterfall while the run is still
|
||||||
|
going). Same schema, second consumer — build when a live run is actually observed
|
||||||
|
from outside; the hardening of the loop has priority.
|
||||||
|
|
||||||
## 10. Risks
|
## 10. Risks
|
||||||
|
|
||||||
|
|||||||
@@ -418,3 +418,97 @@ PR-1 skim surfaces + unit-pattern signals + chunk ranking + {{cvt}} unit
|
|||||||
fix; PR-2 opportunistic harvest + seen-index + link queue; PR-3 skim
|
fix; PR-2 opportunistic harvest + seen-index + link queue; PR-3 skim
|
||||||
notices to the machine. The lucky same-article case is NOT the design
|
notices to the machine. The lucky same-article case is NOT the design
|
||||||
target — the goal-aware harvest is.
|
target — the goal-aware harvest is.
|
||||||
|
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Tooling — OTel traces + Jaeger (2026-10-27, no run)
|
||||||
|
|
||||||
|
**Not a run — the observability half of the owner's 26/10 ruling** ('vull
|
||||||
|
poder fer com un debug amb l'IDE de programació, però a posteriori de
|
||||||
|
l'execució'): the flight recorder's `events.jsonl` now exports as
|
||||||
|
OpenTelemetry, and the viewer is Jaeger instead of a hand-grown report.
|
||||||
|
|
||||||
|
**What was built:**
|
||||||
|
- `floop/traces.py` (stdlib only): one run = one trace (deterministic id =
|
||||||
|
sha of the run dir name — stable UI links); root span named by the
|
||||||
|
question, final answer as attribute; INIT/ROUTE/EXPERT/ANSWER as nested
|
||||||
|
component spans; every `llm.done`/`probe.done`/`fact.merged`/... event
|
||||||
|
one span with its attributes; recursive child runs (same file, own
|
||||||
|
`run_ts`, `seq` restarts) nest as per-run spans. Post-mortem only: the
|
||||||
|
run itself never touches the network.
|
||||||
|
- Jaeger v2.22 all-in-one, docker on agentvps, bound to 10.3.14.59 only
|
||||||
|
(UI :16686, OTLP :4318) — reachable from the VPN, zero exposure by
|
||||||
|
itself; Emili's apache at 10.3.14.1 fronts it publicly.
|
||||||
|
- `python -m floop.traces runs/<dir>` pushes one run; `--latest N` the
|
||||||
|
newest; `--dry` builds without pushing. `tests/traces.py` 5/5.
|
||||||
|
|
||||||
|
**Live-found bugs (the reason this took an afternoon):**
|
||||||
|
1. Pre-reading the LAST event's timestamp before the loop poisoned the
|
||||||
|
midnight detector → every span +24h. Law now written down: the clock
|
||||||
|
is only ever fed in emission order.
|
||||||
|
2. `comp.out` spans were closed but never appended — the payload shipped
|
||||||
|
every event as an orphan under the root.
|
||||||
|
3. Child-run blocks share events.jsonl; run-spans got double-appended
|
||||||
|
(stack + direct append) → duplicate span ids, Jaeger rejects.
|
||||||
|
4. OTLP/JSON wants full proto enum names (`SPAN_KIND_INTERNAL`,
|
||||||
|
`STATUS_CODE_OK`) and rejects empty `parentSpanId` on the root.
|
||||||
|
5. Jaeger v2 serves the query API at `/api/traces/...` on :16686 (not
|
||||||
|
`/api/services` — gone in v2; not under `/jaeger/api/` for reads —
|
||||||
|
that route is the SPA catch-all).
|
||||||
|
|
||||||
|
**Verified against real runs:** the 09:15 Pedro run exports 393 spans —
|
||||||
|
root 1193.8s, INIT→ROUTE→EXPERT→ROUTE→EXPERT→ANSWER children, 128 llm
|
||||||
|
spans with call_seq/dur_s/prompt-file — read back from Jaeger's own API
|
||||||
|
(393 stored, service `floop`); the fractal `goal` run nests child runs
|
||||||
|
depth 6. Three traces pushed live. ARCHITECTURE §9-bis updated: BUILT
|
||||||
|
(post-mortem), LIVE in-process export still deferred.
|
||||||
|
|
||||||
|
**Emili's open item:** the vhost at oniricapps (he configures the apache
|
||||||
|
reverse proxy + LE cert for e.g. jaeger.oniricapps.com; the container is
|
||||||
|
already reachable at 10.3.14.59:16686 from his server).
|
||||||
|
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Tooling 2 — named inputs/outputs in the traces (2026-10-27, PM)
|
||||||
|
|
||||||
|
**His review of the first export** (the four asks, verbatim in the PR):
|
||||||
|
inputs and outputs of everything below the floop/expert components; the
|
||||||
|
prompt accessible from Jaeger itself; the expert's name in the span
|
||||||
|
names (EXPERT knowledge, knowledge.search inside); Signature inputs and
|
||||||
|
outputs on LLM calls. All four landed on the same branch (PR #32).
|
||||||
|
|
||||||
|
**What was added:**
|
||||||
|
- `fn.done` events (fn, in, out) at the knowledge pipeline's main
|
||||||
|
functions: search (in.query/limit -> out.titles), fetch (in.title ->
|
||||||
|
out.url/chars/tables), skim, compose, chunk_gate, serve_set,
|
||||||
|
list_ingest, harvest, promote, check, judge (in.question/rows ->
|
||||||
|
out.value/confidence). Named arguments, structured values as compact
|
||||||
|
JSON.
|
||||||
|
- `sig.start`/`sig.done` from the dspy prompt-log callback: every module
|
||||||
|
forward emits the Signature's input fields (in.question,
|
||||||
|
in.entities...) and typed outputs (out.entities, out.facts,
|
||||||
|
out.value...). The LLM span and the sig span are one node.
|
||||||
|
- The `prompt` child span: the exact prompt + raw response read from
|
||||||
|
prompts/NN-stage.txt AT EXPORT TIME — retroactive for old runs (the
|
||||||
|
128-file Pedro run re-exports with 128 clickable prompts).
|
||||||
|
- Expert names: `streams.call(..., expert=...)` on the EXPERT component;
|
||||||
|
the exporter renders 'EXPERT knowledge', prefixes children
|
||||||
|
(knowledge.state, knowledge.TYPE, knowledge.search), and exports each
|
||||||
|
expert under its own OTel service — Jaeger's service selector and
|
||||||
|
colors group by component.
|
||||||
|
|
||||||
|
**Live-found bugs (mine, fixed before commit):** the harvest fn.done
|
||||||
|
referenced a local of another function (NameError) and the list_ingest
|
||||||
|
event read `verify` before it existed (UnboundLocalError) — the
|
||||||
|
value_clean test's `__new__` fake caught that _rec touched
|
||||||
|
self.streams; the law now: `_rec` reads getattr(self, "streams", None)
|
||||||
|
(__new__-built fakes never define it). Smoke run live (glm-5.3-flash):
|
||||||
|
MASK carries in.question -> out.entities [{France, PLACE}], EXPERT
|
||||||
|
knowledge nests knowledge.TranslateToDSL — verified in the export
|
||||||
|
before the run finished (the recorder flushes).
|
||||||
|
|
||||||
|
**Still open from his review:** the trace-level 'which input fed which
|
||||||
|
output' is event-adjacency, not a dataflow edge — the honest limit of
|
||||||
|
post-mortem spans. And baseline/`--baseline` mode has no recorder yet.
|
||||||
|
|||||||
Generated
+3
@@ -0,0 +1,3 @@
|
|||||||
|
# Default ignored files
|
||||||
|
/shelf/
|
||||||
|
/workspace.xml
|
||||||
Generated
+11
@@ -0,0 +1,11 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<module external.system.id="pyproject.toml" type="PYTHON_MODULE" version="4">
|
||||||
|
<component name="NewModuleRootManager">
|
||||||
|
<content url="file://$MODULE_DIR$">
|
||||||
|
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
|
||||||
|
<excludeFolder url="file://$MODULE_DIR$/.venv" />
|
||||||
|
</content>
|
||||||
|
<orderEntry type="jdk" jdkName="~/Labs/oniric.ai/19.floop/floop/code/.venv" jdkType="Python SDK" />
|
||||||
|
<orderEntry type="sourceFolder" forTests="false" />
|
||||||
|
</component>
|
||||||
|
</module>
|
||||||
+13
@@ -0,0 +1,13 @@
|
|||||||
|
<component name="InspectionProjectProfileManager">
|
||||||
|
<profile version="1.0">
|
||||||
|
<option name="myName" value="Project Default" />
|
||||||
|
<inspection_tool class="PyPackageRequirementsInspection" enabled="true" level="WARNING" enabled_by_default="true">
|
||||||
|
<option name="ignoredPackages">
|
||||||
|
<list>
|
||||||
|
<option value="chainlit" />
|
||||||
|
<option value="dspy" />
|
||||||
|
</list>
|
||||||
|
</option>
|
||||||
|
</inspection_tool>
|
||||||
|
</profile>
|
||||||
|
</component>
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
<component name="InspectionProjectProfileManager">
|
||||||
|
<settings>
|
||||||
|
<option name="USE_PROJECT_PROFILE" value="false" />
|
||||||
|
<version value="1.0" />
|
||||||
|
</settings>
|
||||||
|
</component>
|
||||||
Generated
+8
@@ -0,0 +1,8 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="ProjectModuleManager">
|
||||||
|
<modules>
|
||||||
|
<module fileurl="file://$PROJECT_DIR$/.idea/floop.iml" filepath="$PROJECT_DIR$/.idea/floop.iml" />
|
||||||
|
</modules>
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
Generated
+6
@@ -0,0 +1,6 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="VcsDirectoryMappings">
|
||||||
|
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
@@ -71,9 +71,95 @@ floop/llm.py dspy LM configuration (OpenAI-compatible endpoints)
|
|||||||
floop/dspy_modules.py every LLM call as a dspy module (INIT, ROUTE, EXPERT, MISSING, ANSWER)
|
floop/dspy_modules.py every LLM call as a dspy module (INIT, ROUTE, EXPERT, MISSING, ANSWER)
|
||||||
floop/engine.py engine interface + draft stub engines
|
floop/engine.py engine interface + draft stub engines
|
||||||
floop/machine.py FloopRun — the loop; recursion for the `floop` attendant
|
floop/machine.py FloopRun — the loop; recursion for the `floop` attendant
|
||||||
|
floop/recorder.py the flight recorder — events.jsonl (one JSON line per component)
|
||||||
|
floop/traces.py events.jsonl -> OpenTelemetry spans; push a run to Jaeger (post-mortem)
|
||||||
|
floop/inspect_html.py events.jsonl -> self-contained inspect.html (offline viewer)
|
||||||
tests/state.py unit tests (no LLM)
|
tests/state.py unit tests (no LLM)
|
||||||
|
tests/traces.py exporter tests (no network)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Knowledge pipeline structure
|
||||||
|
|
||||||
|
`KnowledgeExpert.answer_question` in `knowledge/expert.py` orchestrates proof,
|
||||||
|
stored answers, and article-by-article gathering with early exit. Focused methods
|
||||||
|
handle stored-answer gating, query composition/search, cached fetching, skimming,
|
||||||
|
and post-ingestion answer checks. Stateless module-level helpers build probe
|
||||||
|
seeds and filter goal-relevant skim notices; `knowledge/ranking.py` ranks search
|
||||||
|
results. Run-wide page
|
||||||
|
and link caches survive calls; extraction entities, skim notices, and pending
|
||||||
|
skim leads reset per call after the proof path falls through.
|
||||||
|
|
||||||
|
Offline orchestration regression tests (no Wikipedia, embedder, or LLM required):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
.venv/bin/python knowledge/tests/answer_question.py
|
||||||
|
```
|
||||||
|
|
||||||
|
### Wikipedia candidate ranking
|
||||||
|
|
||||||
|
`WikipediaClient.search` returns `WikiSearchResult` objects with `title` and
|
||||||
|
plain-text `snippet` (MediaWiki's query-specific search excerpt, not the full
|
||||||
|
introductory summary). HTML highlight tags are removed and entities decoded;
|
||||||
|
missing snippets leave the title available for ranking without an extra fetch.
|
||||||
|
|
||||||
|
All searches finish before fetching articles. Results are deduplicated by title,
|
||||||
|
retaining distinct snippets from different queries. Every unique candidate is
|
||||||
|
ranked against the **original question**, using **title + snippet**, not the
|
||||||
|
composed search queries:
|
||||||
|
|
||||||
|
- BM25 lexical relevance (k1=1.5, b=0.75) over the candidate pool, using the
|
||||||
|
existing word tokenizer and stemmer.
|
||||||
|
- Cosine similarity from the configured embedding service (`embed_model` /
|
||||||
|
`embed_url`), reusing the cached question vector and batch-embedding candidates.
|
||||||
|
- Equal-weight reciprocal rank fusion, `1/(60 + lexical_rank) +
|
||||||
|
1/(60 + semantic_rank)`. Ties share ranks; final ties retain encounter order.
|
||||||
|
|
||||||
|
There is **no query-winner priority**. `max_articles` is applied only after global
|
||||||
|
ranking. If embeddings are unavailable or malformed, the failure is logged and
|
||||||
|
ranking falls back to BM25 alone. Search events retain titles and snippets;
|
||||||
|
`rank_articles` events record the question, candidates, ranking method, BM25,
|
||||||
|
cosine, and final scores. Snippets only guide retrieval; fetched-page containment
|
||||||
|
checks still govern which facts may enter the KG.
|
||||||
|
|
||||||
|
Offline API, ranking, embedding-validation and fallback tests:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
.venv/bin/python knowledge/tests/semantic_fetch.py
|
||||||
|
```
|
||||||
|
|
||||||
|
## Viewing a run as traces (Jaeger, 2026-10-27)
|
||||||
|
|
||||||
|
Every run records `events.jsonl`; `floop/traces.py` replays it as one
|
||||||
|
OpenTelemetry trace and pushes it to the Jaeger container on the agentvps
|
||||||
|
(`http://10.3.14.59:16686` on the VPN; OTLP ingest on `:4318`):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
uv run python -m floop.traces runs/<ts>-<slug> # one run -> Jaeger
|
||||||
|
uv run python -m floop.traces --latest 3 # the newest runs
|
||||||
|
uv run python -m floop.traces <dir> --dry # build the payload, don't push
|
||||||
|
```
|
||||||
|
|
||||||
|
The root span is the run (named by the question, final answer as an
|
||||||
|
attribute); INIT/ROUTE/EXPERT/ANSWER components nest under it, every LLM
|
||||||
|
call is a span with its stage/duration/prompt file, and recursive child
|
||||||
|
runs appear as nested run-spans. Trace ids are deterministic — re-pushing
|
||||||
|
a run lands on the same trace. Stdlib only; the run itself never touches
|
||||||
|
the network.
|
||||||
|
|
||||||
|
Since 2026-10-27 (visibility laws), inputs and outputs are data:
|
||||||
|
- Pipeline functions emit `fn.done` — spans carry in.query / out.titles
|
||||||
|
(search), in.title / out.{url, chars, tables} (fetch), the judge's
|
||||||
|
question/value, compose/skim/chunk_gate/serve_set/list_ingest/harvest/
|
||||||
|
promote/check, each with NAMED arguments.
|
||||||
|
- dspy calls emit `sig.start`/`sig.done` — the Signature's input and
|
||||||
|
output fields as typed attributes (in.question, out.entities, out.facts).
|
||||||
|
- Every LLM span carries a CHILD `prompt` span with the exact prompt and
|
||||||
|
raw response (read from prompts/NN-stage.txt at export time) — click and
|
||||||
|
read, retroactively for old runs too.
|
||||||
|
- EXPERT spans carry the attendant name (EXPERT knowledge); nested spans
|
||||||
|
use the expert prefix (knowledge.search, knowledge.state); each expert
|
||||||
|
exports under its own OTel service (floop / knowledge / ...).
|
||||||
|
|
||||||
## Next steps (design order from the docs)
|
## Next steps (design order from the docs)
|
||||||
|
|
||||||
1. Real check layer on expert arrival (well-formedness per expert kind) — the
|
1. Real check layer on expert arrival (well-formedness per expert kind) — the
|
||||||
|
|||||||
+19
-13
@@ -15,29 +15,33 @@ import dspy
|
|||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
|
||||||
|
ENTITY_TYPES = {
|
||||||
|
"PERSON": "individual human beings or legal entities",
|
||||||
|
"ORGANIZATION": "companies, institutions, and groups",
|
||||||
|
"LOCATION": "geographical locations such as cities and countries",
|
||||||
|
"DATE": "specific dates or time periods",
|
||||||
|
"PRODUCT": "items or goods, including brands and models",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
class NamedEntity(BaseModel):
|
class NamedEntity(BaseModel):
|
||||||
"""One named entity found in the question."""
|
"""One named entity found in the question."""
|
||||||
name: str = dspy.OutputField(
|
name: str = dspy.OutputField(
|
||||||
desc="the entity's exact surface text as it appears in the question, copied verbatim")
|
desc="the entity's exact surface text as it appears in the question, copied verbatim")
|
||||||
kind: str = dspy.OutputField(
|
kind: str = dspy.OutputField(
|
||||||
desc="PERSON, ORGANIZATION, PLACE, WORK, EVENT, or OTHER")
|
desc="; ".join(f"{kind}: {definition}"
|
||||||
|
for kind, definition in ENTITY_TYPES.items()))
|
||||||
|
|
||||||
|
|
||||||
class EntityMaskSignature(dspy.Signature):
|
class NamedEntityRecognitionSignature(dspy.Signature):
|
||||||
"""You are the MASK step of a reasoning machine. Find the named entities
|
"""Find the named entities in the input text. Use only the kinds and
|
||||||
in the question — people, organizations, places, titles of works, events.
|
definitions in the NamedEntity schema. Copy each entity's text exactly
|
||||||
Copy each one's text exactly as it appears; do not add entities that are
|
as it appears; do not add entities that are not explicitly named."""
|
||||||
not explicitly named."""
|
text: str = dspy.InputField()
|
||||||
question: str = dspy.InputField()
|
|
||||||
entities: list[NamedEntity] = dspy.OutputField(
|
entities: list[NamedEntity] = dspy.OutputField(
|
||||||
desc="the named entities found; empty when none")
|
desc="the named entities found; empty when none")
|
||||||
|
|
||||||
|
|
||||||
# placeholder order: PERSON_1, PERSON_2, ORGANIZATION_1, ...
|
|
||||||
_PREFIX = {"PERSON": "PERSON", "ORGANIZATION": "ORGANIZATION", "PLACE": "PLACE",
|
|
||||||
"WORK": "WORK", "EVENT": "EVENT", "OTHER": "OTHER"}
|
|
||||||
|
|
||||||
|
|
||||||
def apply_mask(question: str, entities: list[NamedEntity]) -> tuple[str, dict]:
|
def apply_mask(question: str, entities: list[NamedEntity]) -> tuple[str, dict]:
|
||||||
"""Mask the question deterministically. Longer names first (so
|
"""Mask the question deterministically. Longer names first (so
|
||||||
'Pedro Sánchez Pérez-Castejón' is masked before its substrings).
|
'Pedro Sánchez Pérez-Castejón' is masked before its substrings).
|
||||||
@@ -50,7 +54,9 @@ def apply_mask(question: str, entities: list[NamedEntity]) -> tuple[str, dict]:
|
|||||||
if not name or name not in masked:
|
if not name or name not in masked:
|
||||||
continue
|
continue
|
||||||
kind = ent.kind.strip().upper()
|
kind = ent.kind.strip().upper()
|
||||||
prefix = _PREFIX.get(kind, "OTHER")
|
if kind not in ENTITY_TYPES:
|
||||||
|
continue
|
||||||
|
prefix = kind
|
||||||
counters[prefix] = counters.get(prefix, 0) + 1
|
counters[prefix] = counters.get(prefix, 0) + 1
|
||||||
ph = f"{prefix}_{counters[prefix]}"
|
ph = f"{prefix}_{counters[prefix]}"
|
||||||
if ph in restore: # same surface text twice: keep one mask
|
if ph in restore: # same surface text twice: keep one mask
|
||||||
|
|||||||
@@ -20,8 +20,8 @@ try:
|
|||||||
except ImportError: # pragma: no cover — dspy <3.x
|
except ImportError: # pragma: no cover — dspy <3.x
|
||||||
AdapterParseError = type("AdapterParseError", (Exception,), {"lm_response": ""})
|
AdapterParseError = type("AdapterParseError", (Exception,), {"lm_response": ""})
|
||||||
|
|
||||||
from .anonymize import (EntityMaskSignature, apply_mask, identity_answer,
|
from .anonymize import (NamedEntityRecognitionSignature, apply_mask,
|
||||||
restore_mask)
|
identity_answer, restore_mask)
|
||||||
|
|
||||||
|
|
||||||
class Subquestion(BaseModel):
|
class Subquestion(BaseModel):
|
||||||
@@ -141,7 +141,7 @@ class FloopModules:
|
|||||||
self.expert = predict(ExpertSignature)
|
self.expert = predict(ExpertSignature)
|
||||||
self.missing = predict(MissingSignature)
|
self.missing = predict(MissingSignature)
|
||||||
self.answer = predict(AnswerSignature)
|
self.answer = predict(AnswerSignature)
|
||||||
self.mask = predict(EntityMaskSignature)
|
self.mask = predict(NamedEntityRecognitionSignature)
|
||||||
|
|
||||||
def init_decompose(self, question: str) -> tuple[list[dict], str]:
|
def init_decompose(self, question: str) -> tuple[list[dict], str]:
|
||||||
"""(parsed subquestions, raw model output). The machine decides what
|
"""(parsed subquestions, raw model output). The machine decides what
|
||||||
@@ -178,7 +178,7 @@ class FloopModules:
|
|||||||
"""Mask named entities to typed placeholders. No entity found (or the
|
"""Mask named entities to typed placeholders. No entity found (or the
|
||||||
mask call dies) -> the question passes unchanged, mask map empty."""
|
mask call dies) -> the question passes unchanged, mask map empty."""
|
||||||
try:
|
try:
|
||||||
pred = self.mask(question=question)
|
pred = self.mask(text=question)
|
||||||
entities = pred.entities or []
|
entities = pred.entities or []
|
||||||
except AdapterParseError:
|
except AdapterParseError:
|
||||||
return question, {}
|
return question, {}
|
||||||
|
|||||||
@@ -0,0 +1,317 @@
|
|||||||
|
"""floop-inspect — the post-mortem HTML debugger (PR B).
|
||||||
|
|
||||||
|
One run dir in -> ONE self-contained inspect.html out. The events are
|
||||||
|
inlined as JSON; the page opens offline from file:// with zero network
|
||||||
|
references. Four views (owner 26/10):
|
||||||
|
- timeline: every component as a bar in time order (LLM vs code
|
||||||
|
colored), the 'where inside which expert are we' view
|
||||||
|
- kg: the snapshot graph (canvas, force layout, temporal windows +
|
||||||
|
last-touch highlighted)
|
||||||
|
- facts: the two-pass debug table (claim -> typed fact -> merge
|
||||||
|
verdict, rejections with reason)
|
||||||
|
- probes: per question, what the semantic search returned
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
def generate(run_dir: str | Path) -> Path:
|
||||||
|
run_dir = Path(run_dir)
|
||||||
|
ev_path = run_dir / "events.jsonl"
|
||||||
|
if not ev_path.exists():
|
||||||
|
print(f"no events.jsonl in {run_dir} — nothing to inspect",
|
||||||
|
file=sys.stderr)
|
||||||
|
raise SystemExit(1)
|
||||||
|
events = []
|
||||||
|
for line in ev_path.read_text(encoding="utf-8").splitlines():
|
||||||
|
line = line.strip()
|
||||||
|
if line:
|
||||||
|
try:
|
||||||
|
events.append(json.loads(line))
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
pass # torn line mid-crash: skip, honest
|
||||||
|
html = _render(events)
|
||||||
|
out = run_dir / "inspect.html"
|
||||||
|
out.write_text(html, encoding="utf-8")
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv: list[str]) -> int:
|
||||||
|
if len(argv) != 2:
|
||||||
|
print("usage: python -m floop.inspect_html <run_dir>", file=sys.stderr)
|
||||||
|
return 2
|
||||||
|
out = generate(argv[1])
|
||||||
|
print(f"inspect: {out}")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def _render(events: list[dict]) -> str:
|
||||||
|
payload = json.dumps(events, default=str)
|
||||||
|
return _TEMPLATE.replace("__EVENTS__", payload)
|
||||||
|
|
||||||
|
|
||||||
|
# ---- the page (vanilla JS, no deps, no network) ---------------------------
|
||||||
|
_TEMPLATE = r"""<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>floop-inspect</title>
|
||||||
|
<style>
|
||||||
|
:root { --bg:#111; --fg:#ddd; --dim:#888; --acc:#4cc2ff; --llm:#c678dd;
|
||||||
|
--ok:#98c379; --bad:#e06c75; --line:#2a2a2a; }
|
||||||
|
* { box-sizing:border-box; }
|
||||||
|
body { margin:0; background:var(--bg); color:var(--fg);
|
||||||
|
font:13px/1.45 "JetBrains Mono","Fira Code",monospace; }
|
||||||
|
header { padding:10px 16px; border-bottom:1px solid var(--line);
|
||||||
|
position:sticky; top:0; background:var(--bg); z-index:9; }
|
||||||
|
header b { color:var(--acc); }
|
||||||
|
nav button { background:none; border:1px solid var(--line); color:var(--dim);
|
||||||
|
padding:4px 12px; margin-right:6px; cursor:pointer; border-radius:3px;
|
||||||
|
font:inherit; }
|
||||||
|
nav button.on { color:var(--fg); border-color:var(--acc); }
|
||||||
|
.view { display:none; padding:14px 16px; }
|
||||||
|
.view.on { display:block; }
|
||||||
|
#timeline { width:100%; height:60vh; }
|
||||||
|
.bar { position:absolute; height:18px; border-radius:3px; opacity:.9; }
|
||||||
|
.bar:hover { outline:1px solid #fff; }
|
||||||
|
.bar.llm { background:var(--llm); } .bar.code { background:var(--acc); }
|
||||||
|
.bar.bad { background:var(--bad); }
|
||||||
|
table { border-collapse:collapse; width:100%; margin-top:8px; }
|
||||||
|
th,td { text-align:left; padding:4px 8px; border-bottom:1px solid var(--line);
|
||||||
|
vertical-align:top; max-width:480px; overflow-wrap:break-word; }
|
||||||
|
th { color:var(--dim); font-weight:normal; }
|
||||||
|
td.ok { color:var(--ok); } td.bad { color:var(--bad); }
|
||||||
|
.pill { display:inline-block; border-radius:8px; padding:0 8px;
|
||||||
|
border:1px solid var(--line); color:var(--dim); font-size:11px; }
|
||||||
|
#kg { width:100%; height:65vh; background:#0b0b0b; border-radius:6px; }
|
||||||
|
#detail { color:var(--dim); padding:6px 0; min-height:24px; }
|
||||||
|
h3 { color:var(--acc); margin:14px 0 4px; font-size:13px; }
|
||||||
|
.final { border:1px solid var(--ok); border-radius:4px; padding:8px 12px;
|
||||||
|
margin:8px 0; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<header>
|
||||||
|
<b>floop-inspect</b> — post-mortem debugger
|
||||||
|
<span id="stats"></span>
|
||||||
|
<nav>
|
||||||
|
<button data-v="timeline" class="on">timeline</button>
|
||||||
|
<button data-v="kg">kg</button>
|
||||||
|
<button data-v="facts">facts</button>
|
||||||
|
<button data-v="probes">probes</button>
|
||||||
|
</nav>
|
||||||
|
<div id="detail">hover/click a bar or node</div>
|
||||||
|
</header>
|
||||||
|
<div id="timeline" class="view on"></div>
|
||||||
|
<div id="kg" class="view"><canvas id="kgc"></canvas></div>
|
||||||
|
<div id="facts" class="view"></div>
|
||||||
|
<div id="probes" class="view"></div>
|
||||||
|
<script>
|
||||||
|
const EV = __EVENTS__;
|
||||||
|
const $ = (s) => document.querySelector(s);
|
||||||
|
|
||||||
|
// ---------- stats ----------
|
||||||
|
const llms = EV.filter(e => e.event === 'llm.done');
|
||||||
|
const total = llms.reduce((a,e) => a + (e.dur_s||0), 0);
|
||||||
|
$('#stats').textContent =
|
||||||
|
`${EV.length} events · ${llms.length} llm calls · ${total.toFixed(1)}s llm time` +
|
||||||
|
(EV.some(e=>e.event==='run.final') ? '' : ' · no final answer');
|
||||||
|
|
||||||
|
// ---------- tabs ----------
|
||||||
|
document.querySelectorAll('nav button').forEach(b => b.onclick = () => {
|
||||||
|
document.querySelectorAll('nav button').forEach(x=>x.classList.remove('on'));
|
||||||
|
document.querySelectorAll('.view').forEach(x=>x.classList.remove('on'));
|
||||||
|
b.classList.add('on'); $('#'+b.dataset.v).classList.add('on');
|
||||||
|
window.dispatchEvent(new Event('resize')); // hidden views measure 0 —
|
||||||
|
}); // remeasure on every activation
|
||||||
|
|
||||||
|
// ---------- timeline ----------
|
||||||
|
(() => {
|
||||||
|
const box = $('#timeline');
|
||||||
|
const t0 = EV.length ? (new Date('2000-01-01T'+EV[0].ts)).getTime() : 0;
|
||||||
|
const tN = EV.length ? (new Date('2000-01-01T'+EV[EV.length-1].ts)).getTime() : 1;
|
||||||
|
const span = Math.max(tN - t0, 1);
|
||||||
|
const W = () => box.clientWidth, H = () => box.clientHeight;
|
||||||
|
const rows = new Map(); // comp -> row index
|
||||||
|
const bars = [];
|
||||||
|
// pair llm.done with the nearest preceding comp.start of the same stage
|
||||||
|
let open = {};
|
||||||
|
for (const e of EV) {
|
||||||
|
if (e.event === 'comp.start') open[e.comp] = e;
|
||||||
|
else if (e.event === 'llm.done') {
|
||||||
|
bars.push({...e, kind:'llm', label:e.stage, ev:e});
|
||||||
|
} else if (e.event === 'comp.out' || e.event === 'state' ||
|
||||||
|
e.event === 'comp.done') {
|
||||||
|
const c = e.comp || '?';
|
||||||
|
bars.push({ts:e.ts, dur:0, kind:'code', label:c, ev:e});
|
||||||
|
} else if (e.event === 'fact.merged' || e.event === 'fact.rejected' ||
|
||||||
|
e.event === 'claims.done' || e.event === 'type.done' ||
|
||||||
|
e.event === 'probe.done' || e.event === 'prover.done') {
|
||||||
|
bars.push({ts:e.ts, dur:0, kind:'code', label:e.event, ev:e});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
bars.forEach(b => { if (!rows.has(b.label)) rows.set(b.label, rows.size); });
|
||||||
|
const rowH = 24;
|
||||||
|
const px = (ts) => ((new Date('2000-01-01T'+ts)).getTime() - t0) / span * (W()-140) + 120;
|
||||||
|
const durPx = (d) => Math.max(d/span*(W()-140), 4);
|
||||||
|
bars.forEach(b => {
|
||||||
|
const x = px(b.ts), w = b.kind==='llm' ? Math.max(durPx((b.dur_s||0)*1000),4) : 8;
|
||||||
|
const y = 10 + rows.get(b.label)*rowH;
|
||||||
|
const el = document.createElement('div');
|
||||||
|
el.className = 'bar ' + (b.kind==='llm'?'llm':'code') +
|
||||||
|
(b.ev.event==='fact.rejected' ? ' bad':'');
|
||||||
|
el.style.left = x+'px'; el.style.top = y+'px';
|
||||||
|
el.style.width = Math.min(w, W()-x-2)+'px';
|
||||||
|
el.dataset.d = JSON.stringify(b.ev).slice(0,600);
|
||||||
|
el.title = b.label;
|
||||||
|
el.onclick = () => { $('#detail').textContent =
|
||||||
|
b.label + ' — ' + (b.ev.dur_s? b.ev.dur_s+'s · ':'') + el.dataset.d; };
|
||||||
|
box.appendChild(el);
|
||||||
|
});
|
||||||
|
// row labels
|
||||||
|
for (const [label, i] of rows) {
|
||||||
|
const s = document.createElement('div');
|
||||||
|
s.textContent = label;
|
||||||
|
s.style.cssText = `position:absolute;left:4px;top:${10+i*rowH}px;color:var(--dim);font-size:11px;width:112px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;`;
|
||||||
|
box.appendChild(s);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
|
||||||
|
// ---------- facts ----------
|
||||||
|
(() => {
|
||||||
|
const box = $('#facts');
|
||||||
|
const rows = [];
|
||||||
|
for (const e of EV) {
|
||||||
|
if (e.event === 'claims.done')
|
||||||
|
rows.push(`<h3>${e.page} — ${e.heading||''} (${(e.out&&e.out.n_claims)||0} claims)</h3>` +
|
||||||
|
((e.out&&e.out.claims)||[]).map(c=>`<div>· ${esc(c)}</div>`).join(''));
|
||||||
|
if (e.event === 'type.done')
|
||||||
|
rows.push(`<div style="color:var(--dim)">type: ${esc(e.claim||'')} → ` +
|
||||||
|
(e.out&&e.out.fact ? `<span class="ok">${esc(JSON.stringify(e.out.fact))}</span>` :
|
||||||
|
'<span class="bad">null (declined)</span>') + `</div>`);
|
||||||
|
if (e.event === 'fact.merged')
|
||||||
|
rows.push(`<div class="ok">merged: ${esc(fmt_fact(e.fact))}</div>`);
|
||||||
|
if (e.event === 'fact.rejected')
|
||||||
|
rows.push(`<div class="bad">rejected (${esc(e.reason)}): ${esc(fmt_fact(e.fact))}</div>`);
|
||||||
|
}
|
||||||
|
const snap = EV.find(e => e.event === 'kg.snapshot');
|
||||||
|
if (snap) rows.push(`<h3>KG final: ${snap.kg.n_live}/${snap.kg.n_edges} live · ${snap.kg.n_conflicts} conflicts</h3>`);
|
||||||
|
const fin = EV.find(e => e.event === 'run.final');
|
||||||
|
if (fin) rows.push(`<div class="final"><b>final:</b> ${esc(fin.out||'')}</div>`);
|
||||||
|
box.innerHTML = rows.join('') || '<i>no extraction events</i>';
|
||||||
|
function esc(s){return String(s).replace(/&/g,'&').replace(/</g,'<');}
|
||||||
|
function fmt_fact(f){return f ? `${f.subject} | ${f.relation} | ${f.object}` : '';}
|
||||||
|
})();
|
||||||
|
|
||||||
|
// ---------- probes ----------
|
||||||
|
(() => {
|
||||||
|
const box = $('#probes');
|
||||||
|
const rows = [];
|
||||||
|
for (const e of EV) {
|
||||||
|
if (e.event === 'probe.done')
|
||||||
|
rows.push(`<h3>probe — ${esc(e.q||'')}</h3>
|
||||||
|
<div>seeds: ${(e.seeds||[]).map(esc).join(', ')}</div>
|
||||||
|
<div>rows: <span class="ok">${e.rows}</span> · semantic adds: <span class="pill">${e.semantic}</span> · tau=${e.tau||'—'}</div>`);
|
||||||
|
if (e.event === 'prover.done')
|
||||||
|
rows.push(`<h3>prover — ${esc(e.q||'')}</h3>
|
||||||
|
<div>verdict: <b class="${e.verdict==='ambiguous'||e.verdict==='closed'?'ok':'bad'}">${e.verdict}</b>${e.reason?' ('+esc(e.reason)+')':''}</div>
|
||||||
|
<div>bindings (${e.n_bindings||0}): ${(e.bindings||[]).map(esc).join(' · ')}</div>
|
||||||
|
<div style="color:var(--dim)">dsl: ${esc(JSON.stringify(e.dsl))}</div>`);
|
||||||
|
}
|
||||||
|
box.innerHTML = rows.join('') || '<i>no probe/prover events</i>';
|
||||||
|
function esc(s){return String(s).replace(/&/g,'&').replace(/</g,'<');}
|
||||||
|
})();
|
||||||
|
|
||||||
|
// ---------- kg canvas (force-ish layout: subjects orbit values) ----------
|
||||||
|
(() => {
|
||||||
|
const cv = $('#kgc'), ctx = cv.getContext('2d');
|
||||||
|
const snap = EV.find(e => e.event === 'kg.snapshot');
|
||||||
|
if (!snap) { $('#kg').innerHTML = '<i style="padding:20px;display:inline-block">no kg.snapshot in this run</i>'; return; }
|
||||||
|
const edges = (snap.kg.edges||[]).filter(e => !e.retracted);
|
||||||
|
const el = $('#kg');
|
||||||
|
let nodes = null, ns = null;
|
||||||
|
function layout(){
|
||||||
|
// node set
|
||||||
|
nodes = new Map();
|
||||||
|
const nid = (name) => { if (!nodes.has(name)) nodes.set(name, {
|
||||||
|
x: Math.random()*cv.width, y: Math.random()*cv.height,
|
||||||
|
vx:0, vy:0, name, deg:0}); return nodes.get(name); };
|
||||||
|
edges.forEach(e => { nid(e.subject).deg++; nid(e.object).deg++; });
|
||||||
|
ns = [...nodes.values()];
|
||||||
|
const K = 24, REP = 1400;
|
||||||
|
for (let it=0; it<220; it++) {
|
||||||
|
for (const n of ns) {
|
||||||
|
let fx=0, fy=0;
|
||||||
|
for (const m of ns) if (m!==n) {
|
||||||
|
let dx=n.x-m.x, dy=n.y-m.y, d2=dx*dx+dy*dy||1;
|
||||||
|
fx += REP*dx/d2; fy += REP*dy/d2;
|
||||||
|
}
|
||||||
|
n.vx=(n.vx+fx)*.85; n.vy=(n.vy+fy)*.85; n.x+=n.vx; n.y+=n.vy;
|
||||||
|
}
|
||||||
|
edges.forEach(e => {
|
||||||
|
const a=nodes.get(e.subject), b=nodes.get(e.object);
|
||||||
|
let dx=b.x-a.x, dy=b.y-a.y, d=Math.sqrt(dx*dx+dy*dy)||1;
|
||||||
|
const f=(d-K)/d*.12;
|
||||||
|
a.vx+=dx*f; a.vy+=dy*f; b.vx-=dx*f; b.vy-=dy*f;
|
||||||
|
a.x+=a.vx*.02; a.y+=a.vy*.02; b.x-=b.vx*.02; b.y-=b.vy*.02;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function resize0(){ if (cv.width !== el.clientWidth) cv.width = el.clientWidth;
|
||||||
|
if (cv.height !== el.clientHeight) cv.height = el.clientHeight; }
|
||||||
|
function draw(){
|
||||||
|
resize0();
|
||||||
|
if (cv.width === 0 || cv.height === 0) return; // hidden: retry on activation
|
||||||
|
if (!nodes) layout();
|
||||||
|
ctx.fillStyle = '#0b0b0b'; ctx.fillRect(0,0,cv.width,cv.height);
|
||||||
|
ctx.strokeStyle = '#3a3a3a';
|
||||||
|
edges.forEach(e => {
|
||||||
|
const a=nodes.get(e.subject), b=nodes.get(e.object);
|
||||||
|
ctx.beginPath(); ctx.moveTo(a.x,a.y); ctx.lineTo(b.x,b.y);
|
||||||
|
ctx.strokeStyle = e.last_touch ? '#4cc2ff' : '#3a3a3a';
|
||||||
|
ctx.lineWidth = e.last_touch ? 1.6 : .8; ctx.stroke();
|
||||||
|
});
|
||||||
|
ctx.font = '10px monospace';
|
||||||
|
ns.forEach(n => {
|
||||||
|
const r = 4 + Math.min(n.deg,8);
|
||||||
|
ctx.beginPath(); ctx.arc(n.x,n.y,r,0,7);
|
||||||
|
ctx.fillStyle = '#c678dd'; ctx.fill();
|
||||||
|
ctx.fillStyle = '#999';
|
||||||
|
ctx.fillText(n.name.slice(0,18), n.x+r+2, n.y+3);
|
||||||
|
});
|
||||||
|
// edge labels near midpoints (windows)
|
||||||
|
ctx.fillStyle = '#777';
|
||||||
|
edges.forEach(e => {
|
||||||
|
const a=nodes.get(e.subject), b=nodes.get(e.object);
|
||||||
|
const lab = e.rel + (e.t_start?` [${e.t_start}${e.t_end?('–'+e.t_end):'–'}]`:'');
|
||||||
|
ctx.fillText(lab.slice(0,24), (a.x+b.x)/2+3, (a.y+b.y)/2-3);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
window.addEventListener('resize', draw);
|
||||||
|
draw();
|
||||||
|
cv.onclick = (m) => {
|
||||||
|
const rect = cv.getBoundingClientRect();
|
||||||
|
const x = m.clientX-rect.left, y = m.clientY-rect.top;
|
||||||
|
for (const n of ns) if ((n.x-x)**2+(n.y-y)**2 < 400) {
|
||||||
|
$('#detail').textContent = n.name + ` (deg ${n.deg})`; return; }
|
||||||
|
for (const e of edges) {
|
||||||
|
const a=nodes.get(e.subject), b=nodes.get(e.object);
|
||||||
|
const mx=(a.x+b.x)/2, my=(a.y+b.y)/2;
|
||||||
|
if ((mx-x)**2+(my-y)**2 < 500) {
|
||||||
|
$('#detail').textContent = `${e.subject} — ${e.rel} — ${e.object}` +
|
||||||
|
(e.t_start?` [${e.t_start}..${e.t_end||'now'}]`:'') +
|
||||||
|
(e.last_touch?` · touched @${e.last_touch.ts} (${e.last_touch.page})`:' · untouched this run');
|
||||||
|
return; }
|
||||||
|
}
|
||||||
|
};
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
"""
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main(sys.argv))
|
||||||
+90
-2
@@ -58,20 +58,95 @@ class PromptLogCallback(dspy.utils.callback.BaseCallback):
|
|||||||
self._starts: dict[str, float] = {} # lm call_id -> monotonic start
|
self._starts: dict[str, float] = {} # lm call_id -> monotonic start
|
||||||
self._stage_of: dict[str, str] = {} # lm call_id -> stage label
|
self._stage_of: dict[str, str] = {} # lm call_id -> stage label
|
||||||
self._file_of: dict[str, Path] = {} # lm call_id -> prompt file
|
self._file_of: dict[str, Path] = {} # lm call_id -> prompt file
|
||||||
|
self._seq_of: dict[str, int] = {} # lm call_id -> prompt seq (budget mirror)
|
||||||
|
self._fname_of: dict[str, str] = {} # lm call_id -> prompt file name
|
||||||
|
self._sig_call_id: str | None = None # innermost module call_id (sig events)
|
||||||
|
self._sig_stage_of: dict[str, str] = {} # module call_id -> stage label
|
||||||
self.reasks = 0 # LM calls the budget did not charge
|
self.reasks = 0 # LM calls the budget did not charge
|
||||||
self.meter = None # callable(str stage) -> None; budget charge
|
self.meter = None # callable(str stage) -> None; budget charge
|
||||||
|
|
||||||
# -- dspy plumbing -------------------------------------------------------
|
# -- dspy plumbing -------------------------------------------------------
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _jsonable(v) -> object:
|
||||||
|
"""Signature field values -> JSON-safe primitives (recorder law:
|
||||||
|
small structured payloads; the exact prompt lives in the file)."""
|
||||||
|
try:
|
||||||
|
import pydantic
|
||||||
|
if isinstance(v, pydantic.BaseModel):
|
||||||
|
return v.model_dump()
|
||||||
|
except Exception: # noqa: BLE001 — best effort, never raises
|
||||||
|
pass
|
||||||
|
if isinstance(v, (str, int, float, bool)) or v is None:
|
||||||
|
return v
|
||||||
|
if isinstance(v, (list, tuple)):
|
||||||
|
return [PromptLogCallback._jsonable(x) for x in v]
|
||||||
|
if isinstance(v, dict):
|
||||||
|
return {str(k): PromptLogCallback._jsonable(x) for k, x in v.items()}
|
||||||
|
return str(v)
|
||||||
|
|
||||||
|
def _emit_sig_start(self, call_id: str, instance, inputs) -> None:
|
||||||
|
"""Signature inputs (owner 27/10): what the call receives, named.
|
||||||
|
dspy 3.4 hands the raw *args/**kwargs — the named form is inside
|
||||||
|
the kwargs repr; unknown shapes degrade to the repr itself
|
||||||
|
(honest, never a crash)."""
|
||||||
|
streams = self.streams
|
||||||
|
if streams is None:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
import ast
|
||||||
|
kw = (inputs or {}).get("kwargs", "")
|
||||||
|
named = ast.literal_eval(kw) if isinstance(kw, str) and kw.strip() \
|
||||||
|
else dict(kw or {})
|
||||||
|
if not isinstance(named, dict):
|
||||||
|
named = {"input": self._jsonable(inputs)}
|
||||||
|
except Exception: # noqa: BLE001 — observability never breaks a call
|
||||||
|
named = {"input": str(inputs)[:500]}
|
||||||
|
sig = getattr(getattr(instance, "signature", None), "__name__", None)
|
||||||
|
streams.recorder.emit("sig.start", stage=sig or "Predict",
|
||||||
|
call_id=call_id,
|
||||||
|
**{f"in.{k}": self._jsonable(v)
|
||||||
|
for k, v in named.items()})
|
||||||
|
|
||||||
|
def _emit_sig_done(self, call_id: str, outputs, exception) -> None:
|
||||||
|
"""Signature outputs (owner 27/10): the typed fields the call
|
||||||
|
produced, named — the Prediction's own attributes (only ones the
|
||||||
|
module's signature declares; dspy appends 'reasoning' internals)."""
|
||||||
|
streams = self.streams
|
||||||
|
if streams is None:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
named: dict[str, object] = {}
|
||||||
|
if isinstance(outputs, dict):
|
||||||
|
named = {k: self._jsonable(v) for k, v in outputs.items()
|
||||||
|
if k not in ("reasoning", "reasoning_model_response")}
|
||||||
|
elif outputs is not None:
|
||||||
|
for k in (getattr(outputs, "_store", None) or {}):
|
||||||
|
if k in ("reasoning", "reasoning_model_response"):
|
||||||
|
continue
|
||||||
|
named[k] = self._jsonable(outputs[k])
|
||||||
|
streams.recorder.emit("sig.done", stage=self._sig_stage_of.pop(call_id, "?"),
|
||||||
|
call_id=call_id,
|
||||||
|
exception=repr(exception)[:120] if exception else None,
|
||||||
|
**{f"out.{k}": v for k, v in named.items()})
|
||||||
|
except Exception: # noqa: BLE001 — observability never breaks a call
|
||||||
|
pass
|
||||||
|
|
||||||
def on_module_start(self, call_id, instance, inputs):
|
def on_module_start(self, call_id, instance, inputs):
|
||||||
sig = getattr(getattr(instance, "signature", None), "__name__", None)
|
sig = getattr(getattr(instance, "signature", None), "__name__", None)
|
||||||
label = _STAGE_BY_MODULE.get(sig or "", sig or type(instance).__name__)
|
label = _STAGE_BY_MODULE.get(sig or "", sig or type(instance).__name__)
|
||||||
self._stack.append(label)
|
self._stack.append(label)
|
||||||
|
self._sig_call_id = call_id
|
||||||
|
self._sig_stage_of[call_id] = label
|
||||||
self._fresh_forward = True # this forward's first LM call is not a re-ask
|
self._fresh_forward = True # this forward's first LM call is not a re-ask
|
||||||
|
self._emit_sig_start(call_id, instance, inputs)
|
||||||
|
|
||||||
def on_module_end(self, call_id, outputs, exception):
|
def on_module_end(self, call_id, outputs, exception):
|
||||||
if self._stack:
|
if self._stack:
|
||||||
self._stack.pop()
|
self._stack.pop()
|
||||||
|
if call_id == self._sig_call_id:
|
||||||
|
self._emit_sig_done(call_id, outputs, exception)
|
||||||
|
self._sig_call_id = None
|
||||||
|
|
||||||
def on_lm_start(self, call_id, instance, inputs):
|
def on_lm_start(self, call_id, instance, inputs):
|
||||||
import time
|
import time
|
||||||
@@ -117,6 +192,8 @@ class PromptLogCallback(dspy.utils.callback.BaseCallback):
|
|||||||
encoding="utf-8",
|
encoding="utf-8",
|
||||||
)
|
)
|
||||||
self._file_of[call_id] = f
|
self._file_of[call_id] = f
|
||||||
|
self._seq_of[call_id] = n
|
||||||
|
self._fname_of[call_id] = fn
|
||||||
streams.log(
|
streams.log(
|
||||||
f"prompt #{n} stage={label} chars={chars} tokens~{chars // 4} "
|
f"prompt #{n} stage={label} chars={chars} tokens~{chars // 4} "
|
||||||
f"-> prompts/{fn}"
|
f"-> prompts/{fn}"
|
||||||
@@ -130,7 +207,10 @@ class PromptLogCallback(dspy.utils.callback.BaseCallback):
|
|||||||
label = self._stage_of.pop(call_id, "lm")
|
label = self._stage_of.pop(call_id, "lm")
|
||||||
start = self._starts.pop(call_id, None)
|
start = self._starts.pop(call_id, None)
|
||||||
f = self._file_of.pop(call_id, None)
|
f = self._file_of.pop(call_id, None)
|
||||||
dur = f"{time.monotonic() - start:.1f}s" if start is not None else "?"
|
n = self._seq_of.pop(call_id, None)
|
||||||
|
fn = self._fname_of.pop(call_id, None)
|
||||||
|
dur_s = (time.monotonic() - start) if start is not None else None
|
||||||
|
dur = f"{dur_s:.1f}s" if dur_s is not None else "?"
|
||||||
# RAW RESPONSE into the same file: the exact LM text, unmodified —
|
# RAW RESPONSE into the same file: the exact LM text, unmodified —
|
||||||
# the parsed OUTPUT can lie by omission (run I)
|
# the parsed OUTPUT can lie by omission (run I)
|
||||||
if f is not None:
|
if f is not None:
|
||||||
@@ -146,6 +226,14 @@ class PromptLogCallback(dspy.utils.callback.BaseCallback):
|
|||||||
+ ")\n" + (raw or "(empty)"))
|
+ ")\n" + (raw or "(empty)"))
|
||||||
if streams is not None:
|
if streams is not None:
|
||||||
streams.log(f"prompt {label} done in {dur}")
|
streams.log(f"prompt {label} done in {dur}")
|
||||||
|
try:
|
||||||
|
streams.recorder.emit(
|
||||||
|
"llm.done", stage=label, call_seq=n,
|
||||||
|
dur_s=(round(dur_s, 2) if dur_s is not None else None),
|
||||||
|
file=f"prompts/{fn}" if fn is not None else None,
|
||||||
|
exception=repr(exception)[:120] if exception else None)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
# dspy module class -> log stage label (knowledge/ + floop/ share the callback)
|
# dspy module class -> log stage label (knowledge/ + floop/ share the callback)
|
||||||
@@ -156,7 +244,7 @@ _STAGE_BY_MODULE = {
|
|||||||
"Expert": "EXPERT",
|
"Expert": "EXPERT",
|
||||||
"Missing": "MISSING",
|
"Missing": "MISSING",
|
||||||
"Answer": "ANSWER",
|
"Answer": "ANSWER",
|
||||||
"EntityMaskSignature": "MASK",
|
"NamedEntityRecognitionSignature": "MASK",
|
||||||
"KnowledgeExpert": "knowledge",
|
"KnowledgeExpert": "knowledge",
|
||||||
"InitSignature": "INIT",
|
"InitSignature": "INIT",
|
||||||
"RouteSignature": "ROUTE",
|
"RouteSignature": "ROUTE",
|
||||||
|
|||||||
@@ -585,14 +585,16 @@ class FloopRun:
|
|||||||
self.knowledge_engine.charge = self._charge
|
self.knowledge_engine.charge = self._charge
|
||||||
self.knowledge_engine.modules = self.modules
|
self.knowledge_engine.modules = self.modules
|
||||||
self.streams.call("EXPERT", f"knowledge pipeline on {q.qid}: {q.text[:80]}",
|
self.streams.call("EXPERT", f"knowledge pipeline on {q.qid}: {q.text[:80]}",
|
||||||
think=self.tprefix + f"asking knowledge (KG pipeline): {q.text[:90]}")
|
think=self.tprefix + f"asking knowledge (KG pipeline): {q.text[:90]}",
|
||||||
|
expert="knowledge")
|
||||||
row = self.knowledge_engine.run(q.qid, instantiate(q.text, self.table),
|
row = self.knowledge_engine.run(q.qid, instantiate(q.text, self.table),
|
||||||
self.query, self.table, q.answer_type,
|
self.query, self.table, q.answer_type,
|
||||||
streams=self.streams)
|
streams=self.streams)
|
||||||
else:
|
else:
|
||||||
engine = LLMExpertEngine(self.modules, self._charge, expert_kind=attendant)
|
engine = LLMExpertEngine(self.modules, self._charge, expert_kind=attendant)
|
||||||
self.streams.call("EXPERT", f"{attendant} on {q.qid}: {q.text[:80]}",
|
self.streams.call("EXPERT", f"{attendant} on {q.qid}: {q.text[:80]}",
|
||||||
think=self.tprefix + f"asking {attendant}: {q.text[:90]}")
|
think=self.tprefix + f"asking {attendant}: {q.text[:90]}",
|
||||||
|
expert=attendant)
|
||||||
row = engine.run(q.qid, instantiate(q.text, self.table),
|
row = engine.run(q.qid, instantiate(q.text, self.table),
|
||||||
self.query, self.table, q.answer_type, streams=self.streams)
|
self.query, self.table, q.answer_type, streams=self.streams)
|
||||||
self.engine_calls += 1
|
self.engine_calls += 1
|
||||||
|
|||||||
@@ -0,0 +1,126 @@
|
|||||||
|
"""The flight recorder — every component of a run leaves a JSON line.
|
||||||
|
|
||||||
|
Owner ruling (26/10): 'vull poder fer com un debug amb l'IDE de
|
||||||
|
programació, però a posteriori de l'execució.' This is the recorder
|
||||||
|
half: LLM calls and code components (gate, skim, claims, type, merge,
|
||||||
|
probe, prover...) each emit one event to runs/<ts>/events.jsonl with
|
||||||
|
their input, output, and parent — the span tree comes from `parent`.
|
||||||
|
|
||||||
|
Design laws:
|
||||||
|
- The recorder must NEVER break a run: emitting is wrapped so any
|
||||||
|
failure is swallowed; with no run dir it is a silent no-op.
|
||||||
|
- One JSON object per line, appended and flushed: the file is
|
||||||
|
tail-able while the run is live and jq-able afterwards.
|
||||||
|
- `seq` is global per run (order of emission = file order).
|
||||||
|
- `in`/`out` carry only the caller-provided payload; the prompt files
|
||||||
|
keep the exact full text — events stay small and structured.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import time
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
|
||||||
|
class Recorder:
|
||||||
|
"""Append-only JSONL event log for one run. No-op without a run dir."""
|
||||||
|
|
||||||
|
def __init__(self, run_dir: str | Path | None = None,
|
||||||
|
memory: bool = False) -> None:
|
||||||
|
self.run_dir = Path(run_dir) if run_dir else None
|
||||||
|
self.run_ts = (datetime.now(timezone.utc).astimezone()
|
||||||
|
.strftime("%H:%M:%S.%f")[:-3])
|
||||||
|
self.seq = 0
|
||||||
|
self.events = 0
|
||||||
|
self._memory = memory # keep events in RAM even without a file
|
||||||
|
self._fh = None
|
||||||
|
self._buffer: list[dict] = []
|
||||||
|
if self.run_dir is not None:
|
||||||
|
try:
|
||||||
|
self._fh = (self.run_dir / "events.jsonl").open(
|
||||||
|
"a", encoding="utf-8")
|
||||||
|
except OSError:
|
||||||
|
self._fh = None
|
||||||
|
|
||||||
|
# -- emission ---------------------------------------------------------
|
||||||
|
|
||||||
|
def emit(self, event: str, **fields: Any) -> None:
|
||||||
|
"""One JSON line. `in_`/`out` are renamed to `in`/`out` (keywords).
|
||||||
|
Never raises: a run must not die for an observability side effect.
|
||||||
|
Without a run dir this is a TOTAL no-op (no file, no buffer, no
|
||||||
|
counters): disabled must mean zero effect.
|
||||||
|
"""
|
||||||
|
if self._fh is None and not self._memory:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
payload = dict(fields)
|
||||||
|
if "in_" in payload:
|
||||||
|
payload["in"] = payload.pop("in_")
|
||||||
|
if "out_" in payload:
|
||||||
|
payload["out"] = payload.pop("out_")
|
||||||
|
self.seq += 1
|
||||||
|
line = {
|
||||||
|
"seq": self.seq,
|
||||||
|
"ts": datetime.now(timezone.utc).astimezone()
|
||||||
|
.strftime("%H:%M:%S.%f")[:-3],
|
||||||
|
"run_ts": self.run_ts,
|
||||||
|
"event": event,
|
||||||
|
**payload,
|
||||||
|
}
|
||||||
|
if self._fh is not None:
|
||||||
|
self._fh.write(json.dumps(line, default=str) + "\n")
|
||||||
|
self._fh.flush()
|
||||||
|
self._buffer.append(line)
|
||||||
|
self.events += 1
|
||||||
|
except Exception: # noqa: BLE001 — observability never kills the run
|
||||||
|
pass
|
||||||
|
|
||||||
|
# -- post-mortem reads --------------------------------------------------
|
||||||
|
|
||||||
|
def events_of(self, event: str) -> list[dict]:
|
||||||
|
"""In-memory events by name (for snapshot annotations)."""
|
||||||
|
return [e for e in self._buffer if e.get("event") == event]
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
if self._fh is not None and not self._fh.closed:
|
||||||
|
try:
|
||||||
|
self._fh.flush()
|
||||||
|
self._fh.close()
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def timed(fn, recorder: Recorder, event: str, **parent_fields):
|
||||||
|
"""Wrap a code component: emit comp.done with in/out and duration."""
|
||||||
|
import functools
|
||||||
|
|
||||||
|
@functools.wraps(fn)
|
||||||
|
def wrapper(*args, **kwargs):
|
||||||
|
t0 = time.monotonic()
|
||||||
|
try:
|
||||||
|
out = fn(*args, **kwargs)
|
||||||
|
recorder.emit(event, dur_ms=int((time.monotonic() - t0) * 1000),
|
||||||
|
ok=True, out=_safe(out), **parent_fields)
|
||||||
|
return out
|
||||||
|
except Exception as e: # noqa: BLE001 — record then re-raise
|
||||||
|
recorder.emit(event, dur_ms=int((time.monotonic() - t0) * 1000),
|
||||||
|
ok=False, error=repr(e)[:200], **parent_fields)
|
||||||
|
raise
|
||||||
|
return wrapper
|
||||||
|
|
||||||
|
|
||||||
|
def _safe(v: Any, _depth: int = 0) -> Any:
|
||||||
|
"""Best-effort JSON-safety: truncate strings, cap depth."""
|
||||||
|
if _depth > 4:
|
||||||
|
return "..."
|
||||||
|
if isinstance(v, str):
|
||||||
|
return v if len(v) <= 500 else v[:500] + "…"
|
||||||
|
if isinstance(v, dict):
|
||||||
|
return {str(k): _safe(x, _depth + 1) for k, x in list(v.items())[:30]}
|
||||||
|
if isinstance(v, (list, tuple)):
|
||||||
|
return [_safe(x, _depth + 1) for x in list(v)[:50]]
|
||||||
|
if v is None or isinstance(v, (bool, int, float)):
|
||||||
|
return v
|
||||||
|
return str(v)[:200]
|
||||||
+17
-2
@@ -12,6 +12,8 @@ import sys
|
|||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
from .recorder import Recorder
|
||||||
|
|
||||||
|
|
||||||
def _slug(text: str, maxlen: int = 40) -> str:
|
def _slug(text: str, maxlen: int = 40) -> str:
|
||||||
s = re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")
|
s = re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")
|
||||||
@@ -35,6 +37,7 @@ class RunStreams:
|
|||||||
self.log_path = self.run_dir / "run.log"
|
self.log_path = self.run_dir / "run.log"
|
||||||
self.verbose = verbose
|
self.verbose = verbose
|
||||||
self.prompt_seq = 0 # exact-prompt files: prompts/NN-stage.txt
|
self.prompt_seq = 0 # exact-prompt files: prompts/NN-stage.txt
|
||||||
|
self.recorder = Recorder(run_dir=self.run_dir, memory=True)
|
||||||
self._fh = open(self.log_path, "a", encoding="utf-8")
|
self._fh = open(self.log_path, "a", encoding="utf-8")
|
||||||
|
|
||||||
def bump_prompt_seq(self) -> int:
|
def bump_prompt_seq(self) -> int:
|
||||||
@@ -65,21 +68,32 @@ class RunStreams:
|
|||||||
|
|
||||||
# ---- structural events -------------------------------------------------
|
# ---- structural events -------------------------------------------------
|
||||||
|
|
||||||
def call(self, stage: str, description: str, think: str | None = None) -> None:
|
def call(self, stage: str, description: str, think: str | None = None,
|
||||||
"""An LLM call or engine step is starting."""
|
expert: str | None = None) -> None:
|
||||||
|
"""An LLM call or engine step is starting. `expert` names the
|
||||||
|
attendant for EXPERT steps: the trace span reads 'EXPERT
|
||||||
|
knowledge' and its children carry the 'knowledge.' prefix
|
||||||
|
(owner 27/10: inside an expert, see the expert's name)."""
|
||||||
self._emit_log(f"CALL {stage}: {description}")
|
self._emit_log(f"CALL {stage}: {description}")
|
||||||
|
if expert:
|
||||||
|
self.recorder.emit("comp.start", comp=stage, desc=description[:200],
|
||||||
|
expert=expert)
|
||||||
|
else:
|
||||||
|
self.recorder.emit("comp.start", comp=stage, desc=description[:200])
|
||||||
if think is not None:
|
if think is not None:
|
||||||
self.think_line(f"[{stage}] {think}")
|
self.think_line(f"[{stage}] {think}")
|
||||||
|
|
||||||
def output(self, stage: str, text: str, think: bool = True) -> None:
|
def output(self, stage: str, text: str, think: bool = True) -> None:
|
||||||
"""Raw LLM (or engine) output as it lands."""
|
"""Raw LLM (or engine) output as it lands."""
|
||||||
self._emit_log(f"OUTPUT {stage}: {text}")
|
self._emit_log(f"OUTPUT {stage}: {text}")
|
||||||
|
self.recorder.emit("comp.out", comp=stage, out=text[:500])
|
||||||
if think:
|
if think:
|
||||||
self.think(text)
|
self.think(text)
|
||||||
|
|
||||||
def state(self, text: str, think: bool = False) -> None:
|
def state(self, text: str, think: bool = False) -> None:
|
||||||
"""State change: evidence appended, question status, budget."""
|
"""State change: evidence appended, question status, budget."""
|
||||||
self._emit_log(f"STATE {text}")
|
self._emit_log(f"STATE {text}")
|
||||||
|
self.recorder.emit("state", text=text[:300])
|
||||||
if think:
|
if think:
|
||||||
self.think_line(text)
|
self.think_line(text)
|
||||||
|
|
||||||
@@ -94,6 +108,7 @@ class RunStreams:
|
|||||||
|
|
||||||
def final(self, text: str) -> None:
|
def final(self, text: str) -> None:
|
||||||
self._emit_log(f"FINAL {text}")
|
self._emit_log(f"FINAL {text}")
|
||||||
|
self.recorder.emit("run.final", out=text[:2000])
|
||||||
self.think_line(f"[FINAL] {text}")
|
self.think_line(f"[FINAL] {text}")
|
||||||
|
|
||||||
# ---- internals ---------------------------------------------------------
|
# ---- internals ---------------------------------------------------------
|
||||||
|
|||||||
@@ -0,0 +1,521 @@
|
|||||||
|
"""floop-traces — replay a run's events.jsonl as OpenTelemetry spans.
|
||||||
|
|
||||||
|
ARCHITECTURE.md §9-bis, built: one run = one trace; each LLM call, engine
|
||||||
|
step (probe, search, fetch, check, merge) and evidence append = one span.
|
||||||
|
Post-mortem only: it reads runs/<ts>/events.jsonl after the run and pushes
|
||||||
|
OTLP/HTTP-JSON to Jaeger (or any OTLP consumer) — the run itself never
|
||||||
|
touches the network (observability never kills a run).
|
||||||
|
|
||||||
|
Owner's visibility laws (27/10), what the exporter renders:
|
||||||
|
- INPUTS/OUTPUTS NAMED: fn.done events (search, fetch, judge, compose...)
|
||||||
|
become spans carrying in.<arg> / out.<arg> attributes; LLM calls carry
|
||||||
|
the Signature's fields in.<field> / out.<field> (sig.start/sig.done,
|
||||||
|
emitted by the dspy callback), not just the prompt-file pointer.
|
||||||
|
- THE PROMPT IS CLICKABLE: every LLM span gets a child 'prompt' span whose
|
||||||
|
attributes carry the prompt-file's full text (prompt + raw response),
|
||||||
|
read from the run dir at export time — old runs work retroactively.
|
||||||
|
- EXPERT NAMES: an EXPERT comp.start with expert= reads 'EXPERT
|
||||||
|
knowledge'; everything nested inside carries the 'knowledge.' prefix
|
||||||
|
(knowledge.state, knowledge.TYPE, knowledge.search...), and spans of an
|
||||||
|
expert are exported under their own OTel SERVICE (floop / knowledge /
|
||||||
|
...) so Jaeger groups and colors them by component.
|
||||||
|
- Recursive child runs share the parent's events.jsonl (each child has its
|
||||||
|
own run_ts and restarts seq); each contiguous run_ts block becomes its
|
||||||
|
own span — the fractal recursion shows as nested runs in the waterfall.
|
||||||
|
|
||||||
|
Usage (from code/):
|
||||||
|
uv run python -m floop.traces runs/<ts>-<slug> # one run (or several)
|
||||||
|
uv run python -m floop.traces --latest 3 # the 3 newest runs
|
||||||
|
uv run python -m floop.traces <dir> --dry # build, don't push
|
||||||
|
|
||||||
|
Endpoint: --url or FLOOP_OTLP_URL, default http://10.3.14.59:4318/v1/traces
|
||||||
|
(the Jaeger container on this VPS). Stdlib only — no new dependencies.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import urllib.request
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
|
DEFAULT_URL = "http://10.3.14.59:4318/v1/traces"
|
||||||
|
DEFAULT_UI = "http://10.3.14.59:16686"
|
||||||
|
_TZ = ZoneInfo("Europe/Madrid") # event `ts` is local wall time (recorder law)
|
||||||
|
_PROMPT_CAP = 60_000 # chars per prompt/response attribute
|
||||||
|
|
||||||
|
|
||||||
|
def load_events(run_dir: str | Path) -> list[dict]:
|
||||||
|
"""Read events.jsonl; skip empty/torn lines; honest error if absent/empty."""
|
||||||
|
run_dir = Path(run_dir)
|
||||||
|
ev_path = run_dir / "events.jsonl"
|
||||||
|
if not ev_path.exists():
|
||||||
|
print(f"no events.jsonl in {run_dir} — nothing to export", file=sys.stderr)
|
||||||
|
raise SystemExit(1)
|
||||||
|
events = []
|
||||||
|
for line in ev_path.read_text(encoding="utf-8").splitlines():
|
||||||
|
line = line.strip()
|
||||||
|
if not line:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
events.append(json.loads(line))
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
pass # torn line mid-crash: skip, honest
|
||||||
|
if not events:
|
||||||
|
print(f"events.jsonl in {run_dir} is empty — nothing to export",
|
||||||
|
file=sys.stderr)
|
||||||
|
raise SystemExit(1)
|
||||||
|
return events
|
||||||
|
|
||||||
|
|
||||||
|
def _cap(v: Any, depth: int = 0) -> Any:
|
||||||
|
"""Attribute safety: truncate strings, cap depth/width. The kg snapshot
|
||||||
|
alone can carry 100+ edges — spans must stay small and readable."""
|
||||||
|
if isinstance(v, str):
|
||||||
|
return v if len(v) <= 500 else v[:497] + "…"
|
||||||
|
if v is None or isinstance(v, (bool, int, float)):
|
||||||
|
return v
|
||||||
|
if depth >= 3:
|
||||||
|
return "…"
|
||||||
|
if isinstance(v, dict):
|
||||||
|
return {str(k): _cap(x, depth + 1) for k, x in list(v.items())[:20]}
|
||||||
|
if isinstance(v, (list, tuple)):
|
||||||
|
return [_cap(x, depth + 1) for x in list(v)[:5]]
|
||||||
|
return str(v)[:200]
|
||||||
|
|
||||||
|
|
||||||
|
def _attrs(**fields: Any) -> dict[str, str]:
|
||||||
|
return {f"floop.{k}": str(_cap(v)) for k, v in fields.items() if v is not None}
|
||||||
|
|
||||||
|
|
||||||
|
def _flat_attrs(prefix: str, d: Any) -> dict[str, str]:
|
||||||
|
"""in./out. attribute blocks: one attribute per named argument
|
||||||
|
(in.query, out.titles...); structured values compact-JSON (capped)."""
|
||||||
|
out: dict[str, str] = {}
|
||||||
|
if not isinstance(d, dict):
|
||||||
|
return {prefix: str(_cap(d))} if d is not None else out
|
||||||
|
for k, v in d.items():
|
||||||
|
if v is None:
|
||||||
|
continue
|
||||||
|
if isinstance(v, (str, int, float, bool)):
|
||||||
|
out[f"{prefix}.{k}"] = str(_cap(v))
|
||||||
|
else:
|
||||||
|
out[f"{prefix}.{k}"] = str(_cap(json.dumps(v, default=str,
|
||||||
|
ensure_ascii=False)))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _read_prompt(run_dir: Path, rel: str) -> tuple[str, str] | None:
|
||||||
|
"""(prompt_text, raw_response) from a prompts/NN-stage.txt file — the
|
||||||
|
exact rendered prompt and the model's raw answer, verbatim."""
|
||||||
|
p = run_dir / rel
|
||||||
|
if not p.exists():
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
text = p.read_text(encoding="utf-8", errors="replace")
|
||||||
|
except OSError:
|
||||||
|
return None
|
||||||
|
head, sep, resp = text.partition("\n\n# RAW RESPONSE")
|
||||||
|
if not sep:
|
||||||
|
head, resp = text, ""
|
||||||
|
if head.startswith("#") and "\n\n" in head: # drop the '# stage=...' line
|
||||||
|
head = head.split("\n\n", 1)[1]
|
||||||
|
if sep:
|
||||||
|
# the header line continues after '# RAW RESPONSE' ('(after 2.3s)');
|
||||||
|
# the response starts on the NEXT line
|
||||||
|
_, _, resp = resp.partition("\n")
|
||||||
|
return head[:_PROMPT_CAP], resp[:_PROMPT_CAP]
|
||||||
|
|
||||||
|
|
||||||
|
class _Clock:
|
||||||
|
"""Local wall time -> unix nanos. The date comes from the run dir name;
|
||||||
|
a backwards jump in `ts` means midnight crossed (events are monotonic).
|
||||||
|
Only ever called in emission order — pre-reading a later event would
|
||||||
|
poison the midnight detector (found the hard way)."""
|
||||||
|
|
||||||
|
def __init__(self, run_dir: Path) -> None:
|
||||||
|
stamp = run_dir.name.split("-")[0]
|
||||||
|
try:
|
||||||
|
self.day = datetime.strptime(stamp, "%Y%m%d").date()
|
||||||
|
except ValueError: # dir name is not the run contract —
|
||||||
|
mtime = (run_dir / "events.jsonl").stat().st_mtime # fall back
|
||||||
|
self.day = datetime.fromtimestamp(mtime).date() # honestly
|
||||||
|
self._prev_sod = -1
|
||||||
|
|
||||||
|
def nanos(self, ts: str) -> int:
|
||||||
|
t = datetime.strptime(ts, "%H:%M:%S.%f").time()
|
||||||
|
sod = t.hour * 3600 + t.minute * 60 + t.second
|
||||||
|
if sod < self._prev_sod: # wrapped past midnight
|
||||||
|
self.day = self.day + timedelta(days=1)
|
||||||
|
self._prev_sod = sod
|
||||||
|
dt = datetime.combine(self.day, t).replace(tzinfo=_TZ)
|
||||||
|
return int(dt.timestamp() * 1_000_000_000)
|
||||||
|
|
||||||
|
|
||||||
|
def _hex(seed: str, n: int) -> str:
|
||||||
|
return hashlib.sha256(seed.encode()).hexdigest()[:n]
|
||||||
|
|
||||||
|
|
||||||
|
def _blocks(events: list[dict]) -> list[tuple[str, list[dict]]]:
|
||||||
|
"""Split into contiguous run_ts blocks (child runs write the same file).
|
||||||
|
seq restarts are expected across blocks; positions, not seq, identify."""
|
||||||
|
blocks: list[tuple[str, list[dict]]] = []
|
||||||
|
for e in events:
|
||||||
|
rts = str(e.get("run_ts", ""))
|
||||||
|
if not blocks or blocks[-1][0] != rts:
|
||||||
|
blocks.append((rts, []))
|
||||||
|
blocks[-1][1].append(e)
|
||||||
|
return blocks
|
||||||
|
|
||||||
|
|
||||||
|
def _block_question(block: list[dict]) -> str:
|
||||||
|
for e in block:
|
||||||
|
if e["event"] == "comp.start" \
|
||||||
|
and str(e.get("desc", "")).startswith("decompose: "):
|
||||||
|
return str(e["desc"][len("decompose: "):])
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def build_payload(run_dir: str | Path, events: list[dict]) -> tuple[dict, str]:
|
||||||
|
"""events.jsonl -> (OTLP/JSON payload, trace_id). Deterministic ids: the
|
||||||
|
same run always maps to the same trace, so re-pushes land on the same
|
||||||
|
trace and the UI link is stable."""
|
||||||
|
run_dir = Path(run_dir)
|
||||||
|
run_key = run_dir.name # <ts>-<slug>: unique, stable
|
||||||
|
trace_id = _hex(f"floop:{run_key}", 32)
|
||||||
|
root_id = _hex(f"floop:{run_key}:root", 16)
|
||||||
|
clock = _Clock(run_dir)
|
||||||
|
blocks = _blocks(events)
|
||||||
|
multi = len(blocks) > 1
|
||||||
|
|
||||||
|
def span(span_id: str, parent_id: str, name: str, start: int, end: int,
|
||||||
|
attrs: dict[str, str], error: bool = False) -> dict:
|
||||||
|
s = {
|
||||||
|
"traceId": trace_id, "spanId": span_id,
|
||||||
|
"name": name, "kind": "SPAN_KIND_INTERNAL",
|
||||||
|
"startTimeUnixNano": str(start),
|
||||||
|
"endTimeUnixNano": str(max(end, start + 1_000_000)), # >= 1ms
|
||||||
|
"attributes": [{"key": k, "value": {"stringValue": v}}
|
||||||
|
for k, v in attrs.items()],
|
||||||
|
"status": {"code": "STATUS_CODE_ERROR"} if error else
|
||||||
|
{"code": "STATUS_CODE_OK"},
|
||||||
|
"_svc": "floop", # internal keys stripped before the payload
|
||||||
|
}
|
||||||
|
if parent_id: # omitted for the root — empty values are rejected
|
||||||
|
s["parentSpanId"] = parent_id
|
||||||
|
return s
|
||||||
|
|
||||||
|
question = _block_question(blocks[0][1])
|
||||||
|
answer = next((str(_cap(e["out"])) for e in reversed(events)
|
||||||
|
if e["event"] == "run.final" and e.get("out")), "")
|
||||||
|
root_attrs = {"run.id": run_key, "floop.events": str(len(events))}
|
||||||
|
if question:
|
||||||
|
root_attrs["run.question"] = _cap(question)
|
||||||
|
if answer:
|
||||||
|
root_attrs["run.answer"] = answer
|
||||||
|
|
||||||
|
spans: list[dict] = []
|
||||||
|
stack: list[dict] = [] # open spans, outermost first (comps + sig + runs)
|
||||||
|
last_nanos = 0
|
||||||
|
pos = -1 # position in the file — the real identity (seq restarts)
|
||||||
|
mark = 0 # stack depth the current block may not close below
|
||||||
|
|
||||||
|
# -- context helpers (the expert a span lives in) ------------------------
|
||||||
|
def _expert() -> str | None:
|
||||||
|
for s in reversed(stack):
|
||||||
|
if s.get("_expert"):
|
||||||
|
return s["_expert"]
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _prefix() -> str:
|
||||||
|
e = _expert()
|
||||||
|
return f"{e}." if e else ""
|
||||||
|
|
||||||
|
def _service() -> str:
|
||||||
|
return _expert() or "floop"
|
||||||
|
|
||||||
|
def close_block() -> None:
|
||||||
|
"""Block end: everything the block opened closes honestly (a child
|
||||||
|
run never leaves comps dangling into the next block)."""
|
||||||
|
while len(stack) > mark:
|
||||||
|
s = stack.pop()
|
||||||
|
s["endTimeUnixNano"] = str(last_nanos)
|
||||||
|
spans.append(s)
|
||||||
|
|
||||||
|
def add_prompt_child(parent: dict, rel: str, start: int, end: int) -> None:
|
||||||
|
"""The clickable prompt (owner 27/10): the file's full text as a
|
||||||
|
child node under the LLM call it belongs to."""
|
||||||
|
pr = _read_prompt(run_dir, rel)
|
||||||
|
if pr is None:
|
||||||
|
return
|
||||||
|
attrs = {"prompt.file": rel}
|
||||||
|
if pr[0]:
|
||||||
|
attrs["prompt.text"] = pr[0]
|
||||||
|
if pr[1]:
|
||||||
|
attrs["prompt.response"] = pr[1]
|
||||||
|
c = span(_hex(f"floop:{run_key}:p:{parent['spanId']}:{rel}", 16),
|
||||||
|
parent["spanId"], "prompt", start, end, attrs)
|
||||||
|
c["_svc"] = parent["_svc"]
|
||||||
|
spans.append(c)
|
||||||
|
|
||||||
|
for rts, block in blocks:
|
||||||
|
close_block()
|
||||||
|
mark = len(stack)
|
||||||
|
parent = stack[-1]["spanId"] if stack else root_id
|
||||||
|
if multi: # one span per run: the fractal child, visible as nesting
|
||||||
|
bquestion = _block_question(block)
|
||||||
|
bstart = clock.nanos(block[0]["ts"]) # its own first event
|
||||||
|
rs = span(_hex(f"floop:{run_key}:run:{pos + 1}", 16), parent,
|
||||||
|
(bquestion[:120] or f"floop.run {rts}"),
|
||||||
|
bstart, bstart,
|
||||||
|
_attrs(run_ts=rts))
|
||||||
|
stack.append(rs) # shipped by close_block() — never double-append
|
||||||
|
for e in block:
|
||||||
|
pos += 1
|
||||||
|
ev, ts = e["event"], e["ts"]
|
||||||
|
now = clock.nanos(ts)
|
||||||
|
last_nanos = now
|
||||||
|
parent = stack[-1]["spanId"] if stack else root_id
|
||||||
|
extra = {k: v for k, v in e.items()
|
||||||
|
if k not in ("seq", "ts", "run_ts", "event")}
|
||||||
|
sid = _hex(f"floop:{run_key}:s{pos}", 16)
|
||||||
|
|
||||||
|
if ev == "comp.start":
|
||||||
|
expert = e.get("expert")
|
||||||
|
name = str(e.get("comp", "COMP"))
|
||||||
|
if expert:
|
||||||
|
name = f"{name} {expert}"
|
||||||
|
s = span(sid, parent, name, now, now,
|
||||||
|
_attrs(comp=e.get("comp"), desc=e.get("desc")))
|
||||||
|
s["_comp"] = str(e.get("comp", ""))
|
||||||
|
if expert:
|
||||||
|
s["_expert"] = str(expert)
|
||||||
|
s["_svc"] = str(expert)
|
||||||
|
stack.append(s)
|
||||||
|
continue
|
||||||
|
|
||||||
|
if ev == "comp.out": # close the innermost same-comp span
|
||||||
|
# search the WHOLE stack: the parent EXPERT that spawned a
|
||||||
|
# child stays open across block boundaries (its comp.out
|
||||||
|
# arrives in a later block); mark only bounds block cleanup.
|
||||||
|
for j in range(len(stack) - 1, -1, -1):
|
||||||
|
if stack[j].get("_comp") == str(e.get("comp", "")):
|
||||||
|
s = stack[j]
|
||||||
|
s["endTimeUnixNano"] = str(now)
|
||||||
|
s["attributes"].extend(
|
||||||
|
{"key": k, "value": {"stringValue": v}}
|
||||||
|
for k, v in _attrs(out=e.get("out")).items())
|
||||||
|
spans.append(s) # complete: ship it
|
||||||
|
# spans opened INSIDE the comp close with it, honest
|
||||||
|
# (never silently dropped)
|
||||||
|
for inner in stack[j + 1:]:
|
||||||
|
inner["endTimeUnixNano"] = str(now)
|
||||||
|
spans.append(inner)
|
||||||
|
del stack[j:]
|
||||||
|
break
|
||||||
|
else: # unpaired comp.out: honest point span, never dropped
|
||||||
|
spans.append(span(sid, parent, f"{_prefix()}{e.get('comp', '?')}?",
|
||||||
|
now, now, _attrs(**extra)))
|
||||||
|
continue
|
||||||
|
|
||||||
|
if ev == "sig.start": # the Signature's inputs, named
|
||||||
|
s = span(sid, parent, f"{_prefix()}{e.get('stage', 'sig')}",
|
||||||
|
now, now,
|
||||||
|
_flat_attrs("in",
|
||||||
|
{k[3:]: v for k, v in e.items()
|
||||||
|
if k.startswith("in.")}))
|
||||||
|
s["_call_id"] = str(e.get("call_id", ""))
|
||||||
|
s["_svc"] = _service()
|
||||||
|
stack.append(s)
|
||||||
|
continue
|
||||||
|
|
||||||
|
if ev == "sig.done": # the Signature's outputs, named
|
||||||
|
out_attrs = _flat_attrs("out",
|
||||||
|
{k[4:]: v for k, v in e.items()
|
||||||
|
if k.startswith("out.")})
|
||||||
|
target = None
|
||||||
|
for j in range(len(stack) - 1, -1, -1):
|
||||||
|
if stack[j].get("_call_id") == str(e.get("call_id", "")):
|
||||||
|
target = stack[j]
|
||||||
|
break
|
||||||
|
if target is None: # unpaired: honest point span
|
||||||
|
spans.append(span(sid, parent,
|
||||||
|
f"{_prefix()}{e.get('stage', 'sig')}",
|
||||||
|
now, now, out_attrs,
|
||||||
|
error=bool(e.get("exception"))))
|
||||||
|
continue
|
||||||
|
# close it where it sits; everything above closes with it
|
||||||
|
j = stack.index(target)
|
||||||
|
target["endTimeUnixNano"] = str(now)
|
||||||
|
target["attributes"].extend(
|
||||||
|
{"key": k, "value": {"stringValue": v}}
|
||||||
|
for k, v in out_attrs.items())
|
||||||
|
if e.get("exception"):
|
||||||
|
target["status"] = {"code": "STATUS_CODE_ERROR"}
|
||||||
|
spans.append(target)
|
||||||
|
for inner in stack[j + 1:]:
|
||||||
|
inner["endTimeUnixNano"] = str(now)
|
||||||
|
spans.append(inner)
|
||||||
|
del stack[j:]
|
||||||
|
continue
|
||||||
|
|
||||||
|
if ev == "llm.done":
|
||||||
|
dur = int(float(e.get("dur_s") or 0) * 1_000_000_000)
|
||||||
|
stage = str(e.get("stage", "lm"))
|
||||||
|
# attach to the innermost open sig span (new runs); the
|
||||||
|
# sig span IS the call. Old runs: a standalone span.
|
||||||
|
host = None
|
||||||
|
for j in range(len(stack) - 1, -1, -1):
|
||||||
|
if "_call_id" in stack[j]:
|
||||||
|
host = stack[j]
|
||||||
|
break
|
||||||
|
err = bool(e.get("exception"))
|
||||||
|
if host is not None:
|
||||||
|
host["name"] = f"{_prefix()}{stage}"
|
||||||
|
host["attributes"].extend(
|
||||||
|
{"key": k, "value": {"stringValue": v}}
|
||||||
|
for k, v in _attrs(
|
||||||
|
dur_s=e.get("dur_s"), call_seq=e.get("call_seq"),
|
||||||
|
file=e.get("file")).items())
|
||||||
|
if err:
|
||||||
|
host["status"] = {"code": "STATUS_CODE_ERROR"}
|
||||||
|
rel = e.get("file")
|
||||||
|
if rel:
|
||||||
|
add_prompt_child(host, str(rel), now - dur, now)
|
||||||
|
else:
|
||||||
|
name = f"{'llm.'}{stage}" if not _prefix() \
|
||||||
|
else f"{_prefix()}{stage}"
|
||||||
|
s = span(sid, parent, name, now - dur, now,
|
||||||
|
_attrs(dur_s=e.get("dur_s"), call_seq=e.get("call_seq"),
|
||||||
|
file=e.get("file"), exception=e.get("exception")),
|
||||||
|
error=err)
|
||||||
|
s["_svc"] = _service()
|
||||||
|
spans.append(s)
|
||||||
|
rel = e.get("file")
|
||||||
|
if rel:
|
||||||
|
add_prompt_child(s, str(rel), now - dur, now)
|
||||||
|
continue
|
||||||
|
|
||||||
|
if ev == "fn.done": # a pipeline function, in/out named
|
||||||
|
fn = str(e.get("fn", "fn"))
|
||||||
|
attrs = _flat_attrs("in", e.get("in"))
|
||||||
|
attrs.update(_flat_attrs("out", e.get("out")))
|
||||||
|
s = span(sid, parent, f"{_prefix()}{fn}", now, now, attrs,
|
||||||
|
error=bool(e.get("error")))
|
||||||
|
s["_svc"] = _service()
|
||||||
|
spans.append(s)
|
||||||
|
continue
|
||||||
|
|
||||||
|
# every other event = one span (§9-bis: engine step / evidence
|
||||||
|
# append / state). kg.snapshot keeps only the counts (size law).
|
||||||
|
if "kg" in extra and isinstance(extra["kg"], dict):
|
||||||
|
kg = extra.pop("kg")
|
||||||
|
extra["kg"] = {k: kg.get(k) for k in ("n_edges", "n_live",
|
||||||
|
"n_conflicts")}
|
||||||
|
spans.append(span(sid, parent, f"{_prefix()}{ev}", now, now,
|
||||||
|
_attrs(**extra)))
|
||||||
|
spans[-1]["_svc"] = _service()
|
||||||
|
close_block()
|
||||||
|
|
||||||
|
# strip the exporter's internal keys; group spans by service
|
||||||
|
all_spans = []
|
||||||
|
for s in spans:
|
||||||
|
all_spans.append(s)
|
||||||
|
|
||||||
|
# root: the run itself — the honest envelope of every span inside it
|
||||||
|
t_start = min(int(s["startTimeUnixNano"]) for s in all_spans) if all_spans else 0
|
||||||
|
t_end = max(int(s["endTimeUnixNano"]) for s in all_spans) if all_spans else 0
|
||||||
|
root = span(root_id, "", (question[:120] or "floop.run"),
|
||||||
|
t_start, t_end, root_attrs)
|
||||||
|
|
||||||
|
by_svc: dict[str, list[dict]] = {"floop": [root]}
|
||||||
|
for s in all_spans:
|
||||||
|
by_svc.setdefault(s.get("_svc") or "floop", []).append(s)
|
||||||
|
for s in all_spans: # final strip AFTER grouping by service
|
||||||
|
for k in ("_svc", "_comp", "_expert", "_call_id"):
|
||||||
|
s.pop(k, None)
|
||||||
|
|
||||||
|
payload = {"resourceSpans": [
|
||||||
|
{"resource": {"attributes": [
|
||||||
|
{"key": "service.name", "value": {"stringValue": svc}},
|
||||||
|
{"key": "service.version", "value": {"stringValue": "0.1"}}]},
|
||||||
|
"scopeSpans": [{"spans": group}]}
|
||||||
|
for svc, group in by_svc.items()]}
|
||||||
|
return payload, trace_id
|
||||||
|
|
||||||
|
|
||||||
|
def _post_json(url: str, body: bytes) -> int:
|
||||||
|
req = urllib.request.Request(url, data=body, method="POST",
|
||||||
|
headers={"Content-Type": "application/json"})
|
||||||
|
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||||
|
return resp.status
|
||||||
|
|
||||||
|
|
||||||
|
def push(run_dir: str | Path, url: str = DEFAULT_URL) -> str:
|
||||||
|
payload, trace_id = build_payload(run_dir, load_events(run_dir))
|
||||||
|
status = _post_json(url, json.dumps(payload).encode())
|
||||||
|
if status != 200:
|
||||||
|
raise RuntimeError(f"OTLP endpoint answered {status}")
|
||||||
|
return trace_id
|
||||||
|
|
||||||
|
|
||||||
|
def _latest(n: int) -> list[Path]:
|
||||||
|
runs = Path("runs")
|
||||||
|
out = []
|
||||||
|
for d in sorted(runs.iterdir(), reverse=True):
|
||||||
|
if (d / "events.jsonl").exists() \
|
||||||
|
and (d / "events.jsonl").stat().st_size > 0:
|
||||||
|
out.append(d)
|
||||||
|
if len(out) >= n:
|
||||||
|
break
|
||||||
|
if not out:
|
||||||
|
print("no run dir with a non-empty events.jsonl under runs/",
|
||||||
|
file=sys.stderr)
|
||||||
|
raise SystemExit(1)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv: list[str]) -> int:
|
||||||
|
url = os.environ.get("FLOOP_OTLP_URL", DEFAULT_URL)
|
||||||
|
dry, dirs = False, []
|
||||||
|
i = 1
|
||||||
|
while i < len(argv):
|
||||||
|
a = argv[i]
|
||||||
|
if a == "--url":
|
||||||
|
i += 1
|
||||||
|
url = argv[i]
|
||||||
|
elif a == "--dry":
|
||||||
|
dry = True
|
||||||
|
elif a == "--latest":
|
||||||
|
n = int(argv[i + 1]) if i + 1 < len(argv) and \
|
||||||
|
argv[i + 1].isdigit() else 3
|
||||||
|
i += 1
|
||||||
|
dirs.extend(_latest(n))
|
||||||
|
else:
|
||||||
|
dirs.append(Path(a))
|
||||||
|
i += 1
|
||||||
|
if not dirs:
|
||||||
|
print("usage: python -m floop.traces <run_dir>... | --latest [N]"
|
||||||
|
" [--url URL] [--dry]", file=sys.stderr)
|
||||||
|
return 2
|
||||||
|
for d in dirs:
|
||||||
|
payload, trace_id = build_payload(d, load_events(d))
|
||||||
|
n = sum(len(rs["scopeSpans"][0]["spans"])
|
||||||
|
for rs in payload["resourceSpans"])
|
||||||
|
svcs = ", ".join(sorted(
|
||||||
|
rs["resource"]["attributes"][0]["value"]["stringValue"]
|
||||||
|
for rs in payload["resourceSpans"]))
|
||||||
|
print(f"{d.name}: {n} spans [{svcs}], trace {trace_id}")
|
||||||
|
if dry:
|
||||||
|
continue
|
||||||
|
status = _post_json(url, json.dumps(payload).encode())
|
||||||
|
print(f" pushed -> {status} {DEFAULT_UI}/trace/{trace_id}")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main(sys.argv))
|
||||||
@@ -9,6 +9,7 @@ dead run). No API keys in code.
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import json
|
import json
|
||||||
|
import math
|
||||||
import urllib.request
|
import urllib.request
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
@@ -36,10 +37,20 @@ def embed(texts: list[str], model: str = DEFAULT_MODEL,
|
|||||||
data = json.load(r)
|
data = json.load(r)
|
||||||
except Exception as e: # noqa: BLE001 — one honest exception type
|
except Exception as e: # noqa: BLE001 — one honest exception type
|
||||||
raise EmbedderDown(f"{url}: {e}") from e
|
raise EmbedderDown(f"{url}: {e}") from e
|
||||||
vecs = data.get("embeddings")
|
vecs = data.get("embeddings") if isinstance(data, dict) else None
|
||||||
if not vecs or len(vecs) != len(texts):
|
if not isinstance(vecs, list) or len(vecs) != len(texts):
|
||||||
raise EmbedderDown(f"{url}: expected {len(texts)} vectors, got "
|
raise EmbedderDown(f"{url}: expected {len(texts)} vectors, got "
|
||||||
f"{len(vecs) if vecs else 0}")
|
f"{len(vecs) if isinstance(vecs, list) else 0}")
|
||||||
|
dimension = None
|
||||||
|
for vector in vecs:
|
||||||
|
if (not isinstance(vector, list) or not vector
|
||||||
|
or any(type(x) not in (int, float) or not math.isfinite(x)
|
||||||
|
for x in vector)
|
||||||
|
or not any(vector)):
|
||||||
|
raise EmbedderDown(f"{url}: expected finite, nonzero numeric vectors")
|
||||||
|
if dimension is not None and len(vector) != dimension:
|
||||||
|
raise EmbedderDown(f"{url}: inconsistent embedding dimensions")
|
||||||
|
dimension = len(vector)
|
||||||
return vecs
|
return vecs
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+316
-180
@@ -29,15 +29,16 @@ from floop.llm import predict
|
|||||||
|
|
||||||
from .checks import check_candidate, quote_containment
|
from .checks import check_candidate, quote_containment
|
||||||
from .chunker import chunk_page
|
from .chunker import chunk_page
|
||||||
from .skim import find_quantities, skim_article
|
from .skim import SkimSheet, find_quantities, skim_article
|
||||||
from .extract import (AnswerFromKG, ExtractClaims, ExtractSignature, Fact,
|
from .extract import (AnswerFromKG, ExtractClaims, ExtractSignature, Fact,
|
||||||
SelectTableSignature, SkimPromoteSignature,
|
SelectTableSignature, SkimPromoteSignature,
|
||||||
SkimTableSignature, TypeClaim, VerifyCountSignature)
|
SkimTableSignature, TypeClaim, VerifyCountSignature)
|
||||||
from .embeddings import EmbedderDown, embed
|
from .embeddings import EmbedderDown, cosine, embed
|
||||||
from .queries import compose_queries, keywords, proper_nouns
|
from .queries import compose_queries, keywords, proper_nouns
|
||||||
|
from .ranking import merge_search_results, rank_articles
|
||||||
from .store import KnowledgeStore, norm_name
|
from .store import KnowledgeStore, norm_name
|
||||||
from .two_pass import claims_from, fact_from_claim
|
from .two_pass import claims_from, fact_from_claim
|
||||||
from .wiki import (WikipediaClient, WikiPage, WikiTable, resolve_convert,
|
from .wiki import (WikipediaClient, WikiPage, WikiSearchResult, WikiTable, resolve_convert,
|
||||||
tables_as_chunks, format_table_frag)
|
tables_as_chunks, format_table_frag)
|
||||||
|
|
||||||
WORD_RE = re.compile(r"[A-Za-zÀ-ÿ0-9']+")
|
WORD_RE = re.compile(r"[A-Za-zÀ-ÿ0-9']+")
|
||||||
@@ -144,6 +145,27 @@ def _proper_nouns(question: str) -> set[str]:
|
|||||||
return proper_nouns(question)
|
return proper_nouns(question)
|
||||||
|
|
||||||
|
|
||||||
|
def _probe_seeds(kws: list[str], evidence: str) -> list[str]:
|
||||||
|
"""Augment keywords with short values from the parent's evidence."""
|
||||||
|
seeds = list(kws)
|
||||||
|
for line in (evidence or "").splitlines():
|
||||||
|
if ":" in line:
|
||||||
|
val = line.split(":", 1)[1].split("(answers")[0].strip()
|
||||||
|
if val and len(val.split()) <= 4:
|
||||||
|
seeds.extend(val.split())
|
||||||
|
return seeds
|
||||||
|
|
||||||
|
|
||||||
|
def _goal_skim_notice(sheet: SkimSheet, goal_terms: list[str]) -> str:
|
||||||
|
"""Keep goal-relevant notices and quantity signals, not unrelated prose."""
|
||||||
|
notice = sheet.notice()
|
||||||
|
if notice and (not goal_terms
|
||||||
|
or any(_term_hits(gt, notice) for gt in goal_terms)
|
||||||
|
or any(find_quantities(notice))):
|
||||||
|
return notice
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class KnowledgeConfig:
|
class KnowledgeConfig:
|
||||||
kb_path: str = "knowledge_store/kg.sqlite"
|
kb_path: str = "knowledge_store/kg.sqlite"
|
||||||
@@ -209,6 +231,17 @@ class KnowledgeExpert:
|
|||||||
if self.streams:
|
if self.streams:
|
||||||
self.streams.state(text, think=think)
|
self.streams.state(text, think=think)
|
||||||
|
|
||||||
|
def _rec(self, event: str, **fields) -> None:
|
||||||
|
"""Flight-recorder event (post-mortem debugging, owner 26/10):
|
||||||
|
every component, LLM or not, leaves one JSON line. No streams ->
|
||||||
|
silent no-op (the recorder law: observability never breaks a run;
|
||||||
|
__new__-built test fakes never define it either)."""
|
||||||
|
if getattr(self, "streams", None) is not None:
|
||||||
|
try:
|
||||||
|
self.streams.recorder.emit(event, **fields)
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
pass
|
||||||
|
|
||||||
def _qvec(self, question: str) -> list[float] | None:
|
def _qvec(self, question: str) -> list[float] | None:
|
||||||
"""Question vector, cached per question text. None = embedder down
|
"""Question vector, cached per question text. None = embedder down
|
||||||
(the probe degrades to lexical — offline fallback law, never dead)."""
|
(the probe degrades to lexical — offline fallback law, never dead)."""
|
||||||
@@ -235,9 +268,13 @@ class KnowledgeExpert:
|
|||||||
rows = self.store.probe(seeds)
|
rows = self.store.probe(seeds)
|
||||||
qv = self._qvec(question)
|
qv = self._qvec(question)
|
||||||
if qv is None:
|
if qv is None:
|
||||||
|
self._rec("probe.done", q=question[:80], seeds=list(seeds),
|
||||||
|
rows=len(rows), semantic=0)
|
||||||
return rows
|
return rows
|
||||||
sem = self.store.semantic_probe(qv, tau=self.cfg.semantic_tau)
|
sem = self.store.semantic_probe(qv, tau=self.cfg.semantic_tau)
|
||||||
if not sem:
|
if not sem:
|
||||||
|
self._rec("probe.done", q=question[:80], seeds=list(seeds),
|
||||||
|
rows=len(rows), semantic=0)
|
||||||
return rows
|
return rows
|
||||||
seen = {r.eid for r in rows}
|
seen = {r.eid for r in rows}
|
||||||
added = 0
|
added = 0
|
||||||
@@ -250,6 +287,9 @@ class KnowledgeExpert:
|
|||||||
if added:
|
if added:
|
||||||
self._log(f"semantic probe: +{added} edges the lexical probe missed "
|
self._log(f"semantic probe: +{added} edges the lexical probe missed "
|
||||||
f"(tau={self.cfg.semantic_tau})", think=True)
|
f"(tau={self.cfg.semantic_tau})", think=True)
|
||||||
|
self._rec("probe.done", q=question[:80], seeds=list(seeds),
|
||||||
|
rows=len(rows), semantic=added,
|
||||||
|
tau=self.cfg.semantic_tau)
|
||||||
return rows
|
return rows
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@@ -287,6 +327,10 @@ class KnowledgeExpert:
|
|||||||
ordered = self.store.list_is_ordered(set_name)
|
ordered = self.store.list_is_ordered(set_name)
|
||||||
members = self.store.list_members(set_name, ordered=ordered)
|
members = self.store.list_members(set_name, ordered=ordered)
|
||||||
quote, url = self.store.set_provenance(set_name)
|
quote, url = self.store.set_provenance(set_name)
|
||||||
|
self._rec("fn.done", fn="serve_set",
|
||||||
|
in_={"set": set_name, "question": question},
|
||||||
|
out_={"members": members[:50], "count": len(members),
|
||||||
|
"ranked": ordered})
|
||||||
self._log(f"kg set hit: {set_name} ({len(members)} members"
|
self._log(f"kg set hit: {set_name} ({len(members)} members"
|
||||||
f"{', ranked' if ordered else ', unordered'})", think=True)
|
f"{', ranked' if ordered else ', unordered'})", think=True)
|
||||||
return {"value": str(len(members)), "list_items": members,
|
return {"value": str(len(members)), "list_items": members,
|
||||||
@@ -335,14 +379,20 @@ class KnowledgeExpert:
|
|||||||
ok, reason = validate_query(q)
|
ok, reason = validate_query(q)
|
||||||
if not ok:
|
if not ok:
|
||||||
self._log(f"prover: invalid DSL term ({reason}); judge path", think=True)
|
self._log(f"prover: invalid DSL term ({reason}); judge path", think=True)
|
||||||
|
self._rec("prover.done", q=question[:80], verdict="invalid_dsl",
|
||||||
|
reason=reason, dsl=q)
|
||||||
return None
|
return None
|
||||||
proof = evaluate(self.store, q)
|
proof = evaluate(self.store, q)
|
||||||
if not proof.bindings:
|
if not proof.bindings:
|
||||||
self._log(f"prover: no closed path; judge path", think=True)
|
self._log(f"prover: no closed path; judge path", think=True)
|
||||||
|
self._rec("prover.done", q=question[:80], verdict="no_closed_path",
|
||||||
|
dsl=q)
|
||||||
return None
|
return None
|
||||||
if not re_execute(self.store, q, proof):
|
if not re_execute(self.store, q, proof):
|
||||||
self._log("prover: re-execution mismatch (store changed?); judge path",
|
self._log("prover: re-execution mismatch (store changed?); judge path",
|
||||||
think=True)
|
think=True)
|
||||||
|
self._rec("prover.done", q=question[:80],
|
||||||
|
verdict="reexecution_mismatch", dsl=q)
|
||||||
return None
|
return None
|
||||||
vals = []
|
vals = []
|
||||||
quote = ""
|
quote = ""
|
||||||
@@ -378,8 +428,47 @@ class KnowledgeExpert:
|
|||||||
self._log(f"prover: closed path ({n} binding(s): "
|
self._log(f"prover: closed path ({n} binding(s): "
|
||||||
f"{'; '.join(v[:40] for v in vals[:3])}) — no judge call",
|
f"{'; '.join(v[:40] for v in vals[:3])}) — no judge call",
|
||||||
think=True)
|
think=True)
|
||||||
|
self._rec("prover.done", q=question[:80],
|
||||||
|
verdict="closed" if n == 1 else "ambiguous",
|
||||||
|
dsl=q, n_bindings=n, bindings=[v[:80] for v in vals])
|
||||||
return answer
|
return answer
|
||||||
|
|
||||||
|
def kg_snapshot(self) -> dict:
|
||||||
|
"""The KG as a JSON-safe object for the flight recorder: every
|
||||||
|
live edge with its temporal window and its LAST-TOUCH event (owner
|
||||||
|
26/10: 'cada fila del kg podria tenir anotat quan s'afegeix o
|
||||||
|
edita'). The last-touch map comes from this run's merge events
|
||||||
|
(in the recorder's memory); rows the run never touched carry the
|
||||||
|
empty marker. One snapshot per run — emitted once at the end."""
|
||||||
|
try:
|
||||||
|
last_touch: dict[int, dict] = {}
|
||||||
|
rec = (self.streams.recorder if self.streams else None)
|
||||||
|
if rec is not None:
|
||||||
|
for e in rec.events_of("fact.merged"):
|
||||||
|
if e.get("eid") is not None:
|
||||||
|
last_touch[e["eid"]] = {"seq": e.get("seq"),
|
||||||
|
"ts": e.get("ts"),
|
||||||
|
"page": e.get("page")}
|
||||||
|
edges = []
|
||||||
|
for (eid, subj, rel, dstv, s, en, red) in self.store.db.execute(
|
||||||
|
"SELECT e.id, n.norm_name, e.rel, e.dst_value, "
|
||||||
|
"e.t_start, e.t_end, e.retracted "
|
||||||
|
"FROM edges e JOIN nodes n ON n.id=e.src_node "
|
||||||
|
"ORDER BY e.id").fetchall():
|
||||||
|
edges.append({
|
||||||
|
"eid": eid, "subject": subj, "rel": rel,
|
||||||
|
"object": dstv, "t_start": s, "t_end": en,
|
||||||
|
"retracted": bool(red),
|
||||||
|
"last_touch": last_touch.get(eid),
|
||||||
|
})
|
||||||
|
conflicts = self.store.db.execute(
|
||||||
|
"SELECT COUNT(*) FROM conflicts").fetchone()[0]
|
||||||
|
return {"n_edges": len(edges),
|
||||||
|
"n_live": sum(1 for e in edges if not e["retracted"]),
|
||||||
|
"n_conflicts": conflicts, "edges": edges}
|
||||||
|
except Exception: # noqa: BLE001 — a snapshot must never kill a run
|
||||||
|
return {"n_edges": 0, "n_live": 0, "n_conflicts": 0, "edges": []}
|
||||||
|
|
||||||
def answer_question(self, question: str, parent_question: str = "",
|
def answer_question(self, question: str, parent_question: str = "",
|
||||||
evidence: str = "", charge_llm=None,
|
evidence: str = "", charge_llm=None,
|
||||||
answer_type: str = "") -> dict:
|
answer_type: str = "") -> dict:
|
||||||
@@ -388,60 +477,87 @@ class KnowledgeExpert:
|
|||||||
`parent_question` + `evidence` are the machine's context: the original
|
`parent_question` + `evidence` are the machine's context: the original
|
||||||
goal and the rows this question depends on (design §4: instantiated
|
goal and the rows this question depends on (design §4: instantiated
|
||||||
question + parent + referenced rows in). References like 'that state'
|
question + parent + referenced rows in). References like 'that state'
|
||||||
resolve against them."""
|
resolve against them. Orchestrates proof, cached answers, then
|
||||||
|
article-by-article gathering with early exit."""
|
||||||
t0 = time.time()
|
t0 = time.time()
|
||||||
# parent_question/evidence ARE the machine's context (design §4) —
|
|
||||||
# consumed directly by the probe seeds, the query composer and the
|
|
||||||
# guards; no prompt ever renders them into a TRANSLATE call anymore.
|
|
||||||
kws = self._keywords(question)
|
kws = self._keywords(question)
|
||||||
goal_terms = self._keywords(parent_question) if parent_question else []
|
goal_terms = self._keywords(parent_question) if parent_question else []
|
||||||
self._current_goal_terms = goal_terms # the harvest reads these
|
self._current_goal_terms = goal_terms
|
||||||
self._current_goal_question = parent_question or question
|
self._current_goal_question = parent_question or question
|
||||||
# ---- phase 3b: the derived-answer engine, BEFORE any judge ----
|
proven = self._try_prover_answer(question, charge_llm)
|
||||||
# If the question translates to the DSL and the store closes the
|
|
||||||
# path, the proof term IS the answer (re-execution = the check,
|
|
||||||
# verified=True) — the judge never runs on this question. No
|
|
||||||
# translation or no closed path -> the judge path, unchanged.
|
|
||||||
try:
|
|
||||||
proven = self._prover_answer(question, charge_llm)
|
|
||||||
except Exception as e: # noqa: BLE001 — the prover must never kill a run
|
|
||||||
self._log(f"prover path failed ({e!r}); judge path", think=True)
|
|
||||||
proven = None
|
|
||||||
if proven is not None:
|
if proven is not None:
|
||||||
return proven
|
return proven
|
||||||
# per-CALL skim state (PR-3): notices for the machine + ambiguous
|
|
||||||
# leads pending the bounded promotion decision
|
self._prepare_gather_state()
|
||||||
self._skim_notices: list[str] = []
|
ev_entities = self._expected_entities(evidence or "")[:8]
|
||||||
self._skim_leads: list[tuple[WikiPage, object]] = []
|
|
||||||
ev_entities = [e for e in self._expected_entities(evidence or "")][:8]
|
|
||||||
# the extractor's ENTITIES (research/semantic-kg): TRANSLATE resolves
|
|
||||||
# them; keywords of the question are the fallback when it returns none
|
|
||||||
self._extract_entities: list[str] = []
|
|
||||||
# SEEN-INDEX (PR-2): articles already fetched this RUN — consulted
|
|
||||||
# before network search so a later question pays zero re-fetch
|
|
||||||
if not hasattr(self, "_seen_pages"):
|
|
||||||
self._seen_pages: dict[str, WikiPage] = {}
|
|
||||||
# LINK QUEUE (PR-2): goal-region links from skims, joining the fetch
|
|
||||||
# order as candidates (hops still live in the plan — the law stands)
|
|
||||||
if not hasattr(self, "_link_queue"):
|
|
||||||
self._link_queue: list[str] = []
|
|
||||||
# LIST activation (moved up: the set gate needs it before the probe)
|
|
||||||
list_mode = (str(answer_type or "").upper() == "LIST"
|
list_mode = (str(answer_type or "").upper() == "LIST"
|
||||||
or self._is_enumeration(question))
|
or self._is_enumeration(question))
|
||||||
self._log(f"knowledge: question={question[:80]!r} keywords={kws}", think=True)
|
self._log(f"knowledge: question={question[:80]!r} keywords={kws}", think=True)
|
||||||
|
probe_seeds = _probe_seeds(kws, evidence)
|
||||||
|
answer = self._try_stored_answer(question, probe_seeds, list_mode, charge_llm)
|
||||||
|
if answer is not None:
|
||||||
|
return answer
|
||||||
|
|
||||||
# 2. HYBRID KG probe: lexical seeds UNION semantic rank (embeddings)
|
ordered = self._search_articles(question, ev_entities, list_mode)
|
||||||
probe_seeds = list(kws)
|
pages: list[WikiPage] = []
|
||||||
for line in (evidence or "").splitlines():
|
for title in ordered[: self.cfg.max_articles]:
|
||||||
if ":" in line:
|
page = self._fetch_page(title)
|
||||||
val = line.split(":", 1)[1].split("(answers")[0].strip()
|
if page is None:
|
||||||
if val and len(val.split()) <= 4:
|
continue
|
||||||
probe_seeds.extend(val.split())
|
pages.append(page)
|
||||||
|
sheet = self._skim_page(page, kws, goal_terms, ev_entities)
|
||||||
|
self._harvest_side_tables(page, sheet, question, evidence)
|
||||||
|
self._promote_leads(evidence, charge_llm)
|
||||||
|
if list_mode and page.tables:
|
||||||
|
ans = self._list_from_page(page, question, charge_llm)
|
||||||
|
if ans is not None and self._guard_ingest(ans, evidence):
|
||||||
|
self._log(f"early exit after {page.title}: list "
|
||||||
|
f"({ans['list_count']} items)", think=True)
|
||||||
|
return {**ans, "source": "knowledge_graph",
|
||||||
|
"stats": {**self._skim_stats(pages),
|
||||||
|
"skim": self._skim_notices}}
|
||||||
|
self._process_page(page, question, kws, charge_llm,
|
||||||
|
goal_terms=goal_terms)
|
||||||
|
answer = self._try_gathered_answer(
|
||||||
|
question, probe_seeds, list_mode, page.title, charge_llm)
|
||||||
|
if answer is not None:
|
||||||
|
return {**answer, "source": "knowledge_graph",
|
||||||
|
"stats": {**self._skim_stats(pages),
|
||||||
|
"skim": self._skim_notices}}
|
||||||
|
|
||||||
|
rows = self._probe(question, probe_seeds)
|
||||||
|
self._log(f"merged {self._merged}/{self._checked} candidates; re-probe: {len(rows)} rows", think=True)
|
||||||
|
answer = self._answer_from_rows(question, rows, charge_llm)
|
||||||
|
src = "knowledge_graph" if answer["value"].upper() != "UNKNOWN" else "wikipedia_miss"
|
||||||
|
return {**self._audit_ambiguity(question, answer, rows, charge_llm), "source": src,
|
||||||
|
"stats": {**self._skim_stats(pages),
|
||||||
|
"checked": self._checked, "merged": self._merged,
|
||||||
|
"skim": self._skim_notices,
|
||||||
|
"elapsed_s": round(time.time() - t0, 1)}}
|
||||||
|
|
||||||
|
def _try_prover_answer(self, question: str, charge_llm=None) -> dict | None:
|
||||||
|
"""A closed proof bypasses the judge; a failed proof must not kill a run."""
|
||||||
|
try:
|
||||||
|
return self._prover_answer(question, charge_llm)
|
||||||
|
except Exception as e: # noqa: BLE001 — the prover must never kill a run
|
||||||
|
self._log(f"prover path failed ({e!r}); judge path", think=True)
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _prepare_gather_state(self) -> None:
|
||||||
|
"""Reset per-call extraction/skim state, preserving the run's page cache."""
|
||||||
|
self._skim_notices = []
|
||||||
|
self._skim_leads = []
|
||||||
|
self._extract_entities = []
|
||||||
|
if not hasattr(self, "_seen_pages"):
|
||||||
|
self._seen_pages: dict[str, WikiPage] = {}
|
||||||
|
if not hasattr(self, "_link_queue"):
|
||||||
|
self._link_queue: list[str] = []
|
||||||
|
|
||||||
|
def _try_stored_answer(self, question: str, probe_seeds: list[str],
|
||||||
|
list_mode: bool, charge_llm=None) -> dict | None:
|
||||||
|
"""Probe held knowledge, enforcing the membership-set gate for lists."""
|
||||||
rows = self._probe(question, probe_seeds)
|
rows = self._probe(question, probe_seeds)
|
||||||
self._log(f"kg probe ({probe_seeds}): {len(rows)} rows", think=True)
|
self._log(f"kg probe ({probe_seeds}): {len(rows)} rows", think=True)
|
||||||
# SET GATE (lists): mention rows never answer an enumeration — only a
|
|
||||||
# membership set does. With no set held, the probe result is not
|
|
||||||
# answerability evidence; the gather must run.
|
|
||||||
if list_mode:
|
if list_mode:
|
||||||
kg_set = self._set_gate_hit(probe_seeds, question)
|
kg_set = self._set_gate_hit(probe_seeds, question)
|
||||||
if kg_set:
|
if kg_set:
|
||||||
@@ -455,150 +571,125 @@ class KnowledgeExpert:
|
|||||||
self._log(f"kg hit: {answer['value'][:60]}", think=True)
|
self._log(f"kg hit: {answer['value'][:60]}", think=True)
|
||||||
return {**self._audit_ambiguity(question, answer, rows, charge_llm),
|
return {**self._audit_ambiguity(question, answer, rows, charge_llm),
|
||||||
"source": "knowledge_graph", "kg_rows": len(rows)}
|
"source": "knowledge_graph", "kg_rows": len(rows)}
|
||||||
|
return None
|
||||||
|
|
||||||
# 3-4. gap -> search + fetch. COMPOSE (deterministic, from main 23/10 —
|
def _search_articles(self, question: str, ev_entities: list[str],
|
||||||
# the model's own knowledge of the entities can no longer steer
|
list_mode: bool) -> list[str]:
|
||||||
# retrieval) + the branch's extract-entities contract: the
|
"""Compose and search all queries before globally ranking candidates."""
|
||||||
# question-blind extractor transcribes facts about THESE.
|
|
||||||
queries, entity_terms = compose_queries(
|
queries, entity_terms = compose_queries(
|
||||||
question, evidence_entities=ev_entities, list_mode=list_mode)
|
question, evidence_entities=ev_entities, list_mode=list_mode)
|
||||||
|
self._rec("fn.done", fn="compose",
|
||||||
|
in_={"question": question, "evidence_entities": ev_entities,
|
||||||
|
"list_mode": list_mode},
|
||||||
|
out_={"queries": queries, "entities": entity_terms})
|
||||||
self._extract_entities = list(dict.fromkeys(
|
self._extract_entities = list(dict.fromkeys(
|
||||||
e for e in (entity_terms + sorted(_proper_nouns(question))) if e))
|
e for e in (entity_terms + sorted(_proper_nouns(question))) if e))
|
||||||
self._log(f"compose -> queries {queries} entities {entity_terms}",
|
self._log(f"compose -> queries {queries} entities {entity_terms}",
|
||||||
think=True)
|
think=True)
|
||||||
|
per_query: list[list[WikiSearchResult]] = []
|
||||||
# search ALL queries first; merge + dedupe candidates; rank GLOBALLY
|
|
||||||
# by title relevance; then fetch one at a time with early exit
|
|
||||||
# (per-query quotas let generic articles eat the slots before the
|
|
||||||
# decisive article from a later query is even considered)
|
|
||||||
from .store import norm_name, stem
|
|
||||||
title_terms = {t for w in entity_terms + kws if len(w) > 2
|
|
||||||
for t in (norm_name(w), stem(w))}
|
|
||||||
|
|
||||||
def relevance(title: str) -> int:
|
|
||||||
tt = norm_name(title)
|
|
||||||
return sum(1 for t in title_terms if t and t in tt)
|
|
||||||
|
|
||||||
candidates: list[str] = []
|
|
||||||
seen_titles: set[str] = set()
|
|
||||||
per_query: list[list[str]] = []
|
|
||||||
for query in queries:
|
for query in queries:
|
||||||
found = self.client.search(query, limit=self.cfg.max_search_results)
|
found = self.client.search(query, limit=self.cfg.max_search_results)
|
||||||
per_query.append(found)
|
per_query.append(found)
|
||||||
self._log(f"wiki search ({query!r}): {found}", think=True)
|
self._rec("fn.done", fn="search",
|
||||||
for title in found:
|
in_={"query": query, "limit": self.cfg.max_search_results},
|
||||||
if title not in seen_titles:
|
out_={"titles": [h.title for h in found],
|
||||||
seen_titles.add(title)
|
"results": [{"title": h.title, "snippet": h.snippet}
|
||||||
candidates.append(title)
|
for h in found]})
|
||||||
# hybrid order: each query's #1 is guaranteed a slot (the engine's own
|
self._log(f"wiki search ({query!r}): {[h.title for h in found]}", think=True)
|
||||||
# relevance catches entity pages whose title shares no words with the
|
ordered = self._rank_search_results(question, merge_search_results(per_query))
|
||||||
# question — e.g. 'Loire' for 'longest river in France'); the rest are
|
|
||||||
# ranked by title relevance (which pulls list articles up when they
|
|
||||||
# are the right source)
|
|
||||||
ordered: list[str] = []
|
|
||||||
picked: set[str] = set()
|
|
||||||
for found in per_query:
|
|
||||||
if found and found[0] not in picked:
|
|
||||||
picked.add(found[0])
|
|
||||||
ordered.append(found[0])
|
|
||||||
for title in sorted((t for t in candidates if t not in picked),
|
|
||||||
key=relevance, reverse=True):
|
|
||||||
ordered.append(title)
|
|
||||||
self._log(f"fetch order: {ordered[: self.cfg.max_articles]}", think=True)
|
self._log(f"fetch order: {ordered[: self.cfg.max_articles]}", think=True)
|
||||||
|
return ordered
|
||||||
|
|
||||||
pages: list[WikiPage] = []
|
def _rank_search_results(self, question: str,
|
||||||
for title in ordered[: self.cfg.max_articles]:
|
articles: list[WikiSearchResult]) -> list[str]:
|
||||||
if title in self._seen_pages:
|
"""Globally rank title+snippet candidates against the original question."""
|
||||||
page = self._seen_pages[title]
|
similarities = None
|
||||||
self._log(f"seen-index hit: {title} (already fetched this run)",
|
if articles:
|
||||||
think=True)
|
qvec = self._qvec(question)
|
||||||
else:
|
if qvec is not None:
|
||||||
try:
|
try:
|
||||||
page = self.client.fetch_rich(title)
|
vectors = embed([a.text for a in articles],
|
||||||
except Exception as e: # noqa: BLE001 — network honesty: log and continue
|
model=self.cfg.embed_model, url=self.cfg.embed_url)
|
||||||
self._log(f"fetch failed: {title}: {e}")
|
if any(len(v) != len(qvec) for v in vectors):
|
||||||
continue
|
raise EmbedderDown("question/article embedding dimensions differ")
|
||||||
self._seen_pages[title] = page
|
similarities = [cosine(qvec, v) for v in vectors]
|
||||||
pages.append(page)
|
except EmbedderDown as e:
|
||||||
# SKIM (PR-1): the structural read, in passing — question AND goal
|
self._embed_ok = False
|
||||||
# oriented; surfaces + signals, zero LLM. The sheet drives chunk
|
self._log(f"article ranking: embedder down ({e}); BM25-only fallback")
|
||||||
# ranking in _process_page; PR-2's harvest runs on its signals.
|
|
||||||
sheet = skim_article(page, question_terms=kws, goal_terms=goal_terms,
|
|
||||||
evidence_entities=ev_entities)
|
|
||||||
self._log(f"skim {page.title}: {len(sheet.tables)} tables, "
|
|
||||||
f"{len(sheet.infobox_quantities)} infobox quantities, "
|
|
||||||
f"{len(sheet.link_candidates)} link candidates", think=True)
|
|
||||||
# PR-3 — the skim notice: goal-relevant surfaces seen in passing,
|
|
||||||
# so later steps (router context, run notes) know what exists
|
|
||||||
# and where it lives. Filtered to goal signals: the notice is a
|
|
||||||
# pointer, not a dump.
|
|
||||||
notice = sheet.notice()
|
|
||||||
if notice:
|
|
||||||
goal_signal = (any(_term_hits(gt, notice) for gt in goal_terms)
|
|
||||||
or any(find_quantities(notice)))
|
|
||||||
if goal_signal or not goal_terms:
|
|
||||||
self._skim_notices.append(notice)
|
|
||||||
if self.cfg.skim_link_queue:
|
|
||||||
for link in sheet.link_candidates:
|
|
||||||
if link not in self._link_queue:
|
|
||||||
self._link_queue.append(link)
|
|
||||||
# PR-2 — the opportunistic harvest: goal-relevant side-tables
|
|
||||||
# seen in passing become typed edges (zero LLM, containment law)
|
|
||||||
self._harvest_side_tables(page, sheet, question, evidence)
|
|
||||||
# PR-3 — bounded promotion of ambiguous leads (one LLM call,
|
|
||||||
# only when leads exist): promoted tables ingest through the
|
|
||||||
# same containment-checked path as the deterministic harvest
|
|
||||||
self._promote_leads(evidence, charge_llm)
|
|
||||||
# LIST path: one SELECT TABLE call per article; on hit, ingest ALL
|
|
||||||
# rows and answer by aggregation (no extract calls, no gate)
|
|
||||||
if list_mode and page.tables:
|
|
||||||
ans = self._list_from_page(page, question, charge_llm)
|
|
||||||
if ans is not None and self._guard_ingest(ans, evidence):
|
|
||||||
self._log(f"early exit after {page.title}: list "
|
|
||||||
f"({ans['list_count']} items)", think=True)
|
|
||||||
return {**ans, "source": "knowledge_graph",
|
|
||||||
"stats": {**self._skim_stats(pages),
|
|
||||||
"skim": self._skim_notices}}
|
|
||||||
# refused by the guard: wrong article's list — keep gathering
|
|
||||||
# EARLY EXIT: one article at a time; if the KG already answers,
|
|
||||||
# stop spending calls (the gather exists to fill the gap, not to
|
|
||||||
# hoover every candidate). For enumerations the set gate applies
|
|
||||||
# here too: mention rows never answer a list question.
|
|
||||||
self._process_page(page, question, kws, charge_llm,
|
|
||||||
goal_terms=goal_terms)
|
|
||||||
if list_mode:
|
|
||||||
hit = self._set_gate_hit(probe_seeds, question)
|
|
||||||
if hit is not None:
|
|
||||||
self._log(f"early exit after {page.title}: set {hit}", think=True)
|
|
||||||
return {**self._serve_set(hit, question), "source": "knowledge_graph",
|
|
||||||
"stats": {**self._skim_stats(pages),
|
|
||||||
"skim": self._skim_notices}}
|
|
||||||
else:
|
else:
|
||||||
answer = self._answer_from_rows(
|
self._log("article ranking: embeddings unavailable; BM25-only fallback",
|
||||||
question, self._probe(question, probe_seeds), charge_llm)
|
think=True)
|
||||||
if answer["value"] and answer["value"].upper() != "UNKNOWN":
|
ranked = rank_articles(question, articles, similarities)
|
||||||
self._log(f"early exit after {page.title}: "
|
self._rec("fn.done", fn="rank_articles",
|
||||||
f"{answer['value'][:60]}", think=True)
|
in_={"question": question,
|
||||||
return {**self._audit_ambiguity(question, answer,
|
"articles": [{"title": a.title, "snippet": a.snippet}
|
||||||
self._probe(question, probe_seeds),
|
for a in articles]},
|
||||||
charge_llm),
|
out_={"method": "bm25+cosine_rrf" if similarities is not None else "bm25",
|
||||||
"source": "knowledge_graph",
|
"ranked": [{"title": r.article.title, "bm25": r.bm25,
|
||||||
"stats": {**self._skim_stats(pages),
|
"cosine": r.semantic, "score": r.score} for r in ranked]})
|
||||||
"skim": self._skim_notices}}
|
return [r.article.title for r in ranked]
|
||||||
|
|
||||||
# 5-7. remaining pages already processed inline via _process_page
|
def _fetch_page(self, title: str) -> WikiPage | None:
|
||||||
# (early exit); fall through to the final re-probe and answer.
|
"""Reuse fetched articles; log network failures and let gathering continue."""
|
||||||
|
if title in self._seen_pages:
|
||||||
|
self._rec("fn.done", fn="fetch", in_={"title": title},
|
||||||
|
out_={"cached": True})
|
||||||
|
self._log(f"seen-index hit: {title} (already fetched this run)",
|
||||||
|
think=True)
|
||||||
|
return self._seen_pages[title]
|
||||||
|
try:
|
||||||
|
page = self.client.fetch_rich(title)
|
||||||
|
except Exception as e: # noqa: BLE001 — network honesty: log and continue
|
||||||
|
self._log(f"fetch failed: {title}: {e}")
|
||||||
|
return None
|
||||||
|
self._seen_pages[title] = page
|
||||||
|
self._rec("fn.done", fn="fetch", in_={"title": title},
|
||||||
|
out_={"url": page.url, "chars": len(page.text),
|
||||||
|
"tables": len(page.tables)})
|
||||||
|
return page
|
||||||
|
|
||||||
# 8. re-probe (same seeds, hybrid) and answer from the merged KG
|
def _skim_page(self, page: WikiPage, kws: list[str], goal_terms: list[str],
|
||||||
rows = self._probe(question, probe_seeds)
|
ev_entities: list[str]) -> SkimSheet:
|
||||||
self._log(f"merged {self._merged}/{self._checked} candidates; re-probe: {len(rows)} rows", think=True)
|
"""Record structural signals and retain notices/links for later questions."""
|
||||||
answer = self._answer_from_rows(question, rows, charge_llm)
|
sheet = skim_article(page, question_terms=kws, goal_terms=goal_terms,
|
||||||
src = "knowledge_graph" if answer["value"].upper() != "UNKNOWN" else "wikipedia_miss"
|
evidence_entities=ev_entities)
|
||||||
return {**self._audit_ambiguity(question, answer, rows, charge_llm), "source": src,
|
self._rec("fn.done", fn="skim",
|
||||||
"stats": {**self._skim_stats(pages),
|
in_={"title": page.title, "question_terms": kws,
|
||||||
"checked": self._checked, "merged": self._merged,
|
"goal_terms": goal_terms},
|
||||||
"skim": self._skim_notices,
|
out_={"tables": len(sheet.tables),
|
||||||
"elapsed_s": round(time.time() - t0, 1)}}
|
"infobox_quantities": len(sheet.infobox_quantities),
|
||||||
|
"link_candidates": len(sheet.link_candidates),
|
||||||
|
"notice": sheet.notice()[:200]})
|
||||||
|
self._log(f"skim {page.title}: {len(sheet.tables)} tables, "
|
||||||
|
f"{len(sheet.infobox_quantities)} infobox quantities, "
|
||||||
|
f"{len(sheet.link_candidates)} link candidates", think=True)
|
||||||
|
notice = _goal_skim_notice(sheet, goal_terms)
|
||||||
|
if notice:
|
||||||
|
self._skim_notices.append(notice)
|
||||||
|
if self.cfg.skim_link_queue:
|
||||||
|
for link in sheet.link_candidates:
|
||||||
|
if link not in self._link_queue:
|
||||||
|
self._link_queue.append(link)
|
||||||
|
return sheet
|
||||||
|
|
||||||
|
def _try_gathered_answer(self, question: str, probe_seeds: list[str],
|
||||||
|
list_mode: bool, page_title: str,
|
||||||
|
charge_llm=None) -> dict | None:
|
||||||
|
"""Stop after an article closes the gap, using the list gate or judge."""
|
||||||
|
if list_mode:
|
||||||
|
hit = self._set_gate_hit(probe_seeds, question)
|
||||||
|
if hit is not None:
|
||||||
|
self._log(f"early exit after {page_title}: set {hit}", think=True)
|
||||||
|
return self._serve_set(hit, question)
|
||||||
|
else:
|
||||||
|
answer = self._answer_from_rows(
|
||||||
|
question, self._probe(question, probe_seeds), charge_llm)
|
||||||
|
if answer["value"] and answer["value"].upper() != "UNKNOWN":
|
||||||
|
self._log(f"early exit after {page_title}: "
|
||||||
|
f"{answer['value'][:60]}", think=True)
|
||||||
|
return self._audit_ambiguity(
|
||||||
|
question, answer, self._probe(question, probe_seeds), charge_llm)
|
||||||
|
return None
|
||||||
|
|
||||||
def _skim_stats(self, pages: list[WikiPage]) -> dict:
|
def _skim_stats(self, pages: list[WikiPage]) -> dict:
|
||||||
"""stats shared by every return path: pages seen + link queue state."""
|
"""stats shared by every return path: pages seen + link queue state."""
|
||||||
@@ -889,6 +980,11 @@ class KnowledgeExpert:
|
|||||||
# table (the extract text is the article prose; tables are separate).
|
# table (the extract text is the article prose; tables are separate).
|
||||||
# One bounded call; failure = honest 'no corroboration', never a loop.
|
# One bounded call; failure = honest 'no corroboration', never a loop.
|
||||||
verify = self._verify_count(set_name, len(items), page.text, charge_llm)
|
verify = self._verify_count(set_name, len(items), page.text, charge_llm)
|
||||||
|
self._rec("fn.done", fn="list_ingest",
|
||||||
|
in_={"title": page.title, "table": idx, "set": set_name,
|
||||||
|
"rows": table.total_rows},
|
||||||
|
out_={"members": items[:50], "count": len(items),
|
||||||
|
"verified": bool(verify)})
|
||||||
coverage = {"source": page.title, "table": idx,
|
coverage = {"source": page.title, "table": idx,
|
||||||
"rows_total": table.total_rows,
|
"rows_total": table.total_rows,
|
||||||
"rows_ingested": len(members),
|
"rows_ingested": len(members),
|
||||||
@@ -1028,6 +1124,10 @@ class KnowledgeExpert:
|
|||||||
merged = self._ingest_scalar_table(page, t, ent_i, val_i)
|
merged = self._ingest_scalar_table(page, t, ent_i, val_i)
|
||||||
if merged:
|
if merged:
|
||||||
harvested += 1
|
harvested += 1
|
||||||
|
self._rec("fn.done", fn="harvest",
|
||||||
|
in_={"title": page.title, "table": t.idx,
|
||||||
|
"column": t.header[val_i] if val_i < len(t.header) else "value"},
|
||||||
|
out_={"merged": merged})
|
||||||
return harvested
|
return harvested
|
||||||
|
|
||||||
def _promote_leads(self, evidence: str, charge_llm) -> int:
|
def _promote_leads(self, evidence: str, charge_llm) -> int:
|
||||||
@@ -1089,6 +1189,10 @@ class KnowledgeExpert:
|
|||||||
continue
|
continue
|
||||||
merged = self._ingest_scalar_table(page, t, ent_i, val_i)
|
merged = self._ingest_scalar_table(page, t, ent_i, val_i)
|
||||||
if merged:
|
if merged:
|
||||||
|
self._rec("fn.done", fn="promote",
|
||||||
|
in_={"title": page.title, "table": d.table_index,
|
||||||
|
"column": col},
|
||||||
|
out_={"merged": merged, "refused": False})
|
||||||
self._log(f"skim promote: {merged} rows of table {d.table_index} "
|
self._log(f"skim promote: {merged} rows of table {d.table_index} "
|
||||||
f"({page.title}) ingested (LLM-proposed)", think=True)
|
f"({page.title}) ingested (LLM-proposed)", think=True)
|
||||||
promoted += 1
|
promoted += 1
|
||||||
@@ -1127,6 +1231,10 @@ class KnowledgeExpert:
|
|||||||
return (sig + 2 * len(find_quantities(c.text)), -c.idx)
|
return (sig + 2 * len(find_quantities(c.text)), -c.idx)
|
||||||
gated.sort(key=rank, reverse=True)
|
gated.sort(key=rank, reverse=True)
|
||||||
capped = gated[: self.cfg.max_chunks_extracted]
|
capped = gated[: self.cfg.max_chunks_extracted]
|
||||||
|
self._rec("fn.done", fn="chunk_gate",
|
||||||
|
in_={"title": page.title, "chunks": len(chunks),
|
||||||
|
"question_terms": kws, "entities": entities},
|
||||||
|
out_={"gated": len(gated), "extracted": len(capped)})
|
||||||
|
|
||||||
# ---- TABLE SKIM (research/semantic-kg): decide table relevance
|
# ---- TABLE SKIM (research/semantic-kg): decide table relevance
|
||||||
# BEFORE paying extraction — identity + first rows, one call per
|
# BEFORE paying extraction — identity + first rows, one call per
|
||||||
@@ -1177,17 +1285,26 @@ class KnowledgeExpert:
|
|||||||
extracted = 0
|
extracted = 0
|
||||||
for chunk in capped:
|
for chunk in capped:
|
||||||
if self.cfg.extract_mode == "two_pass":
|
if self.cfg.extract_mode == "two_pass":
|
||||||
# two-pass (26/10): Pass 1 claims (short strings, coref
|
# two-pass (26/10; verbatim moved 1/11): Pass 1 claims WITH
|
||||||
# resolved), Pass 2 one typed Fact per claim — every
|
# their VERBATIM quotes (extracted while the text is in
|
||||||
# output short; the giant typed array is gone from prose.
|
# front of the model), Pass 2 one typed fact per claim —
|
||||||
|
# TYPING only, the model sees JUST the claim (FactNoQuote);
|
||||||
|
# code composes the Fact: FactNoQuote + verbatim.
|
||||||
claims = claims_from(self, entities=ent_str,
|
claims = claims_from(self, entities=ent_str,
|
||||||
heading=chunk.heading_path,
|
heading=chunk.heading_path,
|
||||||
text=chunk.text, charge_llm=charge_llm)
|
text=chunk.text, charge_llm=charge_llm)
|
||||||
|
self._rec("claims.done", page=page.title,
|
||||||
|
heading=chunk.heading_path,
|
||||||
|
out_={"n_claims": len(claims),
|
||||||
|
"claims": [c.__dict__ for c in claims]})
|
||||||
# owner ruling 26/10: completeness beats budget — every
|
# owner ruling 26/10: completeness beats budget — every
|
||||||
# unique claim gets its TYPE call (no cap, dedup only)
|
# unique claim gets its TYPE call (no cap, dedup only)
|
||||||
for claim in claims:
|
for c in claims:
|
||||||
fact = fact_from_claim(self, claim, text=chunk.text,
|
fact = fact_from_claim(self, c.claim, verbatim=c.verbatim,
|
||||||
charge_llm=charge_llm)
|
charge_llm=charge_llm)
|
||||||
|
self._rec("type.done", page=page.title, claim=c.claim[:200],
|
||||||
|
out_={"fact": getattr(fact, "__dict__", None)}
|
||||||
|
if fact is not None else {"fact": None})
|
||||||
if fact is None:
|
if fact is None:
|
||||||
continue # honestly declined: no invention
|
continue # honestly declined: no invention
|
||||||
merged, _eid = self._ingest_candidate(
|
merged, _eid = self._ingest_candidate(
|
||||||
@@ -1263,6 +1380,13 @@ class KnowledgeExpert:
|
|||||||
ok, reason = check_candidate(cand, containment)
|
ok, reason = check_candidate(cand, containment)
|
||||||
if not ok:
|
if not ok:
|
||||||
self._log(f"candidate rejected ({reason}): {cand.get('subject', '')[:40]}")
|
self._log(f"candidate rejected ({reason}): {cand.get('subject', '')[:40]}")
|
||||||
|
self._rec("fact.rejected", reason=reason, fact=dict(cand),
|
||||||
|
page=page.title)
|
||||||
|
self._rec("fn.done", fn="check",
|
||||||
|
in_={"subject": cand.get("subject", ""),
|
||||||
|
"relation": cand.get("relation", ""),
|
||||||
|
"object": cand.get("object", "")},
|
||||||
|
out_={"ok": False, "reason": reason})
|
||||||
return 0, None
|
return 0, None
|
||||||
doc_id = self.store.add_document(
|
doc_id = self.store.add_document(
|
||||||
url=page.url, title=page.title, fetched_at=page.fetched_at,
|
url=page.url, title=page.title, fetched_at=page.fetched_at,
|
||||||
@@ -1273,6 +1397,11 @@ class KnowledgeExpert:
|
|||||||
t_start=cand["start"] or None,
|
t_start=cand["start"] or None,
|
||||||
t_end=cand["end"] or None)
|
t_end=cand["end"] or None)
|
||||||
self._merged += 1
|
self._merged += 1
|
||||||
|
self._rec("fact.merged", eid=eid, fact=dict(cand), page=page.title)
|
||||||
|
self._rec("fn.done", fn="check",
|
||||||
|
in_={"subject": cand["subject"], "relation": cand["relation"],
|
||||||
|
"object": cand["object"]},
|
||||||
|
out_={"ok": True, "merged": True, "eid": eid})
|
||||||
if eid is not None:
|
if eid is not None:
|
||||||
self._cache_edge_vector(eid, cand["subject"], cand["relation"],
|
self._cache_edge_vector(eid, cand["subject"], cand["relation"],
|
||||||
cand["object"])
|
cand["object"])
|
||||||
@@ -1313,10 +1442,17 @@ class KnowledgeExpert:
|
|||||||
f"{' | CONFLICT' if r.conflict else ''}"
|
f"{' | CONFLICT' if r.conflict else ''}"
|
||||||
for i, r in enumerate(rows))
|
for i, r in enumerate(rows))
|
||||||
pred = self.answer(question=question, rows=rendered)
|
pred = self.answer(question=question, rows=rendered)
|
||||||
return {
|
answer = {
|
||||||
"value": _clean_value(pred.value),
|
"value": _clean_value(pred.value),
|
||||||
"quote": pred.quote.strip(),
|
"quote": pred.quote.strip(),
|
||||||
"url": next((r.url for r in rows if r.quote and pred.quote.strip()
|
"url": next((r.url for r in rows if r.quote and pred.quote.strip()
|
||||||
and r.quote.strip() in pred.quote.strip()), rows[0].url),
|
and r.quote.strip() in pred.quote.strip()), rows[0].url),
|
||||||
"confidence": str(pred.confidence.value),
|
"confidence": str(pred.confidence.value),
|
||||||
}
|
}
|
||||||
|
self._rec("fn.done", fn="judge",
|
||||||
|
in_={"question": question,
|
||||||
|
"rows": [f"K{i}: {r.src} | {r.rel} | {r.dst}"
|
||||||
|
for i, r in enumerate(rows)][:12]},
|
||||||
|
out_={"value": answer["value"], "confidence": answer["confidence"],
|
||||||
|
"quote": answer["quote"][:120]})
|
||||||
|
return answer
|
||||||
+52
-21
@@ -3,6 +3,10 @@
|
|||||||
The extractor sees ONE chunk (+ heading path); it proposes typed candidates with
|
The extractor sees ONE chunk (+ heading path); it proposes typed candidates with
|
||||||
VERBATIM spans. The containment check (checks.py) validates every span against
|
VERBATIM spans. The containment check (checks.py) validates every span against
|
||||||
the FULL document text — so chunking can never fake a quote.
|
the FULL document text — so chunking can never fake a quote.
|
||||||
|
|
||||||
|
Two-pass (two_pass.py): Pass 1 (ExtractClaims) extracts the claims WITH their
|
||||||
|
VERBATIM spans; Pass 2 (TypeClaim) types ONE claim — typing only, the model
|
||||||
|
never sees the quote; code composes Fact = FactNoQuote + verbatim (owner 1/11).
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
@@ -56,6 +60,24 @@ class Fact(BaseModel):
|
|||||||
"of the sibling fact>}; empty when the text asserts no order")
|
"of the sibling fact>}; empty when the text asserts no order")
|
||||||
|
|
||||||
|
|
||||||
|
class FactNoQuote(BaseModel):
|
||||||
|
subject: str = dspy.OutputField(desc="the fact's subject entity")
|
||||||
|
relation: str = dspy.OutputField(desc="the relation between subject and object")
|
||||||
|
object: str = dspy.OutputField(desc="the fact's object / value")
|
||||||
|
start: str | None = dspy.OutputField(
|
||||||
|
default=None,
|
||||||
|
desc="when the fact begins, as stated in the claim (a year like 2018, or a full date); empty when the claim states no start")
|
||||||
|
end: str | None = dspy.OutputField(
|
||||||
|
default=None,
|
||||||
|
desc="when the fact ends, as stated in the claim; empty when ongoing/unknown")
|
||||||
|
point: str | None = dspy.OutputField(
|
||||||
|
default=None,
|
||||||
|
desc="for point-in-time facts (events): the stated date; empty otherwise")
|
||||||
|
granularity: str | None = dspy.OutputField(
|
||||||
|
default=None,
|
||||||
|
desc="precision of the stated dates: year, month, or day; empty when no dates")
|
||||||
|
|
||||||
|
|
||||||
class ExtractSignature(dspy.Signature):
|
class ExtractSignature(dspy.Signature):
|
||||||
"""You are the EXTRACT step of a knowledge machine. From the given text,
|
"""You are the EXTRACT step of a knowledge machine. From the given text,
|
||||||
extract facts about the NAMED ENTITIES: biographical facts, positions
|
extract facts about the NAMED ENTITIES: biographical facts, positions
|
||||||
@@ -72,39 +94,48 @@ class ExtractSignature(dspy.Signature):
|
|||||||
desc="the extracted facts; empty list if none")
|
desc="the extracted facts; empty list if none")
|
||||||
|
|
||||||
|
|
||||||
|
class Claim(BaseModel):
|
||||||
|
"""One claim of Pass 1: the free-form claim PLUS the VERBATIM span
|
||||||
|
that states it. The quote is extracted HERE, in the same call that
|
||||||
|
reads the text (owner 1/11: the VERBATIM is obtained before the
|
||||||
|
typing — Pass 2 only enforces the Fact's typing)."""
|
||||||
|
claim: str = dspy.OutputField(
|
||||||
|
desc="the factual claim, coreferences resolved (entities named, "
|
||||||
|
"never pronouns)")
|
||||||
|
verbatim: str = dspy.OutputField(
|
||||||
|
desc="VERBATIM quote from the text that states the claim: the FULL "
|
||||||
|
"sentence or table row, copied exactly (at least 10 characters)")
|
||||||
|
|
||||||
|
|
||||||
class ExtractClaims(dspy.Signature):
|
class ExtractClaims(dspy.Signature):
|
||||||
"""You are the CLAIMS step of a knowledge machine. From the given text,
|
"""You are the CLAIMS step of a knowledge machine. From the given text,
|
||||||
list the FACTUAL CLAIMS it states about the NAMED ENTITIES: positions
|
list the FACTUAL CLAIMS it states about the NAMED ENTITIES: positions
|
||||||
and offices held, biographical facts, events, relationships,
|
and offices held, biographical facts, events, relationships,
|
||||||
quantities with units. One claim per line, plain text, no numbering.
|
quantities with units. Each claim carries the VERBATIM quote that
|
||||||
Resolve coreferences: name the entity in the claim, never a pronoun
|
states it: the FULL sentence or table row, copied exactly (at least
|
||||||
or a shorthand. Only what the text states; no inference."""
|
10 characters). Resolve coreferences: name the entity in the claim,
|
||||||
|
never a pronoun or a shorthand. Only what the text states; no
|
||||||
|
inference."""
|
||||||
entities: str = dspy.InputField(
|
entities: str = dspy.InputField(
|
||||||
desc="the named entities to extract claims about, comma separated")
|
desc="the named entities to extract claims about, comma separated")
|
||||||
heading: str = dspy.InputField(desc="section path of this chunk; context only")
|
heading: str = dspy.InputField(desc="section path of this chunk; context only")
|
||||||
text: str = dspy.InputField()
|
text: str = dspy.InputField()
|
||||||
claims: list[str] = dspy.OutputField(
|
claims: list[Claim] = dspy.OutputField(
|
||||||
desc="the factual claims, one string each, coreferences resolved "
|
desc="the factual claims, each with its VERBATIM quote copied "
|
||||||
"(entities named, never pronouns); empty list if none")
|
"exactly from the text; empty list if none")
|
||||||
|
|
||||||
|
|
||||||
class TypeClaim(dspy.Signature):
|
class TypeClaim(dspy.Signature):
|
||||||
"""You are the TYPE step of a knowledge machine. Given ONE single claim
|
"""You are the TYPE step of a knowledge machine. Given ONE single claim,
|
||||||
and the TEXT it was extracted from, type the claim into the Fact
|
type the claim into the typed fact schema: subject entity, relation,
|
||||||
schema: subject entity, relation, object/value, the VERBATIM quote
|
object/value, and the temporal restrictions the claim states. All
|
||||||
copied EXACTLY from the text (the FULL sentence or table row that
|
temporal fields are optional. Only what the claim states; no
|
||||||
states the claim, at least 10 characters), and the temporal
|
inference. If the claim cannot be typed honestly, return null."""
|
||||||
restrictions the text states. All temporal fields are optional and
|
|
||||||
must be contained in the quote. Only what the claim and its quote
|
|
||||||
state; no inference. If the text does not state the claim, return
|
|
||||||
null."""
|
|
||||||
claim: str = dspy.InputField(desc="the claim to type")
|
claim: str = dspy.InputField(desc="the claim to type")
|
||||||
text: str = dspy.InputField(
|
fact: FactNoQuote | None = dspy.OutputField(
|
||||||
desc="the text the claim was extracted from — find the VERBATIM "
|
desc="the typed fact — subject, relation, object, temporal "
|
||||||
"quote here, copied exactly")
|
"restrictions, or null when the "
|
||||||
fact: Fact | None = dspy.OutputField(
|
"claim cannot be typed honestly")
|
||||||
desc="the typed Fact with its verbatim quote from the text, or "
|
|
||||||
"null when the claim cannot be typed honestly")
|
|
||||||
|
|
||||||
|
|
||||||
class AnswerFromKG(dspy.Signature):
|
class AnswerFromKG(dspy.Signature):
|
||||||
|
|||||||
@@ -0,0 +1,84 @@
|
|||||||
|
"""Question-to-article ranking: BM25 + cosine, reciprocal rank fusion.
|
||||||
|
|
||||||
|
The candidate pool is small (all results from this call's searches), so BM25
|
||||||
|
needs no external index or dependency. Snippets guide fetching, never answers.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import math
|
||||||
|
from collections import Counter
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
from .queries import WORD_RE
|
||||||
|
from .store import stem
|
||||||
|
from .wiki import WikiSearchResult
|
||||||
|
|
||||||
|
|
||||||
|
def merge_search_results(per_query: list[list[WikiSearchResult]]) -> list[WikiSearchResult]:
|
||||||
|
"""Deduplicate by title, retaining distinct query-specific snippets."""
|
||||||
|
snippets: dict[str, list[str]] = {}
|
||||||
|
for results in per_query:
|
||||||
|
for hit in results:
|
||||||
|
parts = snippets.setdefault(hit.title, [])
|
||||||
|
if hit.snippet and hit.snippet not in parts:
|
||||||
|
parts.append(hit.snippet)
|
||||||
|
return [WikiSearchResult(title, "\n".join(parts))
|
||||||
|
for title, parts in snippets.items()]
|
||||||
|
|
||||||
|
|
||||||
|
def bm25_scores(question: str, documents: list[str]) -> list[float]:
|
||||||
|
"""Okapi BM25 (k1=1.5, b=0.75), with positive Robertson IDF.
|
||||||
|
|
||||||
|
Query terms come from the full question, never the composed searches.
|
||||||
|
Tokenization and stemming are shared with the existing lexical retrieval.
|
||||||
|
"""
|
||||||
|
counts = [Counter(stem(t) for t in WORD_RE.findall(doc.casefold()))
|
||||||
|
for doc in documents]
|
||||||
|
lengths = [sum(c.values()) for c in counts]
|
||||||
|
avg_length = sum(lengths) / len(lengths) if lengths else 0
|
||||||
|
if not avg_length:
|
||||||
|
return [0.0] * len(documents)
|
||||||
|
terms = sorted({stem(t) for t in WORD_RE.findall(question.casefold())})
|
||||||
|
df = Counter(t for c in counts for t in c)
|
||||||
|
idf = {t: math.log1p((len(counts) - df[t] + 0.5) / (df[t] + 0.5))
|
||||||
|
for t in terms}
|
||||||
|
return [sum(idf[t] * (c[t] * 2.5) /
|
||||||
|
(c[t] + 1.5 * (0.25 + 0.75 * length / avg_length))
|
||||||
|
for t in terms if c[t])
|
||||||
|
for c, length in zip(counts, lengths)]
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class RankedArticle:
|
||||||
|
article: WikiSearchResult
|
||||||
|
bm25: float
|
||||||
|
semantic: float | None
|
||||||
|
score: float
|
||||||
|
|
||||||
|
|
||||||
|
def rank_articles(question: str, articles: list[WikiSearchResult],
|
||||||
|
similarities: list[float] | None = None) -> list[RankedArticle]:
|
||||||
|
"""Equal-weight RRF (k=60), or BM25 alone when semantics are unavailable.
|
||||||
|
|
||||||
|
Equal scores share a rank, so lexical misses or tied cosine scores do not
|
||||||
|
introduce an arbitrary preference. Final ties preserve search encounter order.
|
||||||
|
"""
|
||||||
|
lexical = bm25_scores(question, [a.text for a in articles])
|
||||||
|
if similarities is not None:
|
||||||
|
if len(similarities) != len(articles) or not all(
|
||||||
|
math.isfinite(s) for s in similarities):
|
||||||
|
raise ValueError("one finite semantic similarity is required per article")
|
||||||
|
|
||||||
|
def reciprocal_rank(scores: list[float], value: float) -> float:
|
||||||
|
rank = 1 + sum(s > value for s in scores)
|
||||||
|
return 1.0 / (60 + rank)
|
||||||
|
|
||||||
|
ranked = []
|
||||||
|
for i, article in enumerate(articles):
|
||||||
|
semantic = similarities[i] if similarities is not None else None
|
||||||
|
score = lexical[i]
|
||||||
|
if similarities is not None:
|
||||||
|
score = reciprocal_rank(lexical, lexical[i])
|
||||||
|
score += reciprocal_rank(similarities, similarities[i])
|
||||||
|
ranked.append(RankedArticle(article, lexical[i], semantic, score))
|
||||||
|
return sorted(ranked, key=lambda a: a.score, reverse=True)
|
||||||
@@ -0,0 +1,267 @@
|
|||||||
|
"""Offline regression tests for knowledge-answer orchestration.
|
||||||
|
|
||||||
|
Run: .venv/bin/python knowledge/tests/answer_question.py
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import Mock, call, patch
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
|
||||||
|
|
||||||
|
from knowledge.expert import (KnowledgeConfig, KnowledgeExpert, _goal_skim_notice,
|
||||||
|
_probe_seeds)
|
||||||
|
from knowledge.skim import SkimSheet
|
||||||
|
from knowledge.wiki import WikiPage, WikiSearchResult, WikiTable
|
||||||
|
|
||||||
|
|
||||||
|
QUESTION = "What is the flow of Po?"
|
||||||
|
UNKNOWN = {"value": "UNKNOWN", "quote": "", "url": ""}
|
||||||
|
ANSWER = {"value": "1540", "quote": "Po flows", "url": "https://example.org/Po"}
|
||||||
|
SET_ANSWER = {**ANSWER, "list_items": ["Po"], "list_count": 1}
|
||||||
|
|
||||||
|
|
||||||
|
def page(title: str, tables: bool = False) -> WikiPage:
|
||||||
|
return WikiPage(
|
||||||
|
title=title, pageid=1, url=f"https://example.org/{title}",
|
||||||
|
text="Po flows", fetched_at="2026-10-28",
|
||||||
|
tables=[WikiTable(idx=1)] if tables else [])
|
||||||
|
|
||||||
|
|
||||||
|
class AnswerQuestionTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.expert = KnowledgeExpert.__new__(KnowledgeExpert)
|
||||||
|
e = self.expert
|
||||||
|
e.cfg = KnowledgeConfig()
|
||||||
|
e.client = Mock()
|
||||||
|
e.client.search.side_effect = [
|
||||||
|
[WikiSearchResult("Po", "Rivers flow through Italy. Po flows.")],
|
||||||
|
[WikiSearchResult("Italy")]]
|
||||||
|
e.client.fetch_rich.side_effect = lambda title: page(title)
|
||||||
|
e._checked, e._merged = 5, 3
|
||||||
|
e._prover_answer = Mock(return_value=None)
|
||||||
|
e._probe = Mock(return_value=["row"])
|
||||||
|
e._qvec = Mock(return_value=None)
|
||||||
|
e._answer_from_rows = Mock(return_value=UNKNOWN)
|
||||||
|
e._audit_ambiguity = Mock(side_effect=lambda _q, ans, _rows, _charge: ans)
|
||||||
|
e._set_gate_hit = Mock(return_value=None)
|
||||||
|
e._serve_set = Mock(return_value=SET_ANSWER)
|
||||||
|
e._list_from_page = Mock(return_value=None)
|
||||||
|
e._process_page = Mock()
|
||||||
|
e._harvest_side_tables = Mock()
|
||||||
|
e._promote_leads = Mock()
|
||||||
|
e._log = Mock()
|
||||||
|
e._rec = Mock()
|
||||||
|
self.compose = self.enterContext(patch(
|
||||||
|
"knowledge.expert.compose_queries",
|
||||||
|
return_value=(["query one", "query two"], ["Po"])))
|
||||||
|
self.skim = self.enterContext(patch(
|
||||||
|
"knowledge.expert.skim_article",
|
||||||
|
side_effect=lambda p, **_kw: SkimSheet(title=p.title, url=p.url)))
|
||||||
|
self.enterContext(patch("knowledge.expert.time.time", side_effect=[10, 12.34]))
|
||||||
|
|
||||||
|
def test_prover_returns_before_gather_state_is_reset(self):
|
||||||
|
e = self.expert
|
||||||
|
e._skim_notices = ["previous"]
|
||||||
|
e._prover_answer.return_value = {"value": "proven", "verified": True}
|
||||||
|
charge = Mock()
|
||||||
|
result = e.answer_question(QUESTION, parent_question="Italy", charge_llm=charge)
|
||||||
|
self.assertEqual(result, {"value": "proven", "verified": True})
|
||||||
|
self.assertEqual(e._skim_notices, ["previous"])
|
||||||
|
self.assertEqual(e._current_goal_question, "Italy")
|
||||||
|
e._prover_answer.assert_called_once_with(QUESTION, charge)
|
||||||
|
e._probe.assert_not_called()
|
||||||
|
e.client.search.assert_not_called()
|
||||||
|
|
||||||
|
def test_scalar_kg_hit_audits_without_search(self):
|
||||||
|
e = self.expert
|
||||||
|
e._answer_from_rows.return_value = ANSWER
|
||||||
|
result = e.answer_question(QUESTION, evidence="E1: Po (answers Q1)")
|
||||||
|
self.assertEqual(result, {**ANSWER, "source": "knowledge_graph", "kg_rows": 1})
|
||||||
|
self.assertEqual(e._probe.call_args.args[1][-1], "Po")
|
||||||
|
e._audit_ambiguity.assert_called_once_with(QUESTION, ANSWER, ["row"], None)
|
||||||
|
e.client.search.assert_not_called()
|
||||||
|
|
||||||
|
def test_list_kg_hit_uses_set_not_scalar_judge(self):
|
||||||
|
e = self.expert
|
||||||
|
e._set_gate_hit.return_value = "rivers"
|
||||||
|
result = e.answer_question(QUESTION, answer_type="list")
|
||||||
|
self.assertEqual(result, {**SET_ANSWER, "source": "knowledge_graph", "kg_rows": 1})
|
||||||
|
e._serve_set.assert_called_once_with("rivers", QUESTION)
|
||||||
|
e._answer_from_rows.assert_not_called()
|
||||||
|
e.client.search.assert_not_called()
|
||||||
|
|
||||||
|
def test_search_deduplicates_and_globally_ranks_title_and_snippet(self):
|
||||||
|
e = self.expert
|
||||||
|
e.cfg.max_articles = 5
|
||||||
|
e.client.search.side_effect = [
|
||||||
|
[WikiSearchResult("First"), WikiSearchResult("Other"),
|
||||||
|
WikiSearchResult("Po flow"), WikiSearchResult("Po river")],
|
||||||
|
[WikiSearchResult("Winner", "Po flow"), WikiSearchResult("First"),
|
||||||
|
WikiSearchResult("Other")]]
|
||||||
|
result = e.answer_question(QUESTION)
|
||||||
|
self.assertEqual(result["stats"]["pages"],
|
||||||
|
["Po flow", "Winner", "Po river", "First", "Other"])
|
||||||
|
self.assertEqual(e.client.search.call_args_list, [
|
||||||
|
call("query one", limit=4), call("query two", limit=4)])
|
||||||
|
self.assertEqual(e._extract_entities, ["Po"])
|
||||||
|
self.assertEqual(e._rec.call_args_list[0], call(
|
||||||
|
"fn.done", fn="compose",
|
||||||
|
in_={"question": QUESTION, "evidence_entities": [], "list_mode": False},
|
||||||
|
out_={"queries": ["query one", "query two"], "entities": ["Po"]}))
|
||||||
|
|
||||||
|
def test_scalar_early_exit_skims_harvests_and_processes_before_answering(self):
|
||||||
|
e = self.expert
|
||||||
|
e._answer_from_rows.side_effect = [UNKNOWN, ANSWER]
|
||||||
|
order = Mock()
|
||||||
|
for name in ("_harvest_side_tables", "_promote_leads", "_process_page",
|
||||||
|
"_answer_from_rows"):
|
||||||
|
order.attach_mock(getattr(e, name), name)
|
||||||
|
charge = Mock()
|
||||||
|
result = e.answer_question(QUESTION, parent_question="Italy", charge_llm=charge)
|
||||||
|
self.assertEqual(result, {
|
||||||
|
**ANSWER, "source": "knowledge_graph",
|
||||||
|
"stats": {"pages": ["Po"], "link_queue": 0, "skim": []}})
|
||||||
|
self.assertEqual([c[0] for c in order.mock_calls], [
|
||||||
|
"_answer_from_rows", "_harvest_side_tables", "_promote_leads",
|
||||||
|
"_process_page", "_answer_from_rows"])
|
||||||
|
self.assertEqual(e._probe.call_count, 3)
|
||||||
|
e._audit_ambiguity.assert_called_once_with(QUESTION, ANSWER, ["row"], charge)
|
||||||
|
e.client.fetch_rich.assert_called_once_with("Po")
|
||||||
|
e._process_page.assert_called_once_with(
|
||||||
|
e._seen_pages["Po"], QUESTION, e._keywords(QUESTION), charge,
|
||||||
|
goal_terms=e._keywords("Italy"))
|
||||||
|
e._promote_leads.assert_called_once_with("", charge)
|
||||||
|
|
||||||
|
def test_table_list_early_exit_skips_extraction(self):
|
||||||
|
e = self.expert
|
||||||
|
e.client.fetch_rich.side_effect = lambda title: page(title, tables=True)
|
||||||
|
e._list_from_page.return_value = SET_ANSWER
|
||||||
|
result = e.answer_question(QUESTION, answer_type="LIST")
|
||||||
|
self.assertEqual(result["list_items"], ["Po"])
|
||||||
|
self.assertEqual(result["stats"]["pages"], ["Po"])
|
||||||
|
e._process_page.assert_not_called()
|
||||||
|
e._answer_from_rows.assert_not_called()
|
||||||
|
|
||||||
|
def test_disjoint_table_list_continues_to_next_article(self):
|
||||||
|
e = self.expert
|
||||||
|
e.client.fetch_rich.side_effect = lambda title: page(title, tables=True)
|
||||||
|
e._list_from_page.side_effect = [
|
||||||
|
{**SET_ANSWER, "list_items": ["Amazon"]}, SET_ANSWER]
|
||||||
|
result = e.answer_question(
|
||||||
|
QUESTION, answer_type="LIST", evidence="E1: Po (answers Q1)")
|
||||||
|
self.assertEqual(result["list_items"], ["Po"])
|
||||||
|
self.assertEqual(result["stats"]["pages"], ["Po", "Italy"])
|
||||||
|
self.assertEqual(e._process_page.call_count, 1)
|
||||||
|
|
||||||
|
def test_list_set_hit_after_processing(self):
|
||||||
|
e = self.expert
|
||||||
|
e._set_gate_hit.side_effect = [None, "rivers"]
|
||||||
|
result = e.answer_question("Which rivers flow through Italy?")
|
||||||
|
self.assertEqual(result["list_items"], ["Po"])
|
||||||
|
self.assertEqual(result["stats"]["pages"], ["Po"])
|
||||||
|
e._process_page.assert_called_once()
|
||||||
|
e._answer_from_rows.assert_not_called()
|
||||||
|
|
||||||
|
def test_final_reprobe_preserves_stats_and_unknown_source(self):
|
||||||
|
e = self.expert
|
||||||
|
result = e.answer_question(QUESTION)
|
||||||
|
self.assertEqual(result, {
|
||||||
|
**UNKNOWN, "source": "wikipedia_miss",
|
||||||
|
"stats": {"pages": ["Po", "Italy"], "link_queue": 0,
|
||||||
|
"checked": 5, "merged": 3, "skim": [], "elapsed_s": 2.3}})
|
||||||
|
self.assertEqual(e._probe.call_count, 4)
|
||||||
|
e._audit_ambiguity.assert_called_once_with(QUESTION, UNKNOWN, ["row"], None)
|
||||||
|
|
||||||
|
def test_final_reprobe_can_answer_after_all_articles(self):
|
||||||
|
e = self.expert
|
||||||
|
e._answer_from_rows.side_effect = [UNKNOWN, UNKNOWN, UNKNOWN, ANSWER]
|
||||||
|
result = e.answer_question(QUESTION)
|
||||||
|
self.assertEqual(result["value"], "1540")
|
||||||
|
self.assertEqual(result["source"], "knowledge_graph")
|
||||||
|
self.assertEqual(result["stats"]["merged"], 3)
|
||||||
|
|
||||||
|
def test_fetch_failure_is_logged_and_remaining_articles_are_processed(self):
|
||||||
|
e = self.expert
|
||||||
|
e.client.fetch_rich.side_effect = [RuntimeError("unavailable"), page("Italy")]
|
||||||
|
result = e.answer_question(QUESTION)
|
||||||
|
self.assertEqual(result["stats"]["pages"], ["Italy"])
|
||||||
|
e._log.assert_any_call("fetch failed: Po: unavailable")
|
||||||
|
|
||||||
|
def test_prover_failure_is_logged_and_gather_continues(self):
|
||||||
|
e = self.expert
|
||||||
|
e._prover_answer.side_effect = RuntimeError("translation failed")
|
||||||
|
result = e.answer_question(QUESTION)
|
||||||
|
self.assertEqual(result["source"], "wikipedia_miss")
|
||||||
|
e._log.assert_any_call(
|
||||||
|
"prover path failed (RuntimeError('translation failed')); judge path",
|
||||||
|
think=True)
|
||||||
|
|
||||||
|
def test_search_failure_propagates(self):
|
||||||
|
self.expert.client.search.side_effect = RuntimeError("search failed")
|
||||||
|
with self.assertRaisesRegex(RuntimeError, "search failed"):
|
||||||
|
self.expert.answer_question(QUESTION)
|
||||||
|
|
||||||
|
def test_cached_pages_and_link_queue_persist_but_not_notices(self):
|
||||||
|
e = self.expert
|
||||||
|
cached = page("Po")
|
||||||
|
e._seen_pages = {"Po": cached}
|
||||||
|
e._link_queue = ["Existing"]
|
||||||
|
e._skim_notices = ["stale"]
|
||||||
|
e._skim_leads = ["stale"]
|
||||||
|
self.skim.side_effect = lambda p, **_kw: SkimSheet(
|
||||||
|
title=p.title, url=p.url, link_candidates=["Existing", "New"])
|
||||||
|
result = e.answer_question(QUESTION)
|
||||||
|
self.assertEqual(result["stats"]["link_queue"], 2)
|
||||||
|
self.assertEqual(e._link_queue, ["Existing", "New"])
|
||||||
|
self.assertNotIn("stale", result["stats"]["skim"])
|
||||||
|
self.assertEqual(len(result["stats"]["skim"]), 2)
|
||||||
|
self.assertEqual(e._skim_leads, [])
|
||||||
|
e.client.fetch_rich.assert_called_once_with("Italy")
|
||||||
|
self.assertIs(e._process_page.call_args_list[0].args[0], cached)
|
||||||
|
e._rec.assert_any_call(
|
||||||
|
"fn.done", fn="fetch", in_={"title": "Po"}, out_={"cached": True})
|
||||||
|
|
||||||
|
def test_skim_notice_filters_goal_terms_but_keeps_quantities(self):
|
||||||
|
self.skim.side_effect = lambda p, **_kw: SkimSheet(
|
||||||
|
title=p.title, url=p.url,
|
||||||
|
infobox_quantities={"flow": "50 m3/s"} if p.title == "Italy" else {},
|
||||||
|
link_candidates=["Unrelated"])
|
||||||
|
result = self.expert.answer_question(QUESTION, parent_question="Italy")
|
||||||
|
self.assertEqual(len(result["stats"]["skim"]), 1)
|
||||||
|
self.assertTrue(result["stats"]["skim"][0].startswith("Italy:"))
|
||||||
|
|
||||||
|
def test_link_queue_can_be_disabled(self):
|
||||||
|
e = self.expert
|
||||||
|
e.cfg.skim_link_queue = False
|
||||||
|
self.skim.side_effect = lambda p, **_kw: SkimSheet(
|
||||||
|
title=p.title, url=p.url, link_candidates=["New"])
|
||||||
|
result = e.answer_question(QUESTION)
|
||||||
|
self.assertEqual(result["stats"]["link_queue"], 0)
|
||||||
|
|
||||||
|
|
||||||
|
class PipelineHelperTests(unittest.TestCase):
|
||||||
|
def test_probe_seeds_preserve_keywords_and_only_add_short_evidence_values(self):
|
||||||
|
kws = ["flow"]
|
||||||
|
evidence = (
|
||||||
|
"E1: Po (answers Q1)\n"
|
||||||
|
"E2: New York\n"
|
||||||
|
"E3: this value has too many words\n"
|
||||||
|
"E4: \n"
|
||||||
|
"no value delimiter")
|
||||||
|
self.assertEqual(_probe_seeds(kws, evidence), ["flow", "Po", "New", "York"])
|
||||||
|
self.assertEqual(kws, ["flow"])
|
||||||
|
self.assertEqual(_probe_seeds(kws, ""), kws)
|
||||||
|
|
||||||
|
def test_skim_notices_include_goal_matches_and_filter_unrelated_surfaces(self):
|
||||||
|
sheet = SkimSheet(title="Po", url="u", link_candidates=["River flow"])
|
||||||
|
self.assertEqual(_goal_skim_notice(sheet, ["flow"]), sheet.notice())
|
||||||
|
self.assertEqual(_goal_skim_notice(sheet, []), sheet.notice())
|
||||||
|
self.assertEqual(_goal_skim_notice(sheet, ["population"]), "")
|
||||||
|
self.assertEqual(_goal_skim_notice(SkimSheet(title="Po", url="u"), []), "")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,229 @@
|
|||||||
|
"""Offline search snippets, BM25, hybrid ranking and degradation tests.
|
||||||
|
|
||||||
|
Run: .venv/bin/python knowledge/tests/semantic_fetch.py
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import math
|
||||||
|
import sys
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import Mock, patch
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
|
||||||
|
|
||||||
|
from knowledge.embeddings import EmbedderDown, embed
|
||||||
|
from knowledge.expert import KnowledgeConfig, KnowledgeExpert
|
||||||
|
from knowledge.ranking import bm25_scores, merge_search_results, rank_articles
|
||||||
|
from knowledge.wiki import WikipediaClient, WikiSearchResult
|
||||||
|
|
||||||
|
|
||||||
|
class WikipediaSearchTests(unittest.TestCase):
|
||||||
|
def test_search_requests_and_cleans_snippets(self):
|
||||||
|
client = WikipediaClient()
|
||||||
|
client._get = Mock(return_value={"query": {"search": [
|
||||||
|
{"title": "River", "snippet":
|
||||||
|
'A <span class="searchmatch">river</span> & '
|
||||||
|
"its "flow".\n More text <water>."},
|
||||||
|
{"title": "No snippet"},
|
||||||
|
]}})
|
||||||
|
self.assertEqual(client.search("river flow", limit=3), [
|
||||||
|
WikiSearchResult("River", 'A river & its "flow". More text <water>.'),
|
||||||
|
WikiSearchResult("No snippet")])
|
||||||
|
client._get.assert_called_once_with(
|
||||||
|
action="query", list="search", srsearch="river flow",
|
||||||
|
srlimit=3, srprop="snippet", srnamespace=0)
|
||||||
|
|
||||||
|
def test_empty_search(self):
|
||||||
|
client = WikipediaClient()
|
||||||
|
client._get = Mock(return_value={"query": {"search": []}})
|
||||||
|
self.assertEqual(client.search("nothing"), [])
|
||||||
|
|
||||||
|
|
||||||
|
class ArticleRankingTests(unittest.TestCase):
|
||||||
|
def test_merge_preserves_distinct_snippets_without_duplicate_weight(self):
|
||||||
|
results = merge_search_results([
|
||||||
|
[], [WikiSearchResult("River"), WikiSearchResult("Other", "first")],
|
||||||
|
[WikiSearchResult("River", "flow"), WikiSearchResult("Other", "first"),
|
||||||
|
WikiSearchResult("River", "length"), WikiSearchResult("River", "flow")]])
|
||||||
|
self.assertEqual(results, [
|
||||||
|
WikiSearchResult("River", "flow\nlength"),
|
||||||
|
WikiSearchResult("Other", "first")])
|
||||||
|
|
||||||
|
def test_bm25_matches_formula(self):
|
||||||
|
scores = bm25_scores("river", ["river river", "stone"])
|
||||||
|
idf = math.log1p(1.5 / 1.5)
|
||||||
|
expected = idf * (2 * 2.5) / (2 + 1.5 * (0.25 + 0.75 * 2 / 1.5))
|
||||||
|
self.assertAlmostEqual(scores[0], expected)
|
||||||
|
self.assertEqual(scores[1], 0)
|
||||||
|
|
||||||
|
def test_bm25_rewards_rare_terms_and_saturates_frequency(self):
|
||||||
|
scores = bm25_scores("water discharge", [
|
||||||
|
"water water", "discharge", "water", "stone"])
|
||||||
|
self.assertGreater(scores[1], scores[0])
|
||||||
|
single = bm25_scores("river", ["river stone", "stone stone"])[0]
|
||||||
|
double = bm25_scores("river", ["river river", "stone stone"])[0]
|
||||||
|
self.assertGreater(double, single)
|
||||||
|
self.assertLess(double, 2 * single)
|
||||||
|
|
||||||
|
def test_bm25_length_normalizes_and_matches_case_stems_and_short_entities(self):
|
||||||
|
scores = bm25_scores("Po rivers", [
|
||||||
|
"PO river", "Po river " + "stone " * 100, "Outflow"])
|
||||||
|
self.assertGreater(scores[0], scores[1])
|
||||||
|
self.assertGreater(scores[1], 0)
|
||||||
|
self.assertEqual(scores[2], 0)
|
||||||
|
|
||||||
|
def test_empty_inputs_and_no_overlap(self):
|
||||||
|
self.assertEqual(bm25_scores("", ["a", ""]), [0, 0])
|
||||||
|
self.assertEqual(bm25_scores("river", ["", ""]), [0, 0])
|
||||||
|
self.assertEqual(bm25_scores("river", []), [])
|
||||||
|
self.assertEqual(rank_articles("river", []), [])
|
||||||
|
self.assertEqual(rank_articles("river", [], []), [])
|
||||||
|
|
||||||
|
def test_lexical_ranking_uses_snippet_and_question_not_title_overlap_only(self):
|
||||||
|
hits = [WikiSearchResult("River"), WikiSearchResult(
|
||||||
|
"Po", "The river discharge is the flow rate of water.")]
|
||||||
|
ranked = rank_articles("What is the river discharge?", hits)
|
||||||
|
self.assertEqual([r.article.title for r in ranked], ["Po", "River"])
|
||||||
|
self.assertIsNone(ranked[0].semantic)
|
||||||
|
self.assertEqual(ranked[0].score, ranked[0].bm25)
|
||||||
|
|
||||||
|
def test_rrf_combines_lexical_and_semantic_ranks(self):
|
||||||
|
hits = [WikiSearchResult("river river"), WikiSearchResult("river stone"),
|
||||||
|
WikiSearchResult("quartz quartz")]
|
||||||
|
lexical = rank_articles("river", hits)
|
||||||
|
hybrid = rank_articles("river", hits, [0.1, 0.9, 0.5])
|
||||||
|
self.assertEqual(lexical[0].article.title, "river river")
|
||||||
|
self.assertEqual(hybrid[0].article.title, "river stone")
|
||||||
|
self.assertAlmostEqual(hybrid[0].score, 1 / 62 + 1 / 61)
|
||||||
|
|
||||||
|
def test_semantics_can_promote_a_lexical_miss(self):
|
||||||
|
hits = [WikiSearchResult("river"), WikiSearchResult("watercourse"),
|
||||||
|
WikiSearchResult("rock"), WikiSearchResult("mineral")]
|
||||||
|
ranked = rank_articles("river", hits, [0.1, 0.99, 0.2, 0.3])
|
||||||
|
self.assertEqual(ranked[0].article.title, "watercourse")
|
||||||
|
|
||||||
|
def test_tied_lexical_scores_do_not_bias_semantic_order(self):
|
||||||
|
hits = [WikiSearchResult("A"), WikiSearchResult("B"), WikiSearchResult("C")]
|
||||||
|
self.assertEqual([r.article.title for r in rank_articles(
|
||||||
|
"unmatched", hits, [0.1, 0.3, 0.9])], ["C", "B", "A"])
|
||||||
|
self.assertEqual([r.article.title for r in rank_articles(
|
||||||
|
"unmatched", hits, [0.5, 0.5, 0.5])], ["A", "B", "C"])
|
||||||
|
self.assertEqual([r.article.title for r in rank_articles(
|
||||||
|
"unmatched", hits)], ["A", "B", "C"])
|
||||||
|
|
||||||
|
def test_invalid_similarities_are_rejected(self):
|
||||||
|
for scores in ([], [float("nan")], [float("inf")]):
|
||||||
|
with self.subTest(scores=scores), self.assertRaises(ValueError):
|
||||||
|
rank_articles("river", [WikiSearchResult("A")], scores)
|
||||||
|
|
||||||
|
|
||||||
|
class ExpertSearchRankingTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.expert = KnowledgeExpert.__new__(KnowledgeExpert)
|
||||||
|
e = self.expert
|
||||||
|
e.cfg = KnowledgeConfig(max_articles=1)
|
||||||
|
e._embed_ok = True
|
||||||
|
e._qvec_cache = {"river": [1.0, 0.0]}
|
||||||
|
e._log = Mock()
|
||||||
|
e._rec = Mock()
|
||||||
|
e.client = Mock()
|
||||||
|
|
||||||
|
def test_all_searches_merge_before_question_based_global_ranking(self):
|
||||||
|
e = self.expert
|
||||||
|
e.client.search.side_effect = [
|
||||||
|
[WikiSearchResult("river river"), WikiSearchResult("river stone")],
|
||||||
|
[WikiSearchResult("quartz quartz"), WikiSearchResult("river stone", "stream")]]
|
||||||
|
vectors = [[0.1, 0.99], [1.0, 0.0], [0.5, 0.86]]
|
||||||
|
with patch("knowledge.expert.compose_queries",
|
||||||
|
return_value=(["unrelated query", "another query"], ["query"])), \
|
||||||
|
patch("knowledge.expert.embed", return_value=vectors) as embedding:
|
||||||
|
ordered = e._search_articles("river", [], False)
|
||||||
|
self.assertEqual(ordered[0], "river stone")
|
||||||
|
self.assertEqual(len(ordered), 3) # max_articles applies only AFTER ranking.
|
||||||
|
embedding.assert_called_once_with(
|
||||||
|
["river river", "river stone\nstream", "quartz quartz"],
|
||||||
|
model=e.cfg.embed_model, url=e.cfg.embed_url)
|
||||||
|
e._rec.assert_any_call(
|
||||||
|
"fn.done", fn="search",
|
||||||
|
in_={"query": "another query", "limit": 4},
|
||||||
|
out_={"titles": ["quartz quartz", "river stone"],
|
||||||
|
"results": [{"title": "quartz quartz", "snippet": ""},
|
||||||
|
{"title": "river stone", "snippet": "stream"}]})
|
||||||
|
rank_event = next(c.kwargs for c in e._rec.call_args_list
|
||||||
|
if c.kwargs.get("fn") == "rank_articles")
|
||||||
|
self.assertEqual(rank_event["in_"]["question"], "river")
|
||||||
|
self.assertEqual(rank_event["out_"]["method"], "bm25+cosine_rrf")
|
||||||
|
self.assertEqual(rank_event["out_"]["ranked"][0]["title"], "river stone")
|
||||||
|
|
||||||
|
def test_question_and_documents_are_embedded_not_composed_queries(self):
|
||||||
|
e = self.expert
|
||||||
|
with patch("knowledge.expert.embed",
|
||||||
|
side_effect=[[[1.0, 0.0]], [[0.0, 1.0]]]) as embedding:
|
||||||
|
e._rank_search_results("original question", [WikiSearchResult("A", "summary")])
|
||||||
|
self.assertEqual(embedding.call_args_list[0].args, (["original question"],))
|
||||||
|
self.assertEqual(embedding.call_args_list[1].args, (["A\nsummary"],))
|
||||||
|
|
||||||
|
def test_document_embedding_failure_logs_bm25_fallback(self):
|
||||||
|
e = self.expert
|
||||||
|
hits = [WikiSearchResult("unrelated"), WikiSearchResult("river")]
|
||||||
|
with patch("knowledge.expert.embed", side_effect=EmbedderDown("offline")):
|
||||||
|
self.assertEqual(e._rank_search_results("river", hits), ["river", "unrelated"])
|
||||||
|
self.assertFalse(e._embed_ok)
|
||||||
|
e._log.assert_called_once_with(
|
||||||
|
"article ranking: embedder down (offline); BM25-only fallback")
|
||||||
|
self.assertEqual(e._rec.call_args.kwargs["out_"]["method"], "bm25")
|
||||||
|
|
||||||
|
def test_question_embedding_failure_and_already_disabled_embedder(self):
|
||||||
|
e = self.expert
|
||||||
|
with patch("knowledge.expert.embed", side_effect=EmbedderDown("offline")) as embedding:
|
||||||
|
for _ in range(2):
|
||||||
|
self.assertEqual(e._rank_search_results(
|
||||||
|
"new question", [WikiSearchResult("A")]), ["A"])
|
||||||
|
embedding.assert_called_once()
|
||||||
|
self.assertFalse(e._embed_ok)
|
||||||
|
self.assertTrue(any("BM25-only fallback" in c.args[0]
|
||||||
|
for c in e._log.call_args_list))
|
||||||
|
|
||||||
|
def test_inconsistent_question_document_dimensions_fall_back(self):
|
||||||
|
with patch("knowledge.expert.embed", return_value=[[1.0]]):
|
||||||
|
self.assertEqual(self.expert._rank_search_results(
|
||||||
|
"river", [WikiSearchResult("river")]), ["river"])
|
||||||
|
self.assertFalse(self.expert._embed_ok)
|
||||||
|
self.assertIn("dimensions differ", self.expert._log.call_args.args[0])
|
||||||
|
|
||||||
|
def test_empty_candidate_pool_does_not_call_embedder(self):
|
||||||
|
with patch("knowledge.expert.embed") as embedding:
|
||||||
|
self.assertEqual(self.expert._rank_search_results("river", []), [])
|
||||||
|
embedding.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
class EmbeddingResponseTests(unittest.TestCase):
|
||||||
|
def test_invalid_embedding_responses_raise_embedder_down(self):
|
||||||
|
responses = [
|
||||||
|
[], {}, {"embeddings": []}, {"embeddings": [[1.0]]},
|
||||||
|
{"embeddings": [[1.0], [1.0, 2.0]]},
|
||||||
|
{"embeddings": [[0.0], [1.0]]},
|
||||||
|
{"embeddings": [[float("nan")], [1.0]]},
|
||||||
|
{"embeddings": [[float("inf")], [1.0]]},
|
||||||
|
{"embeddings": [["bad"], [1.0]]},
|
||||||
|
{"embeddings": [[True], [1.0]]},
|
||||||
|
{"embeddings": [[], []]},
|
||||||
|
]
|
||||||
|
for response in responses:
|
||||||
|
with self.subTest(response=response), patch(
|
||||||
|
"knowledge.embeddings.urllib.request.urlopen",
|
||||||
|
return_value=io.BytesIO(json.dumps(response).encode())):
|
||||||
|
with self.assertRaises(EmbedderDown):
|
||||||
|
embed(["question", "document"])
|
||||||
|
|
||||||
|
def test_valid_embedding_response(self):
|
||||||
|
with patch("knowledge.embeddings.urllib.request.urlopen",
|
||||||
|
return_value=io.BytesIO(b'{"embeddings":[[1,0],[0,1]]}')):
|
||||||
|
self.assertEqual(embed(["question", "document"]), [[1, 0], [0, 1]])
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -1,29 +1,38 @@
|
|||||||
"""The two-pass EXTRACT tests (Pass 1 claims, Pass 2 typed Facts).
|
"""The two-pass EXTRACT tests (Pass 1 claims + verbatim, Pass 2 typing).
|
||||||
|
|
||||||
Law: the old single call asked a slow model for verbatim quotes + typed
|
Law: the old single call asked a slow model for verbatim quotes + typed
|
||||||
temporal fields + sibling order assertions in ONE giant JSON array — the
|
temporal fields + sibling order assertions in ONE giant JSON array — the
|
||||||
output budget that produced the 40-minute arithmetic. The two-pass split
|
output budget that produced the 40-minute arithmetic. The two-pass split
|
||||||
shortens EVERY output: Pass 1 extracts plain claims (free-form strings
|
shortens EVERY output: Pass 1 extracts the claims, each with its
|
||||||
with coreference resolved to the entity names — near-zero format tax);
|
VERBATIM quote (coreference resolved to the entity names); Pass 2 types
|
||||||
Pass 2 types ONE claim into the existing Fact schema per call.
|
ONE claim per call — TYPING only, the model sees ONLY the claim and
|
||||||
|
returns FactNoQuote; code composes the Fact: FactNoQuote + verbatim
|
||||||
|
(owner 1/11: the VERBATIM is obtained before, the TYPE model never sees
|
||||||
|
nor rewrites it).
|
||||||
|
|
||||||
CRITICAL law: Pass 2 works on ONE CLAIM AT A TIME — sibling order
|
CRITICAL law: Pass 2 works on ONE CLAIM AT A TIME — the TYPE schema
|
||||||
assertions become IMPOSSIBLE by construction, so orders are dropped from
|
(FactNoQuote) has NO orders field at all, so sibling order assertions
|
||||||
the two-pass path (the store's fact_order keeps working for whatever
|
are impossible by construction (the store's fact_order keeps working
|
||||||
arrives as a typed Fact with orders; the two-pass facts carry none).
|
for whatever arrives as a typed Fact with orders; the two-pass facts
|
||||||
The store, the containment checks and the merge are UNTOUCHED — Pass 2
|
carry none). The store, the containment checks and the merge are
|
||||||
emits the same typed Fact as before, minus orders.
|
UNTOUCHED — the composed Fact is the same typed Fact as before, minus
|
||||||
|
orders.
|
||||||
|
|
||||||
Pinned:
|
Pinned:
|
||||||
1. ExtractClaims: free-form claim strings, coreferences RESOLVED (the
|
1. ExtractClaims: free-form claims, coreferences RESOLVED (the claim
|
||||||
claim must name its entities, not 'he/it/the party').
|
must name its entities, not 'he/it/the party'), each carrying its
|
||||||
2. TypeClaim: one claim in -> one typed Fact out (same fields as the
|
VERBATIM quote — the quote is extracted HERE, in Pass 1.
|
||||||
legacy ExtractSignature.facts minus orders; temporal fields optional).
|
2. TypeClaim: one claim in -> one FactNoQuote out (Fact minus quote,
|
||||||
3. The pipeline wiring: _extract_two_pass returns typed Fact objects;
|
minus orders; temporal fields optional) — no text, no verbatim
|
||||||
candidates flow into _ingest_candidate exactly as before.
|
input: the TYPE model never sees the quote.
|
||||||
|
3. The pipeline wiring: the two-pass path returns composed Fact
|
||||||
|
objects; candidates flow into _ingest_candidate exactly as before.
|
||||||
4. Honest empty: no claims -> no facts, no invention.
|
4. Honest empty: no claims -> no facts, no invention.
|
||||||
5. The legacy single-pass signature STAYS (table frags use it; flipping
|
5. The legacy single-pass signature STAYS (table frags use it; flipping
|
||||||
the whole pipeline over is a later decision, config-driven).
|
the whole pipeline over is a later decision, config-driven).
|
||||||
|
6. Code COMPOSES the output Fact = FactNoQuote + verbatim (LLMs
|
||||||
|
propose, code decides) — the TYPE model never sees nor rewrites
|
||||||
|
the quote, so it cannot corrupt the span.
|
||||||
|
|
||||||
Run: .venv/bin/python knowledge/tests/two_pass_extract.py
|
Run: .venv/bin/python knowledge/tests/two_pass_extract.py
|
||||||
"""
|
"""
|
||||||
@@ -36,7 +45,8 @@ sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|||||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
|
||||||
|
|
||||||
from knowledge.extract import ExtractClaims, TypeClaim, Fact, ExtractSignature
|
from knowledge.extract import (Claim, ExtractClaims, ExtractSignature, Fact,
|
||||||
|
FactNoQuote, TypeClaim)
|
||||||
from knowledge.two_pass import claims_from, fact_from_claim
|
from knowledge.two_pass import claims_from, fact_from_claim
|
||||||
|
|
||||||
|
|
||||||
@@ -49,55 +59,79 @@ class Scripted:
|
|||||||
|
|
||||||
|
|
||||||
def test_extract_claims_signature():
|
def test_extract_claims_signature():
|
||||||
"""Pass 1: claims are free-form strings; coreferences resolved."""
|
"""Pass 1: claims + their VERBATIM quotes; coreferences resolved."""
|
||||||
fields = set(ExtractClaims.__fields__)
|
fields = set(ExtractClaims.__fields__)
|
||||||
assert fields == {"entities", "heading", "text", "claims"}, fields
|
assert fields == {"entities", "heading", "text", "claims"}, fields
|
||||||
|
a = ExtractClaims.model_fields["claims"].annotation
|
||||||
|
assert "Claim" in str(a), a # each claim now carries its verbatim
|
||||||
# what the model actually sees: dspy keeps desc in json_schema_extra
|
# what the model actually sees: dspy keeps desc in json_schema_extra
|
||||||
d = (ExtractClaims.model_fields["claims"].json_schema_extra or {}).get("desc", "")
|
d = (ExtractClaims.model_fields["claims"].json_schema_extra or {}).get("desc", "")
|
||||||
assert "coreference" in d.lower() or "resolved" in d.lower(), d
|
assert "verbatim" in d.lower(), d
|
||||||
print("ok: ExtractClaims = free-form claims, coreferences resolved in-draft")
|
dv = (Claim.model_fields["verbatim"].json_schema_extra or {}).get("desc", "")
|
||||||
|
assert "verbatim" in dv.lower() and "copied exactly" in dv.lower(), dv
|
||||||
|
print("ok: ExtractClaims = claims with their VERBATIM quotes, coreferences resolved")
|
||||||
|
|
||||||
|
|
||||||
def test_type_claim_signature():
|
def test_type_claim_signature():
|
||||||
"""Pass 2: one claim -> one typed Fact; orders NEVER produced here."""
|
"""Pass 2: one claim -> one typed FactNoQuote; no verbatim, no text;
|
||||||
|
orders IMPOSSIBLE (no orders field at all)."""
|
||||||
fields = set(TypeClaim.__fields__)
|
fields = set(TypeClaim.__fields__)
|
||||||
assert fields == {"claim", "text", "fact"}, fields # text: the quote must be COPIED from it (live finding: without it, 69/70 invented quotes rejected)
|
# the model sees ONLY the claim: the VERBATIM (Pass 1's) is NOT an
|
||||||
|
# input — nothing to copy, nothing to rewrite (owner 1/11).
|
||||||
|
assert fields == {"claim", "fact"}, fields
|
||||||
f = TypeClaim.model_fields["fact"].annotation
|
f = TypeClaim.model_fields["fact"].annotation
|
||||||
assert "Fact" in str(f), f
|
assert "FactNoQuote" in str(f), f
|
||||||
# Fact KEEPS orders (the legacy single-pass path and table frags use
|
# FactNoQuote: Fact minus quote (never shown to the TYPE model)
|
||||||
# them — untouched); the two-pass law is that TypeClaim never fills
|
# minus orders (one claim per call: no siblings to reference — the
|
||||||
# them: one claim per call means no siblings to reference.
|
# two-pass law, now enforced by the SCHEMA itself)
|
||||||
assert "orders" in Fact.model_fields, "legacy Fact must keep orders"
|
assert "quote" not in FactNoQuote.model_fields, "FactNoQuote must not carry a quote"
|
||||||
|
assert "orders" not in FactNoQuote.model_fields, "one claim per call: no siblings to reference"
|
||||||
|
# Fact KEEPS quote + orders (the legacy single-pass path and table
|
||||||
|
# frags use them — untouched)
|
||||||
|
assert "quote" in Fact.model_fields and "orders" in Fact.model_fields
|
||||||
d = TypeClaim.__doc__ or ""
|
d = TypeClaim.__doc__ or ""
|
||||||
assert "one claim" in d.lower() or "single" in d.lower(), d
|
assert "one claim" in d.lower() or "single" in d.lower(), d
|
||||||
print("ok: TypeClaim = one claim -> one Fact; orders never produced (no siblings)")
|
print("ok: TypeClaim = one claim -> FactNoQuote (typing only; no quote, no orders)")
|
||||||
|
|
||||||
|
|
||||||
def test_claims_from_runs_pass1():
|
def test_claims_from_runs_pass1():
|
||||||
e = Scripted(claims=Scripted(claims=["Pedro Sanchez is the prime minister of Spain since 2018",
|
e = Scripted(claims=Scripted(claims=[
|
||||||
"Sanchez became Secretary-General of the PSOE in 2017"]))
|
Claim(claim="Pedro Sanchez is the prime minister of Spain since 2018",
|
||||||
|
verbatim="has been the prime minister of Spain since 2018"),
|
||||||
|
Claim(claim="Sanchez became Secretary-General of the PSOE in 2017",
|
||||||
|
verbatim="Secretary-General of the Spanish Socialist Workers' Party (PSOE) since 2017")]))
|
||||||
out = claims_from(e, entities="Pedro Sanchez, PSOE", heading="", text="...")
|
out = claims_from(e, entities="Pedro Sanchez, PSOE", heading="", text="...")
|
||||||
assert out == ["Pedro Sanchez is the prime minister of Spain since 2018",
|
assert [(c.claim, c.verbatim) for c in out] == [
|
||||||
"Sanchez became Secretary-General of the PSOE in 2017"], out
|
("Pedro Sanchez is the prime minister of Spain since 2018",
|
||||||
print("ok: claims_from extracts the plain claim strings")
|
"has been the prime minister of Spain since 2018"),
|
||||||
|
("Sanchez became Secretary-General of the PSOE in 2017",
|
||||||
|
"Secretary-General of the Spanish Socialist Workers' Party (PSOE) since 2017")], out
|
||||||
|
print("ok: claims_from extracts the claims with their verbatim quotes")
|
||||||
|
|
||||||
|
|
||||||
def test_fact_from_claim_types_one_fact():
|
def test_fact_from_claim_types_one_fact():
|
||||||
e = Scripted(typeclaim=Scripted(fact=Fact(
|
"""Pass 2 types one claim; code COMPOSES the Fact = FactNoQuote +
|
||||||
|
verbatim — the scripted FactNoQuote has no quote to invent, and the
|
||||||
|
returned Fact carries Pass 1's verbatim (LLMs propose, code
|
||||||
|
decides)."""
|
||||||
|
e = Scripted(typeclaim=Scripted(fact=FactNoQuote(
|
||||||
subject="Pedro Sanchez", relation="prime minister of",
|
subject="Pedro Sanchez", relation="prime minister of",
|
||||||
object="Spain", quote="is a Spanish politician who has been the "
|
object="Spain",
|
||||||
"prime minister of Spain since 2018",
|
|
||||||
start="2018", end=None, point=None, granularity="year")))
|
start="2018", end=None, point=None, granularity="year")))
|
||||||
f = fact_from_claim(e, claim="Pedro Sanchez is the prime minister of Spain since 2018", text="...")
|
f = fact_from_claim(e, claim="Pedro Sanchez is the prime minister of Spain since 2018",
|
||||||
|
verbatim="has been the prime minister of Spain since 2018")
|
||||||
assert f.subject == "Pedro Sanchez" and f.start == "2018", f
|
assert f.subject == "Pedro Sanchez" and f.start == "2018", f
|
||||||
print("ok: fact_from_claim returns the typed Fact for one claim")
|
assert f.quote == "has been the prime minister of Spain since 2018", f.quote
|
||||||
|
assert isinstance(f, Fact), f # the store eats a real Fact
|
||||||
|
assert f.orders == [], f.orders # composed default: no siblings
|
||||||
|
print("ok: fact_from_claim composes Fact = FactNoQuote + verbatim")
|
||||||
|
|
||||||
|
|
||||||
def test_honest_empty():
|
def test_honest_empty():
|
||||||
e = Scripted(claims=Scripted(claims=[]))
|
e = Scripted(claims=Scripted(claims=[]))
|
||||||
assert claims_from(e, entities="", heading="", text="") == []
|
assert claims_from(e, entities="", heading="", text="") == []
|
||||||
e2 = Scripted(typeclaim=Scripted(fact=None))
|
e2 = Scripted(typeclaim=Scripted(fact=None))
|
||||||
assert fact_from_claim(e2, claim="", text="") is None
|
assert fact_from_claim(e2, claim="", verbatim="") is None
|
||||||
print("ok: no claims -> no facts; untypeable claim -> None, no invention")
|
print("ok: no claims -> no facts; untypeable claim -> None, no invention")
|
||||||
|
|
||||||
|
|
||||||
@@ -105,25 +139,32 @@ def test_claims_from_dedupes_exact_repeats():
|
|||||||
"""Pass 1 sometimes repeats its own list (live: glm listed 46 claims,
|
"""Pass 1 sometimes repeats its own list (live: glm listed 46 claims,
|
||||||
~26 were exact repeats/thinking leakage). Dedup is CODE, cheap and
|
~26 were exact repeats/thinking leakage). Dedup is CODE, cheap and
|
||||||
deterministic — the claim list must not be capped or filtered
|
deterministic — the claim list must not be capped or filtered
|
||||||
semantically, only made honest: no exact duplicates survive."""
|
semantically, only made honest: no exact duplicates survive. The
|
||||||
|
FIRST occurrence's verbatim is the one kept."""
|
||||||
calls = []
|
calls = []
|
||||||
|
|
||||||
class E: # minimal expert double
|
class E: # minimal expert double
|
||||||
def claims(self, entities, heading, text):
|
def claims(self, entities, heading, text):
|
||||||
calls.append((entities, heading))
|
calls.append((entities, heading))
|
||||||
class Out:
|
class Out:
|
||||||
claims = ["Pedro Sanchez is prime minister of Spain.",
|
claims = [Claim(claim="Pedro Sanchez is prime minister of Spain.",
|
||||||
"pedro sanchez is prime minister of spain. ",
|
verbatim="prime minister of Spain"),
|
||||||
"Pedro Sanchez is Secretary-General of the PSOE.",
|
Claim(claim="pedro sanchez is prime minister of spain. ",
|
||||||
"Pedro Sanchez is prime minister of Spain.",
|
verbatim="the repeat's quote — must not survive"),
|
||||||
"from the text. I need to list factual claims"]
|
Claim(claim="Pedro Sanchez is Secretary-General of the PSOE.",
|
||||||
|
verbatim="Secretary-General of the PSOE"),
|
||||||
|
Claim(claim="Pedro Sanchez is prime minister of Spain.",
|
||||||
|
verbatim="second repeat's quote"),
|
||||||
|
Claim(claim="from the text. I need to list factual claims",
|
||||||
|
verbatim="thinking leakage")]
|
||||||
return Out()
|
return Out()
|
||||||
|
|
||||||
got = claims_from(E(), entities="Pedro Sanchez", heading="h", text="t")
|
got = claims_from(E(), entities="Pedro Sanchez", heading="h", text="t")
|
||||||
assert got == ["Pedro Sanchez is prime minister of Spain.",
|
assert [(c.claim, c.verbatim) for c in got] == [
|
||||||
"Pedro Sanchez is Secretary-General of the PSOE.",
|
("Pedro Sanchez is prime minister of Spain.", "prime minister of Spain"),
|
||||||
"from the text. I need to list factual claims"], got
|
("Pedro Sanchez is Secretary-General of the PSOE.", "Secretary-General of the PSOE"),
|
||||||
print("ok: exact repeats deduped (case/space-insensitive); the rest kept")
|
("from the text. I need to list factual claims", "thinking leakage")], got
|
||||||
|
print("ok: exact repeats deduped (case/space-insensitive); the first verbatim kept")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
@@ -5,6 +5,12 @@ mode ingests the typed facts from Pass 2 exactly as the legacy path
|
|||||||
did — same _ingest_candidate, same containment checks, same merge; the
|
did — same _ingest_candidate, same containment checks, same merge; the
|
||||||
single-pass path keeps working (control). No network: the expert's
|
single-pass path keeps working (control). No network: the expert's
|
||||||
claims/typeclaim/extract modules are scripted.
|
claims/typeclaim/extract modules are scripted.
|
||||||
|
|
||||||
|
The verbatim law (1/11): Pass 1 extracts the VERBATIM quote, Pass 2
|
||||||
|
only types — the model sees ONLY the claim and returns FactNoQuote;
|
||||||
|
code COMPOSES the Fact (FactNoQuote + verbatim), so the STORED quotes
|
||||||
|
(quotes.verbatim) must be Pass 1's spans (contained in the page text),
|
||||||
|
never the TYPE model's.
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
@@ -16,7 +22,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|||||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
|
||||||
|
|
||||||
from knowledge.extract import Fact
|
from knowledge.extract import Claim, FactNoQuote
|
||||||
from knowledge.expert import KnowledgeConfig, KnowledgeExpert
|
from knowledge.expert import KnowledgeConfig, KnowledgeExpert
|
||||||
from knowledge.store import KnowledgeStore
|
from knowledge.store import KnowledgeStore
|
||||||
from knowledge.wiki import WikiPage
|
from knowledge.wiki import WikiPage
|
||||||
@@ -36,14 +42,22 @@ def make_page() -> WikiPage:
|
|||||||
|
|
||||||
|
|
||||||
class ScriptedClaims:
|
class ScriptedClaims:
|
||||||
|
"""Pass 1 double: claims WITH their verbatim quotes — spans that ARE
|
||||||
|
contained in PAGE_TEXT (the containment check runs for real)."""
|
||||||
|
|
||||||
def __call__(self, **kw):
|
def __call__(self, **kw):
|
||||||
class Out:
|
class Out:
|
||||||
claims = ["Pedro Sanchez has been the prime minister of Spain since 2018",
|
claims = [Claim(claim="Pedro Sanchez has been the prime minister of Spain since 2018",
|
||||||
"Pedro Sanchez is Secretary-General of the PSOE since 2017"]
|
verbatim="has been the prime minister of Spain since 2018"),
|
||||||
|
Claim(claim="Pedro Sanchez is Secretary-General of the PSOE since 2017",
|
||||||
|
verbatim="Secretary-General of the Spanish Socialist Workers' Party (PSOE) since 2017")]
|
||||||
return Out()
|
return Out()
|
||||||
|
|
||||||
|
|
||||||
class ScriptedTypeClaim:
|
class ScriptedTypeClaim:
|
||||||
|
"""Pass 2 double: typing only — FactNoQuote, NO quote field at all;
|
||||||
|
code composes the Fact with Pass 1's verbatim."""
|
||||||
|
|
||||||
def __init__(self, facts):
|
def __init__(self, facts):
|
||||||
self.facts = facts
|
self.facts = facts
|
||||||
self.i = 0
|
self.i = 0
|
||||||
@@ -64,15 +78,12 @@ def test_two_pass_ingests_typed_facts():
|
|||||||
store=store)
|
store=store)
|
||||||
e.claims = ScriptedClaims()
|
e.claims = ScriptedClaims()
|
||||||
e.typeclaim = ScriptedTypeClaim([
|
e.typeclaim = ScriptedTypeClaim([
|
||||||
Fact(subject="Pedro Sanchez", relation="prime minister of",
|
FactNoQuote(subject="Pedro Sanchez", relation="prime minister of",
|
||||||
object="Spain",
|
object="Spain",
|
||||||
quote="has been the prime minister of Spain since 2018",
|
start="2018", end=None, point=None, granularity="year"),
|
||||||
start="2018", end=None, point=None, granularity="year"),
|
FactNoQuote(subject="Pedro Sanchez", relation="secretary-general of",
|
||||||
Fact(subject="Pedro Sanchez", relation="secretary-general of",
|
object="PSOE",
|
||||||
object="PSOE",
|
start="2017", end=None, point=None, granularity="year"),
|
||||||
quote="Secretary-General of the Spanish Socialist Workers' "
|
|
||||||
"Party (PSOE) since 2017",
|
|
||||||
start="2017", end=None, point=None, granularity="year"),
|
|
||||||
])
|
])
|
||||||
# per-call state that answer_question initializes (the wiring test
|
# per-call state that answer_question initializes (the wiring test
|
||||||
# drives _process_page directly)
|
# drives _process_page directly)
|
||||||
@@ -89,7 +100,14 @@ def test_two_pass_ingests_typed_facts():
|
|||||||
assert len(rows) == 2, rows
|
assert len(rows) == 2, rows
|
||||||
assert rows[0][1] == "prime minister of" and rows[0][3] == "2018", rows[0]
|
assert rows[0][1] == "prime minister of" and rows[0][3] == "2018", rows[0]
|
||||||
assert rows[1][1] == "secretary-general of" and rows[1][3] == "2017", rows[1]
|
assert rows[1][1] == "secretary-general of" and rows[1][3] == "2017", rows[1]
|
||||||
print("ok: two_pass ingests typed facts (windows kept, legacy checks)")
|
# the verbatim law end-to-end: the STORED quotes are Pass 1's verbatims
|
||||||
|
# (the TYPE model never produced a quote at all — code composed it)
|
||||||
|
quotes = {r[0] for r in store.db.execute(
|
||||||
|
"SELECT verbatim FROM quotes").fetchall()}
|
||||||
|
assert quotes == {"has been the prime minister of Spain since 2018",
|
||||||
|
"Secretary-General of the Spanish Socialist Workers' "
|
||||||
|
"Party (PSOE) since 2017"}, quotes
|
||||||
|
print("ok: two_pass ingests typed facts (Fact = FactNoQuote + verbatim, legacy checks)")
|
||||||
|
|
||||||
|
|
||||||
def test_single_pass_still_works():
|
def test_single_pass_still_works():
|
||||||
|
|||||||
+39
-23
@@ -1,52 +1,68 @@
|
|||||||
"""The two-pass extraction (Pass 1 claims, Pass 2 typed Facts).
|
"""The two-pass extraction (Pass 1 claims + verbatim quotes, Pass 2 typing).
|
||||||
|
|
||||||
The single-pass EXTRACT asked slow local models for a giant JSON array
|
The single-pass EXTRACT asked slow local models for a giant JSON array
|
||||||
of typed Facts with verbatim quotes + temporal restrictions + sibling
|
of typed Facts with verbatim quotes + temporal restrictions + sibling
|
||||||
order assertions — the output budget behind the 40-minute arithmetic.
|
order assertions — the output budget behind the 40-minute arithmetic.
|
||||||
Two-pass shortens every output: Pass 1 lists plain claims (free-form
|
Two-pass shortens every output: Pass 1 lists the claims, each with its
|
||||||
strings, coreferences resolved — near-zero format tax); Pass 2 types
|
VERBATIM quote (extracted while the text is in front of the model);
|
||||||
ONE claim at a time into the same Fact schema the store already eats.
|
Pass 2 types ONE claim at a time — the model sees ONLY the claim and
|
||||||
|
returns FactNoQuote; code composes the Fact the store already eats:
|
||||||
|
Fact = FactNoQuote + verbatim (owner 1/11: the VERBATIM is obtained
|
||||||
|
before, the TYPE model never sees nor rewrites it).
|
||||||
|
|
||||||
Orders: NEVER produced here — one claim per call has no siblings to
|
Orders: NEVER produced here — one claim per call has no siblings to
|
||||||
reference. The legacy single-pass path (and table frags) keeps them.
|
reference, and the TYPE schema (FactNoQuote) has no orders field at
|
||||||
|
all. The legacy single-pass path (and table frags) keeps them.
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from .extract import Claim, Fact
|
||||||
|
|
||||||
|
|
||||||
def claims_from(expert, entities: str, heading: str, text: str,
|
def claims_from(expert, entities: str, heading: str, text: str,
|
||||||
charge_llm=None) -> list[str]:
|
charge_llm=None) -> list[Claim]:
|
||||||
"""Pass 1: the chunk's claims as plain strings, coreferences resolved.
|
"""Pass 1: the chunk's claims, each with its VERBATIM quote — the
|
||||||
|
quote is extracted HERE, in the same call that reads the text.
|
||||||
|
|
||||||
The list is made honest by CODE only: exact repeats are dropped
|
The list is made honest by CODE only: exact repeats are dropped
|
||||||
(live finding 26/10: glm sometimes lists its whole list twice, and
|
(live finding 26/10: glm sometimes lists its whole list twice, and
|
||||||
thinking leakage leaks in as list items). Dedup is case- and
|
thinking leakage leaks in as list items). Dedup is case- and
|
||||||
whitespace-insensitive; the FIRST occurrence's exact text is kept.
|
whitespace-insensitive on the CLAIM text; the FIRST occurrence's
|
||||||
NO cap, NO semantic filter: completeness beats budget (owner ruling
|
(claim, verbatim) is kept. NO cap, NO semantic filter: completeness
|
||||||
26/10) — every unique claim gets its TYPE call.
|
beats budget (owner ruling 26/10) — every unique claim gets its
|
||||||
|
TYPE call.
|
||||||
"""
|
"""
|
||||||
if charge_llm:
|
if charge_llm:
|
||||||
charge_llm()
|
charge_llm()
|
||||||
pred = expert.claims(entities=entities, heading=heading, text=text)
|
pred = expert.claims(entities=entities, heading=heading, text=text)
|
||||||
seen: dict[str, str] = {}
|
seen: dict[str, Claim] = {}
|
||||||
for c in (pred.claims or []):
|
for c in (pred.claims or []):
|
||||||
c = (c or "").strip()
|
claim = (getattr(c, "claim", "") or "").strip()
|
||||||
if c:
|
verbatim = (getattr(c, "verbatim", "") or "").strip()
|
||||||
key = " ".join(c.lower().split())
|
if claim:
|
||||||
|
key = " ".join(claim.lower().split())
|
||||||
if key not in seen:
|
if key not in seen:
|
||||||
seen[key] = c
|
seen[key] = Claim(claim=claim, verbatim=verbatim)
|
||||||
return list(seen.values())
|
return list(seen.values())
|
||||||
|
|
||||||
|
|
||||||
def fact_from_claim(expert, claim: str, text: str, charge_llm=None):
|
def fact_from_claim(expert, claim: str, verbatim: str, charge_llm=None):
|
||||||
"""Pass 2: ONE claim -> one typed Fact (or None, honestly declined).
|
"""Pass 2: ONE claim -> one typed Fact (or None, honestly declined).
|
||||||
|
|
||||||
The Fact's quote is copied VERBATIM from `text` (the chunk the claim
|
TYPING ONLY: the model sees ONLY the claim — no text, no verbatim
|
||||||
came from) — without the text the model invents a quote and the
|
(owner 1/11: the VERBATIM is Pass 1's and the TYPE model never sees
|
||||||
containment check rejects it (live finding 26/10: 69/70 rejected).
|
nor rewrites it). Code COMPOSES the store's Fact: FactNoQuote +
|
||||||
The store's checks validate everything downstream as before. No
|
verbatim (LLMs propose, code decides) — the quote is Pass 1's span
|
||||||
orders: no siblings by construction.
|
BY CONSTRUCTION, and the store's checks validate it downstream as
|
||||||
|
before (a temporal field not contained in the quote rejects the
|
||||||
|
candidate; live finding 26/10: without grounding, 69/70 invented
|
||||||
|
quotes were rejected). No orders: no siblings by construction, and
|
||||||
|
FactNoQuote has no orders field at all.
|
||||||
"""
|
"""
|
||||||
if charge_llm:
|
if charge_llm:
|
||||||
charge_llm()
|
charge_llm()
|
||||||
pred = expert.typeclaim(claim=claim, text=text)
|
pred = expert.typeclaim(claim=claim)
|
||||||
return getattr(pred, "fact", None)
|
nq = getattr(pred, "fact", None)
|
||||||
|
if nq is None:
|
||||||
|
return None
|
||||||
|
return Fact(**nq.model_dump(), quote=verbatim)
|
||||||
+33
-4
@@ -14,6 +14,7 @@ from __future__ import annotations
|
|||||||
import re
|
import re
|
||||||
import time
|
import time
|
||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
|
from html.parser import HTMLParser
|
||||||
|
|
||||||
import requests
|
import requests
|
||||||
|
|
||||||
@@ -22,6 +23,26 @@ UA = "floop-bot/0.1 (research; contact: emili@oniricapps.com)"
|
|||||||
LANG = "en"
|
LANG = "en"
|
||||||
|
|
||||||
|
|
||||||
|
class _SnippetText(HTMLParser):
|
||||||
|
def __init__(self) -> None:
|
||||||
|
super().__init__(convert_charrefs=True)
|
||||||
|
self.parts: list[str] = []
|
||||||
|
|
||||||
|
def handle_data(self, data: str) -> None:
|
||||||
|
self.parts.append(data)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class WikiSearchResult:
|
||||||
|
"""Search metadata, not evidence: snippets still need a fetched source."""
|
||||||
|
title: str
|
||||||
|
snippet: str = ""
|
||||||
|
|
||||||
|
@property
|
||||||
|
def text(self) -> str:
|
||||||
|
return f"{self.title}\n{self.snippet}".strip()
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class WikiTable:
|
class WikiTable:
|
||||||
"""One parsed wikitext table: header row + all data rows, untruncated."""
|
"""One parsed wikitext table: header row + all data rows, untruncated."""
|
||||||
@@ -331,10 +352,18 @@ class WikipediaClient:
|
|||||||
raise WikiError(f"wikipedia api failed after {self.max_retries + 1} attempts: {last_err}")
|
raise WikiError(f"wikipedia api failed after {self.max_retries + 1} attempts: {last_err}")
|
||||||
|
|
||||||
# ---- api surface --------------------------------------------------------
|
# ---- api surface --------------------------------------------------------
|
||||||
def search(self, query: str, limit: int = 5) -> list[str]:
|
def search(self, query: str, limit: int = 5) -> list[WikiSearchResult]:
|
||||||
"""Official search: list=search. Returns candidate article titles."""
|
"""Return titles and plain-text search snippets, without fetching pages."""
|
||||||
data = self._get(action="query", list="search", srsearch=query, srlimit=limit)
|
data = self._get(action="query", list="search", srsearch=query,
|
||||||
return [h["title"] for h in data.get("query", {}).get("search", [])]
|
srlimit=limit, srprop="snippet", srnamespace=0)
|
||||||
|
results = []
|
||||||
|
for hit in data.get("query", {}).get("search", []):
|
||||||
|
parser = _SnippetText()
|
||||||
|
parser.feed(hit.get("snippet", ""))
|
||||||
|
parser.close()
|
||||||
|
snippet = " ".join("".join(parser.parts).split())
|
||||||
|
results.append(WikiSearchResult(title=hit["title"], snippet=snippet))
|
||||||
|
return results
|
||||||
|
|
||||||
def summary(self, title: str) -> str:
|
def summary(self, title: str) -> str:
|
||||||
data = self._get(action="query", titles=title, prop="extracts",
|
data = self._get(action="query", titles=title, prop="extracts",
|
||||||
|
|||||||
@@ -143,6 +143,16 @@ def main() -> None:
|
|||||||
report: RunReport = FloopRun(question, budget, streams=streams,
|
report: RunReport = FloopRun(question, budget, streams=streams,
|
||||||
knowledge_engine=knowledge_engine).run()
|
knowledge_engine=knowledge_engine).run()
|
||||||
finally:
|
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()
|
streams.close()
|
||||||
|
|
||||||
print(f"goal: {report.goal}")
|
print(f"goal: {report.goal}")
|
||||||
|
|||||||
@@ -0,0 +1,2 @@
|
|||||||
|
def main() -> None:
|
||||||
|
print("Hello from code!")
|
||||||
+25
-1
@@ -26,7 +26,9 @@ from dspy._vendor.lm15 import Response, TextPart, Message, Usage
|
|||||||
from dspy.utils.exceptions import AdapterParseError
|
from dspy.utils.exceptions import AdapterParseError
|
||||||
|
|
||||||
from floop.dspy_modules import FloopModules
|
from floop.dspy_modules import FloopModules
|
||||||
from floop.anonymize import NamedEntity, apply_mask, identity_answer, restore_mask
|
from floop.anonymize import (
|
||||||
|
ENTITY_TYPES, NamedEntity, apply_mask, identity_answer, restore_mask,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def _lm(script: list[str]) -> None:
|
def _lm(script: list[str]) -> None:
|
||||||
@@ -75,6 +77,27 @@ def test_apply_restore_deterministic():
|
|||||||
print("ok: apply/restore deterministic (longest-first, typed, reorder-safe)")
|
print("ok: apply/restore deterministic (longest-first, typed, reorder-safe)")
|
||||||
|
|
||||||
|
|
||||||
|
def test_entity_types_drive_schema_and_masks():
|
||||||
|
description = NamedEntity.model_fields["kind"].json_schema_extra["desc"]
|
||||||
|
for kind, definition in ENTITY_TYPES.items():
|
||||||
|
assert f"{kind}: {definition}" in description
|
||||||
|
|
||||||
|
entities = [NamedEntity(name=name, kind=kind) for kind, name in (
|
||||||
|
("PERSON", "Ada"), ("ORGANIZATION", "Acme"),
|
||||||
|
("LOCATION", "Paris"), ("DATE", "2026"),
|
||||||
|
("PRODUCT", "Widget"),
|
||||||
|
)]
|
||||||
|
entities.append(NamedEntity(name="Unknown", kind="OTHER"))
|
||||||
|
masked, restore = apply_mask("Ada Acme Paris 2026 Widget Unknown", entities)
|
||||||
|
assert masked == (
|
||||||
|
"PERSON_1 ORGANIZATION_1 LOCATION_1 DATE_1 PRODUCT_1 Unknown")
|
||||||
|
assert restore == {
|
||||||
|
"PERSON_1": "Ada", "ORGANIZATION_1": "Acme",
|
||||||
|
"LOCATION_1": "Paris", "DATE_1": "2026", "PRODUCT_1": "Widget",
|
||||||
|
}
|
||||||
|
print("ok: schema descriptions and mask prefixes use the shared entity types")
|
||||||
|
|
||||||
|
|
||||||
def test_init_decompose_masks_and_restores():
|
def test_init_decompose_masks_and_restores():
|
||||||
# script: first call = MASK, second = INIT
|
# script: first call = MASK, second = INIT
|
||||||
_lm([_MASKED_ENTS, _TWO_SUBS])
|
_lm([_MASKED_ENTS, _TWO_SUBS])
|
||||||
@@ -147,6 +170,7 @@ def test_mask_death_passthrough():
|
|||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
test_apply_restore_deterministic()
|
test_apply_restore_deterministic()
|
||||||
|
test_entity_types_drive_schema_and_masks()
|
||||||
test_init_decompose_masks_and_restores()
|
test_init_decompose_masks_and_restores()
|
||||||
test_no_entities_passthrough()
|
test_no_entities_passthrough()
|
||||||
test_identity_subquestion_seeded()
|
test_identity_subquestion_seeded()
|
||||||
|
|||||||
@@ -0,0 +1,109 @@
|
|||||||
|
"""floop-inspect tests (PR B: the post-mortem HTML debugger).
|
||||||
|
|
||||||
|
Law: one run dir in, ONE self-contained inspect.html out — the events
|
||||||
|
JSON inlined, zero network references (opens offline from file://),
|
||||||
|
every tab present (timeline, KG, facts, probes), and the run's final
|
||||||
|
answer visible. A run dir without events.jsonl errors honestly."""
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
|
|
||||||
|
from floop.inspect_html import generate
|
||||||
|
|
||||||
|
EVENTS = [
|
||||||
|
{"seq": 1, "ts": "10:00:00.000", "run_ts": "10:00:00.000",
|
||||||
|
"event": "comp.start", "comp": "INIT", "desc": "decompose: q0"},
|
||||||
|
{"seq": 2, "ts": "10:00:01.000", "run_ts": "10:00:00.000",
|
||||||
|
"event": "llm.done", "stage": "INIT", "call_seq": 1, "dur_s": 0.9,
|
||||||
|
"file": "prompts/01-INIT.txt", "exception": None},
|
||||||
|
{"seq": 3, "ts": "10:00:01.100", "run_ts": "10:00:00.000",
|
||||||
|
"event": "comp.out", "comp": "INIT", "out": "Q1 sub"},
|
||||||
|
{"seq": 4, "ts": "10:00:02.000", "run_ts": "10:00:00.000",
|
||||||
|
"event": "claims.done", "page": "Pedro Sanchez",
|
||||||
|
"heading": "Career", "out": {"n_claims": 1,
|
||||||
|
"claims": [{"claim": "PM of Spain since 2018",
|
||||||
|
"verbatim": "prime minister of Spain since 2018"}]}},
|
||||||
|
{"seq": 5, "ts": "10:00:03.000", "run_ts": "10:00:00.000",
|
||||||
|
"event": "type.done", "page": "Pedro Sanchez",
|
||||||
|
"claim": "PM of Spain since 2018",
|
||||||
|
"out": {"fact": {"subject": "Pedro Sanchez",
|
||||||
|
"relation": "prime minister of", "object": "Spain"}}},
|
||||||
|
{"seq": 6, "ts": "10:00:03.500", "run_ts": "10:00:00.000",
|
||||||
|
"event": "fact.merged", "eid": 7,
|
||||||
|
"fact": {"subject": "Pedro Sanchez", "relation": "prime minister of",
|
||||||
|
"object": "Spain"}, "page": "Pedro Sanchez"},
|
||||||
|
{"seq": 7, "ts": "10:00:04.000", "run_ts": "10:00:00.000",
|
||||||
|
"event": "probe.done", "q": "Q1 sub", "seeds": ["pedro"], "rows": 3,
|
||||||
|
"semantic": 1, "tau": 0.45},
|
||||||
|
{"seq": 8, "ts": "10:00:05.000", "run_ts": "10:00:00.000",
|
||||||
|
"event": "prover.done", "q": "Q1 sub", "verdict": "ambiguous",
|
||||||
|
"dsl": {"lookup": {"subject": "pedro sanchez",
|
||||||
|
"rel_any": ["prime minister of"], "bind": "x"}},
|
||||||
|
"n_bindings": 2, "bindings": ["Spain", "PSOE"]},
|
||||||
|
{"seq": 9, "ts": "10:00:06.000", "run_ts": "10:00:00.000",
|
||||||
|
"event": "kg.snapshot",
|
||||||
|
"kg": {"n_edges": 1, "n_live": 1, "n_conflicts": 0,
|
||||||
|
"edges": [{"eid": 7, "subject": "pedro sanchez",
|
||||||
|
"rel": "prime minister of", "object": "Spain",
|
||||||
|
"t_start": "2018", "t_end": None, "retracted": False,
|
||||||
|
"last_touch": {"seq": 6, "ts": "10:00:03.500",
|
||||||
|
"page": "Pedro Sanchez"}}]}},
|
||||||
|
{"seq": 10, "ts": "10:00:07.000", "run_ts": "10:00:00.000",
|
||||||
|
"event": "run.final", "out": "Spain and PSOE"},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _make_run(tmp: Path, events) -> Path:
|
||||||
|
run_dir = tmp / "run"
|
||||||
|
run_dir.mkdir(parents=True)
|
||||||
|
(run_dir / "events.jsonl").write_text(
|
||||||
|
"\n".join(json.dumps(e) for e in events), encoding="utf-8")
|
||||||
|
return run_dir
|
||||||
|
|
||||||
|
|
||||||
|
def test_generate_writes_selfcontained_html():
|
||||||
|
import tempfile
|
||||||
|
tmp = Path(tempfile.mkdtemp())
|
||||||
|
run_dir = _make_run(tmp, EVENTS)
|
||||||
|
out = generate(run_dir)
|
||||||
|
assert out == run_dir / "inspect.html", out
|
||||||
|
html = out.read_text(encoding="utf-8")
|
||||||
|
# self-contained: zero network refs, JSON inlined
|
||||||
|
assert "http://" not in html and "https://" not in html, "network ref!"
|
||||||
|
assert '"PM of Spain since 2018"' in html # events inlined
|
||||||
|
for tab in ("timeline", "kg", "facts", "probes"):
|
||||||
|
assert f'id="{tab}"' in html, tab # all tabs present
|
||||||
|
assert "Spain and PSOE" in html # final answer in
|
||||||
|
assert "prime minister of" in html # KG data in
|
||||||
|
print("ok: one self-contained inspect.html (offline, all tabs, inlined)")
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_events_errors_honestly():
|
||||||
|
import tempfile
|
||||||
|
tmp = Path(tempfile.mkdtemp())
|
||||||
|
run_dir = tmp / "run"
|
||||||
|
run_dir.mkdir()
|
||||||
|
try:
|
||||||
|
generate(run_dir)
|
||||||
|
raise AssertionError("must fail")
|
||||||
|
except SystemExit as e:
|
||||||
|
assert e.code not in (0, None), e
|
||||||
|
print("ok: no events.jsonl -> honest error (exit != 0)")
|
||||||
|
|
||||||
|
|
||||||
|
def test_empty_events_still_renders():
|
||||||
|
import tempfile
|
||||||
|
tmp = Path(tempfile.mkdtemp())
|
||||||
|
run_dir = _make_run(tmp, [])
|
||||||
|
out = generate(run_dir)
|
||||||
|
assert out.exists()
|
||||||
|
print("ok: empty run renders an honest empty view")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
test_generate_writes_selfcontained_html()
|
||||||
|
test_missing_events_errors_honestly()
|
||||||
|
test_empty_events_still_renders()
|
||||||
|
print("\ninspect_run: 3/3 ok")
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
"""The flight recorder tests (events.jsonl).
|
||||||
|
|
||||||
|
Law: every component of a run — LLM or not — leaves one JSON line in
|
||||||
|
runs/<ts>/events.jsonl with its input, output, and parent, so the run
|
||||||
|
can be debugged a posteriori like an IDE session (owner 26/10: 'vull
|
||||||
|
fer com un debug amb l'IDE, però a posteriori'). The recorder must
|
||||||
|
never break a run: emitting is side-effect-free and cheap, and with no
|
||||||
|
run dir it is a silent no-op.
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
|
|
||||||
|
from floop.recorder import Recorder
|
||||||
|
|
||||||
|
|
||||||
|
def test_emit_writes_valid_jsonl_lines(tmp=None):
|
||||||
|
import tempfile
|
||||||
|
tmp = Path(tempfile.mkdtemp())
|
||||||
|
r = Recorder(run_dir=tmp)
|
||||||
|
r.emit("comp.done", comp="gate", parent="page:pedro", in_={"heading": "x"},
|
||||||
|
out={"kept": True}, dur_ms=3)
|
||||||
|
r.emit("fact.merged", fact={"s": "a"}, verdict="merged", eid=42)
|
||||||
|
lines = (tmp / "events.jsonl").read_text().strip().splitlines()
|
||||||
|
assert len(lines) == 2, lines
|
||||||
|
e1, e2 = (json.loads(l) for l in lines)
|
||||||
|
assert e1["event"] == "comp.done" and e1["comp"] == "gate", e1
|
||||||
|
assert e1["in"] == {"heading": "x"} and e1["out"] == {"kept": True}, e1
|
||||||
|
assert e1["parent"] == "page:pedro" and e1["seq"] == 1 and e1["dur_ms"] == 3
|
||||||
|
assert "ts" in e1 and e1["run_ts"], e1
|
||||||
|
assert e2["seq"] == 2 and e2["verdict"] == "merged" and e2["eid"] == 42
|
||||||
|
print("ok: emit -> one valid JSON line each, seq/ts/in/out/parent kept")
|
||||||
|
|
||||||
|
|
||||||
|
def test_disabled_recorder_is_a_silent_noop():
|
||||||
|
r = Recorder(run_dir=None)
|
||||||
|
r.emit("comp.done", comp="gate", out={"kept": True}) # must not raise
|
||||||
|
assert r.events == 0
|
||||||
|
print("ok: no run dir -> no-op, never breaks a run")
|
||||||
|
|
||||||
|
|
||||||
|
def test_in_memory_events_readable_for_snapshot():
|
||||||
|
import tempfile
|
||||||
|
tmp = Path(tempfile.mkdtemp())
|
||||||
|
r = Recorder(run_dir=tmp)
|
||||||
|
r.emit("merge.done", eid=7, verdict="merged")
|
||||||
|
r.emit("merge.done", eid=7, verdict="dup") # corroboration bump
|
||||||
|
evs = r.events_of("merge.done")
|
||||||
|
assert [e["eid"] for e in evs] == [7, 7]
|
||||||
|
assert [e["verdict"] for e in evs] == ["merged", "dup"]
|
||||||
|
# last-touch annotation: per-row latest event
|
||||||
|
last = {}
|
||||||
|
for e in evs:
|
||||||
|
last[e["eid"]] = e["verdict"]
|
||||||
|
assert last == {7: "dup"}
|
||||||
|
print("ok: events_of() lets the snapshot annotate each row's last touch")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
test_emit_writes_valid_jsonl_lines()
|
||||||
|
test_disabled_recorder_is_a_silent_noop()
|
||||||
|
test_in_memory_events_readable_for_snapshot()
|
||||||
|
print("\nrecorder: 3/3 ok")
|
||||||
@@ -0,0 +1,220 @@
|
|||||||
|
"""The traces exporter tests (events.jsonl -> OTel spans).
|
||||||
|
|
||||||
|
Law (ARCHITECTURE.md §9-bis): one run = one trace; each LLM call, engine
|
||||||
|
step and evidence append = one span. The exporter is POST-MORTEM only — it
|
||||||
|
reads the recorded events and never touches the run itself. These tests
|
||||||
|
check the structural invariants against synthetic event files: unique
|
||||||
|
span ids, no orphan children, the root envelope, deterministic trace ids,
|
||||||
|
child-run blocks nesting, and the owner's 27/10 visibility laws — named
|
||||||
|
in./out. attributes on fn.done and Signature spans, the prompt file as a
|
||||||
|
clickable child node, expert names on EXPERT spans (EXPERT knowledge) with
|
||||||
|
the expert prefix inside (knowledge.search), and one OTel service per
|
||||||
|
expert. No network: payloads are built, never pushed.
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
|
|
||||||
|
from floop.traces import build_payload, load_events, _cap, _read_prompt
|
||||||
|
|
||||||
|
|
||||||
|
def _run_dir(events: list[dict], prompts: dict[str, str] | None = None,
|
||||||
|
name: str = "20261027-000000-test") -> Path:
|
||||||
|
tmp = Path(tempfile.mkdtemp(prefix=name + "-"))
|
||||||
|
(tmp / "events.jsonl").write_text(
|
||||||
|
"\n".join(json.dumps(e) for e in events) + "\n")
|
||||||
|
if prompts:
|
||||||
|
(tmp / "prompts").mkdir()
|
||||||
|
for fn, text in prompts.items():
|
||||||
|
(tmp / "prompts" / fn).write_text(text)
|
||||||
|
return tmp
|
||||||
|
|
||||||
|
|
||||||
|
def _services(payload: dict) -> dict[str, list[dict]]:
|
||||||
|
out = {}
|
||||||
|
for rs in payload["resourceSpans"]:
|
||||||
|
svc = rs["resource"]["attributes"][0]["value"]["stringValue"]
|
||||||
|
out[svc] = rs["scopeSpans"][0]["spans"]
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _check(spans: list[dict], label: str) -> None:
|
||||||
|
ids = {s["spanId"] for s in spans}
|
||||||
|
assert len(ids) == len(spans), f"{label}: duplicate span ids"
|
||||||
|
orphans = [s["name"] for s in spans
|
||||||
|
if s.get("parentSpanId") and s["parentSpanId"] not in ids]
|
||||||
|
assert not orphans, f"{label}: orphans {orphans[:3]}"
|
||||||
|
|
||||||
|
|
||||||
|
def _attrs(span: dict) -> dict[str, str]:
|
||||||
|
return {a["key"]: a["value"]["stringValue"] for a in span["attributes"]}
|
||||||
|
|
||||||
|
|
||||||
|
def test_builds_one_trace_per_run():
|
||||||
|
tmp = _run_dir([
|
||||||
|
{"seq": 1, "ts": "09:15:21.295", "run_ts": "09:15:21.136",
|
||||||
|
"event": "comp.start", "comp": "INIT",
|
||||||
|
"desc": "decompose: What is 2+2?"},
|
||||||
|
{"seq": 2, "ts": "09:15:22.000", "run_ts": "09:15:21.136",
|
||||||
|
"event": "llm.done", "stage": "INIT", "call_seq": 1,
|
||||||
|
"dur_s": 0.7, "file": "prompts/01-INIT.txt", "exception": None},
|
||||||
|
{"seq": 3, "ts": "09:15:23.000", "run_ts": "09:15:21.136",
|
||||||
|
"event": "comp.out", "comp": "INIT", "out": "What is 4?"},
|
||||||
|
{"seq": 4, "ts": "09:15:24.000", "run_ts": "09:15:21.136",
|
||||||
|
"event": "run.final", "out": "4"},
|
||||||
|
], prompts={"01-INIT.txt":
|
||||||
|
"# stage=INIT call_seq=1\n\n[user] What is 2+2?\n\n"
|
||||||
|
"# RAW RESPONSE (after 0.7s)\n{'text': '[[ ## subquestions ## ]]'}\n"})
|
||||||
|
payload, _ = build_payload(tmp, load_events(tmp))
|
||||||
|
svcs = _services(payload)
|
||||||
|
_check(sum(svcs.values(), []), "single run")
|
||||||
|
root = svcs["floop"][0]
|
||||||
|
assert root["name"] == "What is 2+2?" and not root.get("parentSpanId")
|
||||||
|
assert _attrs(root)["run.answer"] == "4"
|
||||||
|
# the LLM span keeps its real duration and a prompt child
|
||||||
|
llm = next(s for s in svcs["floop"] if s["name"] == "llm.INIT")
|
||||||
|
dur = (int(llm["endTimeUnixNano"]) - int(llm["startTimeUnixNano"])) / 1e9
|
||||||
|
assert abs(dur - 0.7) < 0.01, dur
|
||||||
|
child = next(s for s in svcs["floop"]
|
||||||
|
if s.get("parentSpanId") == llm["spanId"] and s["name"] == "prompt")
|
||||||
|
pa = _attrs(child)
|
||||||
|
assert "What is 2+2?" in pa["prompt.text"]
|
||||||
|
assert "subquestions" in pa["prompt.response"]
|
||||||
|
print("ok: one run -> one trace, question-named root, prompt child")
|
||||||
|
|
||||||
|
|
||||||
|
def test_trace_id_is_deterministic():
|
||||||
|
tmp = _run_dir([{"seq": 1, "ts": "09:15:21.295", "run_ts": "09:15:21.136",
|
||||||
|
"event": "run.final", "out": "x"}])
|
||||||
|
_, t1 = build_payload(tmp, load_events(tmp))
|
||||||
|
_, t2 = build_payload(tmp, load_events(tmp))
|
||||||
|
assert t1 == t2 and len(t1) == 32
|
||||||
|
print("ok: same run -> same trace id (stable UI link)")
|
||||||
|
|
||||||
|
|
||||||
|
def test_child_runs_nest_as_blocks():
|
||||||
|
events = []
|
||||||
|
for rts in ("09:15:21.100", "09:15:21.200"): # two child runs, one file
|
||||||
|
events += [
|
||||||
|
{"seq": 1, "ts": rts, "run_ts": rts, "event": "comp.start",
|
||||||
|
"comp": "INIT", "desc": "decompose: child question?"},
|
||||||
|
{"seq": 2, "ts": rts, "run_ts": rts, "event": "comp.out",
|
||||||
|
"comp": "INIT", "out": "done"},
|
||||||
|
]
|
||||||
|
tmp = _run_dir(events)
|
||||||
|
payload, _ = build_payload(tmp, load_events(tmp))
|
||||||
|
svcs = _services(payload)
|
||||||
|
_check(sum(svcs.values(), []), "child runs")
|
||||||
|
runs = [s for s in svcs["floop"][1:] if s["name"] == "child question?"]
|
||||||
|
assert len(runs) == 2, [s["name"] for s in svcs["floop"]]
|
||||||
|
print("ok: child runs in one file nest as per-run spans, no dups")
|
||||||
|
|
||||||
|
|
||||||
|
def test_clock_only_in_event_order():
|
||||||
|
tmp = _run_dir([
|
||||||
|
{"seq": 1, "ts": "23:59:59.500", "run_ts": "23:59:59.1",
|
||||||
|
"event": "run.final", "out": "a"},
|
||||||
|
{"seq": 2, "ts": "00:00:01.500", "run_ts": "23:59:59.1",
|
||||||
|
"event": "run.final", "out": "b"},
|
||||||
|
], name="20261027-235959-test")
|
||||||
|
payload, _ = build_payload(tmp, load_events(tmp))
|
||||||
|
root = _services(payload)["floop"][0]
|
||||||
|
r0 = int(root["startTimeUnixNano"])
|
||||||
|
r1 = int(root["endTimeUnixNano"])
|
||||||
|
assert 0 < (r1 - r0) < 10 * 1_000_000_000, (r1 - r0) # 2s, not +24h
|
||||||
|
print("ok: midnight crossing handled (clock read in event order only)")
|
||||||
|
|
||||||
|
|
||||||
|
def test_expert_names_prefix_and_services():
|
||||||
|
"""The owner's 27/10 laws: EXPERT knowledge on the component span; inside
|
||||||
|
it every span carries the knowledge. prefix; the expert's spans export
|
||||||
|
under their OWN OTel service; fn.done events carry named in./out.
|
||||||
|
attributes; Signature events carry in./out. field attributes."""
|
||||||
|
events = [
|
||||||
|
{"seq": 1, "ts": "12:00:00.100", "run_ts": "12:00:00.050",
|
||||||
|
"event": "comp.start", "comp": "INIT", "desc": "decompose: What is X?"},
|
||||||
|
{"seq": 2, "ts": "12:00:00.400", "run_ts": "12:00:00.050",
|
||||||
|
"event": "comp.out", "comp": "INIT", "out": "What is X?"},
|
||||||
|
{"seq": 3, "ts": "12:00:00.500", "run_ts": "12:00:00.050",
|
||||||
|
"event": "comp.start", "comp": "EXPERT", "desc": "knowledge on Q1",
|
||||||
|
"expert": "knowledge"},
|
||||||
|
{"seq": 4, "ts": "12:00:00.600", "run_ts": "12:00:00.050",
|
||||||
|
"event": "fn.done", "fn": "search",
|
||||||
|
"in": {"query": "X", "limit": 4},
|
||||||
|
"out": {"titles": ["X", "X (film)"]}},
|
||||||
|
{"seq": 5, "ts": "12:00:01.000", "run_ts": "12:00:00.050",
|
||||||
|
"event": "sig.start", "stage": "EXTRACT", "call_id": "m1",
|
||||||
|
"in.entities": "X", "in.text": "chunk"},
|
||||||
|
{"seq": 6, "ts": "12:00:03.300", "run_ts": "12:00:00.050",
|
||||||
|
"event": "llm.done", "stage": "EXTRACT", "call_seq": 3, "dur_s": 2.3,
|
||||||
|
"file": "prompts/03-EXTRACT.txt", "exception": None},
|
||||||
|
{"seq": 7, "ts": "12:00:03.300", "run_ts": "12:00:00.050",
|
||||||
|
"event": "sig.done", "stage": "EXTRACT", "call_id": "m1",
|
||||||
|
"out.facts": [{"subject": "X", "relation": "is", "object": "Y"}]},
|
||||||
|
{"seq": 8, "ts": "12:00:03.400", "run_ts": "12:00:00.050",
|
||||||
|
"event": "state", "text": "merged"},
|
||||||
|
{"seq": 9, "ts": "12:00:03.500", "run_ts": "12:00:00.050",
|
||||||
|
"event": "comp.out", "comp": "EXPERT", "out": "Q1 -> ANSWER value=Y"},
|
||||||
|
]
|
||||||
|
tmp = _run_dir(events, prompts={
|
||||||
|
"03-EXTRACT.txt": "# stage=EXTRACT call_seq=3\n\n[user] Extract\n\n"
|
||||||
|
"# RAW RESPONSE (after 2.3s)\n{'text': 'facts'}\n"})
|
||||||
|
payload, _ = build_payload(tmp, load_events(tmp))
|
||||||
|
svcs = _services(payload)
|
||||||
|
assert "knowledge" in svcs, list(svcs)
|
||||||
|
_check(sum(svcs.values(), []), "expert run")
|
||||||
|
fp_names = [s["name"] for s in svcs["floop"]]
|
||||||
|
kn_names = [s["name"] for s in svcs["knowledge"]]
|
||||||
|
assert "EXPERT knowledge" in fp_names + kn_names, fp_names + kn_names
|
||||||
|
assert "knowledge.search" in kn_names, kn_names
|
||||||
|
assert "knowledge.EXTRACT" in kn_names, kn_names
|
||||||
|
assert "knowledge.state" in kn_names, kn_names
|
||||||
|
# fn.done named in/out
|
||||||
|
srch = next(s for s in svcs["knowledge"] if s["name"] == "knowledge.search")
|
||||||
|
a = _attrs(srch)
|
||||||
|
assert a["in.query"] == "X" and "X (film)" in a["out.titles"], a
|
||||||
|
# sig in/out + duration + prompt child
|
||||||
|
sig = next(s for s in svcs["knowledge"] if s["name"] == "knowledge.EXTRACT")
|
||||||
|
a = _attrs(sig)
|
||||||
|
assert a["in.entities"] == "X" and '"subject"' in a["out.facts"], a
|
||||||
|
assert a["floop.dur_s"] == "2.3"
|
||||||
|
child = next(s for s in svcs["knowledge"]
|
||||||
|
if s.get("parentSpanId") == sig["spanId"] and s["name"] == "prompt")
|
||||||
|
assert "Extract" in _attrs(child)["prompt.text"]
|
||||||
|
# the state span inside the expert is prefixed too
|
||||||
|
assert "knowledge.state" in kn_names
|
||||||
|
print("ok: expert names, knowledge.* prefix, own service, in/out named")
|
||||||
|
|
||||||
|
|
||||||
|
def test_cap_keeps_spans_small():
|
||||||
|
big = {"k" + str(i): "x" * 100 for i in range(50)}
|
||||||
|
assert len(_cap(big)) <= 20
|
||||||
|
deep = _cap({"a": {"b": {"c": {"d": {"e": "x"}}}}})
|
||||||
|
assert deep != {"a": {"b": {"c": {"d": {"e": "x"}}}}}
|
||||||
|
assert _cap("y" * 1000) == ("y" * 497 + "…")
|
||||||
|
print("ok: _cap truncates depth/width/strings (kg snapshot stays small)")
|
||||||
|
|
||||||
|
|
||||||
|
def test_prompt_parser_splits_raw_response():
|
||||||
|
tmp = _run_dir([], prompts={
|
||||||
|
"01-INIT.txt": "# stage=INIT call_seq=1\n\n[user] What is 2+2?\n\n"
|
||||||
|
"# RAW RESPONSE (after 0.7s)\n{'text': '[[ ## a ## ]]'}\n"})
|
||||||
|
pr = _read_prompt(tmp, "prompts/01-INIT.txt")
|
||||||
|
assert pr is not None
|
||||||
|
assert "What is 2+2?" in pr[0] and "# RAW" not in pr[0]
|
||||||
|
assert pr[1].startswith("{'text'"), repr(pr[1][:30])
|
||||||
|
print("ok: prompt parser keeps prompt + raw response verbatim")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
test_builds_one_trace_per_run()
|
||||||
|
test_trace_id_is_deterministic()
|
||||||
|
test_child_runs_nest_as_blocks()
|
||||||
|
test_clock_only_in_event_order()
|
||||||
|
test_expert_names_prefix_and_services()
|
||||||
|
test_cap_keeps_spans_small()
|
||||||
|
test_prompt_parser_splits_raw_response()
|
||||||
|
print("\ntraces: 7/7 ok")
|
||||||
Reference in New Issue
Block a user