Compare commits
43
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bc543459c7 | ||
|
|
77fef0a499 | ||
|
|
12fb3c78b2 | ||
|
|
a007e8da25 | ||
|
|
1af308ae60 | ||
|
|
6ea769b7d1 | ||
|
|
d6c5bed443 | ||
|
|
e365f6d1e8 | ||
|
|
9f2fbd711c | ||
|
|
d384a10a8d | ||
|
|
86af2c968d | ||
|
|
964189387d | ||
|
|
2ee3b54661 | ||
|
|
a9837981b3 | ||
|
|
88769c508c | ||
|
|
f6e9164e92 | ||
|
|
95dfdf7123 | ||
|
|
6ba0bce863 | ||
|
|
31c7e02e22 | ||
|
|
f31b30d811 | ||
|
|
27c4bf3812 | ||
|
|
2cfcb1a59d | ||
|
|
ee315e0644 | ||
|
|
fb612686d6 | ||
|
|
99f8b6e9db | ||
|
|
b4b26c5ee6 | ||
|
|
f32a6db531 | ||
|
|
096326e3a3 | ||
|
|
4c9c762b91 | ||
|
|
985aec2f60 | ||
|
|
262f40b981 | ||
|
|
9cfc068ad6 | ||
|
|
e594339629 | ||
|
|
7dfac55cf4 | ||
|
|
302e50120c | ||
|
|
004c7974c6 | ||
|
|
1df3ec591b | ||
|
|
8a3f8b37e3 | ||
|
|
bb4afb6a66 | ||
|
|
dec1fccb53 | ||
|
|
0f5a3f4ceb | ||
|
|
30d0a48f7a | ||
|
|
522341a1f3 |
@@ -136,6 +136,40 @@ them) are dimensions of the answer function, never branches. And one thing can n
|
|||||||
retracted: the user. A user-supplied fact colliding with a source is presented verbatim
|
retracted: the user. A user-supplied fact colliding with a source is presented verbatim
|
||||||
to the user — never silently resolved.
|
to the user — never silently resolved.
|
||||||
|
|
||||||
|
## 6-bis. Execution branches over ambiguity (2026-10-23, coded)
|
||||||
|
|
||||||
|
When an expert answers with SEVERAL defensible readings (the knowledge ablation audit
|
||||||
|
flags `ambiguous` + named alternatives), a question that DEPENDS on that row does not
|
||||||
|
inherit the coin-flip. The machine opens ONE EXECUTION BRANCH PER READING:
|
||||||
|
|
||||||
|
- **Lazy.** The branch is born only when the ambiguous row has an open dependent
|
||||||
|
subtree — an ambiguity nobody downstream needs stays a note; the picked reading rides.
|
||||||
|
The subtree is frozen at fork time: every branch of the fork copies the same questions.
|
||||||
|
- **A branch is a world, not a fork of the run.** The branch reads the shared evidence
|
||||||
|
table through a VIEW that binds the ambiguous row to its reading (the same law as the
|
||||||
|
ablation mask: the table is never mutated — the original row keeps all its readings)
|
||||||
|
and hides other branches' rows. Acquired knowledge (new rows, KG facts, fetched
|
||||||
|
articles, conclusions) lands in the ONE shared store, tagged with the branch id —
|
||||||
|
a later branch reuses an earlier branch's gathering for free.
|
||||||
|
- **Death is honest.** A branch dies by contradiction, dead end (all its questions
|
||||||
|
failed — UNKNOWN), or natural merge (its answer equals another branch's — deduped by
|
||||||
|
normalized value, one conclusion). Never by an absurdity judge: surprising-but-cited
|
||||||
|
answers render.
|
||||||
|
- **Nesting composes.** An ambiguous row answered INSIDE a branch (with its own
|
||||||
|
dependent) opens sub-branches under it, under the same branch cap; a parent carries
|
||||||
|
its children's conditional as its answer.
|
||||||
|
- **The final answer is conditional, composed by fixed code** — `if you meant the
|
||||||
|
PM-of-Spain reading -> Rajoy | if you meant Socialist International -> Papandreou`.
|
||||||
|
Never one reading chosen inside a synthesis prompt; never the alternatives handed to
|
||||||
|
the next question's context (that only moves the coin-flip into answer_kg).
|
||||||
|
- Clarifying with the user instead of running the branches is a POLICY ABOVE this
|
||||||
|
mechanism (layer 3): asking = picking one branch upstairs. The mechanism itself
|
||||||
|
always runs the worlds it needs.
|
||||||
|
|
||||||
|
Budget: branches share the run's `llm_calls` pool (a fork of N readings costs ~N× the
|
||||||
|
dependent subtree — leave headroom or the later branches die by budget, honestly noted);
|
||||||
|
branch count is capped (extra readings are dropped and NAMED, never silent).
|
||||||
|
|
||||||
## 7. Per-call context composition
|
## 7. Per-call context composition
|
||||||
|
|
||||||
Every LLM call gets its own purpose-built context, assembled by fixed code within the
|
Every LLM call gets its own purpose-built context, assembled by fixed code within the
|
||||||
|
|||||||
@@ -260,6 +260,66 @@ 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 (2026-10-27): OpenTelemetry export, BUILT
|
||||||
|
|
||||||
|
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
|
||||||
|
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
|
||||||
|
but closed: reading it means tailing files.
|
||||||
|
|
||||||
|
**BUILT (post-mortem half):** the run exports as **OpenTelemetry** traces/spans
|
||||||
|
(`floop/traces.py`), so floop is observable from the standard tooling that already
|
||||||
|
exists — Jaeger (running on the agentvps as a docker container), Grafana Tempo, any
|
||||||
|
OTLP consumer — instead of floop growing its own dashboards. The mapping is the
|
||||||
|
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).
|
||||||
|
`events.jsonl` (the flight recorder's machine-readable event stream) is the single
|
||||||
|
schema with two consumers: offline self-analysis in META.md, and `python -m
|
||||||
|
floop.traces <run_dir>` replaying it into Jaeger over OTLP/HTTP after the run — the
|
||||||
|
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.
|
||||||
|
|
||||||
|
Conventions the exporter keeps:
|
||||||
|
- 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
|
||||||
|
|
||||||
1. **Misformalization** (top failure mode) — wrong formalization, correct math, wrong
|
1. **Misformalization** (top failure mode) — wrong formalization, correct math, wrong
|
||||||
|
|||||||
@@ -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>
|
||||||
+88
-1
@@ -48,8 +48,9 @@ Compare: `--baseline` vs the loop's many small directed calls.
|
|||||||
| MISSING — gap decomposition on stuck goal | real (dspy) | `floop/dspy_modules.py` |
|
| MISSING — gap decomposition on stuck goal | real (dspy) | `floop/dspy_modules.py` |
|
||||||
| ROUTE — one LLM judgement over the catalogue | real (dspy) | `floop/dspy_modules.py` |
|
| ROUTE — one LLM judgement over the catalogue | real (dspy) | `floop/dspy_modules.py` |
|
||||||
| Expert attendants (the draft answer) | **BASELINE engine**: LLM answers from its weights; `verified=False`; source recorded (`model_weights`/`given_evidence`) | `floop/engine.py` |
|
| Expert attendants (the draft answer) | **BASELINE engine**: LLM answers from its weights; `verified=False`; source recorded (`model_weights`/`given_evidence`) | `floop/engine.py` |
|
||||||
| **knowledge** expert | **REAL pipeline** (2026-10-17): KG probe (entity+relation, stemmed) -> TRANSLATE (queries+entities from context) -> en.wikipedia search -> fetch_rich (text + wikitext tables) -> section chunks -> lexical gate -> EXTRACT (verbatim quotes) -> containment check -> merge (4 contradiction cases) -> answer from quoted rows. Fallback: baseline LLM on pipeline failure. | `knowledge/` + `floop/engine.py:KnowledgeEngine` |
|
| **knowledge** expert | **REAL pipeline** (2026-10-17): KG probe (entity+relation, stemmed) -> COMPOSE queries (deterministic, from question ∪ evidence — the old TRANSLATE LLM removed 23/10) -> en.wikipedia search -> fetch_rich (text + wikitext tables) -> section chunks -> lexical gate -> EXTRACT (verbatim quotes) -> containment check -> merge (4 contradiction cases) -> answer from quoted rows. Fallback: baseline LLM on pipeline failure. | `knowledge/` + `floop/engine.py:KnowledgeEngine` |
|
||||||
| Arrival check (type check + contradiction) | **STUB**: only UNKNOWN refusal | `machine._append_checked` |
|
| Arrival check (type check + contradiction) | **STUB**: only UNKNOWN refusal | `machine._append_checked` |
|
||||||
|
| Execution branches over ambiguity (ALGORITHM §6-bis) | **REAL** (2026-10-23): lazy fork per reading of an ambiguous row with an open dependent; BranchView binds the reading (table never mutated), acquired knowledge shared + branch-tagged; death by contradiction/dead end/natural merge; nested sub-branches; conditional final answer composed by fixed code | `floop/branches.py` + `floop/machine.py:_run_branch` |
|
||||||
| Prover (stop condition, derivability) | **STUB**: question stack terminal | `machine._finish` |
|
| Prover (stop condition, derivability) | **STUB**: question stack terminal | `machine._finish` |
|
||||||
| `user` expert | not wired — explicit failure row | `floop/engine.py` |
|
| `user` expert | not wired — explicit failure row | `floop/engine.py` |
|
||||||
| Backtracking / retraction (TMS) | not in the draft (§5 comes with the prover) | — |
|
| Backtracking / retraction (TMS) | not in the draft (§5 comes with the prover) | — |
|
||||||
@@ -70,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
|
||||||
|
|||||||
@@ -0,0 +1,381 @@
|
|||||||
|
# RESEARCH: derived answers — conflicts, time, and a prover instead of a judge
|
||||||
|
|
||||||
|
Status: RESEARCH BRANCH (research/semantic-kg). Design doc, not code.
|
||||||
|
Opened: 2026-10-25, from the conflicts inventory + the (K5) session (see
|
||||||
|
RESEARCH-semantic-kg.md, "Findings from the live A/B and the (K5) bug").
|
||||||
|
|
||||||
|
Scope note: this spans more than knowledge/ — the conflict taxonomy and the
|
||||||
|
temporal layer live in the store (knowledge/), the extractor vocabulary in
|
||||||
|
the pipeline (knowledge/), but the derived-answer engine replaces the
|
||||||
|
AnswerFromKG judge inside the loop and talks to the machine, INIT and the
|
||||||
|
evidence table (floop/). Hence the doc lives at code/ level.
|
||||||
|
|
||||||
|
The three findings this design grows from (all measured, live):
|
||||||
|
|
||||||
|
1. 20 conflict pairs in the KG after one Pedro run, ZERO real
|
||||||
|
contradictions — the 4-case classifier conflates conjunction,
|
||||||
|
paraphrase, temporal succession, and genuine polisèmia.
|
||||||
|
2. The (K5) bug: the judge is the last place where an LLM DECIDES inside
|
||||||
|
the loop, and its interface bugs (value contamination) silently kill
|
||||||
|
the ambiguity audit. Multi-binding ambiguity is a SET question; a
|
||||||
|
judge forced to return ONE value is the wrong instrument for it.
|
||||||
|
3. The three-presidency ambiguity is detectable deterministically at
|
||||||
|
ingest (the conflicts table holds it pairwise), yet the system only
|
||||||
|
hears about it through an expensive, fragile judge-time audit.
|
||||||
|
|
||||||
|
## Part 1 — the conflict taxonomy (merge-time, deterministic)
|
||||||
|
|
||||||
|
Four buckets replace the single "contradiction" case. Ordered by signal
|
||||||
|
cost; each pair falls into the FIRST bucket whose signal it matches.
|
||||||
|
|
||||||
|
### A. co-asserted (same quote_id)
|
||||||
|
|
||||||
|
Both values come from the SAME verbatim quote. A trusted source asserting
|
||||||
|
A and B in one sentence means the world holds A and B: conjunction, not
|
||||||
|
conflict. Kills the 10 same-quote "called for" pairs on provenance alone.
|
||||||
|
Zero extra machinery: quote_id is already an edge column.
|
||||||
|
|
||||||
|
### B. temporal succession
|
||||||
|
|
||||||
|
Dates are stated in the text (inside the dst or the quote: "since YYYY",
|
||||||
|
"in YYYY", "from X to Y") but ref_date is empty, so _classify never sees
|
||||||
|
them. With the temporal layer (Part 2), windows are extracted at ingest
|
||||||
|
and the classification is interval arithmetic: disjoint windows →
|
||||||
|
succession (the "became" pair: Leader-of-Opposition in 2014, prime
|
||||||
|
minister in 2018). Overlapping windows → they coexist → bucket C.
|
||||||
|
Backfill: for existing conflicting pairs with empty windows, one
|
||||||
|
targeted re-extraction pass over their quotes (bounded by the conflict
|
||||||
|
count, not the corpus).
|
||||||
|
|
||||||
|
### C. alternatives (the polisèmia)
|
||||||
|
|
||||||
|
Different facts, co-true, from different discriminant entities. The
|
||||||
|
signal chain, all deterministic:
|
||||||
|
|
||||||
|
- discriminant-token analysis: the two values differ not just in
|
||||||
|
order/articles/parenthetical expansions → not a paraphrase;
|
||||||
|
- tail resolution: the institution tails resolve to DIFFERENT nodes
|
||||||
|
("prime minister of Spain" vs "Secretary-General of the PSOE") —
|
||||||
|
same store lookup/stemming the lexical probe already uses;
|
||||||
|
- value type: dst is an entity NAME (not a date/quantity) → the
|
||||||
|
relation is multi-valued by nature (a person holds many positions);
|
||||||
|
dst is a date for a date-like relation → functional → only one value
|
||||||
|
can be true → bucket D;
|
||||||
|
- functionality statistics: per-relation multi-value rate over the
|
||||||
|
growing store (date_of_birth never multi, position held often
|
||||||
|
multi) — an oracle of functionality earned by scale. Cold-store
|
||||||
|
fallback: type logic + co-assertion.
|
||||||
|
|
||||||
|
THE THREE PRESIDENCIES are the type case: pairwise position-held
|
||||||
|
conflicts whose tails resolve to Spain / PSOE / SI. This bucket IS the
|
||||||
|
ambiguity substrate: what the ablation audit re-derives at judge-time
|
||||||
|
(re-asking an LLM per round) is already known here at ingest-time. The
|
||||||
|
flag, not the choice — the alternatives are served to whoever asks.
|
||||||
|
|
||||||
|
### D. real contradiction
|
||||||
|
|
||||||
|
Same src + functional rel + incompatible values, none of the above
|
||||||
|
applies. Two different birth dates. The honest conflict-exposed state of
|
||||||
|
the current design — expected to be RARE (none in the live inventory).
|
||||||
|
|
||||||
|
### Paraphrase → merge (pre-bucket check)
|
||||||
|
|
||||||
|
Before bucketing: same discriminant-free surface (modulo order,
|
||||||
|
articles, "(Spanish: …)" expansions) OR both tails resolve to the same
|
||||||
|
node OR both canonicalize to the same Wikipedia redirect target → SAME
|
||||||
|
FACT. Append-only law: merge is an alias/same_as edge, never a delete;
|
||||||
|
the canonical form guides retrieval, both surfaces remain queryable.
|
||||||
|
|
||||||
|
### What embeddings do and do NOT do here
|
||||||
|
|
||||||
|
Cosine measures TOPIC similarity, not fact identity:
|
||||||
|
"Prime Minister of Spain" vs "Prime Minister of France" ~0.9 — different
|
||||||
|
facts; "…of Spain" vs "president of the Government (Spanish: …)" ~0.65
|
||||||
|
— same fact. A cosine threshold would merge France into Spain and miss
|
||||||
|
the real alias. Embeddings CONFIRM and RANK inside a bucket (best merge
|
||||||
|
candidate first); they never decide the bucket. The curated-semantics
|
||||||
|
channel is Wikipedia's redirect graph (already fetched, redirects=1) —
|
||||||
|
canonicalization grounded in a trusted source, not model weights. Same
|
||||||
|
law as everywhere else in floop: deterministic signals decide; the model
|
||||||
|
never does.
|
||||||
|
|
||||||
|
## Part 2 — time on the KG
|
||||||
|
|
||||||
|
### Representation
|
||||||
|
|
||||||
|
- Edge columns (the Wikidata qualifier model): start, end, point,
|
||||||
|
granularity (year/month/day — "since 2022" is the interval
|
||||||
|
[2022, 2023), not a date). valid time (the fact's window) stays
|
||||||
|
distinct from fetched_at (transaction time), as today.
|
||||||
|
- fact_order(edge_a, edge_b, rel, quote_id) with rel ∈ {before, after,
|
||||||
|
concurrent}: ordering BETWEEN facts. Edges are already addressable
|
||||||
|
(integer ids) — reification comes free in a property graph; no fact
|
||||||
|
nodes to materialize.
|
||||||
|
- Open intervals: "since 2018" → end=open. The overlap of two open
|
||||||
|
intervals is PROVABLE coexistence — the polisèmia signal as interval
|
||||||
|
arithmetic (bucket C), per fact, no statistics needed.
|
||||||
|
|
||||||
|
### The extractor's temporal vocabulary — RESTRICTIONS, not labels
|
||||||
|
|
||||||
|
The extractor transcribes what the text COMMITS, as typed optional
|
||||||
|
fields on Fact (the feature/typed-facts BaseModel is the vehicle):
|
||||||
|
|
||||||
|
- order: before / after / concurrent — asserted ONLY when the text has
|
||||||
|
the connective ("abans de", "alhora", "while", "també") and NO dates
|
||||||
|
would let code compute it; quotable, containment-checkable;
|
||||||
|
- duration: quantity + unit (the skim's quantity regex already knows);
|
||||||
|
- anchor: start/end → date | event-node ("fins que va dimitir de A"
|
||||||
|
anchors F1's end to an EVENT, not a date — events are addressable
|
||||||
|
nodes, dates resolve later by propagation);
|
||||||
|
- immediacy: bool ("l'endemà", "fins que").
|
||||||
|
|
||||||
|
Full Allen algebra is a COMPUTED VIEW, not an extraction target: with
|
||||||
|
endpoints extracted, overlaps/during/starts/finishes/meets are endpoint
|
||||||
|
arithmetic in the store. The text CAN carry the full gamut ("president
|
||||||
|
of A and B at the same time for a month until he resigned from A") but
|
||||||
|
what it carries is three RESTRICTIONS (concurrent F1–F2, duration 1
|
||||||
|
month, F1.end anchored to the resignation event) — asking the model to
|
||||||
|
also CHOOSE an Allen label would (a) replace transcription with
|
||||||
|
classification, (b) produce labels with no quotable connective to check
|
||||||
|
against, (c) create a second channel of truth that silently disagrees
|
||||||
|
with the computed one 1% of the time, (d) invite confident labels at
|
||||||
|
granularity the prose lacks. Restrictions are honest (optional fields
|
||||||
|
stay empty when the text is silent), checkable (containment), and they
|
||||||
|
UPDATE: when a later source dates the resignation, the network
|
||||||
|
propagates and the Allen view recomputes itself — a label extracted on
|
||||||
|
day one never would.
|
||||||
|
|
||||||
|
### Check
|
||||||
|
|
||||||
|
Same law as facts: the temporal field must be contained in the quote
|
||||||
|
("2022" not in quote → reject the date; connective absent → reject the
|
||||||
|
order). LLM proposes, code verifies against the source surface.
|
||||||
|
|
||||||
|
## Part 3 — the derived-answer engine (no judge in the loop)
|
||||||
|
|
||||||
|
The end state he steered to: the component that generates the answer is
|
||||||
|
NOT an LLM. The LLMs translate at the two ends (question → logic on the
|
||||||
|
way in; proven object → prose later, outside the loop) and never in the
|
||||||
|
middle. This is the Logic-LM move of the lineage (lm→solver) applied to
|
||||||
|
floop's own layer, and the real prover the v0.1 map always listed as a
|
||||||
|
stub.
|
||||||
|
|
||||||
|
### The query DSL (small, typed)
|
||||||
|
|
||||||
|
The store's atoms are ground, containment-checked rows; floop's
|
||||||
|
answer_type enum is already the type signature. Six operators:
|
||||||
|
|
||||||
|
- lookup: bind a relation with variables — position_held(sanchez, ?o, I)
|
||||||
|
- temporal filter: contains(I, now), end(I_x) ≤ start(I_s) — Allen as
|
||||||
|
computed views over extracted endpoints;
|
||||||
|
- order & selection: latest, max, nth (ranking questions);
|
||||||
|
- set ops: difference/intersection/count (the setop engine exists);
|
||||||
|
- arithmetic composition: typed templates over intervals (the Run T3
|
||||||
|
composition: n_physical = n_logical × ratio);
|
||||||
|
- path: member_of, succeeded, same_as (multi-hop = chaining; the plan's
|
||||||
|
depends_on already encodes hops).
|
||||||
|
|
||||||
|
Not full FOL — a conjunctive + temporal + algebraic fragment with
|
||||||
|
negation only as inequality. Typed: a term that type-checks against the
|
||||||
|
answer_type is valid before any evaluation; a mistranslation surfaces as
|
||||||
|
an invalid term, deterministically. The translator is one LLM call with
|
||||||
|
structured output (the MASK/EXTRACT class — typed, question-local, no
|
||||||
|
goal leakage), validated before execution.
|
||||||
|
|
||||||
|
### Evaluation = proof = the answer object
|
||||||
|
|
||||||
|
Goal-directed evaluation (SLD-style) over the store:
|
||||||
|
|
||||||
|
q(x) :- position_held(sanchez, O, I_s), % his office, window
|
||||||
|
position_held(x, O, I_x), % any holder of the SAME office
|
||||||
|
x ≠ sanchez,
|
||||||
|
end(I_x) ≤ start(I_s), % term ended before his began
|
||||||
|
latest_by(end(I_x)) % the most recent such holder
|
||||||
|
|
||||||
|
Leaves = edge ids (each carries quote + url); steps = one of the six
|
||||||
|
operators; checks = interval arithmetic. The proof term IS the payload:
|
||||||
|
re-execution over the store is the verification — deterministic, no
|
||||||
|
LLM. verified=True stops being the setop's generous flag and gets a
|
||||||
|
real prover; the stop-check becomes "does the goal have a closed path"
|
||||||
|
— the derivability check the _finish stub owes.
|
||||||
|
|
||||||
|
### What the three findings become under this engine
|
||||||
|
|
||||||
|
- Multi-binding IS the ambiguity: "of what is Sánchez president" as
|
||||||
|
position_held(sanchez, ?x, I), contains(I, now) returns THREE
|
||||||
|
bindings (Spain, PSOE, SI), deterministically, each with its proof.
|
||||||
|
The ablation audit becomes redundant for store-derivable rows; the
|
||||||
|
(K5) bug dies at the root — there is no judge to contaminate a value
|
||||||
|
and no single-value pressure. Branches map 1:1 to bindings.
|
||||||
|
- Silence is the failure mode: no closed path → UNKNOWN → the gather
|
||||||
|
runs. The judge's failure mode was a fluent wrong answer (SI with
|
||||||
|
confidence: high).
|
||||||
|
- The unbound variable IS the missing subquestion: when evaluation
|
||||||
|
stalls, the unligated variable names what to go fetch — MISSING
|
||||||
|
becomes semi-deterministic.
|
||||||
|
- Conflicts/alternatives become disjunction: each alternative pair is
|
||||||
|
an OR-node in the proof tree; evaluation branches per reading,
|
||||||
|
preferred picks the default reading, the question can force the
|
||||||
|
others. The polisèmia stops being an internal anomaly and becomes
|
||||||
|
semantic branching of the proof search.
|
||||||
|
|
||||||
|
### Honest limits
|
||||||
|
|
||||||
|
- Soft questions (why/compare/significance) are synthesis over many
|
||||||
|
rows, not queries: they stay LLM-composed — over proven components
|
||||||
|
(proof terms and leaves), not free prose over the store.
|
||||||
|
- The prover does not remove retrieval; it removes the judge inside
|
||||||
|
the loop. Facts absent from the store still need the gather.
|
||||||
|
- same_as/aliases are load-bearing: without the redirect-canonicalized
|
||||||
|
ontology, evaluation fails on vocabulary, not logic ("President of
|
||||||
|
the Government" vs "Prime Minister of Spain").
|
||||||
|
- Cross-granularity comparison needs the year-as-interval convention
|
||||||
|
decided once, not per query.
|
||||||
|
|
||||||
|
### Engine choice
|
||||||
|
|
||||||
|
Hand-written goal-directed evaluator over SQLite first (six operators,
|
||||||
|
proof terms as objects, re-execution as check) — fixed code that
|
||||||
|
reasons, the house law. clingo earns its place if re-decomposition goes
|
||||||
|
declarative (answer sets = readings); Z3 earns it in FUNCTION
|
||||||
|
composition over intervals (Run T3 with certificates). Neither is a
|
||||||
|
dependency for v1 of this.
|
||||||
|
|
||||||
|
## Verification plan (before any of this is mergeable)
|
||||||
|
|
||||||
|
1. Taxonomy unit tests over the live 20-pair inventory as fixtures:
|
||||||
|
every pair lands in its measured bucket (10 co-asserted, 3+1
|
||||||
|
temporal, 3 alternatives, 5 multi-valued co-true, 0 real).
|
||||||
|
2. Temporal: the "became" pair classified succession from quote-stated
|
||||||
|
dates; the three presidencies classified overlapping-open-intervals
|
||||||
|
→ alternatives; no date invented anywhere (empty windows stay empty
|
||||||
|
until a source closes them).
|
||||||
|
3. Extractor restrictions: the month-duration/resignation sentence
|
||||||
|
yields concurrent + duration + event-anchored end with containment
|
||||||
|
checks passing; a date not in the quote is rejected.
|
||||||
|
4. Query engine: the Pedro question proves Rajoy as a closed path with
|
||||||
|
re-execution verifying; "of what" returns the three bindings as a
|
||||||
|
set; the rivers regression stays green; judge LLM calls per
|
||||||
|
knowledge question go to zero on store-derivable paths.
|
||||||
|
5. The K5 repro pair becomes the regression: raw glm-style judge values
|
||||||
|
never exist anymore on proven paths (nothing to clean — the
|
||||||
|
interface is gone, not patched).
|
||||||
|
|
||||||
|
## What this does NOT touch
|
||||||
|
|
||||||
|
- The gather, the skim, the LIST path, setop guard — unchanged.
|
||||||
|
- The ablation audit stays for the one job left to it: readings that
|
||||||
|
are NOT store-derivable (judge-visible ambiguity in free text).
|
||||||
|
- Branching (floop/branches.py) gains a cleaner trigger (a binding set)
|
||||||
|
but its death/merge semantics are untouched.
|
||||||
|
|
||||||
|
## Implementation plan (proposed — awaiting his approval; no code yet)
|
||||||
|
|
||||||
|
Phases ordered by dependency; each closes with tests + live runs.
|
||||||
|
Phase 0 is main-bound and independent of the research direction.
|
||||||
|
|
||||||
|
### Phase 0 — hygiene (main; small, shippable alone)
|
||||||
|
|
||||||
|
1. (K5) fix: clean the judge's value at the output boundary
|
||||||
|
(_answer_from_rows) — regex anchored to TRAILING row-citation shapes
|
||||||
|
("(K5)", "(cited from rows K16 and K30)") so legitimate parentheticals
|
||||||
|
("(PSOE)") survive. Prompt side: value desc gains "answer only, no
|
||||||
|
row citations". Regression = the K5 repro pair (raw value → audit
|
||||||
|
runs and flags the Spain alternative).
|
||||||
|
2. --no-cache CLI flag (his ruling 25/10: the dspy disk cache is not a
|
||||||
|
bug; it stays the default): when set, configure_lm builds dspy.LM
|
||||||
|
with cache=False — a per-process bypass, the cache dir untouched.
|
||||||
|
For A/B and freshness testing.
|
||||||
|
3. Import assert at startup: the resolved floop/ and knowledge/ module
|
||||||
|
paths must be under the repo being run — the shared venv's editable
|
||||||
|
pth pins imports to MAIN's tree and ran main code inside the branch
|
||||||
|
worktree without any signal (run 085457). Abort loudly on mismatch.
|
||||||
|
|
||||||
|
### Phase 1 — conflict taxonomy at merge (this branch, store)
|
||||||
|
|
||||||
|
_classify 4 → 6 cases, signals in cost order: same quote_id →
|
||||||
|
co-asserted (conjunction, never a conflict); extracted windows →
|
||||||
|
temporal (interval arithmetic: disjoint = succession, overlapping =
|
||||||
|
alternatives); discriminant tokens + tail resolution against nodes →
|
||||||
|
alternatives vs paraphrase-merge (merge = same_as edge, append-only);
|
||||||
|
what survives with a functional relation = real contradiction. The
|
||||||
|
edge gains a class field; the alternatives bucket is exposed to the
|
||||||
|
audit and the render. Fixtures: the live 20-pair inventory (10
|
||||||
|
co-asserted, 3+1 temporal, 3 alternatives, 0 real).
|
||||||
|
|
||||||
|
**LIVE RESULT (run 20261025-201413, cold KG, glm-5.3-flash, f32a6db):**
|
||||||
|
204 edges, **0 conflicts** (was 20), 30 alternatives, 0 same_as. The
|
||||||
|
three presidencies land pairwise in alternatives and
|
||||||
|
alternatives_of('pedro sanchez','position held') returns the co-true
|
||||||
|
set — the ambiguity substrate is queryable at ingest time. Rajoy
|
||||||
|
answered correctly, judge values clean (phase 0 alive in the pipeline).
|
||||||
|
|
||||||
|
Honest noise, accepted by design (do NOT "fix" with word lists — the
|
||||||
|
run-J lesson): cross-quote conjunctions (the ministers he appointed)
|
||||||
|
land in alternatives too. Same-quote pairs are caught by provenance;
|
||||||
|
cross-quote conjunction is indistinguishable from co-true readings
|
||||||
|
WITHOUT the temporal layer (phase 2 windows + per-relation
|
||||||
|
functionality statistics). The bucket is neutral; the consumer
|
||||||
|
(audit / fork) decides which alternatives are defensible readings FOR
|
||||||
|
A QUESTION. Known follow-ups: same_as recorded but not yet consumed
|
||||||
|
by probe/render (phase 4); paraphrase via tail resolution needs the
|
||||||
|
extractor to RESOLVE dst_node more often (most live edges carry
|
||||||
|
dst_node=None — the paraphrase signal rarely fires).
|
||||||
|
|
||||||
|
### Phase 2 — temporal layer (this branch, extractor + store)
|
||||||
|
|
||||||
|
Typed Fact (feature/typed-facts vehicle) gains start/end/point/
|
||||||
|
granularity, orders [{before|after|concurrent, refs}], duration,
|
||||||
|
anchor (date | event node), immediacy — every field containment-
|
||||||
|
checked against the quote. Store: edge start/end columns + fact_order
|
||||||
|
table. _classify consumes interval arithmetic. Bounded backfill:
|
||||||
|
re-extract quotes of existing conflicting pairs with empty windows.
|
||||||
|
NO Allen labels anywhere — the algebra stays a computed view.
|
||||||
|
|
||||||
|
### Phase 3 — the query prover (the new core)
|
||||||
|
|
||||||
|
Hand-written goal-directed evaluator over SQLite: six operators
|
||||||
|
(lookup, temporal filter, order/select, setops, arithmetic
|
||||||
|
composition, path), typed DSL, proof term as the payload, re-execution
|
||||||
|
as the check. Translator question→DSL: one structured-output LLM call
|
||||||
|
(MASK/EXTRACT class), validated before execution. Wiring: the prover
|
||||||
|
becomes the real stop-check at machine._finish (derivability);
|
||||||
|
AnswerFromKG stays only as the fallback for non-translatable
|
||||||
|
questions. Regression: Pedro proves Rajoy as a closed path; "of what"
|
||||||
|
returns the three bindings as a set; rivers stay green; judge LLM
|
||||||
|
calls drop to zero on store-derivable paths.
|
||||||
|
|
||||||
|
**SHIPPED (3a `fb61268` + 3b `ee315e0`) — live-verified (run
|
||||||
|
20261025-211302, cold KG, glm-5.3-flash):** 3a pinned the evaluator
|
||||||
|
first (prover.py 5/5: the three-presidency fixture returns the three
|
||||||
|
bindings as a set; the predecessor proves RAJOY as a closed path
|
||||||
|
citing both edges; empty = UNKNOWN; re-execution FAILS a stale proof
|
||||||
|
after a retraction — the check is real). 3b wired it: TranslateToDSL
|
||||||
|
(one structured call, the store's relation vocabulary in),
|
||||||
|
validate_query as the shared grammar gate (a mistranslation is an
|
||||||
|
invalid term, NEVER executed), _prover_answer BEFORE any judge with
|
||||||
|
honest fallback on decline/no-path/re-execution-mismatch.
|
||||||
|
LIVE: the gate caught a live invalid term ("no lookup" — the model
|
||||||
|
proposed a filterless shape for the date question; rejected
|
||||||
|
deterministically, judge answered 2018 clean); Q2's predecessor
|
||||||
|
needed the judge (this run's KG lacked Rajoy's closed window — the
|
||||||
|
blind extractor did not transcribe t_end), final Rajoy correct.
|
||||||
|
Honest gap to close in phase 4: the prover closes only when the KG
|
||||||
|
holds the needed windows; either the EXTRACT prompt asks for
|
||||||
|
start/end more explicitly, or `before` degrades to start-vs-start
|
||||||
|
comparison when the old holder's end is open.
|
||||||
|
|
||||||
|
### Phase 4 — consumers
|
||||||
|
|
||||||
|
The audit reduces to "is the binding set already multi?" (cheap,
|
||||||
|
deterministic) + ablation only for non-derivable readings. The branch
|
||||||
|
fork (floop/branches.py) starts from binding multiplicity. ANSWER and
|
||||||
|
any surviving judge render over proof terms, not free prose.
|
||||||
|
|
||||||
|
### Open decisions (his call, before Phase 3 coding)
|
||||||
|
|
||||||
|
- DSL vocabulary: the translator and the evaluator share one grammar —
|
||||||
|
its exact terms.
|
||||||
|
- Order primitives: inside Fact (same call) vs a separate pass.
|
||||||
|
- Translator location: inside INIT (the decomposition and the query
|
||||||
|
born together) vs a post-INIT step per question.
|
||||||
+22
-1
@@ -8,15 +8,36 @@ lm:
|
|||||||
model: qwen3.8-27b-uc-64k:latest
|
model: qwen3.8-27b-uc-64k:latest
|
||||||
max_tokens: 4096
|
max_tokens: 4096
|
||||||
temperature: 0.0
|
temperature: 0.0
|
||||||
|
# transport ceiling (fix: EXTRACT hangs >600s on a busy 3090; the
|
||||||
|
# silent-ollama proxy in front cuts at its own READ_TIMEOUT=600s).
|
||||||
|
# read_timeout_s -> lm15 Timeouts(read=) — one attempt may run this long.
|
||||||
|
# num_retries -> dspy's retry loop (LMTransportError is retryable);
|
||||||
|
# each retry costs up to read_timeout_s, so keep retries LOW locally.
|
||||||
|
read_timeout_s: 1800 # 30 min: one honest attempt for a long EXTRACT
|
||||||
|
num_retries: 1 # one re-try after a cut, not 3x30min
|
||||||
ollama-cloud:
|
ollama-cloud:
|
||||||
base_url: https://ollama.com/v1
|
base_url: https://ollama.com/v1
|
||||||
model: glm-5.3-flash
|
model: glm-5.3-flash
|
||||||
max_tokens: 4096
|
max_tokens: 4096
|
||||||
temperature: 0.0
|
temperature: 0.0
|
||||||
api_key_env: OLLAMA_API_KEY
|
api_key_env: OLLAMA_API_KEY
|
||||||
|
read_timeout_s: 300 # glm answers EXTRACT in ~3s; 300s bounds a wedged call
|
||||||
|
num_retries: 2 # cloud retries are cheap
|
||||||
|
|
||||||
|
# per-signature settings: lm[<SignatureName>] overrides the active provider's
|
||||||
|
# settings for that stage ONLY (model/max_tokens/temperature/...). provider:
|
||||||
|
# selects which provider block inherits base_url + transport ceiling; model:
|
||||||
|
# builds a dedicated cached LM for that stage. No block -> run defaults.
|
||||||
|
lm[ExtractSignature]:
|
||||||
|
provider: local
|
||||||
|
max_tokens: 1800 # EXTRACT output is facts+quotes: ~120 tok/fact;
|
||||||
|
# 4096 was 3x headroom that only extended hangs
|
||||||
|
# on slow local models (the 40-min arithmetic)
|
||||||
|
|
||||||
budget:
|
budget:
|
||||||
max_llm_calls: 80 # per FLOOP run (children get a slice; fan-outs multiply
|
# owner ruling 26/10: completeness beats budget — the budget must never
|
||||||
|
# silently truncate extraction; it bounds runaway runs only
|
||||||
|
max_llm_calls: 200 # per FLOOP run (children get a slice; fan-outs multiply
|
||||||
# entity questions — a 3-river fan needs ~3x a scalar)
|
# entity questions — a 3-river fan needs ~3x a scalar)
|
||||||
min_child_budget: 6
|
min_child_budget: 6
|
||||||
max_depth: 2 # recursion cap (PIPELINE.md §8.4)
|
max_depth: 2 # recursion cap (PIPELINE.md §8.4)
|
||||||
|
|||||||
+39
-18
@@ -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
|
||||||
@@ -82,18 +88,33 @@ def identity_answer(masked_text: str, restore: dict[str, str]) -> str | None:
|
|||||||
Conservative by law (never over-detect): exactly one placeholder in
|
Conservative by law (never over-detect): exactly one placeholder in
|
||||||
the text, and the question is literally 'who/what is <ph>' (ending
|
the text, and the question is literally 'who/what is <ph>' (ending
|
||||||
there or in punctuation — 'who is PERSON_1's predecessor' does NOT
|
there or in punctuation — 'who is PERSON_1's predecessor' does NOT
|
||||||
match) or it names the mask mechanism ('placeholder', 'refer(s) to')."""
|
match) or it names the mask mechanism with the placeholder as the
|
||||||
|
REFERENT: 'refer(s) to' must govern <ph> DIRECTLY ('what does
|
||||||
|
PERSON_1 refer to?', 'the placeholder PERSON_1 refers to…'). A bare
|
||||||
|
'refer to' anywhere in the sentence no longer fires — his 23/10 run:
|
||||||
|
INIT's hidden-precondition phrasing 'does the title "President"
|
||||||
|
refer to in relation to PERSON_1?' asked about the TITLE, the old
|
||||||
|
clause seeded 'Pedro Sanchez' as the answer to which office was
|
||||||
|
meant (a false positive with wrong semantics)."""
|
||||||
phs = [ph for ph in restore if re.search(rf"\b{re.escape(ph)}\b",
|
phs = [ph for ph in restore if re.search(rf"\b{re.escape(ph)}\b",
|
||||||
masked_text)]
|
masked_text)]
|
||||||
if len(phs) != 1:
|
if len(phs) != 1:
|
||||||
return None
|
return None
|
||||||
ph = phs[0]
|
ph = phs[0]
|
||||||
t = masked_text.strip()
|
t = masked_text.strip()
|
||||||
|
# lookahead: end-of-sentence/punctuation AFTER the placeholder — but
|
||||||
|
# never an apostrophe: "PERSON_1's predecessor" is a possessive, not an
|
||||||
|
# identity question (pre-existing trap found while verifying the 23/10
|
||||||
|
# fix; the old test only covered 'Who WAS…', which dodges the literal)
|
||||||
literal = re.match(
|
literal = re.match(
|
||||||
rf"^(?:who|what)\s+(?:is|are)\s+{re.escape(ph)}(?=$|[\s,.?!:;)\"'])",
|
rf"^(?:who|what)\s+(?:is|are)\s+{re.escape(ph)}(?=$|[\s,.?!:;)\"])",
|
||||||
t, flags=re.IGNORECASE)
|
t, flags=re.IGNORECASE)
|
||||||
mechanism = any(k in t.casefold() for k in
|
if literal:
|
||||||
("placeholder", "refer to", "refers to"))
|
|
||||||
if literal or mechanism:
|
|
||||||
return restore[ph]
|
return restore[ph]
|
||||||
|
# mechanism mention: strict — the placeholder must be the REFERENT of
|
||||||
|
# 'refer(s) to', not merely present in a sentence that uses the verb
|
||||||
|
for pat in (rf"\brefer(?:s)?\s+to\s+{re.escape(ph)}\b",
|
||||||
|
rf"{re.escape(ph)}\s+refer(?:s)?\s+to\b"):
|
||||||
|
if re.search(pat, t, flags=re.IGNORECASE):
|
||||||
|
return restore[ph]
|
||||||
return None
|
return None
|
||||||
@@ -0,0 +1,319 @@
|
|||||||
|
"""Execution branches (his branching design, 22-23/10 — now coded).
|
||||||
|
|
||||||
|
When an expert answers a question with SEVERAL defensible readings
|
||||||
|
(payload['ambiguous'] + alternatives, the knowledge expert's ablation
|
||||||
|
audit), the machine does NOT hand the alternatives to the next
|
||||||
|
subquestion's context (the rejected design — it only moves the
|
||||||
|
coin-flip into answer_kg) and does NOT collapse them inside ANSWER
|
||||||
|
(run L: 'Papandreou was the predecessor' — the exact rejected
|
||||||
|
behaviour). Instead, when a question DEPENDS on an ambiguous row, the
|
||||||
|
machine opens ONE LAZY EXECUTION BRANCH PER READING:
|
||||||
|
|
||||||
|
- a branch is a machine-level construct at floop DEPTH+1-like nesting,
|
||||||
|
but INSIDE this run: it owns its question stack and reads the
|
||||||
|
evidence through a BranchView that BINDS the ambiguous row to ONE
|
||||||
|
reading (a VIEW, never a store mutation — the same law as the
|
||||||
|
ablation mask);
|
||||||
|
- LAZY: the branch is born only when a dependent of the ambiguous row
|
||||||
|
becomes pickable — until then, nothing forks;
|
||||||
|
- SHARED: the knowledge acquired by every branch lands in the ONE
|
||||||
|
evidence table (the machine's working memory) and the KG/seen-index
|
||||||
|
live in the expert, shared by construction — a later branch reuses
|
||||||
|
what an earlier one gathered for free;
|
||||||
|
- per-branch is the READING of the ambiguous row + the subquestions
|
||||||
|
born under it; branch id rides every row's provenance;
|
||||||
|
- a branch DIES only by contradiction (its checked arrival refusing a
|
||||||
|
value), dead end (its terminal questions all failed — honest
|
||||||
|
UNKNOWN), or NATURAL MERGE (its answers converge with another
|
||||||
|
branch's — dedupe by value, keep the first) — never by an absurdity
|
||||||
|
judge (surprising-but-cited answers render, they are not
|
||||||
|
pocket-judged);
|
||||||
|
- the final answer is CONDITIONAL over surviving branches, composed
|
||||||
|
by FIXED CODE from the branch results — 'si et referies a president
|
||||||
|
d'Espanya -> Rajoy; si SI -> Papandreou; si PSOE -> qui sigui' —
|
||||||
|
never one reading chosen inside a synthesis prompt;
|
||||||
|
- nested ambiguity: a branch that hits its OWN ambiguous row forks
|
||||||
|
sub-branches under the same mechanism and the same caps.
|
||||||
|
|
||||||
|
Open by design (layer 3, a policy ABOVE this mechanism): asking the
|
||||||
|
user instead of running all branches = picking one branch upstairs.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from .state import EvidenceRow, EvidenceTable
|
||||||
|
|
||||||
|
# a branch result that is honestly nothing: dead end / contradiction /
|
||||||
|
# everything failed. The conditional render skips it (the branch's death
|
||||||
|
# is already in the notes), it never masquerades as an answer reading.
|
||||||
|
DEAD_END = "UNKNOWN"
|
||||||
|
|
||||||
|
|
||||||
|
def _norm(v: str) -> str:
|
||||||
|
"""Merge/dedupe key: casefolded alphanumerics (norm_name's machine-level
|
||||||
|
cousin — 'Rajoy' == 'rajoy', 'Pedro Sánchez' == 'Pedro Sanchez')."""
|
||||||
|
return re.sub(r"[^a-z0-9]+", " ", (v or "").casefold()).strip()
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class BranchSpec:
|
||||||
|
"""One reading of one ambiguous row. The branch binds the row to
|
||||||
|
value; reading is the human-legible label ('as President of Spain')."""
|
||||||
|
id: str
|
||||||
|
ambiguous_eid: str
|
||||||
|
ambiguous_qid: str
|
||||||
|
value: str # the reading this branch binds
|
||||||
|
reading: str # label for the conditional render
|
||||||
|
origin: str = "" # the id of the branch that forked this one ("" = root)
|
||||||
|
# the open dependent SUBTREE copied into every branch of this fork,
|
||||||
|
# frozen at fork time (B1 consuming the originals must not change
|
||||||
|
# what B2 copies — the qids in qid order, deps rewired per branch)
|
||||||
|
subtree_qids: list[str] = field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class BranchResult:
|
||||||
|
"""What a branch concluded, for the conditional render."""
|
||||||
|
spec: BranchSpec
|
||||||
|
answer: str = "" # the branch's final answer (synthesized inside it)
|
||||||
|
status: str = "open" # open | answered | dead | merged
|
||||||
|
|
||||||
|
|
||||||
|
class BranchView:
|
||||||
|
"""The evidence table AS ONE BRANCH SEES IT.
|
||||||
|
|
||||||
|
The shared table is untouched — the ambiguous row is REPLACED in
|
||||||
|
this view by a synthetic row binding the branch's reading (same
|
||||||
|
qid, same answer_type, the reading's own quote/url, verified as
|
||||||
|
its source rows were — the reading IS the expert's pick or one of
|
||||||
|
its alternatives, each carried with quote+url by the audit). Rows
|
||||||
|
from other branches (provenance['branch'] set and different) are
|
||||||
|
HIDDEN: they answer questions that never existed in this world.
|
||||||
|
|
||||||
|
Everything else (rows with no branch tag, rows this branch appended)
|
||||||
|
passes through unchanged — acquired knowledge is shared.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, table: "EvidenceTable", spec: BranchSpec) -> None:
|
||||||
|
self._table = table
|
||||||
|
self._spec = spec
|
||||||
|
|
||||||
|
def _bound_row(self) -> "EvidenceRow":
|
||||||
|
from .state import EvidenceRow
|
||||||
|
src = self._table.row(self._spec.ambiguous_eid)
|
||||||
|
payload = {k: v for k, v in (src.payload or {}).items()
|
||||||
|
if k not in ("ambiguous", "alternatives")}
|
||||||
|
payload["value"] = self._spec.value
|
||||||
|
payload["quote"] = self._reading_quote()
|
||||||
|
payload["branch_binding"] = True # the branch-fake's marker: this
|
||||||
|
# row IS the bound reading
|
||||||
|
if self._spec.origin:
|
||||||
|
payload["branch_reading"] = self._spec.reading
|
||||||
|
return EvidenceRow(
|
||||||
|
qid=src.qid, answer_type=src.answer_type, payload=payload,
|
||||||
|
engine=src.engine + ":branch-bind",
|
||||||
|
trace=[f"branch {self._spec.id}: ambiguous row bound to reading "
|
||||||
|
f"'{self._spec.value}'"],
|
||||||
|
provenance=dict(src.provenance, branch=self._spec.id),
|
||||||
|
verified=src.verified, note="")
|
||||||
|
|
||||||
|
def _reading_quote(self) -> str:
|
||||||
|
"""The reading's OWN quote when the row carries alternatives with
|
||||||
|
quotes; else the picked answer's quote (branch = the pick)."""
|
||||||
|
src = self._table.row(self._spec.ambiguous_eid)
|
||||||
|
for a in (src.payload.get("alternatives") or []):
|
||||||
|
if _norm(a.get("value", "")) == _norm(self._spec.value) and a.get("quote"):
|
||||||
|
return a["quote"]
|
||||||
|
return str(src.payload.get("quote", ""))
|
||||||
|
|
||||||
|
# -- the EvidenceTable interface the machine reads ---------------------
|
||||||
|
def row(self, eid: str) -> "EvidenceRow | None":
|
||||||
|
if eid == self._spec.ambiguous_eid:
|
||||||
|
return self._bound_row()
|
||||||
|
r = self._table.row(eid)
|
||||||
|
if r is not None and self._hidden(r):
|
||||||
|
return None
|
||||||
|
return r
|
||||||
|
|
||||||
|
def append(self, row: "EvidenceRow") -> "EvidenceRow":
|
||||||
|
"""A branch's new rows land in the SHARED table (acquired knowledge
|
||||||
|
is shared — a later branch reuses them) tagged with the branch id
|
||||||
|
(other branches' views hide them until they merge)."""
|
||||||
|
row.provenance["branch"] = self._spec.id
|
||||||
|
return self._table.append(row)
|
||||||
|
|
||||||
|
def rows(self) -> "list[EvidenceRow]":
|
||||||
|
return ([self._bound_row()] if self._bound_row() else []) + \
|
||||||
|
[r for r in self._table.rows() if r.eid != self._spec.ambiguous_eid
|
||||||
|
and not self._hidden(r)]
|
||||||
|
|
||||||
|
def for_question(self, qid: str) -> "list[EvidenceRow]":
|
||||||
|
return [r for r in self.rows() if r.qid == qid]
|
||||||
|
|
||||||
|
def dump(self) -> str:
|
||||||
|
from .state import EvidenceTable
|
||||||
|
flat = EvidenceTable()
|
||||||
|
for r in self.rows():
|
||||||
|
flat.append(type(r)(
|
||||||
|
answer_type=r.answer_type, payload=dict(r.payload),
|
||||||
|
engine=r.engine, qid=r.qid, trace=list(r.trace),
|
||||||
|
provenance=dict(r.provenance), verified=r.verified,
|
||||||
|
note=r.note, retracted=r.retracted))
|
||||||
|
return flat.dump()
|
||||||
|
|
||||||
|
def _hidden(self, r: "EvidenceRow") -> bool:
|
||||||
|
b = r.provenance.get("branch")
|
||||||
|
return bool(b) and b != self._spec.id
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class BranchManager:
|
||||||
|
"""The fork bookkeeping. The machine asks 'should I fork on this row?'
|
||||||
|
(is it ambiguous AND does an open question depend on it), gets one
|
||||||
|
BranchSpec per reading, executes branches lazily, and renders the
|
||||||
|
surviving results conditionally.
|
||||||
|
|
||||||
|
The manager holds no execution logic — the machine runs each branch
|
||||||
|
as a plain FloopRun loop over its own stack; the manager owns the
|
||||||
|
specs, the merge policy, and the conditional render.
|
||||||
|
"""
|
||||||
|
max_branches: int = 6
|
||||||
|
specs: list[BranchSpec] = field(default_factory=list)
|
||||||
|
results: dict[str, BranchResult] = field(default_factory=dict)
|
||||||
|
dropped: list[str] = field(default_factory=list)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def pending(self) -> list[BranchSpec]:
|
||||||
|
"""Specs not yet executed (FIFO — the picked reading runs first)."""
|
||||||
|
return [s for s in self.specs
|
||||||
|
if self.results.get(s.id) is None
|
||||||
|
or self.results[s.id].status == "open"]
|
||||||
|
|
||||||
|
def fork_specs(self, row: "EvidenceRow", origin: str = "",
|
||||||
|
subtree_qids: list[str] | None = None) -> list[BranchSpec]:
|
||||||
|
"""One spec per defensible reading of an ambiguous row whose open
|
||||||
|
dependent subtree (computed by the caller, frozen here) is non-
|
||||||
|
empty. LAZY LAW: an empty subtree means no fork — the ambiguity
|
||||||
|
is noted, the run continues on the pick.
|
||||||
|
`origin`: the branch we are inside when the fork fires ("" = the
|
||||||
|
root run) — nested ambiguity nests sub-branches under it.
|
||||||
|
Branch cap: past max_branches live specs, the extra readings are
|
||||||
|
dropped and NAMED (never silent)."""
|
||||||
|
if not row.payload.get("ambiguous"):
|
||||||
|
return []
|
||||||
|
alts = row.payload.get("alternatives") or []
|
||||||
|
readings = [(row.payload.get("value", ""), "the picked reading")]
|
||||||
|
readings += [(a.get("value", ""), a.get("value", ""))
|
||||||
|
for a in alts if a.get("value")]
|
||||||
|
specs = []
|
||||||
|
for i, (val, label) in enumerate(readings):
|
||||||
|
if not val or str(val).upper() == "UNKNOWN":
|
||||||
|
continue
|
||||||
|
bid = f"B{len(self.specs) + len(specs) + 1}"
|
||||||
|
spec = BranchSpec(
|
||||||
|
id=bid, ambiguous_eid=row.eid, ambiguous_qid=row.qid,
|
||||||
|
value=str(val),
|
||||||
|
reading=label if label and label != val else f"reading {bid}",
|
||||||
|
origin=origin,
|
||||||
|
subtree_qids=list(subtree_qids or []))
|
||||||
|
specs.append(spec)
|
||||||
|
if len(self.specs) + len(specs) > self.max_branches:
|
||||||
|
keep = self.max_branches - len(self.specs)
|
||||||
|
dropped = [s.reading for s in specs[keep:]]
|
||||||
|
specs = specs[:keep]
|
||||||
|
self.dropped = self.dropped + dropped
|
||||||
|
for s in specs:
|
||||||
|
self.specs.append(s)
|
||||||
|
self.results[s.id] = BranchResult(spec=s)
|
||||||
|
return specs
|
||||||
|
|
||||||
|
def record_answer(self, spec_id: str, answer: str) -> None:
|
||||||
|
res = self.results.get(spec_id)
|
||||||
|
if res is not None:
|
||||||
|
res.answer = answer
|
||||||
|
res.status = "answered"
|
||||||
|
|
||||||
|
def record_dead(self, spec_id: str) -> None:
|
||||||
|
res = self.results.get(spec_id)
|
||||||
|
if res is not None:
|
||||||
|
res.status = "dead"
|
||||||
|
|
||||||
|
def record_merge(self, spec_id: str, into: str) -> None:
|
||||||
|
res = self.results.get(spec_id)
|
||||||
|
if res is not None:
|
||||||
|
res.status = "merged"
|
||||||
|
res.answer = f"(merged with {into})"
|
||||||
|
|
||||||
|
def survivors(self, origin: str = "") -> list[BranchResult]:
|
||||||
|
"""Answered branches at one nesting level (origin), deduped by
|
||||||
|
normalized value — natural merge: two branches that concluded the
|
||||||
|
same thing are one conclusion. First-come order (the picked
|
||||||
|
reading usually leads)."""
|
||||||
|
seen: dict[str, BranchResult] = {}
|
||||||
|
order: list[BranchResult] = []
|
||||||
|
for res in self.results.values():
|
||||||
|
if res.status != "answered" or res.spec.origin != origin:
|
||||||
|
continue
|
||||||
|
key = _norm(res.answer)
|
||||||
|
if key and key in seen:
|
||||||
|
self.record_merge(res.spec.id, seen[key].spec.id)
|
||||||
|
continue
|
||||||
|
if key:
|
||||||
|
seen[key] = res
|
||||||
|
order.append(res)
|
||||||
|
return order
|
||||||
|
|
||||||
|
def conditional_answer(self, goal: str, origin: str = "") -> str:
|
||||||
|
"""The CONDITIONAL final answer, composed by FIXED CODE (run L
|
||||||
|
law: never collapse readings inside a synthesis prompt). All
|
||||||
|
surviving branch answers at one nesting level, one clause per
|
||||||
|
reading; a single survivor renders plain, its branch noted. A
|
||||||
|
branch whose own children answered carries its conditional as
|
||||||
|
its recorded answer — nesting is baked in, not re-rendered.
|
||||||
|
Dead branches are already in the notes; the render never
|
||||||
|
invents their content."""
|
||||||
|
alive = self.survivors(origin)
|
||||||
|
dropped = self.dropped
|
||||||
|
if not alive:
|
||||||
|
parts = ["No reading reached an answer."]
|
||||||
|
if dropped:
|
||||||
|
parts.append(f"(branch cap: readings dropped: {', '.join(dropped)})")
|
||||||
|
return " ".join(parts)
|
||||||
|
if len(alive) == 1:
|
||||||
|
r = alive[0]
|
||||||
|
out = f"{r.answer} (reading: {r.spec.reading})"
|
||||||
|
if dropped:
|
||||||
|
out += f" — other readings hit the branch cap: {', '.join(dropped)}"
|
||||||
|
return out
|
||||||
|
clauses = [f"if you meant {res.spec.reading} -> {res.answer}"
|
||||||
|
for res in alive]
|
||||||
|
out = " | ".join(clauses)
|
||||||
|
if dropped:
|
||||||
|
out += f" | (branch cap: {', '.join(dropped)} not run)"
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def open_subtree(stack, ambiguous_qid: str) -> list[str]:
|
||||||
|
"""The OPEN dependent subtree below one question: direct AND transitive
|
||||||
|
open dependents, qids in discovery order. LAZY: an empty list means
|
||||||
|
no fork — a branch is born only when someone needs the reading.
|
||||||
|
Frozen at fork time: every branch of the fork copies the SAME list
|
||||||
|
(the first branch consuming the originals must not change what the
|
||||||
|
second copies)."""
|
||||||
|
found: dict[str, str] = {} # orig qid -> branch copy qid (filled later)
|
||||||
|
order: list[str] = []
|
||||||
|
changed = True
|
||||||
|
while changed:
|
||||||
|
changed = False
|
||||||
|
for q in stack.items:
|
||||||
|
if (q.status == "open" and not q.parent_goal
|
||||||
|
and q.qid not in order
|
||||||
|
and any(d in found or d == ambiguous_qid for d in q.deps)):
|
||||||
|
order.append(q.qid)
|
||||||
|
found[q.qid] = ""
|
||||||
|
changed = True
|
||||||
|
return order
|
||||||
+30
-18
@@ -10,6 +10,7 @@ import re
|
|||||||
from enum import Enum
|
from enum import Enum
|
||||||
|
|
||||||
import dspy
|
import dspy
|
||||||
|
from floop.llm import predict
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
|
|
||||||
from .state import AnswerType
|
from .state import AnswerType
|
||||||
@@ -19,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):
|
||||||
@@ -31,20 +32,31 @@ class Subquestion(BaseModel):
|
|||||||
answer_type: AnswerType = dspy.OutputField(
|
answer_type: AnswerType = dspy.OutputField(
|
||||||
desc="OPEN for a single value, FUNCTION for a formula, INTERVAL for a range, "
|
desc="OPEN for a single value, FUNCTION for a formula, INTERVAL for a range, "
|
||||||
"CONSTANT for a universal constant, LIST for an enumeration of things, "
|
"CONSTANT for a universal constant, LIST for an enumeration of things, "
|
||||||
"DATE for a specific date (a day, month and year — '15' alone is NOT a date)")
|
"DATE for a specific date")
|
||||||
|
|
||||||
|
|
||||||
class InitSignature(dspy.Signature):
|
class InitSignature(dspy.Signature):
|
||||||
"""You are the INIT step of a reasoning machine. Using ONLY concepts literally
|
"""You are the INIT step of a reasoning machine. Your job is to make the
|
||||||
present in the question plus a generic planning scaffold (number, method,
|
final answer a direct lookup. Follow this procedure:
|
||||||
machine, resources, dependencies), ask: what information or knowledge do I
|
1. Re-read the question and:
|
||||||
need to answer this? Write 1-4 open subquestions in dependency order.
|
1.1. List every word or phrase that could refer to more than one
|
||||||
Masked entities like PERSON_1 or ORGANIZATION_1 are ALREADY-RESOLVED
|
real thing or moment.
|
||||||
named entities from the question — treat each as a known specific entity;
|
1.2. Think: what information or knowledge do I need to answer this?
|
||||||
do not ask what or who the placeholder is."""
|
2. HIDDEN PRECONDITIONS: for every entity, relation, or value that the
|
||||||
|
question assumes but does not state and that is required to answer
|
||||||
|
it (an implicit owner, role, time window, or intermediate fact),
|
||||||
|
write an explicit subquestion that resolves it. NEVER collapse a
|
||||||
|
hidden precondition into the final subquestion. Always use the most
|
||||||
|
generic term to ask about them.
|
||||||
|
3. Write the subquestion that produces the final answer, with
|
||||||
|
depends_on pointing at the preconditions it needs.
|
||||||
|
Order the subquestions by dependency (1-4 in total).
|
||||||
|
Masked entities like PERSON_1 or ORGANIZATION_1 are ALREADY-RESOLVED named
|
||||||
|
entities from the question — treat each as a known specific entity; do not
|
||||||
|
ask what or who the placeholder is."""
|
||||||
question: str = dspy.InputField()
|
question: str = dspy.InputField()
|
||||||
subquestions: list[Subquestion] = dspy.OutputField(
|
subquestions: list[Subquestion] = dspy.OutputField(
|
||||||
desc="1-4 subquestions in dependency order; empty when the question is atomic")
|
desc="1-4 subquestions in dependency order; never empty")
|
||||||
|
|
||||||
|
|
||||||
class Attendant(str, Enum):
|
class Attendant(str, Enum):
|
||||||
@@ -124,12 +136,12 @@ class FloopModules:
|
|||||||
"""All LLM entry points of the draft. Each returns a dspy.Prediction."""
|
"""All LLM entry points of the draft. Each returns a dspy.Prediction."""
|
||||||
|
|
||||||
def __init__(self) -> None:
|
def __init__(self) -> None:
|
||||||
self.init = dspy.Predict(InitSignature)
|
self.init = predict(InitSignature)
|
||||||
self.route = dspy.Predict(RouteSignature)
|
self.route = predict(RouteSignature)
|
||||||
self.expert = dspy.Predict(ExpertSignature)
|
self.expert = predict(ExpertSignature)
|
||||||
self.missing = dspy.Predict(MissingSignature)
|
self.missing = predict(MissingSignature)
|
||||||
self.answer = dspy.Predict(AnswerSignature)
|
self.answer = predict(AnswerSignature)
|
||||||
self.mask = dspy.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
|
||||||
@@ -166,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))
|
||||||
+184
-5
@@ -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",
|
||||||
@@ -164,8 +252,9 @@ _STAGE_BY_MODULE = {
|
|||||||
"MissingSignature": "MISSING",
|
"MissingSignature": "MISSING",
|
||||||
"AnswerSignature": "ANSWER",
|
"AnswerSignature": "ANSWER",
|
||||||
"ExtractSignature": "EXTRACT",
|
"ExtractSignature": "EXTRACT",
|
||||||
|
"ExtractClaims": "CLAIMS",
|
||||||
|
"TypeClaim": "TYPE",
|
||||||
"AnswerFromKG": "answer_kg",
|
"AnswerFromKG": "answer_kg",
|
||||||
"TranslateSignature": "TRANSLATE",
|
|
||||||
"SelectTableSignature": "SELECT_TABLE",
|
"SelectTableSignature": "SELECT_TABLE",
|
||||||
"VerifyCountSignature": "VERIFY_COUNT",
|
"VerifyCountSignature": "VERIFY_COUNT",
|
||||||
"SkimPromoteSignature": "PROMOTE",
|
"SkimPromoteSignature": "PROMOTE",
|
||||||
@@ -173,9 +262,14 @@ _STAGE_BY_MODULE = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def configure_lm() -> dict:
|
def configure_lm(no_cache: bool = False) -> dict:
|
||||||
"""Configure dspy's default LM from config.yaml + FLOOP_LM env override.
|
"""Configure dspy's default LM from config.yaml + FLOOP_LM env override.
|
||||||
|
|
||||||
|
no_cache=True builds the LM with dspy's response cache DISABLED for this
|
||||||
|
process (his ruling 25/10: the cache is caching doing its job — the
|
||||||
|
default stays cache=True; the flag exists for A/B and freshness testing
|
||||||
|
so a repeated question is a real run, not a byte-identical replay).
|
||||||
|
|
||||||
Returns the active provider settings (for provenance logs).
|
Returns the active provider settings (for provenance logs).
|
||||||
"""
|
"""
|
||||||
cfg = _load_yaml()["lm"]
|
cfg = _load_yaml()["lm"]
|
||||||
@@ -192,11 +286,27 @@ def configure_lm() -> dict:
|
|||||||
"temperature": p["temperature"],
|
"temperature": p["temperature"],
|
||||||
"api_key": os.environ.get(p.get("api_key_env", ""), "empty"),
|
"api_key": os.environ.get(p.get("api_key_env", ""), "empty"),
|
||||||
}
|
}
|
||||||
|
# transport ceiling (fix: EXTRACT hangs on slow local models): the
|
||||||
|
# config's read_timeout_s becomes the lm15 Timeouts(read=) via the
|
||||||
|
# `timeout=` kwarg (a plain number of seconds bounds read/write/
|
||||||
|
# pool — dspy 3.4.1 execution.py routes it as RouterConfig timeouts;
|
||||||
|
# the default is 600s, the wall your 2407.3s EXTRACT call died on,
|
||||||
|
# 4 attempts x 600s + backoff). num_retries feeds dspy's retry loop
|
||||||
|
# (LMTransportError IS retryable — execution.py is_retryable_lm_error).
|
||||||
|
# Unset -> dspy defaults (600s / retries 3), nothing invented.
|
||||||
|
if p.get("read_timeout_s"):
|
||||||
|
kwargs["timeout"] = float(p["read_timeout_s"])
|
||||||
|
if p.get("num_retries") is not None:
|
||||||
|
kwargs["num_retries"] = int(p["num_retries"])
|
||||||
|
if no_cache:
|
||||||
|
kwargs["cache"] = False
|
||||||
lm = dspy.LM(**kwargs)
|
lm = dspy.LM(**kwargs)
|
||||||
global _ACTIVE
|
global _ACTIVE
|
||||||
_ACTIVE = lm
|
_ACTIVE = lm
|
||||||
dspy.configure(lm=lm)
|
dspy.configure(lm=lm)
|
||||||
return {"provider": provider, "model": p["model"], "base_url": p["base_url"]}
|
return {"provider": provider, "model": p["model"], "base_url": p["base_url"],
|
||||||
|
"read_timeout_s": p.get("read_timeout_s"),
|
||||||
|
"num_retries": p.get("num_retries")}
|
||||||
|
|
||||||
|
|
||||||
def install_prompt_log(streams) -> None:
|
def install_prompt_log(streams) -> None:
|
||||||
@@ -213,6 +323,75 @@ def install_prompt_log(streams) -> None:
|
|||||||
_ACTIVE: "dspy.LM | None" = None
|
_ACTIVE: "dspy.LM | None" = None
|
||||||
_PROMPT_LOG: "PromptLogCallback | None" = None
|
_PROMPT_LOG: "PromptLogCallback | None" = None
|
||||||
|
|
||||||
|
# per-signature dedicated LMs (lm[<SigName>] blocks with a model override),
|
||||||
|
# keyed f"{provider}:{model}" — ONE LM per provider+model, built once
|
||||||
|
_SIGNATURE_LMS: dict[str, "dspy.LM"] = {}
|
||||||
|
|
||||||
|
|
||||||
|
def _signature_settings(sig) -> dict:
|
||||||
|
"""The lm[<SignatureName>] block for a signature, or {} when absent."""
|
||||||
|
name = getattr(sig, "__name__", None) or str(sig)
|
||||||
|
return _load_yaml().get(f"lm[{name}]") or {}
|
||||||
|
|
||||||
|
|
||||||
|
def signature_overrides() -> dict[str, dict]:
|
||||||
|
"""Every lm[<SigName>] block in config.yaml, by signature name.
|
||||||
|
|
||||||
|
For the run.log provenance line: which stages run with dedicated
|
||||||
|
settings today, visible at startup.
|
||||||
|
"""
|
||||||
|
return {k[3:-1]: v for k, v in _load_yaml().items()
|
||||||
|
if k.startswith("lm[") and k.endswith("]")}
|
||||||
|
|
||||||
|
|
||||||
|
def predict(signature, **extra_config):
|
||||||
|
"""dspy.Predict construction honoring per-signature config blocks.
|
||||||
|
|
||||||
|
A `lm[<SignatureName>]:` block in config.yaml (sibling of `lm:`) may
|
||||||
|
carry: provider (which provider block to inherit base_url + transport
|
||||||
|
ceiling from — defaults to the active provider), model, max_tokens,
|
||||||
|
temperature, and any other dspy.LM kwarg. Settings WITHOUT a model
|
||||||
|
travel as per-call lm_kwargs through Predict's own config (dspy 3.4.1
|
||||||
|
merges self.config into the request — verified on the wire); a model:
|
||||||
|
override builds ONE dedicated cached dspy.LM (same provider ceiling,
|
||||||
|
its own model id) bound to the Predict instance. No block -> a plain
|
||||||
|
dspy.Predict with the run defaults, untouched.
|
||||||
|
|
||||||
|
This is the ONE construction door: swapping dspy.Predict(...) for
|
||||||
|
predict(...) here means a signature's model/settings change by
|
||||||
|
editing config alone — no call-site ifs, now or ever after.
|
||||||
|
"""
|
||||||
|
import dspy
|
||||||
|
block = _signature_settings(signature)
|
||||||
|
if not block:
|
||||||
|
return dspy.Predict(signature, **extra_config)
|
||||||
|
cfg = _load_yaml()["lm"]
|
||||||
|
provider = block.get("provider") or cfg.get("default")
|
||||||
|
base = cfg[provider]
|
||||||
|
settings = {k: v for k, v in block.items() if k != "provider"}
|
||||||
|
model = settings.pop("model", None)
|
||||||
|
if model is None:
|
||||||
|
return dspy.Predict(signature, **settings, **extra_config)
|
||||||
|
key = f"{provider}:{model}"
|
||||||
|
if key not in _SIGNATURE_LMS:
|
||||||
|
kwargs: dict = {
|
||||||
|
"model": f"openai/{model}",
|
||||||
|
"base_url": base["base_url"],
|
||||||
|
"api_base": base["base_url"],
|
||||||
|
"max_tokens": settings.pop("max_tokens", base["max_tokens"]),
|
||||||
|
"temperature": settings.pop("temperature", base["temperature"]),
|
||||||
|
"api_key": os.environ.get(base.get("api_key_env", ""), "empty"),
|
||||||
|
}
|
||||||
|
if base.get("read_timeout_s"):
|
||||||
|
kwargs["timeout"] = float(base["read_timeout_s"])
|
||||||
|
if base.get("num_retries") is not None:
|
||||||
|
kwargs["num_retries"] = int(base["num_retries"])
|
||||||
|
kwargs.update(settings) # any other block keys pass through
|
||||||
|
_SIGNATURE_LMS[key] = dspy.LM(**kwargs)
|
||||||
|
inst = dspy.Predict(signature, **extra_config)
|
||||||
|
inst.lm = _SIGNATURE_LMS[key]
|
||||||
|
return inst
|
||||||
|
|
||||||
|
|
||||||
def active_lm() -> "dspy.LM":
|
def active_lm() -> "dspy.LM":
|
||||||
"""The configured dspy.LM, configuring it lazily if needed (baseline mode uses it raw)."""
|
"""The configured dspy.LM, configuring it lazily if needed (baseline mode uses it raw)."""
|
||||||
|
|||||||
+252
-17
@@ -16,6 +16,8 @@ from dataclasses import dataclass, field
|
|||||||
|
|
||||||
from .engine import CATALOG, LLMExpertEngine, UserRequestEngine
|
from .engine import CATALOG, LLMExpertEngine, UserRequestEngine
|
||||||
from .setops import detect_setop, setop_row
|
from .setops import detect_setop, setop_row
|
||||||
|
from .branches import (BranchManager, BranchResult, BranchSpec, BranchView,
|
||||||
|
DEAD_END, open_subtree)
|
||||||
from .dspy_modules import FloopModules
|
from .dspy_modules import FloopModules
|
||||||
from .state import (AnswerType, Budget, BudgetExhausted, EvidenceRow,
|
from .state import (AnswerType, Budget, BudgetExhausted, EvidenceRow,
|
||||||
EvidenceTable, OpenQuestion, QuestionStack, instantiate)
|
EvidenceTable, OpenQuestion, QuestionStack, instantiate)
|
||||||
@@ -101,6 +103,13 @@ class FloopRun:
|
|||||||
self.knowledge_engine = knowledge_engine # None -> baseline LLM expert
|
self.knowledge_engine = knowledge_engine # None -> baseline LLM expert
|
||||||
self.notes: list[str] = []
|
self.notes: list[str] = []
|
||||||
self.engine_calls = 0
|
self.engine_calls = 0
|
||||||
|
# BRANCHING (his design, 22-23/10): the fork bookkeeping. Specs are
|
||||||
|
# created lazily (only when a dependent of an ambiguous row exists);
|
||||||
|
# the shared table/stack stay THE run's own — a branch reads the
|
||||||
|
# table through a BranchView that binds the ambiguous row to its
|
||||||
|
# reading and hides other branches' rows.
|
||||||
|
self.branches = BranchManager()
|
||||||
|
self._current_branch = "" # "" = the root run; else the branch id
|
||||||
# RE-ASK METER (run L): dspy's adapter fallback fires extra LM calls
|
# RE-ASK METER (run L): dspy's adapter fallback fires extra LM calls
|
||||||
# the budget never charged. The prompt-log callback sees them; wire
|
# the budget never charged. The prompt-log callback sees them; wire
|
||||||
# its meter to our budget so the count is honest. The BEHAVIOUR of
|
# its meter to our budget so the count is honest. The BEHAVIOUR of
|
||||||
@@ -134,6 +143,14 @@ class FloopRun:
|
|||||||
self._init_decompose()
|
self._init_decompose()
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
|
# BRANCHING: a fork pending means an ambiguous row gained a
|
||||||
|
# dependent — its readings each own a world now. Run the
|
||||||
|
# branches to their end BEFORE the main loop continues
|
||||||
|
# (their conclusions/notes land in the shared table/notes;
|
||||||
|
# the conditional render happens at _finish).
|
||||||
|
while self.branches.pending:
|
||||||
|
spec = self.branches.pending[0]
|
||||||
|
self._run_branch(spec)
|
||||||
q = self.stack.pickable(self.table)
|
q = self.stack.pickable(self.table)
|
||||||
if q is None:
|
if q is None:
|
||||||
if self.stack.all_terminal():
|
if self.stack.all_terminal():
|
||||||
@@ -203,7 +220,10 @@ class FloopRun:
|
|||||||
resolved.append(created[tok - 1].qid)
|
resolved.append(created[tok - 1].qid)
|
||||||
q.deps = resolved
|
q.deps = resolved
|
||||||
# anonymization seeds (his design): identity questions the mask map
|
# anonymization seeds (his design): identity questions the mask map
|
||||||
# already answers land as evidence NOW — zero LLM calls
|
# already answers land as evidence NOW — zero LLM calls. WARN on
|
||||||
|
# screen AND log (his 23/10 ask): the machine auto-answered a
|
||||||
|
# question without any expert — legible, and a self-improvement
|
||||||
|
# signal (which phrasings the seed eats -> META's lessons bank).
|
||||||
for q, s in zip(created, subs):
|
for q, s in zip(created, subs):
|
||||||
if s.get("known_answer"):
|
if s.get("known_answer"):
|
||||||
self.table.append(EvidenceRow(
|
self.table.append(EvidenceRow(
|
||||||
@@ -216,6 +236,9 @@ class FloopRun:
|
|||||||
q.reason = "identity seeded from the mask map"
|
q.reason = "identity seeded from the mask map"
|
||||||
self.notes.append(
|
self.notes.append(
|
||||||
f"{q.qid}: seeded from anonymization — no expert call needed")
|
f"{q.qid}: seeded from anonymization — no expert call needed")
|
||||||
|
self.streams.warn(
|
||||||
|
f"SEED auto-answered {q.qid} '{q.text[:60]}' -> "
|
||||||
|
f"'{s['known_answer']}' (mask map; zero expert calls)")
|
||||||
|
|
||||||
# ---- fan-out (the planner's expansion; deterministic guard) --------------
|
# ---- fan-out (the planner's expansion; deterministic guard) --------------
|
||||||
|
|
||||||
@@ -373,6 +396,135 @@ class FloopRun:
|
|||||||
note=(f"partial: {len(nums)} of {len(entity_rows)} values summed"
|
note=(f"partial: {len(nums)} of {len(entity_rows)} values summed"
|
||||||
if partial else ""))
|
if partial else ""))
|
||||||
|
|
||||||
|
def _run_branch(self, spec: BranchSpec) -> None:
|
||||||
|
"""Execute ONE branch to its end, inside this run.
|
||||||
|
|
||||||
|
The branch is a NESTED LOOP SESSION, not a child FloopRun: it
|
||||||
|
swaps the machine's table view (BranchView binds the ambiguous
|
||||||
|
row to this branch's reading, hides other branches' rows) and
|
||||||
|
question stack (the dependent questions re-asked inside this
|
||||||
|
world), runs the same fixed loop, and restores state after.
|
||||||
|
Acquired knowledge (rows) lands in the SHARED table tagged with
|
||||||
|
the branch id; notes and engine_calls accumulate on the run; the
|
||||||
|
budget is the run's own (shared pool — his design: llm_calls
|
||||||
|
pool shared, depth+1 burns the existing depth counter).
|
||||||
|
|
||||||
|
Death: contradiction (a checked arrival refuses the branch's
|
||||||
|
values — the row lands with value UNKNOWN and its questions
|
||||||
|
fail), dead end (the branch's terminal questions all failed),
|
||||||
|
or natural merge (its answer equals an earlier branch's —
|
||||||
|
recorded at survivors()). Never an absurdity judge.
|
||||||
|
"""
|
||||||
|
view = BranchView(self.table, spec)
|
||||||
|
self.streams.warn(
|
||||||
|
f"BRANCH {spec.id} starts: reading '{spec.value[:60]}' "
|
||||||
|
f"(bound from {spec.ambiguous_eid})")
|
||||||
|
main_table, main_stack = self.table, self.stack
|
||||||
|
main_branch = self._current_branch
|
||||||
|
self.table = view # type: ignore[assignment]
|
||||||
|
self._current_branch = spec.id
|
||||||
|
# the branch's stack: the dependent subtree FROZEN at fork time —
|
||||||
|
# the same question set for every branch of the fork (B1 consuming
|
||||||
|
# the originals changed nothing about what B2 copies). Copied
|
||||||
|
# inside this world with BRANCH-SCOPED qids (a collision would make
|
||||||
|
# a copy look already-answered) and deps rewired to the copies.
|
||||||
|
branch_stack = QuestionStack(spec.value)
|
||||||
|
by_orig = {q.qid: q for q in main_stack.items}
|
||||||
|
copies_by_orig: dict[str, str] = {}
|
||||||
|
for orig_qid in spec.subtree_qids:
|
||||||
|
orig = by_orig.get(orig_qid)
|
||||||
|
if orig is None:
|
||||||
|
continue
|
||||||
|
nq = branch_stack.add(OpenQuestion(
|
||||||
|
text=orig.text, answer_type=orig.answer_type,
|
||||||
|
deps=[], reason=f"branch {spec.id} of {orig_qid}"))
|
||||||
|
nq.qid = f"{spec.id}.{orig_qid}"
|
||||||
|
# deps: the ambiguous row is BOUND (present in the view with its
|
||||||
|
# reading fixed — not a dependency anymore); deps on copied
|
||||||
|
# siblings point at the COPIES; deps on other already-answered
|
||||||
|
# questions keep the reference (their rows live in the shared table)
|
||||||
|
nq.deps = [copies_by_orig.get(d, d) for d in orig.deps
|
||||||
|
if d != spec.ambiguous_qid]
|
||||||
|
copies_by_orig[orig_qid] = nq.qid
|
||||||
|
for q in main_stack.items:
|
||||||
|
if q.qid in copies_by_orig:
|
||||||
|
q.status = "answered"
|
||||||
|
q.reason = f"answered by branches over {spec.ambiguous_qid}"
|
||||||
|
self.stack = branch_stack # type: ignore[assignment]
|
||||||
|
try:
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
# NESTED FORK: an ambiguous row inside this branch with
|
||||||
|
# its own dependent opens sub-branches (origin=this
|
||||||
|
# branch); run them to their end before continuing —
|
||||||
|
# the same lazy law, one level deeper.
|
||||||
|
while any(s.origin == spec.id
|
||||||
|
for s in self.branches.pending):
|
||||||
|
sub = next(s for s in self.branches.pending
|
||||||
|
if s.origin == spec.id)
|
||||||
|
self._run_branch(sub)
|
||||||
|
q = self.stack.pickable(self.table)
|
||||||
|
if q is None:
|
||||||
|
if self.stack.all_terminal():
|
||||||
|
break
|
||||||
|
if self.budget.missing_used >= self.budget.missing_extensions:
|
||||||
|
self.notes.append(
|
||||||
|
"missing-extension limit reached inside a branch")
|
||||||
|
break
|
||||||
|
self._missing_round()
|
||||||
|
continue
|
||||||
|
self._route_and_execute(q)
|
||||||
|
except BudgetExhausted:
|
||||||
|
self.notes.append(
|
||||||
|
f"budget exhausted inside branch {spec.id} "
|
||||||
|
f"at llm_calls={self.budget.llm_calls}")
|
||||||
|
break
|
||||||
|
except Exception as e: # noqa: BLE001
|
||||||
|
if _lm_dead(e):
|
||||||
|
self.notes.append(
|
||||||
|
f"LM unreachable inside branch {spec.id}; "
|
||||||
|
f"branch aborted honestly")
|
||||||
|
break
|
||||||
|
raise
|
||||||
|
# the branch's conclusion. A branch whose OWN children
|
||||||
|
# answered carries the CHILDREN's conditional as its answer
|
||||||
|
# (nesting composes); otherwise synthesize from its rows.
|
||||||
|
answer = ""
|
||||||
|
kids = [s for s in self.branches.specs if s.origin == spec.id]
|
||||||
|
if kids and branch_stack.open_count() == 0:
|
||||||
|
answer = self.branches.conditional_answer(self.query, origin=spec.id)
|
||||||
|
if answer and not answer.startswith("No reading"):
|
||||||
|
self.branches.record_answer(spec.id, answer)
|
||||||
|
self.streams.state(
|
||||||
|
f"branch {spec.id} concluded (nested, "
|
||||||
|
f"{len(kids)} sub-branches): {answer[:80]}", think=True)
|
||||||
|
else:
|
||||||
|
self.branches.record_dead(spec.id)
|
||||||
|
self.notes.append(
|
||||||
|
f"branch {spec.id}: dead — no sub-reading survived")
|
||||||
|
elif (branch_stack.open_count() == 0 and branch_stack.items[1:]
|
||||||
|
and any(i.status == "answered"
|
||||||
|
for i in branch_stack.items[1:])):
|
||||||
|
try:
|
||||||
|
self._charge()
|
||||||
|
answer = self.modules.synthesize(
|
||||||
|
self.query, view.dump(), unverified=True)
|
||||||
|
self.branches.record_answer(spec.id, answer)
|
||||||
|
self.streams.state(
|
||||||
|
f"branch {spec.id} concluded: {answer[:80]}", think=True)
|
||||||
|
except (BudgetExhausted, Exception) as e: # noqa: BLE001
|
||||||
|
self.branches.record_dead(spec.id)
|
||||||
|
self.notes.append(f"branch {spec.id}: synthesis failed ({e})")
|
||||||
|
else:
|
||||||
|
self.branches.record_dead(spec.id)
|
||||||
|
self.notes.append(
|
||||||
|
f"branch {spec.id}: dead — no reading survived "
|
||||||
|
f"(all dependents failed)")
|
||||||
|
finally:
|
||||||
|
self.table = main_table
|
||||||
|
self.stack = main_stack
|
||||||
|
self._current_branch = main_branch
|
||||||
|
|
||||||
def _route_and_execute(self, q: OpenQuestion) -> None:
|
def _route_and_execute(self, q: OpenQuestion) -> None:
|
||||||
# SETOP GUARD: a count over list rows already in evidence is
|
# SETOP GUARD: a count over list rows already in evidence is
|
||||||
# computation, not routing — the machine computes it deterministically
|
# computation, not routing — the machine computes it deterministically
|
||||||
@@ -433,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
|
||||||
@@ -512,6 +666,25 @@ class FloopRun:
|
|||||||
f"other readings: " + "; ".join(
|
f"other readings: " + "; ".join(
|
||||||
a.get("value") for a in alts[:3]))
|
a.get("value") for a in alts[:3]))
|
||||||
self.table.append(row)
|
self.table.append(row)
|
||||||
|
# BRANCHING TRIGGER (his design): an ambiguous row with an OPEN
|
||||||
|
# dependent subtree forks the run into one branch per reading —
|
||||||
|
# LAZY (empty subtree: no fork, the ambiguity stays a note, the
|
||||||
|
# pick rides), the subtree FROZEN here so every branch of the
|
||||||
|
# fork copies the same questions (the first branch consuming the
|
||||||
|
# originals must not change what the second copies).
|
||||||
|
if row.payload.get("ambiguous"):
|
||||||
|
subtree = open_subtree(self.stack, q.qid)
|
||||||
|
if subtree:
|
||||||
|
specs = self.branches.fork_specs(
|
||||||
|
row, origin=self._current_branch, subtree_qids=subtree)
|
||||||
|
if specs:
|
||||||
|
self.notes.append(
|
||||||
|
f"{q.qid}: forking {len(specs)} branches over the "
|
||||||
|
f"readings of {row.eid}: "
|
||||||
|
+ "; ".join(f"{s.id}={s.value[:40]}" for s in specs))
|
||||||
|
self.streams.warn(
|
||||||
|
f"FORK {q.qid} over {row.eid}: {len(specs)} readings "
|
||||||
|
f"-> branches {', '.join(s.id for s in specs)}")
|
||||||
if str(row.payload.get("value", "")).strip().upper() == "UNKNOWN":
|
if str(row.payload.get("value", "")).strip().upper() == "UNKNOWN":
|
||||||
q.status = "failed"
|
q.status = "failed"
|
||||||
q.reason = "expert returned UNKNOWN"
|
q.reason = "expert returned UNKNOWN"
|
||||||
@@ -560,21 +733,45 @@ class FloopRun:
|
|||||||
def _finish(self, t0: float) -> RunReport:
|
def _finish(self, t0: float) -> RunReport:
|
||||||
verified = False # STUB prover — v0.2: derivability check (clingo/Z3)
|
verified = False # STUB prover — v0.2: derivability check (clingo/Z3)
|
||||||
answer = ""
|
answer = ""
|
||||||
try:
|
# CLARIFICATION FIRST (his 23/10 run): a run that ASKED THE USER
|
||||||
self._charge()
|
# something ends IN THE QUESTION — composed by fixed code from the
|
||||||
self.streams.call("ANSWER", f"synthesize answer for: {self.query[:80]}",
|
# pending user rows, never by a synthesis prompt reading
|
||||||
think=self.tprefix + "writing the answer from the evidence table")
|
# needs_user_input as plain text and inventing 'the evidence is
|
||||||
answer = self.modules.synthesize(
|
# unknown'. The branch answer handles ambiguity (its readings);
|
||||||
self.query, self.table.dump(), unverified=not verified)
|
# this handles every OTHER honest defer: the machine knows what
|
||||||
|
# it wants to ask — it says so, and only that.
|
||||||
|
pending_user = [r for r in self.table.rows()
|
||||||
|
if r.note == "needs_user_input" and not r.retracted]
|
||||||
|
if self.branches.specs:
|
||||||
|
# CONDITIONAL ANSWER (run L law): several readings survived —
|
||||||
|
# the answer is composed by FIXED CODE from the branch results,
|
||||||
|
# never by one synthesis prompt choosing a reading inside itself.
|
||||||
|
answer = self.branches.conditional_answer(self.query)
|
||||||
self.streams.final(answer)
|
self.streams.final(answer)
|
||||||
except BudgetExhausted:
|
self.notes.append(
|
||||||
self.notes.append("budget died before the answer step")
|
f"conditional answer over {len(self.branches.specs)} branches: "
|
||||||
except Exception as e: # noqa: BLE001 — a dead LM answers nothing
|
+ "; ".join(f"{s.id}={self.branches.results[s.id].status}"
|
||||||
if _lm_dead(e):
|
for s in self.branches.specs))
|
||||||
self.notes.append(f"LM unreachable before synthesis ({type(e).__name__}); "
|
elif pending_user:
|
||||||
"evidence is kept, the answer is not written")
|
answer = self._clarify_answer(pending_user)
|
||||||
else:
|
self.streams.final(answer)
|
||||||
raise
|
self.notes.append("answer: clarification requested from the user")
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
self._charge()
|
||||||
|
self.streams.call("ANSWER", f"synthesize answer for: {self.query[:80]}",
|
||||||
|
think=self.tprefix + "writing the answer from the evidence table")
|
||||||
|
answer = self.modules.synthesize(
|
||||||
|
self.query, self.table.dump(), unverified=not verified)
|
||||||
|
self.streams.final(answer)
|
||||||
|
except BudgetExhausted:
|
||||||
|
self.notes.append("budget died before the answer step")
|
||||||
|
except Exception as e: # noqa: BLE001 — a dead LM answers nothing
|
||||||
|
if _lm_dead(e):
|
||||||
|
self.notes.append(f"LM unreachable before synthesis ({type(e).__name__}); "
|
||||||
|
f"evidence is kept, the answer is not written")
|
||||||
|
else:
|
||||||
|
raise
|
||||||
return RunReport(
|
return RunReport(
|
||||||
goal=self.query, final_answer=answer, verified=verified,
|
goal=self.query, final_answer=answer, verified=verified,
|
||||||
llm_calls=self.budget.llm_calls, engine_calls=self.engine_calls,
|
llm_calls=self.budget.llm_calls, engine_calls=self.engine_calls,
|
||||||
@@ -582,3 +779,41 @@ class FloopRun:
|
|||||||
questions=[(i.qid, i.status, i.text) for i in self.stack.items],
|
questions=[(i.qid, i.status, i.text) for i in self.stack.items],
|
||||||
evidence_rows=self.table.dump().splitlines(),
|
evidence_rows=self.table.dump().splitlines(),
|
||||||
elapsed_s=round(time.time() - t0, 1))
|
elapsed_s=round(time.time() - t0, 1))
|
||||||
|
|
||||||
|
def _clarify_answer(self, pending_user: list[EvidenceRow]) -> str:
|
||||||
|
"""The run ends in its QUESTION to the user, composed by fixed
|
||||||
|
code. Each pending user row carries the instantiated question its
|
||||||
|
ROUTE deferred (the row's qid names the open question); the
|
||||||
|
answer asks them, names what the machine already holds so the
|
||||||
|
user answers with context, and states what was left un-answered.
|
||||||
|
Zero LLM calls — the question text was already composed by the
|
||||||
|
loop; this renders it."""
|
||||||
|
parts: list[str] = []
|
||||||
|
for r in pending_user:
|
||||||
|
q = next((i for i in self.stack.items if i.qid == r.qid), None)
|
||||||
|
qtext = q.text if q is not None else "(deferred question)"
|
||||||
|
# what the machine holds that motivated the ask — the row the
|
||||||
|
# deferring question depended on, rendered plain (value +
|
||||||
|
# ambiguity note when present)
|
||||||
|
context = ""
|
||||||
|
if q is not None:
|
||||||
|
for d in q.deps:
|
||||||
|
for dep in self.table.for_question(d):
|
||||||
|
val = str(dep.payload.get("value", ""))
|
||||||
|
if not val or val.upper() == "UNKNOWN":
|
||||||
|
continue
|
||||||
|
if dep.payload.get("ambiguous"):
|
||||||
|
alts = dep.payload.get("alternatives") or []
|
||||||
|
others = " / ".join(
|
||||||
|
a.get("value", "") for a in alts[:3])
|
||||||
|
context = (f" (so far: {val} — but other "
|
||||||
|
f"defensible readings exist: {others})")
|
||||||
|
else:
|
||||||
|
context = f" (so far: {val})"
|
||||||
|
break
|
||||||
|
if context:
|
||||||
|
break
|
||||||
|
parts.append(f"I need to ask you: {qtext}{context}")
|
||||||
|
if len(parts) == 1:
|
||||||
|
return parts[0]
|
||||||
|
return "I need to ask you a few things: " + " | ".join(parts)
|
||||||
@@ -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]
|
||||||
+26
-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,26 +68,47 @@ 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)
|
||||||
|
|
||||||
|
def warn(self, text: str) -> None:
|
||||||
|
"""A machine judgement worth a human's eye even non-verbose:
|
||||||
|
the seed that auto-answered a question, a guard refusing an
|
||||||
|
ingest, a budget starvation. Self-improvement signal (META.md):
|
||||||
|
the offline analysis counts these first. Log always; screen
|
||||||
|
ALWAYS (unlike thinking, the [W] line is the point)."""
|
||||||
|
self._emit_log(f"WARNING {text}")
|
||||||
|
print(f"[W] {text}", flush=True)
|
||||||
|
|
||||||
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))
|
||||||
@@ -118,8 +118,13 @@ One routed knowledge question = one internal pipeline run, bounded by budget:
|
|||||||
```
|
```
|
||||||
question instantiate (already done by the machine)
|
question instantiate (already done by the machine)
|
||||||
│
|
│
|
||||||
▼ TRANSLATE (LLM): question + answer_type → retrieval focus:
|
▼ COMPOSE (engine, 23/10 — the old TRANSLATE LLM removed): question ∪
|
||||||
│ keywords, entry entities, what shape of fact closes the gap
|
│ evidence → queries + entity terms. Every token traces to the
|
||||||
|
│ question or an evidence row; the model's own knowledge of the
|
||||||
|
│ entities can no longer steer retrieval (it was putting the
|
||||||
|
│ ANSWER into queries). Top-N asks slice the first N evidence
|
||||||
|
│ members by source order; enumerations get the list-article
|
||||||
|
│ shape ('List of rivers of Italy').
|
||||||
▼ KG PROBE (engine): BFS from seeds → candidate edges + linked quotes
|
▼ KG PROBE (engine): BFS from seeds → candidate edges + linked quotes
|
||||||
│ gap report: is the question's answer_type coverable from what's found?
|
│ gap report: is the question's answer_type coverable from what's found?
|
||||||
│ YES → skip gather, go to SELECT
|
│ YES → skip gather, go to SELECT
|
||||||
@@ -135,10 +140,14 @@ question instantiate (already done by the machine)
|
|||||||
▼ return: top-k rows payload {quote, url, access_date, kg_corroboration}
|
▼ return: top-k rows payload {quote, url, access_date, kg_corroboration}
|
||||||
```
|
```
|
||||||
|
|
||||||
LLM calls: TRANSLATE, EXTRACT-per-chunk (+ retries), and nothing else — the
|
LLM calls: EXTRACT-per-chunk (+ retries), SELECT TABLE (lists), VERIFY
|
||||||
probe, search, chunking, checking, merging, selecting are all engines. That is
|
COUNT, SKIM PROMOTE, and ANSWER — and nothing else. The query
|
||||||
the law compliance: the LLM translates; deterministic code decides what is
|
composition, probe, search, chunking, checking, merging, selecting are
|
||||||
valid, what is dedupe, what is ranked.
|
all engines. That is the law compliance: the LLM translates; deterministic
|
||||||
|
code decides what is valid, what is dedupe, what is ranked — and since
|
||||||
|
23/10 even the retrieval focus is code (the old TRANSLATE LLM became
|
||||||
|
`knowledge/queries.py`: every query token traces to question ∪ evidence,
|
||||||
|
so no model weight ever steers retrieval).
|
||||||
|
|
||||||
## 5. Context budget & chunking (the 16–32k constraint)
|
## 5. Context budget & chunking (the 16–32k constraint)
|
||||||
|
|
||||||
@@ -307,9 +316,10 @@ against the stored table text — the same string the parser produced — so the
|
|||||||
check stays verbatim and deterministic. The wikitext raw form is kept in the
|
check stays verbatim and deterministic. The wikitext raw form is kept in the
|
||||||
document artifact for audit.
|
document artifact for audit.
|
||||||
|
|
||||||
**Budget law in the LIST path.** TRANSLATE + SELECT TABLE are the only LLM
|
**Budget law in the LIST path.** SELECT TABLE (and the optional VERIFY
|
||||||
calls (2 + retries); ingestion and aggregation are free. A 500-row table
|
COUNT) are the only LLM calls; ingestion and aggregation are free (the
|
||||||
costs the same LLM budget as a 5-row one — the cost of an enumeration is
|
query composition is engine since 23/10). A 500-row table costs the
|
||||||
|
same LLM budget as a 5-row one — the cost of an enumeration is
|
||||||
O(1) in the size of the list.
|
O(1) in the size of the list.
|
||||||
|
|
||||||
## 12. Answer-level verification — the CHECK step for answers (2026-10-19)
|
## 12. Answer-level verification — the CHECK step for answers (2026-10-19)
|
||||||
|
|||||||
@@ -97,9 +97,118 @@ rows were never extracted".
|
|||||||
the third (strictness with "as President") lives in the judge by
|
the third (strictness with "as President") lives in the judge by
|
||||||
agreement.
|
agreement.
|
||||||
|
|
||||||
|
## Findings from the live E2E (23/10, glm-5.3-flash, this branch)
|
||||||
|
|
||||||
|
- MACHINERY LIVE AND WORKING: semantic probe fires ("+1 edges the
|
||||||
|
lexical probe missed"), blind extractor ingests fat entity facts
|
||||||
|
(12-fact chunks), vectors cache, hybrid dedup clean, table skim runs.
|
||||||
|
- PEDRO RUN — a reading trap, NOT a retrieval failure: the KG held the
|
||||||
|
right facts, but the top search hit was 'Third government of Pedro
|
||||||
|
Sánchez' and the judge answered the LITERAL question: the 3rd
|
||||||
|
government succeeded the 2nd Sánchez government, so "immediately
|
||||||
|
before this term" = Sánchez himself. The Pedro Sánchez article (with
|
||||||
|
the Rajoy motion-of-no-confidence sentence) was in the fetch order
|
||||||
|
but the early exit at the first article starved it. ALSO: INIT
|
||||||
|
returned garbage this run ("no parseable subquestions from 3 chars")
|
||||||
|
and the honest degrade routed the ORIGINAL question — worked, but
|
||||||
|
the INIT raw should be watched (model flakiness, not code).
|
||||||
|
- RIVERS RUN — BUDGET DEATH BY FAN-OUT, not by this PR: the Q1 LIST
|
||||||
|
path worked perfectly (22 members ingested from the right table).
|
||||||
|
But the planner expanded 'length of each' into 22 entity questions
|
||||||
|
and EVERY child paid ROUTE + answer_kg (44 calls) for data the
|
||||||
|
parent's table already held; the join (top-3) never ran. Fix
|
||||||
|
candidates (machine-level, next on this branch): (a) fan-out
|
||||||
|
children inherit the parent's engine (zero ROUTE), (b) the fan-out
|
||||||
|
attribute question checks the KG first (the LIST ingest usually
|
||||||
|
wrote the members as edges), (c) cap entity questions per fan-out.
|
||||||
|
- COST NOTE: question-blind extraction is slower per chunk (more facts
|
||||||
|
ingested, each vector-cached: one HTTP call per edge at ingest —
|
||||||
|
batching pending). No 22k-char hangs, no STOP confusion, logs clean.
|
||||||
|
|
||||||
## What stays untouched
|
## What stays untouched
|
||||||
|
|
||||||
- The mask/ablation audit (dst-first law, run-L fix) — it gains signal.
|
- The mask/ablation audit (dst-first law, run-L fix) — it gains signal.
|
||||||
- Anonymization before INIT (PR-16/17) — orthogonal.
|
- Anonymization before INIT (PR-16/17) — orthogonal.
|
||||||
- The branching design — still pending discussion; this branch may
|
- The branching design — still pending discussion; this branch may
|
||||||
feed it better questions, but does not implement it.
|
feed it better questions, but does not implement it.
|
||||||
|
|
||||||
|
## Findings from the live A/B and the (K5) bug (24–25/10, glm-5.3-flash)
|
||||||
|
|
||||||
|
**The A/B he asked for** (his question, cold KG both sides, dspy disk
|
||||||
|
cache deleted per run):
|
||||||
|
|
||||||
|
- glm-5.3-flash (cloud, cold KG): Rajoy, correct, 28 calls, 148 s.
|
||||||
|
- qwen3.8-27b (his PC via the house router, cold KG): honest UNKNOWN,
|
||||||
|
33 calls, 3,025 s. The KG HELD Rajoy (K12 "Rajoy recommended Sánchez
|
||||||
|
as his successor") — the judge lost it to a noise row ("ninth
|
||||||
|
president of Socialist International" made it read "that specific
|
||||||
|
presidency" as the SI).
|
||||||
|
- Warm-KG glm answered "Sánchez himself" (the third-succeeded-second
|
||||||
|
reading trap). Substrate state weighs as much as the model.
|
||||||
|
- Cloud is non-deterministic at temperature 0: identical INIT prompt,
|
||||||
|
two different decompositions (2 vs 3 subquestions) across runs.
|
||||||
|
- MEASUREMENT NOTE (both A/B sides): dspy.LM defaults cache=True and
|
||||||
|
persists to ~/.dspy_cache ACROSS processes and days, keyed on the
|
||||||
|
request (model+prompt+params, not base_url). A repeated question is
|
||||||
|
a byte-identical REPLAY wearing inference's clothes (0.4 s "runs").
|
||||||
|
Proven by curl (server does not cache) and by running the whole app
|
||||||
|
in an isolated netns (unshare -rn) — it completed with no network.
|
||||||
|
HIS RULING (25/10): NOT a bug — caching doing its job; the CLI gains
|
||||||
|
a --no-cache flag for test runs, the default stays. Until that flag
|
||||||
|
exists: rm -rf ~/.dspy_cache before any run that must be fresh.
|
||||||
|
|
||||||
|
**The (K5) bug — the audit's silent death** (run 085457):
|
||||||
|
|
||||||
|
- glm answered Q1 ("which country or organization was he President
|
||||||
|
of?") with value="Socialist International (K5)" — the row-id glued
|
||||||
|
to the value, because AnswerFromKG says "cite rows by id" but has NO
|
||||||
|
citation output field. The judge sees K{i} ids (positional
|
||||||
|
enumerate indices over the probe's view — NOT store keys), so it
|
||||||
|
cites in the only field it has.
|
||||||
|
- _audit_ambiguity's _carries looks for the value inside row dsts:
|
||||||
|
"socialist international (k5)" is in no dst → support = [] → "the
|
||||||
|
judge invented it: nothing to ablate" → silent return. The audit
|
||||||
|
never runs. Repro on the warm KG: raw value → no audit; cleaned
|
||||||
|
value ("Socialist International") → ambiguous=True with Spain
|
||||||
|
alternatives (two rounds). The detector works; the interface kills
|
||||||
|
it. Value contamination is systematic with glm-5.3-flash, three
|
||||||
|
observed shapes: "(K5)" suffix, parenthetical reasoning ("2018
|
||||||
|
(Pedro Sánchez has been Prime Minister … cited from rows K16 and
|
||||||
|
K30)"), and a DATE question answered "15 (list of 15 members: …)"
|
||||||
|
via the LIST path.
|
||||||
|
- SECOND violation: pred.value.strip() enters the evidence payload
|
||||||
|
untyped — "typed payloads, never LLM prose" broken at the same spot.
|
||||||
|
- FIX DIRECTION (agreed, not yet coded): clean at the judge's output
|
||||||
|
boundary (_answer_from_rows), regex-anchored to trailing
|
||||||
|
row-citation shapes only ( "(PSOE)" inside a name is legitimate and
|
||||||
|
must survive).
|
||||||
|
|
||||||
|
**Run 090402 — the branch's own machinery, live and green:**
|
||||||
|
|
||||||
|
- Semantic probe live via VPS-local nomic-embed-text (his PC was down;
|
||||||
|
the house router had cloud-failovered and ollama.com has NO
|
||||||
|
embeddings API — same model pulled locally, identical vectors,
|
||||||
|
tau=0.45 calibration holds). "+9/+11 edges the lexical probe missed"
|
||||||
|
on both subquestions; final Rajoy correct.
|
||||||
|
- 0 AMBIGUOUS is CORRECT for this run: INIT decomposed to 2 subqs
|
||||||
|
(term-start → predecessor) and never asked "of what", so no scalar
|
||||||
|
answer ever faced the three readings. The ambiguity needs either
|
||||||
|
the "of what" subquestion or the conflicts-table signal (below).
|
||||||
|
- INFRA PITFAL: the code venv carries an editable-install pth that
|
||||||
|
pins imports to MAIN's tree — a PYTHONPATH shim that imported
|
||||||
|
knowledge.expert silently resolved to main and ran main's pipeline
|
||||||
|
inside the branch worktree (run 085457 was main code with the
|
||||||
|
branch's config; its "compose -> queries" line is main's
|
||||||
|
deterministic composer). Always assert the resolved module path
|
||||||
|
when running branch code with the shared venv.
|
||||||
|
|
||||||
|
**The conflicts inventory (20 pairs in the live KG, ZERO real
|
||||||
|
contradictions):** 10 same-quote "called for" (co-asserted
|
||||||
|
conjunction, one platform sentence split into 5 triples), 5
|
||||||
|
cross-quote "called for" (a multi-valued relation), 3 "position held"
|
||||||
|
(THE THREE PRESIDENCIES, pairwise — the polisèmia sitting in the
|
||||||
|
store since ingest), 1 "became" (temporal: 2014 vs 2018 live in the
|
||||||
|
quotes, ref_date empty), 1 "re-elected as" (entity-diff PSOE/PM).
|
||||||
|
The taxonomy, the temporal representation, and the answer engine that
|
||||||
|
consumes all of this are designed in RESEARCH-derived-answers.md (this
|
||||||
|
branch, same session).
|
||||||
@@ -42,4 +42,11 @@ def check_candidate(cand: dict, full_text: str) -> tuple[bool, str]:
|
|||||||
subj, rel, obj = cand.get("subject", ""), cand.get("relation", ""), cand.get("object", "")
|
subj, rel, obj = cand.get("subject", ""), cand.get("relation", ""), cand.get("object", "")
|
||||||
if not (subj and rel and obj):
|
if not (subj and rel and obj):
|
||||||
return False, "incomplete triple"
|
return False, "incomplete triple"
|
||||||
|
# phase 2: temporal restrictions are quotable — every stated date must
|
||||||
|
# be CONTAINED IN THE QUOTE (an invented date rejects the candidate;
|
||||||
|
# the model proposes, code verifies against the source surface)
|
||||||
|
for field in ("start", "end", "point"):
|
||||||
|
val = (cand.get(field) or "").strip()
|
||||||
|
if val and val not in quote:
|
||||||
|
return False, f"temporal {field} not in quote"
|
||||||
return True, "ok"
|
return True, "ok"
|
||||||
@@ -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
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+520
-217
@@ -1,7 +1,7 @@
|
|||||||
"""The knowledge expert pipeline: KG-first, gather on gap, containment-checked.
|
"""The knowledge expert pipeline: KG-first, gather on gap, containment-checked.
|
||||||
|
|
||||||
Per question (one routed knowledge call):
|
Per question (one routed knowledge call):
|
||||||
1. TRANSLATE: question -> search queries + resolved entities [LLM, cheap]
|
1. COMPOSE: question + evidence -> queries/entities (deterministic) [engine]
|
||||||
2. KG PROBE: hybrid — lexical seeds UNION semantic rank (embeddings)[engine]
|
2. KG PROBE: hybrid — lexical seeds UNION semantic rank (embeddings)[engine]
|
||||||
3. gap? -> SEARCH en.wikipedia (official search) [engine]
|
3. gap? -> SEARCH en.wikipedia (official search) [engine]
|
||||||
4. FETCH top articles, CHUNK by sections; TABLE SKIM decides which
|
4. FETCH top articles, CHUNK by sections; TABLE SKIM decides which
|
||||||
@@ -25,20 +25,63 @@ import time
|
|||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
|
|
||||||
import dspy
|
import dspy
|
||||||
|
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, ExtractSignature, Fact, SelectTableSignature,
|
from .extract import (AnswerFromKG, ExtractClaims, ExtractSignature, Fact,
|
||||||
SkimPromoteSignature, SkimTableSignature,
|
SelectTableSignature, SkimPromoteSignature,
|
||||||
TranslateSignature, VerifyCountSignature)
|
SkimTableSignature, TypeClaim, VerifyCountSignature)
|
||||||
from .embeddings import EmbedderDown, embed
|
from .embeddings import EmbedderDown, cosine, embed
|
||||||
|
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 .wiki import (WikipediaClient, WikiPage, WikiTable, resolve_convert,
|
from .two_pass import claims_from, fact_from_claim
|
||||||
|
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']+")
|
||||||
|
|
||||||
|
# (K5) bug (run 085457, 24-25/10): glm-5.3-flash glues row citations and
|
||||||
|
# glosses onto the value field (AnswerFromKG says "cite rows by id" but has
|
||||||
|
# no citation output field, so the model cites in the only field it has).
|
||||||
|
# Three live shapes, stripped at the judge's output boundary — BEFORE the
|
||||||
|
# evidence payload and the ablation audit see the value:
|
||||||
|
# "... (K5)" — row-id citation suffix
|
||||||
|
# "... (…; cited from rows K16 and K30)" — parenthetical gloss citing rows
|
||||||
|
# "15 (list of 15 members: …)" — the LIST path's own gloss of a count
|
||||||
|
# Trailing-only, marker-anchored: "(PSOE)" inside a name, "(since 2018)",
|
||||||
|
# "(Presidente del Gobierno)" are legitimate and MUST survive. Fixed code
|
||||||
|
# cleans the model's proposal (LLMs propose, code decides — the audit's
|
||||||
|
# _carries then finds the support rows and the ambiguity audit can run).
|
||||||
|
_ROW_CITATION_RE = re.compile(
|
||||||
|
r"\s*\(\s*(?:row\s+|rows\s+)?K\d+(?:\s*(?:,|and|;)\s*K?\d+)*\s*\)\s*$",
|
||||||
|
re.IGNORECASE)
|
||||||
|
_ROW_CITED_GLOSS_RE = re.compile(
|
||||||
|
r"\s*\([^()]*\bcited from (?:row|rows)\b[^()]*\)\s*$",
|
||||||
|
re.IGNORECASE)
|
||||||
|
_LIST_GLOSS_RE = re.compile(
|
||||||
|
r"\s*\(\s*list of\b[^()]*\)\s*$",
|
||||||
|
re.IGNORECASE)
|
||||||
|
|
||||||
|
|
||||||
|
def _clean_value(value: str) -> str:
|
||||||
|
"""Strip trailing citation/gloss parentheticals from a judge value.
|
||||||
|
|
||||||
|
The boundary law: only TRAILING shapes with a citation/list marker are
|
||||||
|
touched; mid-value text and legitimate parentheticals are the model's
|
||||||
|
own words and stay. Idempotent by construction (a cleaned value ends
|
||||||
|
clean). UNKNOWN and empty pass through untouched.
|
||||||
|
"""
|
||||||
|
v = (value or "").strip()
|
||||||
|
if not v or v.upper() == "UNKNOWN":
|
||||||
|
return v
|
||||||
|
for rx in (_ROW_CITATION_RE, _ROW_CITED_GLOSS_RE, _LIST_GLOSS_RE):
|
||||||
|
v = rx.sub("", v).rstrip()
|
||||||
|
return v.strip()
|
||||||
|
|
||||||
|
|
||||||
# header/caption terms that name the ENTITY column of a typical scalar table
|
# header/caption terms that name the ENTITY column of a typical scalar table
|
||||||
_ENTITY_COL = ("river", "country", "name", "state", "city", "entity", "member")
|
_ENTITY_COL = ("river", "country", "name", "state", "city", "entity", "member")
|
||||||
|
|
||||||
@@ -96,16 +139,31 @@ def _prop_hit(prop: str, toks: set[str]) -> bool:
|
|||||||
|
|
||||||
|
|
||||||
def _proper_nouns(question: str) -> set[str]:
|
def _proper_nouns(question: str) -> set[str]:
|
||||||
"""Capitalized non-question words: 'Italy', 'Po' — the SUBJECT of the
|
"""The subject guard's noun extractor — delegates to knowledge/queries.py
|
||||||
question. The definitive guard for 'which are the three longest rivers
|
(single source: the query composer and the guards share the NE law).
|
||||||
of Italy?' never accepting a world table (run H: Q1 answered Nile/
|
Semantics unchanged: capitalized non-question words ('Italy', 'Po')."""
|
||||||
Amazon/Yangtze because the top search hit was the world list and the
|
return proper_nouns(question)
|
||||||
disjointness guard was vacuous — no evidence, nothing to check)."""
|
|
||||||
words = re.findall(r"[A-Z][a-zÀ-ÿ]+(?:'[A-Za-z]+)?", question or "")
|
|
||||||
stops = {"What", "Which", "Who", "When", "Where", "Why", "How", "The",
|
def _probe_seeds(kws: list[str], evidence: str) -> list[str]:
|
||||||
"Is", "Are", "Was", "Were", "In", "On", "At", "For", "Of",
|
"""Augment keywords with short values from the parent's evidence."""
|
||||||
"Their", "Its", "Those", "These", "That", "This"}
|
seeds = list(kws)
|
||||||
return {w for w in words if w not in stops}
|
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
|
||||||
@@ -128,6 +186,13 @@ class KnowledgeConfig:
|
|||||||
semantic_tau: float = 0.45 # calibration: rivers 0.49-0.52 in, Pedro
|
semantic_tau: float = 0.45 # calibration: rivers 0.49-0.52 in, Pedro
|
||||||
# cross-question 0.35-0.38 out, spouse-noise ~0.67
|
# cross-question 0.35-0.38 out, spouse-noise ~0.67
|
||||||
max_facts_per_chunk: int = 12 # question-blind extraction needs a cap
|
max_facts_per_chunk: int = 12 # question-blind extraction needs a cap
|
||||||
|
max_claims_per_chunk: int = 6 # DEPRECATED (owner ruling 26/10:
|
||||||
|
# completeness beats budget) — no longer
|
||||||
|
# read by the two-pass loop; kept only for
|
||||||
|
# the table-frags legacy path
|
||||||
|
extract_mode: str = "two_pass" # "two_pass" (claims -> typed Facts, short
|
||||||
|
# outputs) | "single" (legacy one-call typed
|
||||||
|
# array — table frags keep using it)
|
||||||
|
|
||||||
|
|
||||||
class KnowledgeExpert:
|
class KnowledgeExpert:
|
||||||
@@ -140,13 +205,14 @@ class KnowledgeExpert:
|
|||||||
self.store = store or KnowledgeStore(self.cfg.kb_path)
|
self.store = store or KnowledgeStore(self.cfg.kb_path)
|
||||||
self.client = client or WikipediaClient()
|
self.client = client or WikipediaClient()
|
||||||
self.streams = streams
|
self.streams = streams
|
||||||
self.extract = dspy.Predict(ExtractSignature)
|
self.extract = predict(ExtractSignature)
|
||||||
self.answer = dspy.Predict(AnswerFromKG)
|
self.claims = predict(ExtractClaims)
|
||||||
self.translate = dspy.Predict(TranslateSignature)
|
self.typeclaim = predict(TypeClaim)
|
||||||
self.select_table = dspy.Predict(SelectTableSignature)
|
self.answer = predict(AnswerFromKG)
|
||||||
self.verify_count = dspy.Predict(VerifyCountSignature)
|
self.select_table = predict(SelectTableSignature)
|
||||||
self.skim_promote = dspy.Predict(SkimPromoteSignature)
|
self.verify_count = predict(VerifyCountSignature)
|
||||||
self.skim_tables = dspy.Predict(SkimTableSignature)
|
self.skim_promote = predict(SkimPromoteSignature)
|
||||||
|
self.skim_tables = predict(SkimTableSignature)
|
||||||
self._checked = 0
|
self._checked = 0
|
||||||
self._merged = 0
|
self._merged = 0
|
||||||
# semantic probe: cached question vector for this call (the probe
|
# semantic probe: cached question vector for this call (the probe
|
||||||
@@ -165,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)."""
|
||||||
@@ -191,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
|
||||||
@@ -206,20 +287,17 @@ 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
|
||||||
def _keywords(question: str, k: int = 6) -> list[str]:
|
def _keywords(question: str, k: int = 6) -> list[str]:
|
||||||
"""Deterministic lexical focus: content words of the question (draft)."""
|
"""Deterministic lexical focus — delegates to knowledge/queries.py
|
||||||
stops = {"what", "which", "who", "when", "where", "is", "are", "was", "were",
|
(single source: the probe seeds and the query composer share the
|
||||||
"the", "of", "in", "on", "at", "a", "an", "and", "or", "to", "for",
|
same keyword law)."""
|
||||||
"does", "do", "did", "by", "its", "it", "that", "this", "most", "second"}
|
return keywords(question, k)
|
||||||
words = [w.lower() for w in WORD_RE.findall(question)]
|
|
||||||
seen: list[str] = []
|
|
||||||
for w in words:
|
|
||||||
if w not in stops and len(w) > 2 and w not in seen:
|
|
||||||
seen.append(w)
|
|
||||||
return seen[:k]
|
|
||||||
|
|
||||||
def _set_gate_hit(self, probe_seeds: list[str], question: str) -> str | None:
|
def _set_gate_hit(self, probe_seeds: list[str], question: str) -> str | None:
|
||||||
"""The membership set (if any) this question may be served from.
|
"""The membership set (if any) this question may be served from.
|
||||||
@@ -249,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,
|
||||||
@@ -261,6 +343,132 @@ class KnowledgeExpert:
|
|||||||
"ranked": ordered}}
|
"ranked": ordered}}
|
||||||
|
|
||||||
# ---- the pipeline --------------------------------------------------------
|
# ---- the pipeline --------------------------------------------------------
|
||||||
|
def _prover_answer(self, question: str, charge_llm=None) -> dict | None:
|
||||||
|
"""The derived-answer path (phase 3b): translate -> validate ->
|
||||||
|
evaluate -> re-execute. Returns the answer dict with the proof
|
||||||
|
term, or None to fall back to the judge.
|
||||||
|
|
||||||
|
The laws, end to end: the LLM only TRANSLATES (one structured
|
||||||
|
call, the store's relation vocabulary in); the term is validated
|
||||||
|
BEFORE evaluation (a mistranslation is an invalid term, never a
|
||||||
|
wrong answer); the proof's steps name every edge; re-execution
|
||||||
|
IS the check (verified=True with a real prover, not a flag);
|
||||||
|
multi-binding returns the SET with ambiguous=True — the three
|
||||||
|
readings surface as what they are, deterministically.
|
||||||
|
"""
|
||||||
|
from .prover import evaluate, re_execute, validate_query
|
||||||
|
from .translate_dsl import TranslateToDSL
|
||||||
|
if not hasattr(self, "translate_dsl"):
|
||||||
|
self.translate_dsl = predict(TranslateToDSL)
|
||||||
|
rels = [r[0] for r in self.store.db.execute(
|
||||||
|
"SELECT DISTINCT rel FROM edges WHERE retracted=0 "
|
||||||
|
"ORDER BY rel LIMIT 200").fetchall()]
|
||||||
|
if not rels:
|
||||||
|
return None
|
||||||
|
if charge_llm:
|
||||||
|
charge_llm()
|
||||||
|
try:
|
||||||
|
pred = self.translate_dsl(question=question,
|
||||||
|
relations=", ".join(rels))
|
||||||
|
except Exception as e: # noqa: BLE001 — translation failure = fallback
|
||||||
|
self._log(f"translate-to-DSL failed ({e!r}); judge path", think=True)
|
||||||
|
return None
|
||||||
|
q = getattr(pred, "query", None)
|
||||||
|
if not q:
|
||||||
|
return None # the model honestly declined
|
||||||
|
ok, reason = validate_query(q)
|
||||||
|
if not ok:
|
||||||
|
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
|
||||||
|
proof = evaluate(self.store, q)
|
||||||
|
if not proof.bindings:
|
||||||
|
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
|
||||||
|
if not re_execute(self.store, q, proof):
|
||||||
|
self._log("prover: re-execution mismatch (store changed?); judge path",
|
||||||
|
think=True)
|
||||||
|
self._rec("prover.done", q=question[:80],
|
||||||
|
verdict="reexecution_mismatch", dsl=q)
|
||||||
|
return None
|
||||||
|
vals = []
|
||||||
|
quote = ""
|
||||||
|
url = ""
|
||||||
|
for b in proof.bindings:
|
||||||
|
v = next((bv["value"] for k, bv in b.items()
|
||||||
|
if isinstance(bv, dict) and bv.get("value")), None)
|
||||||
|
if v:
|
||||||
|
vals.append(v)
|
||||||
|
if not quote:
|
||||||
|
eid = next((bv["eid"] for k, bv in b.items()
|
||||||
|
if isinstance(bv, dict) and bv.get("eid")), None)
|
||||||
|
if eid:
|
||||||
|
row = self.store.db.execute(
|
||||||
|
"SELECT q.verbatim, q.url FROM quotes q "
|
||||||
|
"JOIN edges e ON e.quote_id=q.id WHERE e.id=?",
|
||||||
|
(eid,)).fetchone()
|
||||||
|
if row:
|
||||||
|
quote, url = row
|
||||||
|
n = len(vals)
|
||||||
|
if n == 1:
|
||||||
|
answer = {"value": vals[0], "quote": quote, "url": url,
|
||||||
|
"source": "derived_proof", "confidence": "high",
|
||||||
|
"verified": True, "proof": proof}
|
||||||
|
else:
|
||||||
|
answer = {"value": "; ".join(vals), "quote": quote, "url": url,
|
||||||
|
"source": "derived_proof", "confidence": "high",
|
||||||
|
"verified": True, "proof": proof,
|
||||||
|
"ambiguous": True,
|
||||||
|
"axis": f"which reading of '{question[:60]}'?",
|
||||||
|
"alternatives": [{"value": v, "quote": quote, "url": url}
|
||||||
|
for v in vals]}
|
||||||
|
self._log(f"prover: closed path ({n} binding(s): "
|
||||||
|
f"{'; '.join(v[:40] for v in vals[:3])}) — no judge call",
|
||||||
|
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
|
||||||
|
|
||||||
|
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:
|
||||||
@@ -269,48 +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()
|
||||||
context = (f"Original question: {parent_question}" if parent_question else "")
|
|
||||||
if evidence:
|
|
||||||
context += (chr(10) * 2 if context else "") + f"Evidence:\n{evidence}"
|
|
||||||
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
|
||||||
# per-CALL skim state (PR-3): notices for the machine + ambiguous
|
proven = self._try_prover_answer(question, charge_llm)
|
||||||
# leads pending the bounded promotion decision
|
if proven is not None:
|
||||||
self._skim_notices: list[str] = []
|
return proven
|
||||||
self._skim_leads: list[tuple[WikiPage, object]] = []
|
|
||||||
ev_entities = [e for e in self._expected_entities(evidence or "")][:8]
|
self._prepare_gather_state()
|
||||||
# the extractor's ENTITIES (research/semantic-kg): TRANSLATE resolves
|
ev_entities = self._expected_entities(evidence or "")[:8]
|
||||||
# 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:
|
||||||
@@ -324,157 +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. TRANSLATE (LLM) first: the question becomes
|
def _search_articles(self, question: str, ev_entities: list[str],
|
||||||
# entity-first Wikipedia queries — deterministic keywords alone surface
|
list_mode: bool) -> list[str]:
|
||||||
# list articles and miss demographics pages.
|
"""Compose and search all queries before globally ranking candidates."""
|
||||||
if charge_llm:
|
queries, entity_terms = compose_queries(
|
||||||
charge_llm()
|
question, evidence_entities=ev_entities, list_mode=list_mode)
|
||||||
pred = self.translate(question=question, context=context)
|
self._rec("fn.done", fn="compose",
|
||||||
queries = [q.strip() for q in (pred.queries or []) if q.strip()][:2]
|
in_={"question": question, "evidence_entities": ev_entities,
|
||||||
if not queries:
|
"list_mode": list_mode},
|
||||||
queries = [" ".join(kws[:3])]
|
out_={"queries": queries, "entities": entity_terms})
|
||||||
entity_terms = [t.strip() for t in (pred.entities or []) if t.strip()][:4]
|
|
||||||
# the extractor's entities: TRANSLATE's resolved names + evidence
|
|
||||||
# entities + (fallback) the question's proper nouns — the
|
|
||||||
# question-blind extractor transcribes facts about THESE
|
|
||||||
self._extract_entities = list(dict.fromkeys(
|
self._extract_entities = list(dict.fromkeys(
|
||||||
e for e in (entity_terms + ev_entities
|
e for e in (entity_terms + sorted(_proper_nouns(question))) if e))
|
||||||
+ sorted(_proper_nouns(question))) if e))
|
self._log(f"compose -> queries {queries} entities {entity_terms}",
|
||||||
self._log(f"translate -> 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."""
|
||||||
@@ -765,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),
|
||||||
@@ -904,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:
|
||||||
@@ -965,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
|
||||||
@@ -1003,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
|
||||||
@@ -1052,12 +1284,55 @@ class KnowledgeExpert:
|
|||||||
think=True)
|
think=True)
|
||||||
extracted = 0
|
extracted = 0
|
||||||
for chunk in capped:
|
for chunk in capped:
|
||||||
|
if self.cfg.extract_mode == "two_pass":
|
||||||
|
# two-pass (26/10): Pass 1 claims (short strings, coref
|
||||||
|
# resolved), Pass 2 one typed Fact per claim — every
|
||||||
|
# output short; the giant typed array is gone from prose.
|
||||||
|
claims = claims_from(self, entities=ent_str,
|
||||||
|
heading=chunk.heading_path,
|
||||||
|
text=chunk.text, charge_llm=charge_llm)
|
||||||
|
self._rec("claims.done", page=page.title,
|
||||||
|
heading=chunk.heading_path,
|
||||||
|
out_={"n_claims": len(claims),
|
||||||
|
"claims": list(claims)})
|
||||||
|
# owner ruling 26/10: completeness beats budget — every
|
||||||
|
# unique claim gets its TYPE call (no cap, dedup only)
|
||||||
|
for claim in claims:
|
||||||
|
fact = fact_from_claim(self, claim, text=chunk.text,
|
||||||
|
charge_llm=charge_llm)
|
||||||
|
self._rec("type.done", page=page.title, claim=claim[:200],
|
||||||
|
out_={"fact": getattr(fact, "__dict__", None)}
|
||||||
|
if fact is not None else {"fact": None})
|
||||||
|
if fact is None:
|
||||||
|
continue # honestly declined: no invention
|
||||||
|
merged, _eid = self._ingest_candidate(
|
||||||
|
fact, page, containment=page.text)
|
||||||
|
extracted += merged
|
||||||
|
continue
|
||||||
if charge_llm:
|
if charge_llm:
|
||||||
charge_llm()
|
charge_llm()
|
||||||
raw = self.extract(entities=ent_str, heading=chunk.heading_path,
|
raw = self.extract(entities=ent_str, heading=chunk.heading_path,
|
||||||
text=chunk.text)
|
text=chunk.text)
|
||||||
|
# phase 2: ingest with order assertions — fact_ids collects the
|
||||||
|
# edge id per 0-based position in THIS extraction's facts list,
|
||||||
|
# so 'orders' sibling references resolve to real edges
|
||||||
|
fact_ids: list[int | None] = []
|
||||||
for cand in (raw.facts or [])[: self.cfg.max_facts_per_chunk]:
|
for cand in (raw.facts or [])[: self.cfg.max_facts_per_chunk]:
|
||||||
extracted += self._ingest_candidate(cand, page, containment=page.text)
|
merged, eid = self._ingest_candidate(cand, page, containment=page.text)
|
||||||
|
extracted += merged
|
||||||
|
fact_ids.append(eid)
|
||||||
|
# second pass: the order assertions of all facts of this chunk
|
||||||
|
for cand, fid in zip((raw.facts or [])[: self.cfg.max_facts_per_chunk], fact_ids):
|
||||||
|
if fid is None:
|
||||||
|
continue
|
||||||
|
for o in (getattr(cand, "orders", None) or []):
|
||||||
|
other = o.get("other")
|
||||||
|
rel = o.get("rel")
|
||||||
|
if (other is None or rel not in ("before", "after", "concurrent")
|
||||||
|
or not 0 <= other < len(fact_ids)
|
||||||
|
or fact_ids[other] is None):
|
||||||
|
continue # malformed reference: skip honestly
|
||||||
|
self.store.add_fact_order(fid, fact_ids[other], rel)
|
||||||
# ---- table fragments (extract path) -----------------------------
|
# ---- table fragments (extract path) -----------------------------
|
||||||
from .store import stem as _stem
|
from .store import stem as _stem
|
||||||
# containment target: prose + ALL table rows (the fragment's rows
|
# containment target: prose + ALL table rows (the fragment's rows
|
||||||
@@ -1083,31 +1358,52 @@ class KnowledgeExpert:
|
|||||||
heading = f"== Tables == (table {frag['table_idx']}, part {frag['part']}/{frag['of']})"
|
heading = f"== Tables == (table {frag['table_idx']}, part {frag['part']}/{frag['of']})"
|
||||||
raw = self.extract(entities=ent_str, heading=heading, text=text)
|
raw = self.extract(entities=ent_str, heading=heading, text=text)
|
||||||
for cand in (raw.facts or [])[: self.cfg.max_facts_per_chunk]:
|
for cand in (raw.facts or [])[: self.cfg.max_facts_per_chunk]:
|
||||||
extracted += self._ingest_candidate(cand, page, containment=containment)
|
merged, _eid = self._ingest_candidate(cand, page, containment=containment)
|
||||||
|
extracted += merged
|
||||||
return self._merged
|
return self._merged
|
||||||
|
|
||||||
def _ingest_candidate(self, cand, page: WikiPage, containment: str) -> int:
|
def _ingest_candidate(self, cand, page: WikiPage, containment: str) -> tuple[int, int | None]:
|
||||||
"""Containment-check one typed Fact, merge it, cache its vector.
|
"""Containment-check one typed Fact, merge it, cache its vector.
|
||||||
Returns 1 when merged, 0 otherwise. Shared by the prose and table-
|
|
||||||
fragment extract paths (research/semantic-kg)."""
|
Returns (merged, eid): merged=1 when the candidate was accepted
|
||||||
|
(a duplicate counts — corroboration was recorded), eid=None when
|
||||||
|
no NEW edge was created (duplicate or reject). Phase 2: the CALLER
|
||||||
|
wires order assertions through the returned eid."""
|
||||||
self._checked += 1
|
self._checked += 1
|
||||||
cand = {"subject": cand.subject, "relation": cand.relation,
|
cand = {"subject": cand.subject, "relation": cand.relation,
|
||||||
"object": cand.object, "quote": cand.quote}
|
"object": cand.object, "quote": cand.quote,
|
||||||
|
"start": getattr(cand, "start", None),
|
||||||
|
"end": getattr(cand, "end", None),
|
||||||
|
"point": getattr(cand, "point", None)}
|
||||||
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]}")
|
||||||
return 0
|
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
|
||||||
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,
|
||||||
sha256=hashlib.sha256(page.text.encode()).hexdigest())
|
sha256=hashlib.sha256(page.text.encode()).hexdigest())
|
||||||
qid = self.store.add_quote(doc_id, cand["quote"], page.url, page.fetched_at)
|
qid = self.store.add_quote(doc_id, cand["quote"], page.url, page.fetched_at)
|
||||||
eid = self.store.add_edge(cand["subject"], cand["relation"],
|
eid = self.store.add_edge(cand["subject"], cand["relation"],
|
||||||
cand["object"], qid)
|
cand["object"], qid,
|
||||||
|
t_start=cand["start"] 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"])
|
||||||
return 1
|
return 1, eid
|
||||||
|
|
||||||
def _cache_edge_vector(self, eid: int, subject: str, relation: str,
|
def _cache_edge_vector(self, eid: int, subject: str, relation: str,
|
||||||
obj: str) -> None:
|
obj: str) -> None:
|
||||||
@@ -1144,10 +1440,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": pred.value.strip(),
|
"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
|
||||||
+66
-15
@@ -20,25 +20,40 @@ class Confidence(str, Enum):
|
|||||||
|
|
||||||
|
|
||||||
class Fact(BaseModel):
|
class Fact(BaseModel):
|
||||||
"""One fact extracted from a text, with its verbatim supporting quote."""
|
"""One fact extracted from a text, with its verbatim supporting quote
|
||||||
|
and its TEMPORAL RESTRICTIONS (phase 2 — restrictions, never Allen
|
||||||
|
labels; the algebra is a computed view over these endpoints).
|
||||||
|
|
||||||
|
All temporal fields are optional and must be CONTAINED IN THE QUOTE
|
||||||
|
(an invented date fails the containment check and the whole fact is
|
||||||
|
rejected — the honest law). 'since YYYY' means start=YYYY, end OPEN.
|
||||||
|
Granularity is honest precision: 'year' | 'month' | 'day'.
|
||||||
|
orders: temporal-order assertions BETWEEN SIBLING FACTS of the same
|
||||||
|
extraction, by their 0-based position in the same facts list —
|
||||||
|
{rel: before|after|concurrent, other: <index>}."""
|
||||||
subject: str = dspy.OutputField(desc="the fact's subject entity")
|
subject: str = dspy.OutputField(desc="the fact's subject entity")
|
||||||
relation: str = dspy.OutputField(desc="the relation between subject and object")
|
relation: str = dspy.OutputField(desc="the relation between subject and object")
|
||||||
object: str = dspy.OutputField(desc="the fact's object / value")
|
object: str = dspy.OutputField(desc="the fact's object / value")
|
||||||
quote: str = dspy.OutputField(
|
quote: str = dspy.OutputField(
|
||||||
desc="VERBATIM quote from the text that states the fact: the FULL sentence or table row, copied exactly (at least 10 characters)")
|
desc="VERBATIM quote from the text that states the fact: the FULL sentence or table row, copied exactly (at least 10 characters)")
|
||||||
|
start: str | None = dspy.OutputField(
|
||||||
|
default=None,
|
||||||
class TranslateSignature(dspy.Signature):
|
desc="when the fact begins, as stated in the text (a year like 2018, or a full date); empty when the text states no start")
|
||||||
"""You are the TRANSLATE step of a knowledge machine. Turn the question
|
end: str | None = dspy.OutputField(
|
||||||
into Wikipedia search queries AND resolved entity terms. Resolve
|
default=None,
|
||||||
references ('that state', 'the same river') using the context: the original
|
desc="when the fact ends, as stated in the text; empty when ongoing/unknown")
|
||||||
question and the evidence rows already gathered."""
|
point: str | None = dspy.OutputField(
|
||||||
question: str = dspy.InputField()
|
default=None,
|
||||||
context: str = dspy.InputField(desc="the original question + evidence rows with answers already found; resolve pronouns from here; may be empty")
|
desc="for point-in-time facts (events): the stated date; empty otherwise")
|
||||||
queries: list[str] = dspy.OutputField(
|
granularity: str | None = dspy.OutputField(
|
||||||
desc="1-2 Wikipedia search queries, most specific first")
|
default=None,
|
||||||
entities: list[str] = dspy.OutputField(
|
desc="precision of the stated dates: year, month, or day; empty when no dates")
|
||||||
desc="the resolved entity names the answer is about")
|
orders: list[dict] = dspy.OutputField(
|
||||||
|
default_factory=list,
|
||||||
|
desc="temporal order between THIS fact and SIBLING facts of the same list, "
|
||||||
|
"ONLY when the text asserts it with a connective (before/after/at the same "
|
||||||
|
"time as); each entry {rel: before|after|concurrent, other: <0-based index "
|
||||||
|
"of the sibling fact>}; empty when the text asserts no order")
|
||||||
|
|
||||||
|
|
||||||
class ExtractSignature(dspy.Signature):
|
class ExtractSignature(dspy.Signature):
|
||||||
@@ -57,13 +72,49 @@ class ExtractSignature(dspy.Signature):
|
|||||||
desc="the extracted facts; empty list if none")
|
desc="the extracted facts; empty list if none")
|
||||||
|
|
||||||
|
|
||||||
|
class ExtractClaims(dspy.Signature):
|
||||||
|
"""You are the CLAIMS step of a knowledge machine. From the given text,
|
||||||
|
list the FACTUAL CLAIMS it states about the NAMED ENTITIES: positions
|
||||||
|
and offices held, biographical facts, events, relationships,
|
||||||
|
quantities with units. One claim per line, plain text, no numbering.
|
||||||
|
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(
|
||||||
|
desc="the named entities to extract claims about, comma separated")
|
||||||
|
heading: str = dspy.InputField(desc="section path of this chunk; context only")
|
||||||
|
text: str = dspy.InputField()
|
||||||
|
claims: list[str] = dspy.OutputField(
|
||||||
|
desc="the factual claims, one string each, coreferences resolved "
|
||||||
|
"(entities named, never pronouns); empty list if none")
|
||||||
|
|
||||||
|
|
||||||
|
class TypeClaim(dspy.Signature):
|
||||||
|
"""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
|
||||||
|
schema: subject entity, relation, object/value, the VERBATIM quote
|
||||||
|
copied EXACTLY from the text (the FULL sentence or table row that
|
||||||
|
states the claim, at least 10 characters), and the temporal
|
||||||
|
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")
|
||||||
|
text: str = dspy.InputField(
|
||||||
|
desc="the text the claim was extracted from — find the VERBATIM "
|
||||||
|
"quote here, copied exactly")
|
||||||
|
fact: Fact | None = dspy.OutputField(
|
||||||
|
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):
|
||||||
"""You are the ANSWER step of a knowledge machine. Answer the question using
|
"""You are the ANSWER step of a knowledge machine. Answer the question using
|
||||||
ONLY the given knowledge-graph rows, each with its quote and source. Cite
|
ONLY the given knowledge-graph rows, each with its quote and source. Cite
|
||||||
rows by id. If the rows do not answer it, say UNKNOWN."""
|
rows by id. If the rows do not answer it, say UNKNOWN."""
|
||||||
question: str = dspy.InputField()
|
question: str = dspy.InputField()
|
||||||
rows: str = dspy.InputField(desc="kg rows: id, subject, relation, object, quote, url")
|
rows: str = dspy.InputField(desc="kg rows: id, subject, relation, object, quote, url")
|
||||||
value: str = dspy.OutputField(desc="the answer, or UNKNOWN")
|
value: str = dspy.OutputField(
|
||||||
|
desc="the answer, or UNKNOWN — the value ONLY, no row citations, no parenthetical explanations")
|
||||||
quote: str = dspy.OutputField(desc="VERBATIM supporting quote from the rows, or empty")
|
quote: str = dspy.OutputField(desc="VERBATIM supporting quote from the rows, or empty")
|
||||||
confidence: Confidence = dspy.OutputField(
|
confidence: Confidence = dspy.OutputField(
|
||||||
desc="high: rows settle it; medium: plausible but partial; low: weak support")
|
desc="high: rows settle it; medium: plausible but partial; low: weak support")
|
||||||
|
|||||||
@@ -0,0 +1,224 @@
|
|||||||
|
"""The derived-answer engine (phase 3a, RESEARCH-derived-answers Part 3).
|
||||||
|
|
||||||
|
No LLM in the loop. The query is a small TYPED DSL (conjunctive +
|
||||||
|
temporal, hand-writable — the LLM translator arrives in 3b); the
|
||||||
|
evaluation is goal-directed over the store; THE ANSWER IS THE PROOF
|
||||||
|
TERM: every step names its operator and the edge ids it consumed, and
|
||||||
|
re-execution over the store IS the verification (deterministic, no
|
||||||
|
model). This is the Logic-LM move of the lineage applied to floop's
|
||||||
|
own layer: LLMs translate at the two ends, fixed code decides inside.
|
||||||
|
|
||||||
|
DSL (the subset pinned by tests/prover.py):
|
||||||
|
|
||||||
|
{"lookup": {subject, rel_any, bind} | [lookups...]
|
||||||
|
"filter": [{open_now: [var]}, {before: [a, b]}, {neq_value: [var, lit]}]
|
||||||
|
"select": "all" | "latest_end"}
|
||||||
|
|
||||||
|
lookup binds `var` to every matching edge (subject exact-normalized,
|
||||||
|
rel in rel_any). A second lookup may carry same_value_as: var — a join
|
||||||
|
on the bound value (the SAME office, a different holder). Filters:
|
||||||
|
open_now (the edge's window is open now — end None or >= today's
|
||||||
|
year), before (window a ends before window b starts — the interval
|
||||||
|
succession law), neq_value (a bound subject differs from a literal —
|
||||||
|
exclusion of the queried entity itself). select: all (the binding SET
|
||||||
|
— multi-binding IS the ambiguity) or latest_end (the most recent
|
||||||
|
closed window among the surviving bindings — the predecessor).
|
||||||
|
|
||||||
|
Evaluation semantics, honestly narrow:
|
||||||
|
- values compare through norm_name (the store's normalization);
|
||||||
|
- `before` requires BOTH windows to have real endpoints on the
|
||||||
|
compared sides — an open end is NOT "before" anything (the world
|
||||||
|
moved on, we cannot prove when);
|
||||||
|
- select=latest_end sorts by t_end descending, requiring a real t_end;
|
||||||
|
- nothing is ever invented: no closed path -> empty bindings (UNKNOWN).
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from .store import KnowledgeStore, norm_name
|
||||||
|
|
||||||
|
_THIS_YEAR = "2026" # open_now: an open end or an end >= today coexists
|
||||||
|
|
||||||
|
_KNOWN_FILTERS = {"open_now", "before", "neq_value"}
|
||||||
|
_KNOWN_SELECTS = {"all", "latest_end"}
|
||||||
|
|
||||||
|
|
||||||
|
def validate_query(q: Any) -> tuple[bool, str]:
|
||||||
|
"""The shared grammar: a DSL term type-checks BEFORE evaluation.
|
||||||
|
|
||||||
|
The translator (LLM) proposes; this deterministic gate decides. A
|
||||||
|
mistranslation surfaces as an invalid term — unknown filter, unknown
|
||||||
|
select, empty rel_any, malformed lookup — and NEVER reaches
|
||||||
|
evaluate(): no wrong answer can hide inside an unexecutable query.
|
||||||
|
Returns (ok, reason).
|
||||||
|
"""
|
||||||
|
if not isinstance(q, dict) or not q:
|
||||||
|
return False, "empty or non-dict query"
|
||||||
|
lookups = q.get("lookup")
|
||||||
|
if isinstance(lookups, dict):
|
||||||
|
lookups = [lookups]
|
||||||
|
if not lookups or not isinstance(lookups, list):
|
||||||
|
return False, "no lookup"
|
||||||
|
for lk in lookups:
|
||||||
|
if not isinstance(lk, dict) or not lk.get("subject"):
|
||||||
|
return False, "lookup without subject"
|
||||||
|
if not lk.get("rel_any"):
|
||||||
|
return False, "lookup without rel_any"
|
||||||
|
if not isinstance(lk["rel_any"], list):
|
||||||
|
return False, "rel_any not a list"
|
||||||
|
if not lk.get("bind"):
|
||||||
|
return False, "lookup without bind var"
|
||||||
|
for f in q.get("filter", []):
|
||||||
|
if not isinstance(f, dict) or len(f) != 1:
|
||||||
|
return False, f"malformed filter {f!r}"
|
||||||
|
key = next(iter(f))
|
||||||
|
if key not in _KNOWN_FILTERS:
|
||||||
|
return False, f"unknown filter {key!r}"
|
||||||
|
if not isinstance(f[key], list):
|
||||||
|
return False, f"filter args not a list: {key}"
|
||||||
|
sel = q.get("select", "all")
|
||||||
|
if sel not in _KNOWN_SELECTS:
|
||||||
|
return False, f"unknown select {sel!r}"
|
||||||
|
return True, "ok"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Step:
|
||||||
|
op: str # lookup | filter | select
|
||||||
|
note: str = ""
|
||||||
|
edges: list[int] = field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Proof:
|
||||||
|
bindings: list[dict] = field(default_factory=list)
|
||||||
|
steps: list[Step] = field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
|
def _edges_of(store: KnowledgeStore, subject: str, rel_any: list[str]) -> list:
|
||||||
|
"""All live edges of one subject under any of the rels (order: id)."""
|
||||||
|
rows = store.db.execute(
|
||||||
|
"SELECT e.id, e.rel, e.dst_value, e.t_start, e.t_end, n.norm_name "
|
||||||
|
"FROM edges e JOIN nodes n ON n.id=e.src_node "
|
||||||
|
"WHERE n.norm_name=? AND e.retracted=0 ORDER BY e.id",
|
||||||
|
(norm_name(subject),)).fetchall()
|
||||||
|
return [r for r in rows if r[1] in rel_any]
|
||||||
|
|
||||||
|
|
||||||
|
def _row_to_binding(var: str, r) -> dict:
|
||||||
|
return {var: {"eid": r[0], "rel": r[1], "value": r[2],
|
||||||
|
"start": r[3], "end": r[4], "subject": r[5]}}
|
||||||
|
|
||||||
|
|
||||||
|
def _window_open_now(b: dict) -> bool:
|
||||||
|
end = b["end"]
|
||||||
|
return end is None or end >= _THIS_YEAR
|
||||||
|
|
||||||
|
|
||||||
|
def _before(a: dict, b: dict) -> bool:
|
||||||
|
"""Window a ENDED before window b STARTED. Both sides must be real —
|
||||||
|
an open end is not 'before' anything (honesty: no invented dates)."""
|
||||||
|
if a["end"] is None or b["start"] is None:
|
||||||
|
return False
|
||||||
|
return a["end"] <= b["start"] # year granularity, closed-open
|
||||||
|
|
||||||
|
|
||||||
|
def evaluate(store: KnowledgeStore, query: dict) -> Proof:
|
||||||
|
"""Goal-directed evaluation. Returns the proof term (bindings + steps)."""
|
||||||
|
proof = Proof()
|
||||||
|
lookups = query.get("lookup")
|
||||||
|
if isinstance(lookups, dict):
|
||||||
|
lookups = [lookups]
|
||||||
|
# ---- first lookup: bind every matching edge -------------------------
|
||||||
|
first = lookups[0]
|
||||||
|
var = first["bind"]
|
||||||
|
rows = _edges_of(store, first["subject"], first.get("rel_any", []))
|
||||||
|
proof.steps.append(Step("lookup", f"bind {var}: subject={first['subject']} "
|
||||||
|
f"rels={first.get('rel_any')}",
|
||||||
|
[r[0] for r in rows]))
|
||||||
|
bindings = [_row_to_binding(var, r) for r in rows]
|
||||||
|
# ---- further lookups: JOIN on the bound value -----------------------
|
||||||
|
for lk in lookups[1:]:
|
||||||
|
jvar = lk["bind"]
|
||||||
|
joined = []
|
||||||
|
for b in bindings:
|
||||||
|
same = b[lk.get("same_value_as", var)]["value"]
|
||||||
|
# the joining side's subject may be a VARIABLE (?x): iterate
|
||||||
|
# every live edge under the rels and keep value matches
|
||||||
|
rows = store.db.execute(
|
||||||
|
"SELECT e.id, e.rel, e.dst_value, e.t_start, e.t_end, n.norm_name "
|
||||||
|
"FROM edges e JOIN nodes n ON n.id=e.src_node "
|
||||||
|
"WHERE e.rel IN (%s) AND e.retracted=0 ORDER BY e.id"
|
||||||
|
% ",".join("?" * len(lk.get("rel_any", []))),
|
||||||
|
tuple(lk.get("rel_any", []))).fetchall()
|
||||||
|
for r in rows:
|
||||||
|
if norm_name(r[2]) == norm_name(same):
|
||||||
|
nb = dict(b)
|
||||||
|
nb[jvar] = {"eid": r[0], "rel": r[1], "value": r[2],
|
||||||
|
"start": r[3], "end": r[4], "subject": r[5]}
|
||||||
|
nb["?x"] = r[5] # the OTHER holder
|
||||||
|
joined.append(nb)
|
||||||
|
proof.steps.append(Step("lookup", f"join {jvar} on value={same}",
|
||||||
|
[r[0]]))
|
||||||
|
bindings = joined
|
||||||
|
# ---- filters ----------------------------------------------------------
|
||||||
|
for f in query.get("filter", []):
|
||||||
|
for key, args in f.items():
|
||||||
|
kept = []
|
||||||
|
for b in bindings:
|
||||||
|
if key == "open_now":
|
||||||
|
ok = _window_open_now(b[args[0]])
|
||||||
|
elif key == "before":
|
||||||
|
ok = _before(b[args[0]], b[args[1]])
|
||||||
|
elif key == "neq_value":
|
||||||
|
# the arg may be a bound edge var (dict) or a plain
|
||||||
|
# string var ('?x') holding the joined subject's name
|
||||||
|
ref = b.get(args[0])
|
||||||
|
subj = (ref["subject"] if isinstance(ref, dict)
|
||||||
|
else ref) or ""
|
||||||
|
ok = norm_name(subj) != norm_name(args[1])
|
||||||
|
else:
|
||||||
|
raise ValueError(f"unknown filter {key!r}")
|
||||||
|
if ok:
|
||||||
|
kept.append(b)
|
||||||
|
proof.steps.append(Step("filter", f"{key} {args}",
|
||||||
|
[b[var]["eid"] for b in kept if var in b]))
|
||||||
|
bindings = kept
|
||||||
|
# ---- select -----------------------------------------------------------
|
||||||
|
sel = query.get("select", "all")
|
||||||
|
if sel == "latest_end":
|
||||||
|
def _end_key(b):
|
||||||
|
e = next((v["end"] for k, v in b.items()
|
||||||
|
if isinstance(v, dict) and v.get("end")), None)
|
||||||
|
return e or ""
|
||||||
|
bindings = sorted(bindings, key=_end_key, reverse=True)
|
||||||
|
bindings = bindings[:1]
|
||||||
|
proof.steps.append(Step("select", "latest_end",
|
||||||
|
[b[var]["eid"] for b in bindings if var in b]))
|
||||||
|
elif sel != "all":
|
||||||
|
raise ValueError(f"unknown select {sel!r}")
|
||||||
|
proof.bindings = bindings
|
||||||
|
return proof
|
||||||
|
|
||||||
|
|
||||||
|
def re_execute(store: KnowledgeStore, query: dict, proof: Proof) -> bool:
|
||||||
|
"""The check: the same store must reproduce the SAME closed path.
|
||||||
|
|
||||||
|
Deterministic, no model — evaluation is pure, so this is equality of
|
||||||
|
the re-run proof term against the claimed one. A store that changed
|
||||||
|
under the proof (retractions, new edges winning latest_end) makes
|
||||||
|
the re-run differ and the claimed proof FAILS: the check is real.
|
||||||
|
"""
|
||||||
|
fresh = evaluate(store, query)
|
||||||
|
if len(fresh.bindings) != len(proof.bindings):
|
||||||
|
return False
|
||||||
|
for a, b in zip(fresh.bindings, proof.bindings):
|
||||||
|
ka = {k: (v["eid"] if isinstance(v, dict) else v)
|
||||||
|
for k, v in a.items()}
|
||||||
|
kb = {k: (v["eid"] if isinstance(v, dict) else v)
|
||||||
|
for k, v in b.items()}
|
||||||
|
if ka != kb:
|
||||||
|
return False
|
||||||
|
return True
|
||||||
@@ -0,0 +1,167 @@
|
|||||||
|
"""Deterministic query composition — the old TRANSLATE step as fixed code.
|
||||||
|
|
||||||
|
His 23/10 weights-tightness call: the TRANSLATE LLM was composing search
|
||||||
|
queries from its OWN knowledge of the entities — 'Pedro Sánchez 2018
|
||||||
|
investiture President of the Government of Spain' (the '2018' IS the
|
||||||
|
answer to that term-start question, steered into retrieval from
|
||||||
|
weights), 'Po, Adige, Tiber' proposed for a question that named only
|
||||||
|
Italy. Probed against real Wikipedia over every logged TRANSLATE call of
|
||||||
|
runs 22-23/10: queries composed from the question's named entities and
|
||||||
|
keywords (+ the evidence's resolved entities) put the decisive article at
|
||||||
|
top-1/2 in 8 of 9 cases — the LLM's world knowledge was never the
|
||||||
|
load-bearing part; the search engine's own relevance was. So the step
|
||||||
|
becomes code.
|
||||||
|
|
||||||
|
Laws:
|
||||||
|
- Material: question ∪ evidence only. Every token of every query traces
|
||||||
|
to the question or an evidence row — the weights-tightness law, now
|
||||||
|
structural instead of prompted.
|
||||||
|
- Deterministic: same inputs -> same queries, same order, every time.
|
||||||
|
- Never empty: a question with no NEs still gets its keyword join.
|
||||||
|
- Top-N over a list row in evidence slices the FIRST N members by source
|
||||||
|
order (the ranked-list law) — never dumps all members into one query
|
||||||
|
('Ranked Italy Maira K1 K2' retrieved nothing when a naive composer
|
||||||
|
tried exactly that).
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
|
||||||
|
WORD_RE = re.compile(r"[A-Za-zÀ-ÿ0-9']+")
|
||||||
|
_CAP_RE = re.compile(r"[A-Z][a-zÀ-ÿ]+(?:'[A-Za-z]+)?")
|
||||||
|
|
||||||
|
# capitalized words that are question machinery, not subjects
|
||||||
|
_CAP_STOPS = {"What", "Which", "Who", "When", "Where", "Why", "How", "The",
|
||||||
|
"Is", "Are", "Was", "Were", "In", "On", "At", "For", "Of",
|
||||||
|
"Their", "Its", "Those", "These", "That", "This"}
|
||||||
|
|
||||||
|
# content-word stoplist (single source: probe seeds and composer share it)
|
||||||
|
_KW_STOPS = {"what", "which", "who", "when", "where", "is", "are", "was",
|
||||||
|
"were", "the", "of", "in", "on", "at", "a", "an", "and", "or",
|
||||||
|
"to", "for", "does", "do", "did", "by", "its", "it", "that",
|
||||||
|
"this", "most", "second"}
|
||||||
|
|
||||||
|
_N_WORDS = {"two": 2, "three": 3, "four": 4, "five": 5, "six": 6,
|
||||||
|
"seven": 7, "eight": 8, "nine": 9, "ten": 10, "eleven": 11,
|
||||||
|
"twelve": 12}
|
||||||
|
|
||||||
|
|
||||||
|
def _caps_in_order(question: str) -> list[str]:
|
||||||
|
"""Capitalized words in question order, deduped."""
|
||||||
|
return list(dict.fromkeys(_CAP_RE.findall(question or "")))
|
||||||
|
|
||||||
|
|
||||||
|
def proper_nouns(question: str) -> set[str]:
|
||||||
|
"""Capitalized non-question words: 'Italy', 'Po' — the SUBJECT of the
|
||||||
|
question. The definitive guard for 'which are the three longest rivers
|
||||||
|
of Italy?' never accepting a world table (run H: Q1 answered Nile/
|
||||||
|
Amazon/Yangtze because the top search hit was the world list and the
|
||||||
|
disjointness guard was vacuous — no evidence, nothing to check)."""
|
||||||
|
return {w for w in _caps_in_order(question) if w not in _CAP_STOPS}
|
||||||
|
|
||||||
|
|
||||||
|
def _subjects(question: str) -> list[str]:
|
||||||
|
"""NEs in question order. The SENTENCE-INITIAL word is dropped when
|
||||||
|
other NEs exist: it is capitalized by sentence rules, not because it
|
||||||
|
names an entity ('During what years…', 'Ranked by length…'). When it
|
||||||
|
is the ONLY capitalized word it is kept — it may be the subject
|
||||||
|
('Po length?')."""
|
||||||
|
ne_set = proper_nouns(question)
|
||||||
|
nes = [w for w in _caps_in_order(question) if w in ne_set]
|
||||||
|
first = (question or "").strip().split(" ")[0] if question else ""
|
||||||
|
if len(nes) > 1 and nes and nes[0] == first:
|
||||||
|
nes = nes[1:]
|
||||||
|
return nes
|
||||||
|
|
||||||
|
|
||||||
|
def keywords(question: str, k: int = 6) -> list[str]:
|
||||||
|
"""Deterministic lexical focus: content words of the question."""
|
||||||
|
words = [w.lower() for w in WORD_RE.findall(question)]
|
||||||
|
seen: list[str] = []
|
||||||
|
for w in words:
|
||||||
|
if w not in _KW_STOPS and len(w) > 2 and w not in seen:
|
||||||
|
seen.append(w)
|
||||||
|
return seen[:k]
|
||||||
|
|
||||||
|
|
||||||
|
def _plural_head(kws: list[str]) -> str:
|
||||||
|
"""The enumeration's head noun: first plural content word ('rivers',
|
||||||
|
'countries'). Questions with no plural get no list variant."""
|
||||||
|
return next((w for w in kws if w.endswith("s") and len(w) > 4), "")
|
||||||
|
|
||||||
|
|
||||||
|
def _top_n(question: str) -> int | None:
|
||||||
|
"""The N of a top-N ask ('which three of these…', 'top 5 …'), if any.
|
||||||
|
Only meaningful when the evidence names a list to slice."""
|
||||||
|
for w in WORD_RE.findall(question.casefold()):
|
||||||
|
if w in _N_WORDS:
|
||||||
|
return _N_WORDS[w]
|
||||||
|
if w.isdigit() and 1 <= int(w) <= 12:
|
||||||
|
return int(w)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def compose_queries(question: str,
|
||||||
|
evidence_entities: list[str] | None = None,
|
||||||
|
list_mode: bool = False) -> tuple[list[str], list[str]]:
|
||||||
|
"""Wikipedia search queries + entity terms from question ∪ evidence.
|
||||||
|
|
||||||
|
Returns (queries, entities), both deterministic. Queries (≤ 2, the
|
||||||
|
per-gather search cost of the LLM step this replaces):
|
||||||
|
[0] top-N ask over evidence members -> the FIRST N by source order
|
||||||
|
('Po Adige Tiber' — the members themselves retrieve their
|
||||||
|
articles); enumeration with a subject NE -> subject + head
|
||||||
|
noun ('Italy rivers'); multi-NE -> the join ('Pedro Sanchez
|
||||||
|
President'); single NE -> NE + salient keywords ('Po length');
|
||||||
|
no NE but evidence -> the evidence's entities ('that state' +
|
||||||
|
E1:France -> 'France'); else keyword join
|
||||||
|
[1] enumeration with exactly ONE subject NE -> the Wikipedia
|
||||||
|
list-article shape ('List of rivers of Italy'); else the
|
||||||
|
attribute variant ('Pedro term begin'). A second NE makes the
|
||||||
|
list shape ambiguous ('List of countries of Union') — skipped.
|
||||||
|
entities: sliced evidence members (top-N) or question NEs, then the
|
||||||
|
rest of the evidence entities, question order first.
|
||||||
|
|
||||||
|
Every token of every query traces to the question or the evidence.
|
||||||
|
"""
|
||||||
|
nes = _subjects(question)
|
||||||
|
kws = keywords(question)
|
||||||
|
ev = [e for e in (evidence_entities or []) if e]
|
||||||
|
ne_lower = {n.casefold() for n in nes}
|
||||||
|
salient = [w for w in kws if w not in ne_lower]
|
||||||
|
n_ask = _top_n(question)
|
||||||
|
|
||||||
|
queries: list[str] = []
|
||||||
|
if ev and n_ask:
|
||||||
|
# top-N over a list row in evidence: the first N members by source
|
||||||
|
# order carry the query (a ranked list ranks; unranked order is
|
||||||
|
# still the source's own). Never all members at once.
|
||||||
|
queries.append(" ".join(ev[:n_ask]))
|
||||||
|
elif list_mode and nes and (plural := _plural_head(kws)):
|
||||||
|
queries.append(" ".join(nes[:2] + [plural]))
|
||||||
|
elif len(nes) >= 2:
|
||||||
|
queries.append(" ".join(nes[:3]))
|
||||||
|
elif nes and salient:
|
||||||
|
queries.append(" ".join([nes[0], *salient[:2]]))
|
||||||
|
elif nes:
|
||||||
|
queries.append(nes[0])
|
||||||
|
elif ev:
|
||||||
|
queries.append(" ".join(ev[:3]))
|
||||||
|
elif kws:
|
||||||
|
queries.append(" ".join(kws[:3]))
|
||||||
|
else:
|
||||||
|
queries.append(question.strip()[:60] or "wikipedia")
|
||||||
|
|
||||||
|
variant = ""
|
||||||
|
if list_mode and len(nes) == 1 and (plural := _plural_head(kws)):
|
||||||
|
variant = f"List of {plural} of {nes[0]}"
|
||||||
|
if not variant and salient:
|
||||||
|
base = nes[0] if nes else (ev[0] if ev else "")
|
||||||
|
if base and base.casefold() not in [q.casefold() for q in queries]:
|
||||||
|
variant = " ".join([base, *salient[:2]])
|
||||||
|
if variant and variant not in queries:
|
||||||
|
queries.append(variant)
|
||||||
|
|
||||||
|
entities = list(dict.fromkeys((ev[:n_ask] if ev and n_ask else [])
|
||||||
|
+ nes + ev))[:8]
|
||||||
|
return queries[:2], entities
|
||||||
@@ -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)
|
||||||
+223
-16
@@ -54,6 +54,72 @@ def norm_name(name: str) -> str:
|
|||||||
return re.sub(r"\s+", " ", s).strip().casefold()
|
return re.sub(r"\s+", " ", s).strip().casefold()
|
||||||
|
|
||||||
|
|
||||||
|
# a value is FUNCTIONAL (only one can be true) when it is date-like or a
|
||||||
|
# bare number/quantity: '29 February 1972', '2018', '15', '1,006 km',
|
||||||
|
# '17 november 2023'. Two entity-ish values ('prime minister of Spain' vs
|
||||||
|
# 'Secretary-General of the PSOE') are co-true readings of a multi-valued
|
||||||
|
# relation instead. The signal: no entity WORDS survive after dropping
|
||||||
|
# numbers, month names, and units.
|
||||||
|
_MONTHS = {"january", "february", "march", "april", "may", "june", "july",
|
||||||
|
"august", "september", "october", "november", "december",
|
||||||
|
"gener", "febrer", "marc", "abril", "maig", "juny", "juliol",
|
||||||
|
"agost", "setembre", "octubre", "novembre", "desembre",
|
||||||
|
"de", "d", "of", "the", "in", "on", "at", "since", "until"}
|
||||||
|
_UNITS = {"km", "km2", "mi", "m", "kg", "s", "cu", "ft", "ms", "mm", "cm",
|
||||||
|
"people", "inhabitants", "days", "years", "months", "hours",
|
||||||
|
"percent", "m3", "m3/s", "bps", "kb", "mb", "gb", "%", "eur",
|
||||||
|
"usd", "millions", "billions"}
|
||||||
|
|
||||||
|
|
||||||
|
def _looks_functional(value: str) -> bool:
|
||||||
|
"""True when the value is date-like or a bare quantity (phase 1 signal:
|
||||||
|
functional relations keep the contradiction case; entity-ish pairs go
|
||||||
|
to alternatives). A value with two or more entity words is NOT
|
||||||
|
functional ('prime minister of Spain'); a date or quantity is.
|
||||||
|
A lone entity word ('Spain') is an entity reading, not a datum —
|
||||||
|
functional needs NUMBERS with at most one unit/month word."""
|
||||||
|
words = re.findall(r"[A-Za-zÀ-ÿ]{1,}", value or "")
|
||||||
|
entity_words = [w for w in words
|
||||||
|
if w.lower() not in _MONTHS and w.lower() not in _UNITS]
|
||||||
|
has_number = bool(re.search(r"\d", value or ""))
|
||||||
|
if not has_number:
|
||||||
|
return False # pure words: an entity reading (Spain / PSOE)
|
||||||
|
return len(entity_words) < 2
|
||||||
|
|
||||||
|
|
||||||
|
# ---- phase 2: valid-time windows (RESEARCH-derived-answers Part 2) -----------
|
||||||
|
# A window is (start, end) with None = OPEN. Granularity is compared as
|
||||||
|
# text (ISO-like, left-padded by the extractor: '2018' < '2018-06' <
|
||||||
|
# '2018-06-02' all compare correctly as strings when normalized to the
|
||||||
|
# finest stated granularity — a year window is the interval
|
||||||
|
# [2018, 2019), honest to its precision).
|
||||||
|
|
||||||
|
def _window(start: str | None, end: str | None) -> tuple[str | None, str | None] | None:
|
||||||
|
"""The window, or None when the fact states NO time at all (empty
|
||||||
|
windows stay empty — no invention, no pretending)."""
|
||||||
|
if not start and not end:
|
||||||
|
return None
|
||||||
|
return (start or None, end or None)
|
||||||
|
|
||||||
|
|
||||||
|
def _overlaps(a: tuple[str | None, str | None],
|
||||||
|
b: tuple[str | None, str | None]) -> bool:
|
||||||
|
"""Two valid-time windows overlap? None endpoints are OPEN (±inf).
|
||||||
|
|
||||||
|
The boundary law (year granularity, honest to its precision): an end
|
||||||
|
year CLOSES the window and the next start year OPENS there —
|
||||||
|
[2014,2018) vs [2018,None) is SUCCESSION (the mandate changed hands
|
||||||
|
in 2018), not coexistence. Overlap is max(starts) < min(ends); the
|
||||||
|
open sides degenerate correctly: both starts None (share the
|
||||||
|
indefinite past) or both ends None (both ongoing) always overlap.
|
||||||
|
"""
|
||||||
|
lo = max(a[0] or "-inf", b[0] or "-inf")
|
||||||
|
hi = min(a[1] or "9999", b[1] or "9999")
|
||||||
|
if lo == "-inf" or hi == "9999":
|
||||||
|
return True
|
||||||
|
return lo < hi # strict: touching at one year = succession
|
||||||
|
|
||||||
|
|
||||||
def stem(word: str) -> str:
|
def stem(word: str) -> str:
|
||||||
"""Tiny suffix stemmer so question words match text words (draft):
|
"""Tiny suffix stemmer so question words match text words (draft):
|
||||||
'populated'/'population' -> 'populat', 'states' -> 'state'."""
|
'populated'/'population' -> 'populat', 'states' -> 'state'."""
|
||||||
@@ -109,6 +175,38 @@ class KnowledgeStore:
|
|||||||
if "list_ord" not in cols:
|
if "list_ord" not in cols:
|
||||||
self.db.execute("ALTER TABLE edges ADD COLUMN list_ord INTEGER")
|
self.db.execute("ALTER TABLE edges ADD COLUMN list_ord INTEGER")
|
||||||
self.db.commit()
|
self.db.commit()
|
||||||
|
# ---- phase 2: temporal windows (RESEARCH-derived-answers Part 2) ----
|
||||||
|
for col in ("t_start", "t_end"):
|
||||||
|
if col not in cols:
|
||||||
|
self.db.execute(f"ALTER TABLE edges ADD COLUMN {col} TEXT")
|
||||||
|
self.db.commit()
|
||||||
|
# fact_order: order assertions BETWEEN facts (edges are addressable;
|
||||||
|
# reification is free). rel in {before, after, concurrent}.
|
||||||
|
self.db.execute(
|
||||||
|
"CREATE TABLE IF NOT EXISTS fact_order ("
|
||||||
|
" id INTEGER PRIMARY KEY, edge_a INTEGER, edge_b INTEGER, "
|
||||||
|
" rel TEXT, quote_id INTEGER, "
|
||||||
|
" UNIQUE(edge_a, edge_b, rel))")
|
||||||
|
self.db.commit()
|
||||||
|
# ---- phase 1: the conflict taxonomy (RESEARCH-derived-answers.md) ----
|
||||||
|
# alternatives: co-true readings of one (src, rel) — the polisèmia
|
||||||
|
# (the three presidencies). Same shape as conflicts (pairwise), but
|
||||||
|
# the world holds BOTH: it is the ambiguity substrate, never an
|
||||||
|
# error state.
|
||||||
|
self.db.execute(
|
||||||
|
"CREATE TABLE IF NOT EXISTS alternatives ("
|
||||||
|
" id INTEGER PRIMARY KEY, node INTEGER, rel TEXT, "
|
||||||
|
" value_a TEXT, value_b TEXT, edge_a INTEGER, edge_b INTEGER, "
|
||||||
|
" UNIQUE(node, rel, edge_a, edge_b))")
|
||||||
|
self.db.commit()
|
||||||
|
# same_as: paraphrase merges. Append-only law — the merge never
|
||||||
|
# deletes; the alias pair is recorded and the canonical edge's
|
||||||
|
# corroboration goes up.
|
||||||
|
self.db.execute(
|
||||||
|
"CREATE TABLE IF NOT EXISTS same_as ("
|
||||||
|
" id INTEGER PRIMARY KEY, edge_a INTEGER, edge_b INTEGER, "
|
||||||
|
" UNIQUE(edge_a, edge_b))")
|
||||||
|
self.db.commit()
|
||||||
|
|
||||||
# ---- documents & quotes ------------------------------------------------
|
# ---- documents & quotes ------------------------------------------------
|
||||||
def add_document(self, url: str, title: str, fetched_at: str, sha256: str,
|
def add_document(self, url: str, title: str, fetched_at: str, sha256: str,
|
||||||
@@ -143,8 +241,14 @@ class KnowledgeStore:
|
|||||||
dst_sort: str = "CONCEPT", confidence: float = 0.8,
|
dst_sort: str = "CONCEPT", confidence: float = 0.8,
|
||||||
ref_date: str | None = None,
|
ref_date: str | None = None,
|
||||||
origin_question: str | None = None,
|
origin_question: str | None = None,
|
||||||
list_ord: int | None = None) -> int | None:
|
list_ord: int | None = None,
|
||||||
"""Add an edge, applying the four contradiction cases (KNOWLEDGE.md §2).
|
t_start: str | None = None, t_end: str | None = None) -> int | None:
|
||||||
|
"""Add an edge, applying the taxonomy (KNOWLEDGE.md §2 + the
|
||||||
|
RESEARCH-derived-answers parts 1-2).
|
||||||
|
|
||||||
|
t_start/t_end: the fact's VALID-TIME window as stated in the source
|
||||||
|
('since 2018' -> t_start='2018', t_end=None = OPEN). None/None when
|
||||||
|
the text states no time — empty windows stay empty, no invention.
|
||||||
|
|
||||||
Returns the edge id, or None when the candidate was a duplicate
|
Returns the edge id, or None when the candidate was a duplicate
|
||||||
(corroboration was counted instead).
|
(corroboration was counted instead).
|
||||||
@@ -162,26 +266,45 @@ class KnowledgeStore:
|
|||||||
return None
|
return None
|
||||||
# contradiction classification: same src+rel, different value, not retracted
|
# contradiction classification: same src+rel, different value, not retracted
|
||||||
others = self.db.execute(
|
others = self.db.execute(
|
||||||
"SELECT id, dst_value, ref_date FROM edges WHERE src_node=? AND rel=? "
|
"SELECT id, dst_value, ref_date, dst_node, quote_id, t_start, t_end "
|
||||||
|
"FROM edges WHERE src_node=? AND rel=? "
|
||||||
"AND retracted=0 AND id NOT IN (SELECT supersedes FROM edges WHERE supersedes IS NOT NULL)",
|
"AND retracted=0 AND id NOT IN (SELECT supersedes FROM edges WHERE supersedes IS NOT NULL)",
|
||||||
(src, rel)).fetchall()
|
(src, rel)).fetchall()
|
||||||
cur = self.db.execute(
|
cur = self.db.execute(
|
||||||
"INSERT INTO edges(src_node, rel, dst_value, dst_node, quote_id, "
|
"INSERT INTO edges(src_node, rel, dst_value, dst_node, quote_id, "
|
||||||
"extraction_confidence, origin_question, ref_date, preferred, list_ord) "
|
"extraction_confidence, origin_question, ref_date, preferred, list_ord, t_start, t_end) "
|
||||||
"VALUES(?,?,?,?,?,?,?,?,0,?)",
|
"VALUES(?,?,?,?,?,?,?,?,0,?,?,?)",
|
||||||
(src, rel, dst_value, dst_node, quote_id, confidence, origin_question,
|
(src, rel, dst_value, dst_node, quote_id, confidence, origin_question,
|
||||||
ref_date, list_ord))
|
ref_date, list_ord, t_start, t_end))
|
||||||
edge_id = cur.lastrowid
|
edge_id = cur.lastrowid
|
||||||
for other_id, other_val, other_date in others:
|
for other_id, other_val, other_date, other_dn, other_q, o_ts, o_te in others:
|
||||||
case = self._classify(new_val=dst_value, new_date=ref_date,
|
case = self._classify(new_val=dst_value, new_date=ref_date,
|
||||||
old_val=other_val, old_date=other_date)
|
old_val=other_val, old_date=other_date,
|
||||||
if case == "duplicate":
|
new_node=dst_node, old_node=other_dn,
|
||||||
|
new_quote=quote_id, old_quote=other_q,
|
||||||
|
new_start=t_start, new_end=t_end,
|
||||||
|
old_start=o_ts, old_end=o_te)
|
||||||
|
if case in ("duplicate", "paraphrase"):
|
||||||
|
if case == "paraphrase":
|
||||||
|
self.db.execute(
|
||||||
|
"INSERT OR IGNORE INTO same_as(edge_a, edge_b) VALUES(?,?)",
|
||||||
|
(other_id, edge_id))
|
||||||
|
self.db.execute(
|
||||||
|
"UPDATE edges SET corroboration = corroboration + 1 WHERE id=?",
|
||||||
|
(other_id,))
|
||||||
continue
|
continue
|
||||||
elif case == "supersedes":
|
elif case == "supersedes":
|
||||||
self.db.execute("UPDATE edges SET supersedes=? WHERE id=?", (other_id, edge_id))
|
self.db.execute("UPDATE edges SET supersedes=? WHERE id=?", (other_id, edge_id))
|
||||||
self.db.execute("UPDATE edges SET preferred=1 WHERE id=?", (edge_id,))
|
self.db.execute("UPDATE edges SET preferred=1 WHERE id=?", (edge_id,))
|
||||||
elif case == "temporal":
|
elif case in ("temporal", "coasserted", "succession"):
|
||||||
pass # both coexist; queries pick by date
|
# both dated (series) / one sentence asserts both / disjoint
|
||||||
|
# windows: the world holds or moves on — never a conflict
|
||||||
|
pass
|
||||||
|
elif case == "alternatives":
|
||||||
|
self.db.execute(
|
||||||
|
"INSERT OR IGNORE INTO alternatives(node, rel, value_a, value_b, edge_a, edge_b) "
|
||||||
|
"VALUES(?,?,?,?,?,?)",
|
||||||
|
(src, rel, other_val, dst_value, other_id, edge_id))
|
||||||
else: # contradiction
|
else: # contradiction
|
||||||
self.db.execute(
|
self.db.execute(
|
||||||
"INSERT INTO conflicts(node, rel, value_a, value_b, edge_a, edge_b) "
|
"INSERT INTO conflicts(node, rel, value_a, value_b, edge_a, edge_b) "
|
||||||
@@ -189,19 +312,103 @@ class KnowledgeStore:
|
|||||||
self.db.commit()
|
self.db.commit()
|
||||||
return edge_id
|
return edge_id
|
||||||
|
|
||||||
|
def add_fact_order(self, edge_a: int, edge_b: int, rel: str,
|
||||||
|
quote_id: int | None = None) -> None:
|
||||||
|
"""Record a temporal-order assertion BETWEEN two facts (phase 2).
|
||||||
|
|
||||||
|
The text asserts the order with a connective ('before becoming',
|
||||||
|
'at the same time as'); the extractor transcribes it as an order
|
||||||
|
restriction, code verifies the connective's quote and stores it
|
||||||
|
here. Edges are addressable — reification is free. rel is one of
|
||||||
|
{before, after, concurrent} (the extractor's vocabulary; Allen's
|
||||||
|
finer relations are computed views over the windows, never labels).
|
||||||
|
"""
|
||||||
|
if rel not in ("before", "after", "concurrent"):
|
||||||
|
raise ValueError(f"unknown order relation {rel!r}")
|
||||||
|
self.db.execute(
|
||||||
|
"INSERT OR IGNORE INTO fact_order(edge_a, edge_b, rel, quote_id) "
|
||||||
|
"VALUES(?,?,?,?)", (edge_a, edge_b, rel, quote_id))
|
||||||
|
self.db.commit()
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _classify(new_val: str, new_date: str | None, old_val: str, old_date: str | None) -> str:
|
def _classify(new_val: str, new_date: str | None, old_val: str, old_date: str | None,
|
||||||
"""Deterministic four-case classification (KNOWLEDGE.md §2)."""
|
new_node: int | None = None, old_node: int | None = None,
|
||||||
|
new_quote: int | None = None, old_quote: int | None = None,
|
||||||
|
new_start: str | None = None, new_end: str | None = None,
|
||||||
|
old_start: str | None = None, old_end: str | None = None) -> str:
|
||||||
|
"""Deterministic taxonomy (KNOWLEDGE.md §2 + RESEARCH-derived-answers
|
||||||
|
parts 1-2). Cost-ordered: the cheapest signal decides.
|
||||||
|
|
||||||
|
duplicate same normalized value
|
||||||
|
coasserted same quote — one trusted sentence asserts both
|
||||||
|
(conjunction: the platform sentence split into facts)
|
||||||
|
supersedes subsumption with dates
|
||||||
|
temporal both dated (ref_date), different dates — time series
|
||||||
|
paraphrase tails resolve to the SAME node — the same fact
|
||||||
|
alternatives co-true readings: overlapping VALID-TIME windows
|
||||||
|
(two open ends overlap), or entity-ish values with
|
||||||
|
different tails
|
||||||
|
contradiction the residue: functional values, disjoint windows on
|
||||||
|
a functional relation
|
||||||
|
|
||||||
|
Interval arithmetic (phase 2): windows come from the text via the
|
||||||
|
extractor (t_start/t_end, end=None = OPEN). Two windows OVERLAP ->
|
||||||
|
coexistence -> alternatives. DISJOINT -> succession (never a
|
||||||
|
conflict; the world just moved on). The comparison is honest: a
|
||||||
|
window with no endpoints does not pretend to overlap.
|
||||||
|
"""
|
||||||
nv, ov = norm_name(new_val), norm_name(old_val)
|
nv, ov = norm_name(new_val), norm_name(old_val)
|
||||||
if nv == ov:
|
if nv == ov:
|
||||||
return "duplicate"
|
return "duplicate"
|
||||||
# subsumption: the new value equals the old plus extra qualifiers
|
if new_quote is not None and new_quote == old_quote:
|
||||||
|
return "coasserted"
|
||||||
if ov and ov in nv and (new_date or old_date):
|
if ov and ov in nv and (new_date or old_date):
|
||||||
return "supersedes"
|
return "supersedes"
|
||||||
# both dated -> time series, not contradiction
|
|
||||||
if new_date and old_date and new_date != old_date:
|
if new_date and old_date and new_date != old_date:
|
||||||
return "temporal"
|
return "temporal"
|
||||||
return "contradiction"
|
# ---- phase 2: interval arithmetic over valid-time windows -------
|
||||||
|
new_w = _window(new_start, new_end)
|
||||||
|
old_w = _window(old_start, old_end)
|
||||||
|
if new_w and old_w:
|
||||||
|
if _overlaps(new_w, old_w):
|
||||||
|
return "alternatives" # coexistence is provable
|
||||||
|
# disjoint: succession — not a conflict, not co-true either
|
||||||
|
return "succession"
|
||||||
|
if new_node and old_node and new_node == old_node:
|
||||||
|
return "paraphrase"
|
||||||
|
if _looks_functional(new_val) or _looks_functional(old_val):
|
||||||
|
return "contradiction"
|
||||||
|
return "alternatives"
|
||||||
|
|
||||||
|
# ---- phase 1: alternatives query (the ambiguity substrate) -------------
|
||||||
|
def alternatives_of(self, src_name: str, rel: str) -> list[tuple[str, str]]:
|
||||||
|
"""The co-true readings of one (src, rel): the alternatives bucket.
|
||||||
|
|
||||||
|
Returns [(value, tail_node_name), ...] — the set the audit and the
|
||||||
|
render consume (the ambiguity was detected at INGEST, deterministi-
|
||||||
|
cally; nobody needs to re-derive it at judge time). Values appear
|
||||||
|
once, first-seen order; None tail when the edge carries no node.
|
||||||
|
"""
|
||||||
|
src = self.db.execute("SELECT id FROM nodes WHERE norm_name=?",
|
||||||
|
(norm_name(src_name),)).fetchone()
|
||||||
|
if not src:
|
||||||
|
return []
|
||||||
|
rows = self.db.execute(
|
||||||
|
"SELECT a.value_a, a.value_b, na.norm_name, nb.norm_name "
|
||||||
|
"FROM alternatives a "
|
||||||
|
"LEFT JOIN edges ea ON ea.id = a.edge_a "
|
||||||
|
"LEFT JOIN edges eb ON eb.id = a.edge_b "
|
||||||
|
"LEFT JOIN nodes na ON na.id = ea.dst_node "
|
||||||
|
"LEFT JOIN nodes nb ON nb.id = eb.dst_node "
|
||||||
|
"WHERE a.node=? AND a.rel=? ORDER BY a.id",
|
||||||
|
(src[0], rel)).fetchall()
|
||||||
|
seen: list[tuple[str, str]] = []
|
||||||
|
for va, vb, ta, tb in rows:
|
||||||
|
for val, tail in ((va, ta), (vb, tb)):
|
||||||
|
key = (val, tail or "")
|
||||||
|
if key not in [(s, t or "") for s, t in seen]:
|
||||||
|
seen.append((val, tail or ""))
|
||||||
|
return [(v, t or None) for v, t in seen]
|
||||||
|
|
||||||
# ---- queries --------------------------------------------------------------
|
# ---- queries --------------------------------------------------------------
|
||||||
def probe(self, seeds: list[str], depth: int = 1, limit: int = 20) -> list[EdgeView]:
|
def probe(self, seeds: list[str], depth: int = 1, limit: int = 20) -> list[EdgeView]:
|
||||||
|
|||||||
@@ -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,160 @@
|
|||||||
|
"""The derived-answer engine tests (phase 3a, RESEARCH-derived-answers Part 3).
|
||||||
|
|
||||||
|
No LLM in the loop: the ANSWER IS THE PROOF TERM — every step names its
|
||||||
|
operator and the edge ids it consumed; re-execution over the store IS the
|
||||||
|
verification. The DSL is conjunctive + temporal, typed, hand-writable
|
||||||
|
(the LLM translator arrives in 3b; the evaluator it must satisfy is
|
||||||
|
pinned here first).
|
||||||
|
|
||||||
|
Laws under test (the fixture = the live three-presidencies shape):
|
||||||
|
1. "Of what is Sánchez president?" — one lookup over office rels with
|
||||||
|
an open-now window filter returns the THREE bindings as a set
|
||||||
|
(Spain, PSOE, SI), each citing its edge.
|
||||||
|
2. The predecessor: conjunctive join (his office O + anyone holding O +
|
||||||
|
window-before + not-him) proves RAJOY as a CLOSED PATH — proof steps
|
||||||
|
name the edges and the interval check; re-execution verifies it.
|
||||||
|
3. select=latest_end distinguishes the predecessor (Rajoy ended 2018)
|
||||||
|
from a later holder of the same office (Feijóo, open — not before).
|
||||||
|
4. Empty bindings = UNKNOWN — silence, no invention.
|
||||||
|
5. Re-execution: same store → same proof (deterministic); a changed
|
||||||
|
store → the re-execution FAILS the stale proof (the check is real).
|
||||||
|
|
||||||
|
Run: .venv/bin/python knowledge/tests/prover.py
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
|
||||||
|
|
||||||
|
from knowledge.prover import evaluate, re_execute
|
||||||
|
from knowledge.store import KnowledgeStore
|
||||||
|
|
||||||
|
|
||||||
|
def fixture_kg() -> KnowledgeStore:
|
||||||
|
"""The live shape (phase-2 run): the three presidencies with open
|
||||||
|
windows, plus Rajoy's premiership (closed 2018) and Feijóo's later,
|
||||||
|
unrelated-office row — the distractor select=latest must reject."""
|
||||||
|
store = KnowledgeStore(f"{tempfile.mkdtemp()}/kg.sqlite")
|
||||||
|
docs = {}
|
||||||
|
for i, text in enumerate([
|
||||||
|
"He has been the prime minister of Spain since 2018.",
|
||||||
|
"He is Secretary-General of the PSOE since 2017.",
|
||||||
|
"He is the ninth president of Socialist International since 2022.",
|
||||||
|
"Mariano Rajoy was the prime minister of Spain from 2011 to 2018.",
|
||||||
|
"Alberto Núñez Feijóo has been the leader of the People's Party since 2018.",
|
||||||
|
"Mariano Rajoy lost the motion of no confidence in 2018.",
|
||||||
|
]):
|
||||||
|
url = f"u{i}"
|
||||||
|
doc = store.add_document(url=url, title="t", fetched_at="2026-10-25",
|
||||||
|
sha256=f"{i:064d}")
|
||||||
|
docs[i] = store.add_quote(doc_id=doc, verbatim=text, url=url,
|
||||||
|
access_date="2026-10-25")
|
||||||
|
store.add_edge("pedro sanchez", "prime minister of", "Spain",
|
||||||
|
quote_id=docs[0], t_start="2018")
|
||||||
|
store.add_edge("pedro sanchez", "secretary general of",
|
||||||
|
"Spanish Socialist Workers' Party (PSOE)",
|
||||||
|
quote_id=docs[1], t_start="2017")
|
||||||
|
store.add_edge("pedro sanchez", "president of",
|
||||||
|
"Socialist International", quote_id=docs[2], t_start="2022")
|
||||||
|
store.add_edge("mariano rajoy", "prime minister of", "Spain",
|
||||||
|
quote_id=docs[3], t_start="2011", t_end="2018")
|
||||||
|
store.add_edge("alberto nunez feijoo", "leader of",
|
||||||
|
"People's Party", quote_id=docs[4], t_start="2018")
|
||||||
|
return store
|
||||||
|
|
||||||
|
|
||||||
|
OF_WHAT_QUERY = {
|
||||||
|
"lookup": {"subject": "pedro sanchez",
|
||||||
|
"rel_any": ["prime minister of", "secretary general of",
|
||||||
|
"president of"],
|
||||||
|
"bind": "office"},
|
||||||
|
"filter": [{"open_now": ["office"]}],
|
||||||
|
"select": "all",
|
||||||
|
}
|
||||||
|
|
||||||
|
PREDECESSOR_QUERY = {
|
||||||
|
"lookup": [{"subject": "pedro sanchez",
|
||||||
|
"rel_any": ["prime minister of"],
|
||||||
|
"bind": "his_office"},
|
||||||
|
{"subject": "?x",
|
||||||
|
"rel_any": ["prime minister of"],
|
||||||
|
"bind": "other",
|
||||||
|
"same_value_as": "his_office"}],
|
||||||
|
"filter": [{"neq_value": ["?x", "pedro sanchez"]},
|
||||||
|
{"before": ["other", "his_office"]}],
|
||||||
|
"select": "latest_end",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_three_bindings():
|
||||||
|
store = fixture_kg()
|
||||||
|
proof = evaluate(store, OF_WHAT_QUERY)
|
||||||
|
vals = sorted(b["other_or_office_value"] if "other_or_office_value" in b
|
||||||
|
else b["office"]["value"] for b in proof.bindings)
|
||||||
|
assert "Spain" in vals and "Socialist International" in vals, vals
|
||||||
|
assert any("PSOE" in v for v in vals), vals
|
||||||
|
assert len(proof.bindings) == 3, f"three readings, got {proof.bindings}"
|
||||||
|
assert all(b["office"]["eid"] for b in proof.bindings), "every binding cites its edge"
|
||||||
|
print(f"ok: 'of what' returns the three bindings: {vals}")
|
||||||
|
|
||||||
|
|
||||||
|
def test_predecessor_closed_path():
|
||||||
|
store = fixture_kg()
|
||||||
|
proof = evaluate(store, PREDECESSOR_QUERY)
|
||||||
|
assert len(proof.bindings) == 1, f"one predecessor, got {proof.bindings}"
|
||||||
|
assert proof.bindings[0]["?x"] == "mariano rajoy", proof.bindings
|
||||||
|
edges = {e for step in proof.steps for e in step.edges}
|
||||||
|
assert len(edges) >= 2, "the closed path cites both the Rajoy and Sánchez edges"
|
||||||
|
assert any("before" in (step.note or "") or step.op == "filter"
|
||||||
|
for step in proof.steps), "the interval check is a named step"
|
||||||
|
assert re_execute(store, PREDECESSOR_QUERY, proof), "re-execution verifies"
|
||||||
|
print("ok: predecessor proved as a closed path (Rajoy), re-execution green")
|
||||||
|
|
||||||
|
|
||||||
|
def test_select_latest_rejects_open_distractor():
|
||||||
|
"""Feijóo holds a DIFFERENT office (leader of PP) — the join on
|
||||||
|
same_value_as (office=Spain) must keep him out entirely; the only
|
||||||
|
other Spain-PM is Rajoy. The distractor is structural, not temporal."""
|
||||||
|
store = fixture_kg()
|
||||||
|
proof = evaluate(store, PREDECESSOR_QUERY)
|
||||||
|
names = [b["?x"] for b in proof.bindings]
|
||||||
|
assert "alberto nunez feijoo" not in names, names
|
||||||
|
print(f"ok: distractor rejected (bindings: {names})")
|
||||||
|
|
||||||
|
|
||||||
|
def test_empty_is_unknown():
|
||||||
|
store = fixture_kg()
|
||||||
|
q = {"lookup": {"subject": "pedro sanchez",
|
||||||
|
"rel_any": ["chancellor of"], "bind": "office"},
|
||||||
|
"filter": [{"open_now": ["office"]}],
|
||||||
|
"select": "all"}
|
||||||
|
proof = evaluate(store, q)
|
||||||
|
assert proof.bindings == [], "no closed path: silence, never invention"
|
||||||
|
print("ok: no path -> empty bindings (UNKNOWN), no invention")
|
||||||
|
|
||||||
|
|
||||||
|
def test_reexecution_detects_stale_proof():
|
||||||
|
store = fixture_kg()
|
||||||
|
proof = evaluate(store, PREDECESSOR_QUERY)
|
||||||
|
assert re_execute(store, PREDECESSOR_QUERY, proof)
|
||||||
|
# retract Rajoy's edge -> the stale proof must FAIL re-execution
|
||||||
|
store.db.execute(
|
||||||
|
"UPDATE edges SET retracted=1, retraction_reason='test' "
|
||||||
|
"WHERE src_node IN (SELECT id FROM nodes WHERE norm_name='mariano rajoy')")
|
||||||
|
store.db.commit()
|
||||||
|
assert not re_execute(store, PREDECESSOR_QUERY, proof), \
|
||||||
|
"a changed store must fail the stale proof (the check is real)"
|
||||||
|
print("ok: re-execution fails a stale proof after retraction — the check is real")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
test_three_bindings()
|
||||||
|
test_predecessor_closed_path()
|
||||||
|
test_select_latest_rejects_open_distractor()
|
||||||
|
test_empty_is_unknown()
|
||||||
|
test_reexecution_detects_stale_proof()
|
||||||
|
print("\nprover: 5/5 ok")
|
||||||
@@ -0,0 +1,160 @@
|
|||||||
|
"""Deterministic query composition (the old TRANSLATE LLM, removed 23/10).
|
||||||
|
|
||||||
|
Laws under test (his weights-tightness call):
|
||||||
|
1. Every token of every query traces to the question or the evidence —
|
||||||
|
the model's own knowledge of the entities can no longer steer
|
||||||
|
retrieval. The 22/10 logs caught the LLM putting the ANSWER into
|
||||||
|
queries ('Pedro Sánchez 2018 investiture…' for a term-start question).
|
||||||
|
2. Deterministic: same inputs -> same queries, same order, every time.
|
||||||
|
3. Never empty: a question with no entities still gets its keyword join.
|
||||||
|
4. Top-N over a list row in evidence slices the FIRST N members by source
|
||||||
|
order — never dumps all members into one query.
|
||||||
|
5. The subject NE + plural head noun surface the Wikipedia list article
|
||||||
|
('List of rivers of Italy'), the source enumerations actually live in.
|
||||||
|
|
||||||
|
No network, no LLM. Run: uv run python knowledge/tests/queries.py
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # code/
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent)) # repo root
|
||||||
|
|
||||||
|
from knowledge.queries import compose_queries, keywords, proper_nouns
|
||||||
|
|
||||||
|
|
||||||
|
def test_single_entity_with_attribute():
|
||||||
|
q, e = compose_queries("What is the length of Po?")
|
||||||
|
assert q == ["Po length"], q
|
||||||
|
assert e == ["Po"], e
|
||||||
|
print("ok single entity: NE + salient keywords ('Po length')")
|
||||||
|
|
||||||
|
|
||||||
|
def test_multi_entity_join():
|
||||||
|
q, e = compose_queries("What is the discharge of the Po, Adige and Tiber?")
|
||||||
|
assert q[0].startswith("Po"), q
|
||||||
|
assert "Adige" in q[0] and "Tiber" in q[0], q
|
||||||
|
print("ok multi-NE join:", q)
|
||||||
|
|
||||||
|
|
||||||
|
def test_enumeration_list_variant():
|
||||||
|
q, e = compose_queries("What are the three longest rivers of Italy?",
|
||||||
|
list_mode=True)
|
||||||
|
assert q == ["Italy rivers", "List of rivers of Italy"], q
|
||||||
|
print("ok enumeration: subject + plural, then the list-article shape")
|
||||||
|
|
||||||
|
|
||||||
|
def test_evidence_entities_carry_reference_resolution():
|
||||||
|
# 'that state' + E1: France — the evidence resolves the reference,
|
||||||
|
# not the model's knowledge of anything
|
||||||
|
q, e = compose_queries("What is the longest river in that state?",
|
||||||
|
evidence_entities=["France"])
|
||||||
|
assert q == ["France"], q
|
||||||
|
assert e == ["France"], e
|
||||||
|
print("ok reference resolution from evidence, zero weights")
|
||||||
|
|
||||||
|
|
||||||
|
def test_top_n_slices_evidence_by_source_order():
|
||||||
|
# the case the LLM 'helped' with by guessing Po/Adige/Tiber from its
|
||||||
|
# weights — the members are now sliced from the evidence row itself
|
||||||
|
ev = ["Po", "Adige", "Tiber", "Dora", "Reno", "Ticino"]
|
||||||
|
q, e = compose_queries(
|
||||||
|
"Ranked by length, which three of these rivers are the longest in Italy?",
|
||||||
|
evidence_entities=ev)
|
||||||
|
assert q[0] == "Po Adige Tiber", q
|
||||||
|
assert e[:3] == ["Po", "Adige", "Tiber"], e
|
||||||
|
assert len(e) <= 8, e
|
||||||
|
print("ok top-N ask: first N evidence members by source order")
|
||||||
|
|
||||||
|
|
||||||
|
def test_top_n_never_dumps_all_members():
|
||||||
|
ev = [f"R{i}" for i in range(22)]
|
||||||
|
q, e = compose_queries("which three of these rivers are longest?",
|
||||||
|
evidence_entities=ev)
|
||||||
|
assert q[0].split() == ["R0", "R1", "R2"], q
|
||||||
|
print("ok 22-member list: query carries only the sliced 3")
|
||||||
|
|
||||||
|
|
||||||
|
def test_two_subject_ne_gets_no_list_shape():
|
||||||
|
# 'List of countries of Union' would be garbage — with 2+ NEs the
|
||||||
|
# list-article shape is skipped
|
||||||
|
q, e = compose_queries(
|
||||||
|
"Which countries in the continent of Europe are not members of the European Union?",
|
||||||
|
list_mode=True)
|
||||||
|
assert not any(x.startswith("List of") for x in q), q
|
||||||
|
print("ok two subject NEs: no ambiguous list shape:", q)
|
||||||
|
|
||||||
|
|
||||||
|
def test_no_entities_keyword_join():
|
||||||
|
q, e = compose_queries("What is the speed of light?")
|
||||||
|
assert q == ["speed light"], q
|
||||||
|
assert e == [], e
|
||||||
|
print("ok no NEs: keyword join, never empty")
|
||||||
|
|
||||||
|
|
||||||
|
def test_sentence_initial_capital_not_a_subject():
|
||||||
|
# 'During'/'Ranked' are capitalized by sentence rules; with other NEs
|
||||||
|
# present they must not steer the query
|
||||||
|
q, e = compose_queries("During what years did Pedro Sanchez serve as President?")
|
||||||
|
assert q[0].startswith("Pedro"), q
|
||||||
|
assert "During" not in q[0], q
|
||||||
|
print("ok sentence-initial capital dropped when other NEs exist:", q)
|
||||||
|
|
||||||
|
|
||||||
|
def test_weights_never_enter_queries():
|
||||||
|
# the regression the audit found: model knowledge injected into
|
||||||
|
# retrieval ('2018 investiture', 'Prime Minister of Spain' for a
|
||||||
|
# question that says neither). Compose the same logged questions and
|
||||||
|
# assert every query token traces to question ∪ evidence.
|
||||||
|
cases = [
|
||||||
|
("When did Pedro Sanchez's term as President begin (the start date of their presidency)?", []),
|
||||||
|
("Which country's government does Pedro Sanchez lead as President?", []),
|
||||||
|
("What are the three longest rivers of Italy?", []),
|
||||||
|
("What is the length of Po?", []),
|
||||||
|
]
|
||||||
|
for question, ev in cases:
|
||||||
|
qs, _ = compose_queries(question, evidence_entities=ev)
|
||||||
|
material = set(keywords(question)) | {
|
||||||
|
w.casefold() for w in
|
||||||
|
__import__("re").findall(r"[A-Za-zÀ-ÿ0-9']+", question)} | {
|
||||||
|
w.casefold() for w in ev}
|
||||||
|
for query in qs:
|
||||||
|
for tok in __import__("re").findall(r"[A-Za-zÀ-ÿ0-9']+", query):
|
||||||
|
assert tok.casefold() in material, \
|
||||||
|
f"untraceable token {tok!r} in {query!r} for {question!r}"
|
||||||
|
print("ok every query token traces to question ∪ evidence (logged cases)")
|
||||||
|
|
||||||
|
|
||||||
|
def test_deterministic():
|
||||||
|
args = ("What are the three longest rivers of Italy?", None, True)
|
||||||
|
r1 = compose_queries(*args)
|
||||||
|
r2 = compose_queries(*args)
|
||||||
|
assert r1 == r2
|
||||||
|
print("ok same inputs -> same outputs")
|
||||||
|
|
||||||
|
|
||||||
|
def test_proper_nouns_unchanged():
|
||||||
|
# the guards depend on these exact semantics (guards.py contract)
|
||||||
|
assert proper_nouns("Which are the three longest rivers of Italy?") == {"Italy"}
|
||||||
|
assert proper_nouns("What is the discharge of the Po, Adige and Tiber?") == {"Po", "Adige", "Tiber"}
|
||||||
|
assert keywords("Which are the three longest rivers of Italy?") == \
|
||||||
|
["three", "longest", "rivers", "italy"]
|
||||||
|
print("ok proper_nouns/keywords semantics unchanged for the guards")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
test_single_entity_with_attribute()
|
||||||
|
test_multi_entity_join()
|
||||||
|
test_enumeration_list_variant()
|
||||||
|
test_evidence_entities_carry_reference_resolution()
|
||||||
|
test_top_n_slices_evidence_by_source_order()
|
||||||
|
test_top_n_never_dumps_all_members()
|
||||||
|
test_two_subject_ne_gets_no_list_shape()
|
||||||
|
test_no_entities_keyword_join()
|
||||||
|
test_sentence_initial_capital_not_a_subject()
|
||||||
|
test_weights_never_enter_queries()
|
||||||
|
test_deterministic()
|
||||||
|
test_proper_nouns_unchanged()
|
||||||
|
print("\nqueries tests passed")
|
||||||
@@ -21,7 +21,8 @@ from __future__ import annotations
|
|||||||
import sys
|
import sys
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # code/
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
|
||||||
|
|
||||||
import knowledge.embeddings as emb
|
import knowledge.embeddings as emb
|
||||||
from knowledge.expert import KnowledgeConfig, KnowledgeExpert
|
from knowledge.expert import KnowledgeConfig, KnowledgeExpert
|
||||||
|
|||||||
@@ -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()
|
||||||
@@ -73,11 +73,16 @@ def test_store_four_cases(tmp="/tmp/floop_kg_test.sqlite"):
|
|||||||
assert a and b
|
assert a and b
|
||||||
conflicts = ks.db.execute("SELECT COUNT(*) FROM conflicts").fetchone()[0]
|
conflicts = ks.db.execute("SELECT COUNT(*) FROM conflicts").fetchone()[0]
|
||||||
assert conflicts == 0, "dated different values are a time series, not a conflict"
|
assert conflicts == 0, "dated different values are a time series, not a conflict"
|
||||||
# contradiction: same rel, undated different values -> exposed conflict
|
# contradiction: same rel, undated different FUNCTIONAL values -> exposed conflict
|
||||||
c1 = ks.add_edge("Seine", "length_km", "777", q1)
|
# (phase 1 taxonomy: entity-ish pairs are alternatives; numeric/date
|
||||||
c2 = ks.add_edge("Seine", "length_km", "776", q1)
|
# values on a functional relation keep the contradiction. Different
|
||||||
|
# quotes — same-quote pairs are co-asserted conjunction, by law.)
|
||||||
|
qc1 = ks.add_quote(doc, "The Seine is 777 kilometres long.", "url", "d")
|
||||||
|
qc2 = ks.add_quote(doc, "One source lists the Seine at 776 kilometres.", "url", "d")
|
||||||
|
c1 = ks.add_edge("Seine", "length_km", "777", qc1)
|
||||||
|
c2 = ks.add_edge("Seine", "length_km", "776", qc2)
|
||||||
conflicts = ks.db.execute("SELECT COUNT(*) FROM conflicts").fetchone()[0]
|
conflicts = ks.db.execute("SELECT COUNT(*) FROM conflicts").fetchone()[0]
|
||||||
assert conflicts == 1, "undated different values must be exposed as conflict"
|
assert conflicts == 1, "undated different functional values must be exposed as conflict"
|
||||||
# probe: seeds find edges with quotes
|
# probe: seeds find edges with quotes
|
||||||
rows = ks.probe(["Loire", "loire"])
|
rows = ks.probe(["Loire", "loire"])
|
||||||
assert any(r.rel == "longest_river_of" and r.dst == "France" for r in rows)
|
assert any(r.rel == "longest_river_of" and r.dst == "France" for r in rows)
|
||||||
|
|||||||
@@ -6,7 +6,8 @@ from __future__ import annotations
|
|||||||
import sys
|
import sys
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # code/
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
|
||||||
|
|
||||||
from knowledge.wiki import (parse_tables, tables_as_chunks, format_table_frag,
|
from knowledge.wiki import (parse_tables, tables_as_chunks, format_table_frag,
|
||||||
parse_stop_table)
|
parse_stop_table)
|
||||||
@@ -63,7 +64,7 @@ def test_format_and_parse_stop():
|
|||||||
|
|
||||||
def make_expert(store: KnowledgeStore) -> KnowledgeExpert:
|
def make_expert(store: KnowledgeStore) -> KnowledgeExpert:
|
||||||
e = KnowledgeExpert.__new__(KnowledgeExpert) # no LLM init
|
e = KnowledgeExpert.__new__(KnowledgeExpert) # no LLM init
|
||||||
e.cfg = KnowledgeConfig()
|
e.cfg = KnowledgeConfig(extract_mode="single") # this test pins the LEGACY path
|
||||||
e.store = store
|
e.store = store
|
||||||
e.streams = None
|
e.streams = None
|
||||||
e._checked = e._merged = 0
|
e._checked = e._merged = 0
|
||||||
|
|||||||
@@ -0,0 +1,188 @@
|
|||||||
|
"""Conflict taxonomy tests (phase 1, RESEARCH-derived-answers.md Part 1).
|
||||||
|
|
||||||
|
The four-case classifier conflated conjunction, paraphrase and polisèmia
|
||||||
|
into "contradiction" — 20 conflict pairs in the live KG after one Pedro
|
||||||
|
run, ZERO real contradictions. The taxonomy (deterministic, cost-ordered):
|
||||||
|
|
||||||
|
co-asserted same quote_id — one trusted sentence asserts both values
|
||||||
|
(conjunction, never a conflict)
|
||||||
|
paraphrase discriminant-free surface OR tails resolving to the same
|
||||||
|
node — the same fact said differently: MERGE (same_as,
|
||||||
|
append-only; corroboration up, no conflict row)
|
||||||
|
alternatives different discriminant entity, tails resolve to different
|
||||||
|
nodes, multi-valued relation — co-true readings (the
|
||||||
|
polisèmia: Spain / PSOE / SI). Recorded as alternatives,
|
||||||
|
not contradictions.
|
||||||
|
temporal both dated (time series) — unchanged law
|
||||||
|
contradiction what survives: functional relation, incompatible values
|
||||||
|
|
||||||
|
Laws under test (fixtures = the live 20-pair inventory):
|
||||||
|
1. The platform sentence split into 5 "called for" facts with the SAME
|
||||||
|
quote never yields conflicts (co-asserted).
|
||||||
|
2. "Prime Minister of Spain" vs "president of the Government (Spanish:
|
||||||
|
Presidente del Gobierno)" merges (paraphrase — tails resolve to the
|
||||||
|
same office; no conflict row).
|
||||||
|
3. The three presidencies (PM-of-Spain / SG-of-PSOE / president-of-SI)
|
||||||
|
land in the alternatives bucket, pairwise — never "contradiction".
|
||||||
|
4. Two different birth dates stay a real contradiction (functional rel).
|
||||||
|
5. Both-dated pairs stay temporal.
|
||||||
|
6. The alternatives bucket is queryable: the store exposes, per
|
||||||
|
(src, rel), the co-true value set with their tails — the ambiguity
|
||||||
|
substrate for the audit and the render.
|
||||||
|
|
||||||
|
Run: .venv/bin/python knowledge/tests/taxonomy.py
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
|
||||||
|
|
||||||
|
from knowledge.store import KnowledgeStore, norm_name
|
||||||
|
|
||||||
|
|
||||||
|
def make_store() -> tuple[KnowledgeStore, str]:
|
||||||
|
d = tempfile.mkdtemp()
|
||||||
|
return KnowledgeStore(f"{d}/kg.sqlite"), d
|
||||||
|
|
||||||
|
|
||||||
|
def add_doc(store: KnowledgeStore, text: str) -> int:
|
||||||
|
"""One document + one quote carrying the given verbatim text."""
|
||||||
|
url = f"u{abs(hash(text)) % 10**8}"
|
||||||
|
doc_id = store.add_document(url=url, title="t", fetched_at="2026-10-25",
|
||||||
|
sha256=f"{abs(hash(text)) % 10**16:016x}")
|
||||||
|
return store.add_quote(doc_id=doc_id, verbatim=text, url=url,
|
||||||
|
access_date="2026-10-25")
|
||||||
|
|
||||||
|
|
||||||
|
def test_coasserted_never_conflicts():
|
||||||
|
"""The platform sentence: 5 facts, one quote — conjunction, not conflict."""
|
||||||
|
store, _ = make_store()
|
||||||
|
q = add_doc(store, "Presenting a platform based on political regeneration, "
|
||||||
|
"Sánchez called for constitutional reforms establishing "
|
||||||
|
"federalism; a new progressive fiscal policy; extending "
|
||||||
|
"the welfare state to all citizens; increasing the "
|
||||||
|
"membership of labour unions; and regaining the "
|
||||||
|
"confidence of Socialist voters.")
|
||||||
|
for dst in ("constitutional reforms establishing federalism",
|
||||||
|
"a new progressive fiscal policy",
|
||||||
|
"extending the welfare state to all citizens",
|
||||||
|
"increasing the membership of labour unions",
|
||||||
|
"regaining the confidence of Socialist voters"):
|
||||||
|
store.add_edge("pedro sanchez", "called for", dst, quote_id=q)
|
||||||
|
n = store.db.execute("SELECT COUNT(*) FROM conflicts").fetchone()[0]
|
||||||
|
assert n == 0, f"co-asserted facts must not conflict (got {n})"
|
||||||
|
print("ok: 5 same-quote facts -> 0 conflicts (co-asserted conjunction)")
|
||||||
|
|
||||||
|
|
||||||
|
def test_paraphrase_merges():
|
||||||
|
"""Same office, two surfaces, tails resolve to the same node -> merge."""
|
||||||
|
store, _ = make_store()
|
||||||
|
q1 = add_doc(store, "The prime minister of Spain, officially the president "
|
||||||
|
"of the Government, is the head of government of Spain.")
|
||||||
|
q2 = add_doc(store, "The head of government of Spain is the Prime Minister "
|
||||||
|
"of Spain, often called president of the Government.")
|
||||||
|
a = store.add_edge("pedro sanchez", "position held",
|
||||||
|
"prime minister of Spain",
|
||||||
|
dst_node_name="Prime Minister of Spain", quote_id=q1)
|
||||||
|
b = store.add_edge("pedro sanchez", "position held",
|
||||||
|
"president of the Government (Spanish: Presidente del Gobierno)",
|
||||||
|
dst_node_name="Prime Minister of Spain", quote_id=q2)
|
||||||
|
assert a and b, "both edges ingested"
|
||||||
|
n = store.db.execute("SELECT COUNT(*) FROM conflicts").fetchone()[0]
|
||||||
|
assert n == 0, f"a paraphrase must merge, not conflict (got {n})"
|
||||||
|
# corroboration counted on the canonical edge, same_as alias recorded
|
||||||
|
canon = store.db.execute(
|
||||||
|
"SELECT corroboration FROM edges WHERE id=?", (min(a, b),)).fetchone()
|
||||||
|
assert canon and canon[0] >= 2, "paraphrase merge must corroborate the canonical edge"
|
||||||
|
aliases = store.db.execute(
|
||||||
|
"SELECT COUNT(*) FROM same_as WHERE edge_a IN (?,?) OR edge_b IN (?,?)",
|
||||||
|
(a, b, a, b)).fetchone()[0]
|
||||||
|
assert aliases >= 1, "the merge must record a same_as alias (append-only law)"
|
||||||
|
print("ok: paraphrase merges (canonical corroborated, same_as recorded)")
|
||||||
|
|
||||||
|
|
||||||
|
def test_three_presidencies_are_alternatives():
|
||||||
|
"""THE polisèmia: three offices, three institutions, co-true.
|
||||||
|
|
||||||
|
Live shape (run 090402 inventory): the three readings came from
|
||||||
|
DIFFERENT sentences — the intro sentence carries the party/SI offices,
|
||||||
|
the lead paragraph the premiership. Same-quote co-assertion would be
|
||||||
|
the conjunction case; the presidencies are separate assertions and
|
||||||
|
land in alternatives."""
|
||||||
|
store, _ = make_store()
|
||||||
|
q1 = add_doc(store, "He has been the prime minister of Spain since 2018.")
|
||||||
|
q2 = add_doc(store, "A member of the Spanish Socialist Workers' Party "
|
||||||
|
"(PSOE), he is also Secretary-General of the party "
|
||||||
|
"since 2017.")
|
||||||
|
q3 = add_doc(store, "He is the ninth president of Socialist "
|
||||||
|
"International since 2022.")
|
||||||
|
store.add_edge("pedro sanchez", "position held",
|
||||||
|
"prime minister of Spain since 2018",
|
||||||
|
dst_node_name="Spain", quote_id=q1)
|
||||||
|
store.add_edge("pedro sanchez", "position held",
|
||||||
|
"Secretary-General of the PSOE since 2017",
|
||||||
|
dst_node_name="PSOE", quote_id=q2)
|
||||||
|
store.add_edge("pedro sanchez", "position held",
|
||||||
|
"ninth president of Socialist International since 2022",
|
||||||
|
dst_node_name="Socialist International", quote_id=q3)
|
||||||
|
real = store.db.execute("SELECT COUNT(*) FROM conflicts").fetchone()[0]
|
||||||
|
alts = store.db.execute("SELECT COUNT(*) FROM alternatives").fetchone()[0]
|
||||||
|
assert real == 0, f"co-true readings are not contradictions (got {real})"
|
||||||
|
assert alts == 3, f"three pairwise alternatives expected (got {alts})"
|
||||||
|
print("ok: three presidencies -> 3 alternatives, 0 contradictions")
|
||||||
|
|
||||||
|
|
||||||
|
def test_alternatives_queryable():
|
||||||
|
"""The ambiguity substrate: per (src, rel) the co-true value set."""
|
||||||
|
store, _ = make_store()
|
||||||
|
q1 = add_doc(store, "He has been the prime minister of Spain since 2018.")
|
||||||
|
q2 = add_doc(store, "He is also Secretary-General of the party since 2017.")
|
||||||
|
store.add_edge("pedro sanchez", "position held",
|
||||||
|
"prime minister of Spain since 2018", dst_node_name="Spain", quote_id=q1)
|
||||||
|
store.add_edge("pedro sanchez", "position held",
|
||||||
|
"Secretary-General of the PSOE since 2017",
|
||||||
|
dst_node_name="PSOE", quote_id=q2)
|
||||||
|
got = store.alternatives_of("pedro sanchez", "position held")
|
||||||
|
vals = {norm_name(v)[:30] for v, _t in got}
|
||||||
|
assert len(got) == 2 and len(vals) == 2, f"expected 2 alternative readings, got {got}"
|
||||||
|
print(f"ok: alternatives_of returns the co-true set: {[v[:40] for v, _ in got]}")
|
||||||
|
|
||||||
|
|
||||||
|
def test_functional_contradiction_survives():
|
||||||
|
"""Two different birth dates: a REAL contradiction, kept."""
|
||||||
|
store, _ = make_store()
|
||||||
|
q1 = add_doc(store, "Pedro Sánchez was born on 29 February 1972.")
|
||||||
|
q2 = add_doc(store, "Pedro Sánchez was born on 28 February 1972.")
|
||||||
|
store.add_edge("pedro sanchez", "date of birth", "29 February 1972", quote_id=q1)
|
||||||
|
store.add_edge("pedro sanchez", "date of birth", "28 February 1972", quote_id=q2)
|
||||||
|
real = store.db.execute("SELECT COUNT(*) FROM conflicts").fetchone()[0]
|
||||||
|
assert real == 1, f"a functional contradiction must stay (got {real})"
|
||||||
|
print("ok: two birth dates -> 1 real contradiction (functional rel)")
|
||||||
|
|
||||||
|
|
||||||
|
def test_temporal_unchanged():
|
||||||
|
"""Both dated pairs: temporal, coexist — the old law, untouched."""
|
||||||
|
store, _ = make_store()
|
||||||
|
q1 = add_doc(store, "In 2014 he was elected Secretary-General.")
|
||||||
|
q2 = add_doc(store, "In 2017 he was re-elected Secretary-General.")
|
||||||
|
store.add_edge("pedro sanchez", "elected secretary-general",
|
||||||
|
"in 2014", ref_date="2014", quote_id=q1)
|
||||||
|
store.add_edge("pedro sanchez", "elected secretary-general",
|
||||||
|
"in 2017", ref_date="2017", quote_id=q2)
|
||||||
|
n = store.db.execute("SELECT COUNT(*) FROM conflicts").fetchone()[0]
|
||||||
|
assert n == 0, f"dated pairs are temporal, not conflicts (got {n})"
|
||||||
|
print("ok: both-dated pair stays temporal, no conflict")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
test_coasserted_never_conflicts()
|
||||||
|
test_paraphrase_merges()
|
||||||
|
test_three_presidencies_are_alternatives()
|
||||||
|
test_alternatives_queryable()
|
||||||
|
test_functional_contradiction_survives()
|
||||||
|
test_temporal_unchanged()
|
||||||
|
print("\ntaxonomy: 6/6 ok")
|
||||||
@@ -0,0 +1,161 @@
|
|||||||
|
"""Temporal restriction tests (phase 2, RESEARCH-derived-answers Part 2).
|
||||||
|
|
||||||
|
The extractor's temporal vocabulary is RESTRICTIONS, never Allen labels:
|
||||||
|
start/end/point (dates, optional, containment-checked against the quote),
|
||||||
|
granularity, and fact-order assertions {before, after, concurrent} that
|
||||||
|
reference sibling facts by local index. The Allen algebra stays a
|
||||||
|
COMPUTED VIEW over endpoints (the store's job); asking the model to
|
||||||
|
choose labels would replace transcription with classification and
|
||||||
|
produce uncheckable, granularity-blind, silently-disagreeing labels.
|
||||||
|
|
||||||
|
Laws under test:
|
||||||
|
1. A date field not contained in the quote is REJECTED (the honest law:
|
||||||
|
the model proposes, code verifies against the source surface).
|
||||||
|
2. Windows feed the taxonomy: overlapping open windows on one (src,rel)
|
||||||
|
are alternatives (coexistence is interval arithmetic, not statistics);
|
||||||
|
disjoint windows are succession — never a conflict.
|
||||||
|
3. 'since 2018' means END OPEN; two open ends overlap.
|
||||||
|
4. Order assertions between sibling facts survive ingest as fact_order
|
||||||
|
rows (edges are addressable; reification is free).
|
||||||
|
5. Empty temporal fields stay empty — no invented dates.
|
||||||
|
|
||||||
|
The extractor call itself is scripted (structured-output Fact objects,
|
||||||
|
like the live dspy adapter returns); no network.
|
||||||
|
Run: .venv/bin/python knowledge/tests/temporal.py
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
|
||||||
|
|
||||||
|
from knowledge.extract import Fact
|
||||||
|
from knowledge.store import KnowledgeStore
|
||||||
|
|
||||||
|
|
||||||
|
def make_store() -> KnowledgeStore:
|
||||||
|
return KnowledgeStore(f"{tempfile.mkdtemp()}/kg.sqlite")
|
||||||
|
|
||||||
|
|
||||||
|
def add_doc(store: KnowledgeStore, text: str) -> int:
|
||||||
|
url = f"u{abs(hash(text)) % 10**8}"
|
||||||
|
doc_id = store.add_document(url=url, title="t", fetched_at="2026-10-25",
|
||||||
|
sha256=f"{abs(hash(text)) % 10**16:016x}")
|
||||||
|
return store.add_quote(doc_id=doc_id, verbatim=text, url=url,
|
||||||
|
access_date="2026-10-25")
|
||||||
|
|
||||||
|
|
||||||
|
# --- the Fact contract ---------------------------------------------------------
|
||||||
|
|
||||||
|
def test_fact_temporal_fields():
|
||||||
|
"""Fact carries optional start/end/point/granularity + orders."""
|
||||||
|
f = Fact(subject="X", relation="position held", object="President of A",
|
||||||
|
quote="X was president of A and B at the same time for one month.",
|
||||||
|
start="2020", end=None, point=None, granularity="year",
|
||||||
|
orders=[])
|
||||||
|
assert f.start == "2020" and f.granularity == "year"
|
||||||
|
f2 = Fact(subject="X", relation="position held", object="President of B",
|
||||||
|
quote="X was also president of B.",
|
||||||
|
start=None, end=None, point=None, granularity=None,
|
||||||
|
orders=[{"rel": "concurrent", "other": 0}])
|
||||||
|
assert f2.orders[0]["rel"] == "concurrent"
|
||||||
|
print("ok: Fact typed temporal fields + order assertions")
|
||||||
|
|
||||||
|
|
||||||
|
def test_date_not_in_quote_rejected():
|
||||||
|
"""The honest law: a temporal field must be contained in the quote."""
|
||||||
|
from knowledge.checks import check_candidate
|
||||||
|
good = {"subject": "X", "relation": "term start",
|
||||||
|
"object": "2018", "quote": "X took office in 2018.",
|
||||||
|
"start": "2018"}
|
||||||
|
bad = {"subject": "X", "relation": "term start",
|
||||||
|
"object": "2018", "quote": "X took office some years ago.",
|
||||||
|
"start": "2018"}
|
||||||
|
ok, reason = check_candidate(good, "X took office in 2018.")
|
||||||
|
assert ok, f"contained date must pass: {reason}"
|
||||||
|
ok, reason = check_candidate(bad, "X took office some years ago.")
|
||||||
|
assert not ok, f"invented date must be rejected, got pass ({reason})"
|
||||||
|
print("ok: temporal containment check (invented dates rejected)")
|
||||||
|
|
||||||
|
|
||||||
|
# --- windows feed the taxonomy ---------------------------------------------------
|
||||||
|
|
||||||
|
def test_overlapping_open_windows_are_alternatives():
|
||||||
|
"""'since 2018' and 'since 2022' on one (src, rel): two open intervals
|
||||||
|
overlap -> coexistence -> alternatives, not contradiction."""
|
||||||
|
store = make_store()
|
||||||
|
q1 = add_doc(store, "He has been the prime minister of Spain since 2018.")
|
||||||
|
q2 = add_doc(store, "He is the ninth president of Socialist International since 2022.")
|
||||||
|
store.add_edge("pedro sanchez", "position held",
|
||||||
|
"prime minister of Spain", quote_id=q1, t_start="2018")
|
||||||
|
store.add_edge("pedro sanchez", "position held",
|
||||||
|
"ninth president of Socialist International", quote_id=q2,
|
||||||
|
t_start="2022")
|
||||||
|
conf = store.db.execute("SELECT COUNT(*) FROM conflicts").fetchone()[0]
|
||||||
|
alts = store.db.execute("SELECT COUNT(*) FROM alternatives").fetchone()[0]
|
||||||
|
assert conf == 0, f"overlapping open windows must not conflict (got {conf})"
|
||||||
|
assert alts >= 1, "overlapping open windows are co-true alternatives"
|
||||||
|
print("ok: overlapping open windows -> alternatives (interval arithmetic)")
|
||||||
|
|
||||||
|
|
||||||
|
def test_disjoint_windows_are_succession_not_conflict():
|
||||||
|
"""Leader of the Opposition (2014-2018) vs prime minister (2018-): the
|
||||||
|
'became' pair — disjoint windows mean succession, never a conflict."""
|
||||||
|
store = make_store()
|
||||||
|
q1 = add_doc(store, "In 2014, he was elected, becoming Leader of the Opposition.")
|
||||||
|
q2 = add_doc(store, "In 2018 he became prime minister.")
|
||||||
|
store.add_edge("pedro sanchez", "became", "Leader of the Opposition",
|
||||||
|
quote_id=q1, t_start="2014", t_end="2018")
|
||||||
|
store.add_edge("pedro sanchez", "became", "prime minister",
|
||||||
|
quote_id=q2, t_start="2018")
|
||||||
|
conf = store.db.execute("SELECT COUNT(*) FROM conflicts").fetchone()[0]
|
||||||
|
alts = store.db.execute("SELECT COUNT(*) FROM alternatives").fetchone()[0]
|
||||||
|
assert conf == 0, f"succession is not a conflict (got {conf})"
|
||||||
|
assert alts == 0, f"disjoint windows are not co-true (got {alts} alts)"
|
||||||
|
print("ok: disjoint windows -> succession, no conflict, no alternatives")
|
||||||
|
|
||||||
|
|
||||||
|
def test_empty_windows_stay_empty():
|
||||||
|
"""No dates in the text -> no dates in the edge. No invention."""
|
||||||
|
store = make_store()
|
||||||
|
q1 = add_doc(store, "He was a city councillor in Madrid.")
|
||||||
|
q2 = add_doc(store, "He later was a member of parliament.")
|
||||||
|
e1 = store.add_edge("pedro sanchez", "became", "city councillor", quote_id=q1)
|
||||||
|
e2 = store.add_edge("pedro sanchez", "became", "member of parliament", quote_id=q2)
|
||||||
|
row = store.db.execute("SELECT t_start, t_end FROM edges WHERE id=?", (e1,)).fetchone()
|
||||||
|
assert row == (None, None), f"undated facts keep empty windows ({row})"
|
||||||
|
print("ok: no dates in text -> empty windows stay empty")
|
||||||
|
|
||||||
|
|
||||||
|
# --- fact_order -------------------------------------------------------------------
|
||||||
|
|
||||||
|
def test_order_assertions_ingest():
|
||||||
|
"""'X was leader of the opposition BEFORE being president' -> two facts,
|
||||||
|
one fact_order row (before), reification-free (edges carry ids)."""
|
||||||
|
store = make_store()
|
||||||
|
q = add_doc(store, "X was leader of the opposition before becoming president.")
|
||||||
|
a = store.add_edge("X", "position held", "leader of the opposition", quote_id=q)
|
||||||
|
b = store.add_edge("X", "position held", "president", quote_id=q)
|
||||||
|
store.add_fact_order(a, b, "before", quote_id=q)
|
||||||
|
rows = store.db.execute(
|
||||||
|
"SELECT rel FROM fact_order WHERE edge_a=? AND edge_b=?", (a, b)).fetchall()
|
||||||
|
assert rows and rows[0][0] == "before", f"fact_order row missing: {rows}"
|
||||||
|
# concurrent order also representable
|
||||||
|
c = store.add_edge("X", "position held", "president of B", quote_id=q)
|
||||||
|
store.add_fact_order(b, c, "concurrent", quote_id=q)
|
||||||
|
n = store.db.execute("SELECT COUNT(*) FROM fact_order").fetchone()[0]
|
||||||
|
assert n == 2, f"expected 2 fact_order rows, got {n}"
|
||||||
|
print("ok: fact_order rows ingest (before/concurrent between addressable edges)")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
test_fact_temporal_fields()
|
||||||
|
test_date_not_in_quote_rejected()
|
||||||
|
test_overlapping_open_windows_are_alternatives()
|
||||||
|
test_disjoint_windows_are_succession_not_conflict()
|
||||||
|
test_empty_windows_stay_empty()
|
||||||
|
test_order_assertions_ingest()
|
||||||
|
print("\ntemporal: 6/6 ok")
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
"""The question->DSL translator tests (phase 3b, RESEARCH-derived-answers
|
||||||
|
Part 3) — the LLM at the INPUT boundary, validated before execution.
|
||||||
|
|
||||||
|
Laws under test:
|
||||||
|
1. The translator is ONE structured-output call (the MASK/EXTRACT
|
||||||
|
class): question + the store's relation vocabulary in, typed DSL out.
|
||||||
|
2. Validation before execution: an unknown filter/select/rel in the
|
||||||
|
proposal is REJECTED deterministically (mistranslation surfaces as an
|
||||||
|
invalid term, never as a wrong answer). The model proposes, code
|
||||||
|
decides — a bad translation can never reach evaluate().
|
||||||
|
3. The two live questions translate to terms the pinned evaluator
|
||||||
|
executes: "of what is X president" -> lookup + open_now + all;
|
||||||
|
"who was president before X" -> the two-lookup join + before +
|
||||||
|
latest_end. (Scripted LM responses; no network.)
|
||||||
|
4. Untranslatable questions return None — the caller falls back to the
|
||||||
|
judge path, honestly.
|
||||||
|
|
||||||
|
Run: .venv/bin/python knowledge/tests/translate_dsl.py
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
|
||||||
|
|
||||||
|
from knowledge.prover import validate_query
|
||||||
|
from knowledge.translate_dsl import TranslateToDSL, translate
|
||||||
|
|
||||||
|
|
||||||
|
class ScriptedLM:
|
||||||
|
"""Returns one scripted DSL proposal per call (the dspy adapter's
|
||||||
|
structured output shape: attribute-dict with 'query')."""
|
||||||
|
def __init__(self, query):
|
||||||
|
self.query = query
|
||||||
|
|
||||||
|
def __call__(self, **kwargs):
|
||||||
|
class Out:
|
||||||
|
pass
|
||||||
|
out = Out()
|
||||||
|
out.query = self.query
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def test_translator_signature():
|
||||||
|
"""One structured-output call; the DSL schema is the signature."""
|
||||||
|
fields = set(TranslateToDSL.__fields__)
|
||||||
|
assert "question" in fields and "relations" in fields and "query" in fields, fields
|
||||||
|
print("ok: TranslateToDSL signature (question+relations in, typed query out)")
|
||||||
|
|
||||||
|
|
||||||
|
def test_of_what_translation():
|
||||||
|
e = type("E", (), {})()
|
||||||
|
e.translate_dspy = ScriptedLM({
|
||||||
|
"lookup": {"subject": "pedro sanchez",
|
||||||
|
"rel_any": ["prime minister of", "secretary general of",
|
||||||
|
"president of"],
|
||||||
|
"bind": "office"},
|
||||||
|
"filter": [{"open_now": ["office"]}],
|
||||||
|
"select": "all"})
|
||||||
|
q = translate(e, "Of what is Pedro Sanchez the president?",
|
||||||
|
["prime minister of", "secretary general of", "president of"])
|
||||||
|
assert q and q["select"] == "all" and len(q["filter"]) == 1
|
||||||
|
ok, reason = validate_query(q)
|
||||||
|
assert ok, f"valid term rejected: {reason}"
|
||||||
|
print(f"ok: 'of what' -> lookup+open_now+all (validated: {reason})")
|
||||||
|
|
||||||
|
|
||||||
|
def test_mistranslation_rejected():
|
||||||
|
"""An unknown filter or select never reaches evaluate()."""
|
||||||
|
bad_filters = {"lookup": {"subject": "x", "rel_any": ["r"], "bind": "v"},
|
||||||
|
"filter": [{"contains_now": ["v"]}], # not in the DSL
|
||||||
|
"select": "all"}
|
||||||
|
ok, reason = validate_query(bad_filters)
|
||||||
|
assert not ok and "contains_now" in reason, f"unknown filter slipped: {reason}"
|
||||||
|
bad_select = {"lookup": {"subject": "x", "rel_any": ["r"], "bind": "v"},
|
||||||
|
"filter": [], "select": "second_best"}
|
||||||
|
ok, reason = validate_query(bad_select)
|
||||||
|
assert not ok and "select" in reason, f"unknown select slipped: {reason}"
|
||||||
|
bad_rel = {"lookup": {"subject": "x", "rel_any": [], "bind": "v"},
|
||||||
|
"filter": [], "select": "all"}
|
||||||
|
ok, reason = validate_query(bad_rel)
|
||||||
|
assert not ok, "empty rel_any is an invalid term"
|
||||||
|
print("ok: mistranslations rejected deterministically (never executed)")
|
||||||
|
|
||||||
|
|
||||||
|
def test_untranslatable_returns_none():
|
||||||
|
e = type("E", (), {})()
|
||||||
|
e.translate_dspy = ScriptedLM(None) # the model honestly declines
|
||||||
|
q = translate(e, "Why is the sky blue?", ["length"])
|
||||||
|
assert q is None
|
||||||
|
print("ok: untranslatable question -> None (caller falls back to the judge)")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
test_translator_signature()
|
||||||
|
test_of_what_translation()
|
||||||
|
test_mistranslation_rejected()
|
||||||
|
test_untranslatable_returns_none()
|
||||||
|
print("\ntranslate_dsl: 4/4 ok")
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
"""The two-pass EXTRACT tests (Pass 1 claims, Pass 2 typed Facts).
|
||||||
|
|
||||||
|
Law: the old single call asked a slow model for verbatim quotes + typed
|
||||||
|
temporal fields + sibling order assertions in ONE giant JSON array — the
|
||||||
|
output budget that produced the 40-minute arithmetic. The two-pass split
|
||||||
|
shortens EVERY output: Pass 1 extracts plain claims (free-form strings
|
||||||
|
with coreference resolved to the entity names — near-zero format tax);
|
||||||
|
Pass 2 types ONE claim into the existing Fact schema per call.
|
||||||
|
|
||||||
|
CRITICAL law: Pass 2 works on ONE CLAIM AT A TIME — sibling order
|
||||||
|
assertions become IMPOSSIBLE by construction, so orders are dropped from
|
||||||
|
the two-pass path (the store's fact_order keeps working for whatever
|
||||||
|
arrives as a typed Fact with orders; the two-pass facts carry none).
|
||||||
|
The store, the containment checks and the merge are UNTOUCHED — Pass 2
|
||||||
|
emits the same typed Fact as before, minus orders.
|
||||||
|
|
||||||
|
Pinned:
|
||||||
|
1. ExtractClaims: free-form claim strings, coreferences RESOLVED (the
|
||||||
|
claim must name its entities, not 'he/it/the party').
|
||||||
|
2. TypeClaim: one claim in -> one typed Fact out (same fields as the
|
||||||
|
legacy ExtractSignature.facts minus orders; temporal fields optional).
|
||||||
|
3. The pipeline wiring: _extract_two_pass returns typed Fact objects;
|
||||||
|
candidates flow into _ingest_candidate exactly as before.
|
||||||
|
4. Honest empty: no claims -> no facts, no invention.
|
||||||
|
5. The legacy single-pass signature STAYS (table frags use it; flipping
|
||||||
|
the whole pipeline over is a later decision, config-driven).
|
||||||
|
|
||||||
|
Run: .venv/bin/python knowledge/tests/two_pass_extract.py
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
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.parent))
|
||||||
|
|
||||||
|
from knowledge.extract import ExtractClaims, TypeClaim, Fact, ExtractSignature
|
||||||
|
from knowledge.two_pass import claims_from, fact_from_claim
|
||||||
|
|
||||||
|
|
||||||
|
class Scripted:
|
||||||
|
def __init__(self, **attrs):
|
||||||
|
self.__dict__.update(attrs)
|
||||||
|
|
||||||
|
def __call__(self, **kw):
|
||||||
|
return self
|
||||||
|
|
||||||
|
|
||||||
|
def test_extract_claims_signature():
|
||||||
|
"""Pass 1: claims are free-form strings; coreferences resolved."""
|
||||||
|
fields = set(ExtractClaims.__fields__)
|
||||||
|
assert fields == {"entities", "heading", "text", "claims"}, fields
|
||||||
|
# what the model actually sees: dspy keeps desc in json_schema_extra
|
||||||
|
d = (ExtractClaims.model_fields["claims"].json_schema_extra or {}).get("desc", "")
|
||||||
|
assert "coreference" in d.lower() or "resolved" in d.lower(), d
|
||||||
|
print("ok: ExtractClaims = free-form claims, coreferences resolved in-draft")
|
||||||
|
|
||||||
|
|
||||||
|
def test_type_claim_signature():
|
||||||
|
"""Pass 2: one claim -> one typed Fact; orders NEVER produced here."""
|
||||||
|
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)
|
||||||
|
f = TypeClaim.model_fields["fact"].annotation
|
||||||
|
assert "Fact" in str(f), f
|
||||||
|
# Fact KEEPS orders (the legacy single-pass path and table frags use
|
||||||
|
# them — untouched); the two-pass law is that TypeClaim never fills
|
||||||
|
# them: one claim per call means no siblings to reference.
|
||||||
|
assert "orders" in Fact.model_fields, "legacy Fact must keep orders"
|
||||||
|
d = TypeClaim.__doc__ or ""
|
||||||
|
assert "one claim" in d.lower() or "single" in d.lower(), d
|
||||||
|
print("ok: TypeClaim = one claim -> one Fact; orders never produced (no siblings)")
|
||||||
|
|
||||||
|
|
||||||
|
def test_claims_from_runs_pass1():
|
||||||
|
e = Scripted(claims=Scripted(claims=["Pedro Sanchez is the prime minister of Spain since 2018",
|
||||||
|
"Sanchez became Secretary-General of the PSOE in 2017"]))
|
||||||
|
out = claims_from(e, entities="Pedro Sanchez, PSOE", heading="", text="...")
|
||||||
|
assert out == ["Pedro Sanchez is the prime minister of Spain since 2018",
|
||||||
|
"Sanchez became Secretary-General of the PSOE in 2017"], out
|
||||||
|
print("ok: claims_from extracts the plain claim strings")
|
||||||
|
|
||||||
|
|
||||||
|
def test_fact_from_claim_types_one_fact():
|
||||||
|
e = Scripted(typeclaim=Scripted(fact=Fact(
|
||||||
|
subject="Pedro Sanchez", relation="prime minister of",
|
||||||
|
object="Spain", quote="is a Spanish politician who has been the "
|
||||||
|
"prime minister of Spain since 2018",
|
||||||
|
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="...")
|
||||||
|
assert f.subject == "Pedro Sanchez" and f.start == "2018", f
|
||||||
|
print("ok: fact_from_claim returns the typed Fact for one claim")
|
||||||
|
|
||||||
|
|
||||||
|
def test_honest_empty():
|
||||||
|
e = Scripted(claims=Scripted(claims=[]))
|
||||||
|
assert claims_from(e, entities="", heading="", text="") == []
|
||||||
|
e2 = Scripted(typeclaim=Scripted(fact=None))
|
||||||
|
assert fact_from_claim(e2, claim="", text="") is None
|
||||||
|
print("ok: no claims -> no facts; untypeable claim -> None, no invention")
|
||||||
|
|
||||||
|
|
||||||
|
def test_claims_from_dedupes_exact_repeats():
|
||||||
|
"""Pass 1 sometimes repeats its own list (live: glm listed 46 claims,
|
||||||
|
~26 were exact repeats/thinking leakage). Dedup is CODE, cheap and
|
||||||
|
deterministic — the claim list must not be capped or filtered
|
||||||
|
semantically, only made honest: no exact duplicates survive."""
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
class E: # minimal expert double
|
||||||
|
def claims(self, entities, heading, text):
|
||||||
|
calls.append((entities, heading))
|
||||||
|
class Out:
|
||||||
|
claims = ["Pedro Sanchez is prime minister of Spain.",
|
||||||
|
"pedro sanchez is prime minister of spain. ",
|
||||||
|
"Pedro Sanchez is Secretary-General of the PSOE.",
|
||||||
|
"Pedro Sanchez is prime minister of Spain.",
|
||||||
|
"from the text. I need to list factual claims"]
|
||||||
|
return Out()
|
||||||
|
|
||||||
|
got = claims_from(E(), entities="Pedro Sanchez", heading="h", text="t")
|
||||||
|
assert got == ["Pedro Sanchez is prime minister of Spain.",
|
||||||
|
"Pedro Sanchez is Secretary-General of the PSOE.",
|
||||||
|
"from the text. I need to list factual claims"], got
|
||||||
|
print("ok: exact repeats deduped (case/space-insensitive); the rest kept")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
test_extract_claims_signature()
|
||||||
|
test_type_claim_signature()
|
||||||
|
test_claims_from_dedupes_exact_repeats()
|
||||||
|
test_claims_from_runs_pass1()
|
||||||
|
test_fact_from_claim_types_one_fact()
|
||||||
|
test_honest_empty()
|
||||||
|
print("\ntwo_pass_extract: 6/6 ok")
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
"""The two-pass pipeline wiring test: prose chunks flow claims->facts->store.
|
||||||
|
|
||||||
|
End-to-end on a REAL store (tmp kg.sqlite): _process_page in two_pass
|
||||||
|
mode ingests the typed facts from Pass 2 exactly as the legacy path
|
||||||
|
did — same _ingest_candidate, same containment checks, same merge; the
|
||||||
|
single-pass path keeps working (control). No network: the expert's
|
||||||
|
claims/typeclaim/extract modules are scripted.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
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.parent))
|
||||||
|
|
||||||
|
from knowledge.extract import Fact
|
||||||
|
from knowledge.expert import KnowledgeConfig, KnowledgeExpert
|
||||||
|
from knowledge.store import KnowledgeStore
|
||||||
|
from knowledge.wiki import WikiPage
|
||||||
|
|
||||||
|
|
||||||
|
PAGE_TEXT = (
|
||||||
|
"Pedro Sanchez is a Spanish politician who has been the prime "
|
||||||
|
"minister of Spain since 2018. He is also Secretary-General of the "
|
||||||
|
"Spanish Socialist Workers' Party (PSOE) since 2017."
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def make_page() -> WikiPage:
|
||||||
|
return WikiPage(title="Pedro Sanchez", pageid=1,
|
||||||
|
url="https://en.wikipedia.org/wiki/P",
|
||||||
|
fetched_at="2026-10-26", text=PAGE_TEXT, tables=[])
|
||||||
|
|
||||||
|
|
||||||
|
class ScriptedClaims:
|
||||||
|
def __call__(self, **kw):
|
||||||
|
class Out:
|
||||||
|
claims = ["Pedro Sanchez has been the prime minister of Spain since 2018",
|
||||||
|
"Pedro Sanchez is Secretary-General of the PSOE since 2017"]
|
||||||
|
return Out()
|
||||||
|
|
||||||
|
|
||||||
|
class ScriptedTypeClaim:
|
||||||
|
def __init__(self, facts):
|
||||||
|
self.facts = facts
|
||||||
|
self.i = 0
|
||||||
|
|
||||||
|
def __call__(self, **kw):
|
||||||
|
f = self.facts[self.i]
|
||||||
|
self.i += 1
|
||||||
|
class Out:
|
||||||
|
fact = f
|
||||||
|
return Out()
|
||||||
|
|
||||||
|
|
||||||
|
def test_two_pass_ingests_typed_facts():
|
||||||
|
tmp = tempfile.mkdtemp()
|
||||||
|
store = KnowledgeStore(str(Path(tmp) / "kg.sqlite"))
|
||||||
|
e = KnowledgeExpert(config=KnowledgeConfig(
|
||||||
|
kb_path=str(Path(tmp) / "kg.sqlite"), extract_mode="two_pass"),
|
||||||
|
store=store)
|
||||||
|
e.claims = ScriptedClaims()
|
||||||
|
e.typeclaim = ScriptedTypeClaim([
|
||||||
|
Fact(subject="Pedro Sanchez", relation="prime minister of",
|
||||||
|
object="Spain",
|
||||||
|
quote="has been the prime minister of Spain since 2018",
|
||||||
|
start="2018", end=None, point=None, granularity="year"),
|
||||||
|
Fact(subject="Pedro Sanchez", relation="secretary-general of",
|
||||||
|
object="PSOE",
|
||||||
|
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
|
||||||
|
# drives _process_page directly)
|
||||||
|
e._extract_entities = []
|
||||||
|
e._current_goal_terms = []
|
||||||
|
e._current_goal_question = "the question"
|
||||||
|
n = e._process_page(make_page(), "the question", kws=["pedro", "prime"],
|
||||||
|
charge_llm=None, goal_terms=[])
|
||||||
|
assert n >= 2, f"two_pass should merge both facts (merged={n})"
|
||||||
|
rows = store.db.execute(
|
||||||
|
"SELECT n.norm_name, e.rel, e.dst_value, e.t_start FROM edges e "
|
||||||
|
"JOIN nodes n ON n.id=e.src_node "
|
||||||
|
"WHERE n.norm_name='pedro sanchez' ORDER BY e.id").fetchall()
|
||||||
|
assert len(rows) == 2, rows
|
||||||
|
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]
|
||||||
|
print("ok: two_pass ingests typed facts (windows kept, legacy checks)")
|
||||||
|
|
||||||
|
|
||||||
|
def test_single_pass_still_works():
|
||||||
|
"""Control: extract_mode='single' -> the legacy one-call path."""
|
||||||
|
tmp = tempfile.mkdtemp()
|
||||||
|
store = KnowledgeStore(str(Path(tmp) / "kg.sqlite"))
|
||||||
|
e = KnowledgeExpert(config=KnowledgeConfig(
|
||||||
|
kb_path=str(Path(tmp) / "kg.sqlite"), extract_mode="single"),
|
||||||
|
store=store)
|
||||||
|
from knowledge.extract import Fact
|
||||||
|
|
||||||
|
class ScriptedExtract:
|
||||||
|
def __call__(self, **kw):
|
||||||
|
class Out:
|
||||||
|
facts = [Fact(subject="Pedro Sanchez",
|
||||||
|
relation="prime minister of", object="Spain",
|
||||||
|
quote="has been the prime minister of Spain "
|
||||||
|
"since 2018",
|
||||||
|
start="2018", end=None, point=None,
|
||||||
|
granularity="year")]
|
||||||
|
return Out()
|
||||||
|
|
||||||
|
e.extract = ScriptedExtract()
|
||||||
|
e._extract_entities = []
|
||||||
|
e._current_goal_terms = []
|
||||||
|
e._current_goal_question = "the question"
|
||||||
|
n = e._process_page(make_page(), "the question", kws=["pedro"],
|
||||||
|
charge_llm=None, goal_terms=[])
|
||||||
|
assert n >= 1, n
|
||||||
|
rows = store.db.execute(
|
||||||
|
"SELECT COUNT(*) FROM edges e JOIN nodes n ON n.id=e.src_node "
|
||||||
|
"WHERE n.norm_name='pedro sanchez'"
|
||||||
|
).fetchone()[0]
|
||||||
|
assert rows == 1, rows
|
||||||
|
print("ok: single-pass legacy path untouched (control)")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
test_two_pass_ingests_typed_facts()
|
||||||
|
test_single_pass_still_works()
|
||||||
|
print("\ntwo_pass_wiring: 2/2 ok")
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
"""Judge value cleanup tests (the (K5) bug, run 085457 / 24-25/10 session).
|
||||||
|
|
||||||
|
glm-5.3-flash glues row citations and glosses onto the value field because
|
||||||
|
AnswerFromKG says "cite rows by id" but has no citation output field. Three
|
||||||
|
live shapes, verbatim from the runs:
|
||||||
|
|
||||||
|
"Socialist International (K5)" — row id
|
||||||
|
"2018 (Pedro Sánchez has been Prime Minister of Spain — i.e., ...)" — parenthetical gloss
|
||||||
|
"15 (list of 15 members: 17 november 2023, ...)" — LIST gloss
|
||||||
|
|
||||||
|
Laws under test:
|
||||||
|
1. Trailing citation shapes are STRIPPED from the value, at the judge's
|
||||||
|
output boundary (_clean_value), BEFORE the payload and the audit see it.
|
||||||
|
2. Legitimate parentheticals SURVIVE: "(PSOE)" inside a name,
|
||||||
|
"(Presidente del Gobierno)" inside an office title.
|
||||||
|
3. A cleaned value lets the ablation audit RUN where the raw value killed
|
||||||
|
it silently ("the judge invented it: nothing to ablate").
|
||||||
|
4. The clean is idempotent and does not touch UNKNOWN/empty.
|
||||||
|
|
||||||
|
No network. No LLM: the cleaner is fixed code; the tests call it directly
|
||||||
|
plus one scripted-judge pass through _answer_from_rows.
|
||||||
|
Run: .venv/bin/python knowledge/tests/value_clean.py
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent))
|
||||||
|
|
||||||
|
from knowledge.expert import KnowledgeExpert, _clean_value
|
||||||
|
|
||||||
|
|
||||||
|
def test_row_id_suffix_stripped():
|
||||||
|
assert _clean_value("Socialist International (K5)") == "Socialist International"
|
||||||
|
assert _clean_value("Rajoy (K12)") == "Rajoy"
|
||||||
|
print("ok: row-id citation suffix stripped")
|
||||||
|
|
||||||
|
|
||||||
|
def test_cited_from_rows_gloss_stripped():
|
||||||
|
v = ("2018 (Pedro Sánchez has been Prime Minister of Spain — i.e., "
|
||||||
|
"President of the Government — since 2018; cited from rows K16 and K30)")
|
||||||
|
assert _clean_value(v) == "2018", _clean_value(v)
|
||||||
|
print("ok: 'cited from rows' parenthetical stripped, year kept")
|
||||||
|
|
||||||
|
|
||||||
|
def test_list_gloss_stripped():
|
||||||
|
v = "15 (list of 15 members: 17 november 2023, 28 november 2023, 24 september 2024)"
|
||||||
|
assert _clean_value(v) == "15", _clean_value(v)
|
||||||
|
print("ok: LIST-members gloss stripped, count kept")
|
||||||
|
|
||||||
|
|
||||||
|
def test_legitimate_parentheticals_survive():
|
||||||
|
assert _clean_value("Spanish Socialist Workers' Party (PSOE)") == \
|
||||||
|
"Spanish Socialist Workers' Party (PSOE)"
|
||||||
|
assert _clean_value("Prime Minister of Spain (Presidente del Gobierno)") == \
|
||||||
|
"Prime Minister of Spain (Presidente del Gobierno)"
|
||||||
|
# a parenthetical that merely mentions a number is NOT a citation
|
||||||
|
assert _clean_value("Prime Minister of Spain (since 2018)") == \
|
||||||
|
"Prime Minister of Spain (since 2018)"
|
||||||
|
print("ok: legitimate parentheticals untouched")
|
||||||
|
|
||||||
|
|
||||||
|
def test_unknown_and_empty_untouched():
|
||||||
|
assert _clean_value("UNKNOWN") == "UNKNOWN"
|
||||||
|
assert _clean_value("") == ""
|
||||||
|
assert _clean_value(" Spain ") == "Spain"
|
||||||
|
print("ok: UNKNOWN/empty/whitespace handled")
|
||||||
|
|
||||||
|
|
||||||
|
def test_idempotent_and_mid_value_citations():
|
||||||
|
v = _clean_value("Socialist International (K5)")
|
||||||
|
assert _clean_value(v) == v
|
||||||
|
# a citation in the MIDDLE is not the live bug shape — leave it (no
|
||||||
|
# aggressive surgery on the judge's sentence), the boundary law strips
|
||||||
|
# only the TRAILING gloss
|
||||||
|
assert _clean_value("Per (K2) the answer is Spain") == \
|
||||||
|
"Per (K2) the answer is Spain"
|
||||||
|
print("ok: idempotent; mid-value text untouched (boundary law: trailing only)")
|
||||||
|
|
||||||
|
|
||||||
|
def test_answer_from_rows_boundary():
|
||||||
|
"""The hook: _answer_from_rows cleans pred.value before the payload is
|
||||||
|
built. Scripted dspy-style Predict object; no network."""
|
||||||
|
e = KnowledgeExpert.__new__(KnowledgeExpert)
|
||||||
|
e.cfg = __import__("knowledge.expert", fromlist=["KnowledgeConfig"]).KnowledgeConfig()
|
||||||
|
e._log = lambda *a, **k: None
|
||||||
|
|
||||||
|
class Pred:
|
||||||
|
value = "Socialist International (K5)"
|
||||||
|
quote = "ninth president of Socialist International since 2022"
|
||||||
|
class confidence:
|
||||||
|
value = "high"
|
||||||
|
|
||||||
|
class Row:
|
||||||
|
src = rel = dst = quote = url = "u"
|
||||||
|
conflict = False
|
||||||
|
|
||||||
|
e.answer = lambda question, rows: Pred()
|
||||||
|
out = e._answer_from_rows("which office?", [Row()])
|
||||||
|
assert out["value"] == "Socialist International", out["value"]
|
||||||
|
print("ok: _answer_from_rows boundary cleans the value")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
test_row_id_suffix_stripped()
|
||||||
|
test_cited_from_rows_gloss_stripped()
|
||||||
|
test_list_gloss_stripped()
|
||||||
|
test_legitimate_parentheticals_survive()
|
||||||
|
test_unknown_and_empty_untouched()
|
||||||
|
test_idempotent_and_mid_value_citations()
|
||||||
|
test_answer_from_rows_boundary()
|
||||||
|
print("\nvalue_clean: 7/7 ok")
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
"""The question->DSL translator (phase 3b) — the LLM at the INPUT boundary.
|
||||||
|
|
||||||
|
One structured-output call (the MASK/EXTRACT class): the question + the
|
||||||
|
store's relation vocabulary in; a typed DSL term out; VALIDATED BEFORE
|
||||||
|
EXECUTION — a mistranslation is an invalid term caught deterministically,
|
||||||
|
never a wrong answer. The model never sees the goal, the evidence, or the
|
||||||
|
answer; it sees the question and which relations exist. If the question is
|
||||||
|
not translatable, the call returns None and the caller falls back to the
|
||||||
|
judge path, honestly.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import dspy
|
||||||
|
|
||||||
|
from .prover import validate_query
|
||||||
|
|
||||||
|
|
||||||
|
class TranslateToDSL(dspy.Signature):
|
||||||
|
"""You are the TRANSLATE-TO-QUERY step of a reasoning machine. Turn the
|
||||||
|
question into ONE typed query over the knowledge graph, choosing from
|
||||||
|
the given relations ONLY. The machine executes the query deterministically.
|
||||||
|
|
||||||
|
Shapes you may build:
|
||||||
|
- lookup: {"subject": "<entity>", "rel_any": ["<one or more relations>"], "bind": "<var>"}
|
||||||
|
- a second lookup with {"subject": "?x", "rel_any": [...], "bind": "<var>",
|
||||||
|
"same_value_as": "<bound var>"} — anyone holding the SAME value (e.g. the
|
||||||
|
same office) as the first lookup bound
|
||||||
|
- filters: {"open_now": ["<var>"]} (the fact holds now), {"before": ["<a>", "<b>"]}
|
||||||
|
(a's window ended before b's started), {"neq_value": ["<var-or-?x>", "<literal>"]}
|
||||||
|
(a bound name differs from the literal — e.g. exclude the queried entity)
|
||||||
|
- select: "all" (every binding — the question asks for the SET) or
|
||||||
|
"latest_end" (the most recent one that ended)
|
||||||
|
|
||||||
|
If the question cannot be expressed with these shapes, return an empty
|
||||||
|
query ({} or null) — never force a wrong translation."""
|
||||||
|
question: str = dspy.InputField()
|
||||||
|
relations: str = dspy.InputField(
|
||||||
|
desc="the relations that exist in the graph, comma separated")
|
||||||
|
query: dict | None = dspy.OutputField(
|
||||||
|
desc="the typed query as JSON, or null when not expressible")
|
||||||
|
|
||||||
|
|
||||||
|
_KNOWN_FILTERS = {"open_now", "before", "neq_value"}
|
||||||
|
_KNOWN_SELECTS = {"all", "latest_end"}
|
||||||
|
|
||||||
|
|
||||||
|
def translate(expert, question: str, relations: list[str]) -> dict | None:
|
||||||
|
"""One call: question + relation vocabulary -> a validated DSL term.
|
||||||
|
|
||||||
|
None when the model declines or the proposal is invalid — the caller
|
||||||
|
falls back to the judge path (the prover never executes an invalid
|
||||||
|
term; code decides, the model proposes).
|
||||||
|
"""
|
||||||
|
pred = expert.translate_dspy(question=question,
|
||||||
|
relations=", ".join(sorted(set(relations))))
|
||||||
|
q = getattr(pred, "query", None)
|
||||||
|
if not q:
|
||||||
|
return None
|
||||||
|
ok, _reason = validate_query(q)
|
||||||
|
return q if ok else None
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
"""The two-pass extraction (Pass 1 claims, Pass 2 typed Facts).
|
||||||
|
|
||||||
|
The single-pass EXTRACT asked slow local models for a giant JSON array
|
||||||
|
of typed Facts with verbatim quotes + temporal restrictions + sibling
|
||||||
|
order assertions — the output budget behind the 40-minute arithmetic.
|
||||||
|
Two-pass shortens every output: Pass 1 lists plain claims (free-form
|
||||||
|
strings, coreferences resolved — near-zero format tax); Pass 2 types
|
||||||
|
ONE claim at a time into the same Fact schema the store already eats.
|
||||||
|
|
||||||
|
Orders: NEVER produced here — one claim per call has no siblings to
|
||||||
|
reference. The legacy single-pass path (and table frags) keeps them.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
|
||||||
|
def claims_from(expert, entities: str, heading: str, text: str,
|
||||||
|
charge_llm=None) -> list[str]:
|
||||||
|
"""Pass 1: the chunk's claims as plain strings, coreferences resolved.
|
||||||
|
|
||||||
|
The list is made honest by CODE only: exact repeats are dropped
|
||||||
|
(live finding 26/10: glm sometimes lists its whole list twice, and
|
||||||
|
thinking leakage leaks in as list items). Dedup is case- and
|
||||||
|
whitespace-insensitive; the FIRST occurrence's exact text is kept.
|
||||||
|
NO cap, NO semantic filter: completeness beats budget (owner ruling
|
||||||
|
26/10) — every unique claim gets its TYPE call.
|
||||||
|
"""
|
||||||
|
if charge_llm:
|
||||||
|
charge_llm()
|
||||||
|
pred = expert.claims(entities=entities, heading=heading, text=text)
|
||||||
|
seen: dict[str, str] = {}
|
||||||
|
for c in (pred.claims or []):
|
||||||
|
c = (c or "").strip()
|
||||||
|
if c:
|
||||||
|
key = " ".join(c.lower().split())
|
||||||
|
if key not in seen:
|
||||||
|
seen[key] = c
|
||||||
|
return list(seen.values())
|
||||||
|
|
||||||
|
|
||||||
|
def fact_from_claim(expert, claim: str, text: str, charge_llm=None):
|
||||||
|
"""Pass 2: ONE claim -> one typed Fact (or None, honestly declined).
|
||||||
|
|
||||||
|
The Fact's quote is copied VERBATIM from `text` (the chunk the claim
|
||||||
|
came from) — without the text the model invents a quote and the
|
||||||
|
containment check rejects it (live finding 26/10: 69/70 rejected).
|
||||||
|
The store's checks validate everything downstream as before. No
|
||||||
|
orders: no siblings by construction.
|
||||||
|
"""
|
||||||
|
if charge_llm:
|
||||||
|
charge_llm()
|
||||||
|
pred = expert.typeclaim(claim=claim, text=text)
|
||||||
|
return getattr(pred, "fact", None)
|
||||||
+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",
|
||||||
|
|||||||
+55
-3
@@ -4,6 +4,7 @@
|
|||||||
uv run run_app.py "Per què el cel és blau?" # log only
|
uv run run_app.py "Per què el cel és blau?" # log only
|
||||||
uv run run_app.py --verbose "Per què el cel és blau?" # + thinking on screen
|
uv run run_app.py --verbose "Per què el cel és blau?" # + thinking on screen
|
||||||
uv run run_app.py --baseline "Per què el cel és blau?" # raw LLM, one call (A/B comparison)
|
uv run run_app.py --baseline "Per què el cel és blau?" # raw LLM, one call (A/B comparison)
|
||||||
|
uv run run_app.py --no-cache "..." # dspy response cache OFF for this run
|
||||||
FLOOP_LM=ollama-cloud uv run run_app.py "..."
|
FLOOP_LM=ollama-cloud uv run run_app.py "..."
|
||||||
|
|
||||||
Always: runs/<ts>-<slug>/run.log written with flush -> `tail -f` it from another
|
Always: runs/<ts>-<slug>/run.log written with flush -> `tail -f` it from another
|
||||||
@@ -42,27 +43,67 @@ def run_baseline(question: str, streams: RunStreams) -> str:
|
|||||||
return answer
|
return answer
|
||||||
|
|
||||||
|
|
||||||
|
def _assert_local_imports(code_dir: Path) -> None:
|
||||||
|
"""Abort loudly if floop/knowledge resolve OUTSIDE this repo's tree.
|
||||||
|
|
||||||
|
The shared venv carries an editable-install .pth pointing at another
|
||||||
|
checkout, and a poisoned PYTHONPATH (shim importing knowledge.* first)
|
||||||
|
pins SUBMODULES to another tree even when the package __path__ lists
|
||||||
|
this one — a namespace package recomputes __path__ dynamically, so
|
||||||
|
checking the package proves nothing (run 085457, 25/10: main's pipeline
|
||||||
|
ran inside the branch worktree with zero signal). Check the FILES the
|
||||||
|
run actually executes. A wrong import tree invalidates the run; refuse
|
||||||
|
it, don't log it.
|
||||||
|
"""
|
||||||
|
root = str(code_dir.resolve())
|
||||||
|
for name, relpath in (("floop", "machine.py"), ("floop", "llm.py"),
|
||||||
|
("knowledge", "expert.py"), ("knowledge", "store.py")):
|
||||||
|
try:
|
||||||
|
mod = __import__(f"{name}.{relpath[:-3]}", fromlist=[""])
|
||||||
|
except ImportError as e: # pragma: no cover — broken install, abort anyway
|
||||||
|
raise SystemExit(f"ABORT: cannot import {name}.{relpath[:-3]}: {e}")
|
||||||
|
loaded = str(Path(mod.__file__).resolve())
|
||||||
|
if not loaded.startswith(root):
|
||||||
|
raise SystemExit(
|
||||||
|
f"ABORT: module '{name}.{relpath[:-3]}' resolved outside this repo\n"
|
||||||
|
f" repo: {root}\n"
|
||||||
|
f" loaded: {loaded}\n"
|
||||||
|
"The venv's editable .pth or PYTHONPATH shadows this tree — "
|
||||||
|
"the run would test the WRONG code. Fix sys.path and retry.")
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
args = sys.argv[1:]
|
args = sys.argv[1:]
|
||||||
verbose = "--verbose" in args
|
verbose = "--verbose" in args
|
||||||
baseline = "--baseline" in args
|
baseline = "--baseline" in args
|
||||||
args = [a for a in args if a not in ("--verbose", "--baseline")]
|
no_cache = "--no-cache" in args
|
||||||
|
args = [a for a in args if a not in ("--verbose", "--baseline", "--no-cache")]
|
||||||
if not args:
|
if not args:
|
||||||
print(__doc__)
|
print(__doc__)
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
question = " ".join(args)
|
question = " ".join(args)
|
||||||
|
|
||||||
code_dir = Path(__file__).resolve().parent
|
code_dir = Path(__file__).resolve().parent
|
||||||
|
_assert_local_imports(code_dir) # the editable-pth trap: wrong tree = invalid run
|
||||||
cfg = yaml.safe_load((code_dir / "config.yaml").read_text())
|
cfg = yaml.safe_load((code_dir / "config.yaml").read_text())
|
||||||
b = cfg["budget"]
|
b = cfg["budget"]
|
||||||
budget = Budget(max_llm_calls=b["max_llm_calls"], max_depth=b["max_depth"],
|
budget = Budget(max_llm_calls=b["max_llm_calls"], max_depth=b["max_depth"],
|
||||||
max_retries=b["max_retries"], missing_extensions=b["missing_extensions"],
|
max_retries=b["max_retries"], missing_extensions=b["missing_extensions"],
|
||||||
min_child_budget=b["min_child_budget"])
|
min_child_budget=b["min_child_budget"])
|
||||||
|
|
||||||
lm_info = configure_lm()
|
lm_info = configure_lm(no_cache=no_cache)
|
||||||
streams = RunStreams(question, verbose=verbose, runs_dir=code_dir / "runs")
|
streams = RunStreams(question, verbose=verbose, runs_dir=code_dir / "runs")
|
||||||
install_prompt_log(streams) # every LM call's exact prompt -> prompts/NN-stage.txt
|
install_prompt_log(streams) # every LM call's exact prompt -> prompts/NN-stage.txt
|
||||||
streams.log(f"lm={lm_info['provider']}/{lm_info['model']} verbose={verbose} baseline={baseline}")
|
streams.log(f"lm={lm_info['provider']}/{lm_info['model']} verbose={verbose} "
|
||||||
|
f"baseline={baseline} no_cache={no_cache} "
|
||||||
|
f"read_timeout_s={lm_info.get('read_timeout_s')} "
|
||||||
|
f"num_retries={lm_info.get('num_retries')}")
|
||||||
|
from floop.llm import signature_overrides
|
||||||
|
ov = signature_overrides()
|
||||||
|
if ov:
|
||||||
|
streams.log(f"signature_overrides: "
|
||||||
|
+ ", ".join(f"{name}[{', '.join(f'{k}={v}' for k, v in blk.items())}]"
|
||||||
|
for name, blk in sorted(ov.items())))
|
||||||
|
|
||||||
if baseline:
|
if baseline:
|
||||||
answer = run_baseline(question, streams)
|
answer = run_baseline(question, streams)
|
||||||
@@ -89,6 +130,7 @@ def main() -> None:
|
|||||||
max_chunks_extracted=kcfg.get("max_chunks_extracted", 6),
|
max_chunks_extracted=kcfg.get("max_chunks_extracted", 6),
|
||||||
chunk_chars_target=kcfg.get("chunk_chars_target", 32000),
|
chunk_chars_target=kcfg.get("chunk_chars_target", 32000),
|
||||||
chunk_chars_cap=kcfg.get("chunk_chars_cap", 48000),
|
chunk_chars_cap=kcfg.get("chunk_chars_cap", 48000),
|
||||||
|
extract_mode=kcfg.get("extract_mode", "two_pass"),
|
||||||
)
|
)
|
||||||
ke = KnowledgeExpert(config=kconfig, streams=streams)
|
ke = KnowledgeExpert(config=kconfig, streams=streams)
|
||||||
knowledge_engine = KnowledgeEngine(ke)
|
knowledge_engine = KnowledgeEngine(ke)
|
||||||
@@ -101,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!")
|
||||||
+36
-2
@@ -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])
|
||||||
@@ -121,10 +144,20 @@ def test_identity_detection_conservative():
|
|||||||
assert identity_answer("What is ORGANIZATION_1?", {"ORGANIZATION_1": "PSOE"}) == "PSOE"
|
assert identity_answer("What is ORGANIZATION_1?", {"ORGANIZATION_1": "PSOE"}) == "PSOE"
|
||||||
assert identity_answer("Which specific individual does the placeholder refer to?", r) is None
|
assert identity_answer("Which specific individual does the placeholder refer to?", r) is None
|
||||||
assert identity_answer("Who is PERSON_1, i.e., which specific individual does the placeholder refer to?", r) == "Pedro Sanchez"
|
assert identity_answer("Who is PERSON_1, i.e., which specific individual does the placeholder refer to?", r) == "Pedro Sanchez"
|
||||||
|
assert identity_answer("Who is PERSON_1's predecessor?", r) is None
|
||||||
assert identity_answer("Who was PERSON_1's predecessor?", r) is None
|
assert identity_answer("Who was PERSON_1's predecessor?", r) is None
|
||||||
assert identity_answer("What office does PERSON_1 hold?", r) is None
|
assert identity_answer("What office does PERSON_1 hold?", r) is None
|
||||||
assert identity_answer("Who is PERSON_1 compared to PERSON_2?", {**r, "PERSON_2": "x"}) is None
|
assert identity_answer("Who is PERSON_1 compared to PERSON_2?", {**r, "PERSON_2": "x"}) is None
|
||||||
print("ok: identity detection conservative (possessives/comparatives not eaten)")
|
# his 23/10 false positive: 'refer to' about the TITLE, not the
|
||||||
|
# placeholder — the hidden-precondition INIT phrasing. Strict law:
|
||||||
|
# 'refer(s) to' fires only with the placeholder as its REFERENT.
|
||||||
|
assert identity_answer(
|
||||||
|
'What country, organization, or office does the title "President" '
|
||||||
|
'refer to in relation to PERSON_1?', r) is None
|
||||||
|
# and the strict mechanism shapes still fire
|
||||||
|
assert identity_answer("What does the placeholder PERSON_1 refer to?", r) == "Pedro Sanchez"
|
||||||
|
assert identity_answer("the term PERSON_1 refers to in the question", r) == "Pedro Sanchez"
|
||||||
|
print("ok: identity detection conservative (possessives/comparatives/title-refer not eaten)")
|
||||||
|
|
||||||
|
|
||||||
def test_mask_death_passthrough():
|
def test_mask_death_passthrough():
|
||||||
@@ -137,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,372 @@
|
|||||||
|
"""Execution branches over ambiguous rows (his design, 22-23/10).
|
||||||
|
|
||||||
|
Laws under test:
|
||||||
|
1. LAZY: an ambiguous row with NO dependent never forks (the pick rides,
|
||||||
|
the ambiguity stays a note).
|
||||||
|
2. FORK: an ambiguous row WITH a dependent opens one branch per reading;
|
||||||
|
each branch binds the row to its reading through a VIEW (the shared
|
||||||
|
table is never mutated — the store-unchanged law of the ablation mask).
|
||||||
|
3. SHARED: a branch's acquired rows land in the ONE shared table, tagged
|
||||||
|
with the branch id; another branch's view hides them until they merge.
|
||||||
|
4. The dependent's question runs INSIDE each branch world (its reference
|
||||||
|
resolves from the bound reading — 'that office' means what THIS branch
|
||||||
|
bound, never re-guessed).
|
||||||
|
5. CONDITIONAL ANSWER: the final answer is composed by FIXED CODE over
|
||||||
|
the surviving branches — 'if you meant X -> A | if you meant Y -> B';
|
||||||
|
never one reading chosen inside a synthesis prompt (run L law).
|
||||||
|
6. DEATH: a branch whose dependents all fail dies honestly (recorded
|
||||||
|
'dead', its clause never rendered).
|
||||||
|
7. MERGE: two branches concluding the same value render once.
|
||||||
|
8. NESTED: an ambiguous row inside a branch nests sub-branches under it;
|
||||||
|
the branch carries its children's conditional as its answer.
|
||||||
|
|
||||||
|
No network; FakeModules scripts the LLM; a monkeypatched engine injects
|
||||||
|
the ambiguous knowledge row (the real detector is exercised in
|
||||||
|
knowledge/tests/ablation.py — here we test the MACHINE's fork).
|
||||||
|
Run: uv run python tests/branches.py
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
|
|
||||||
|
from floop.machine import FloopRun
|
||||||
|
from floop.state import AnswerType, Budget, EvidenceRow, EvidenceTable
|
||||||
|
from floop.stream import RunStreams
|
||||||
|
|
||||||
|
|
||||||
|
def budget(n: int = 40, depth: int = 2) -> Budget:
|
||||||
|
return Budget(max_llm_calls=n, max_depth=depth, max_retries=3,
|
||||||
|
missing_extensions=1, min_child_budget=4)
|
||||||
|
|
||||||
|
|
||||||
|
class FakeModules:
|
||||||
|
"""Scripted LLM: INIT returns the fixed subs; ROUTE always knowledge;
|
||||||
|
synthesis returns the evidence dump marker (so we can see WHICH rows
|
||||||
|
each branch synthesized from)."""
|
||||||
|
|
||||||
|
def __init__(self, init_subs, route_fn):
|
||||||
|
self.init_subs = init_subs
|
||||||
|
self.route_fn = route_fn
|
||||||
|
self.synth_calls: list[str] = []
|
||||||
|
self.calls: list[str] = []
|
||||||
|
|
||||||
|
def init_decompose(self, question):
|
||||||
|
self.calls.append("init")
|
||||||
|
return list(self.init_subs), ""
|
||||||
|
|
||||||
|
def missing_decompose(self, goal, evidence):
|
||||||
|
self.calls.append("missing")
|
||||||
|
return []
|
||||||
|
|
||||||
|
def route_question(self, question, catalog, evidence):
|
||||||
|
self.calls.append("route")
|
||||||
|
return self.route_fn(question), "fake"
|
||||||
|
|
||||||
|
def expert_draft(self, question, expert_kind, evidence, parent_question=""):
|
||||||
|
self.calls.append(f"engine:{question[:40]}")
|
||||||
|
return {"value": "stub", "source_quote": "", "confidence": "low"}
|
||||||
|
|
||||||
|
def synthesize(self, goal, evidence, unverified):
|
||||||
|
self.synth_calls.append(evidence)
|
||||||
|
# branch synthesis reads the branch's OWN rows: the answer names
|
||||||
|
# the values it was given (the fork's worlds differ in the
|
||||||
|
# predecessor row their EXPERT produced, scripted per question)
|
||||||
|
vals = [ln for ln in evidence.splitlines() if "Rajoy" in ln or "Papandreou" in ln]
|
||||||
|
if vals:
|
||||||
|
return f"The predecessor was {('Rajoy' if 'Rajoy' in evidence else 'Papandreou')}"
|
||||||
|
return f"SYNTH<{len(evidence)} chars>"
|
||||||
|
|
||||||
|
|
||||||
|
def make_ambiguous_engine(value: str, alts: list[dict]):
|
||||||
|
"""A knowledge engine returning ONE ambiguous scalar row: the Pedro
|
||||||
|
shape (one person, several offices — the picked reading + named
|
||||||
|
alternatives with their own quotes)."""
|
||||||
|
class AmbigEngine:
|
||||||
|
name = "knowledge"
|
||||||
|
def __init__(self, modules, charge, expert_kind):
|
||||||
|
self.charge = charge
|
||||||
|
def run(self, qid, question, parent_question, table, answer_type, streams=None):
|
||||||
|
self.charge()
|
||||||
|
row = EvidenceRow(
|
||||||
|
qid=qid, answer_type=AnswerType.OPEN,
|
||||||
|
payload={"value": value, "ambiguous": True,
|
||||||
|
"axis": "office held as President",
|
||||||
|
"alternatives": alts,
|
||||||
|
"quote": f"quote for {value}", "url": "http://x"},
|
||||||
|
engine="knowledge", trace=[], provenance={"source": "knowledge_graph"},
|
||||||
|
verified=False, note="")
|
||||||
|
if streams is not None:
|
||||||
|
streams.output("EXPERT", f"{qid} -> ANSWER value={value} AMBIGUOUS")
|
||||||
|
return row
|
||||||
|
return AmbigEngine
|
||||||
|
|
||||||
|
|
||||||
|
def branch_answer_engine(answers: dict):
|
||||||
|
"""A knowledge engine answering by BRANCH: the branch-bound reading
|
||||||
|
decides what the predecessor was (the fork's worlds genuinely differ —
|
||||||
|
PM of Spain -> Rajoy; Socialist International -> Papandreou)."""
|
||||||
|
class BranchAnswerEngine:
|
||||||
|
name = "knowledge"
|
||||||
|
def __init__(self, modules, charge, expert_kind):
|
||||||
|
self.charge = charge
|
||||||
|
def run(self, qid, question, parent_question, table, answer_type, streams=None):
|
||||||
|
self.charge()
|
||||||
|
# what reading is bound in this world? the bound row is the
|
||||||
|
# one answering the AMBIGUOUS question — read it from the table
|
||||||
|
bound = ""
|
||||||
|
for r in table.rows():
|
||||||
|
if r.payload.get("ambiguous") or r.payload.get("branch_binding"):
|
||||||
|
bound = str(r.payload.get("value", ""))
|
||||||
|
break
|
||||||
|
val = "UNKNOWN"
|
||||||
|
for key, ans in answers.items():
|
||||||
|
if key.casefold() in bound.casefold():
|
||||||
|
val = ans
|
||||||
|
break
|
||||||
|
if streams is not None:
|
||||||
|
streams.output("EXPERT", f"{qid} -> ANSWER value={val}")
|
||||||
|
return EvidenceRow(
|
||||||
|
qid=qid, answer_type=AnswerType.OPEN,
|
||||||
|
payload={"value": val,
|
||||||
|
"quote": f"quote for {val}"},
|
||||||
|
engine="knowledge", trace=[], provenance={}, verified=False,
|
||||||
|
note="" if val != "UNKNOWN" else "miss")
|
||||||
|
return BranchAnswerEngine
|
||||||
|
|
||||||
|
|
||||||
|
def plain_engine(value: str):
|
||||||
|
class PlainEngine:
|
||||||
|
name = "knowledge"
|
||||||
|
def __init__(self, modules, charge, expert_kind):
|
||||||
|
self.charge = charge
|
||||||
|
self.seen_questions: list[str] = []
|
||||||
|
def run(self, qid, question, parent_question, table, answer_type, streams=None):
|
||||||
|
self.charge()
|
||||||
|
self.seen_questions.append(question)
|
||||||
|
if streams is not None:
|
||||||
|
streams.output("EXPERT", f"{qid} -> ANSWER value={value}")
|
||||||
|
return EvidenceRow(
|
||||||
|
qid=qid, answer_type=AnswerType.OPEN,
|
||||||
|
payload={"value": value, "quote": f"quote for {value}"},
|
||||||
|
engine="knowledge", trace=[], provenance={"source": "knowledge_graph"},
|
||||||
|
verified=False, note="")
|
||||||
|
return PlainEngine
|
||||||
|
|
||||||
|
|
||||||
|
def _run_machine(fm, streams, engine_classes: dict):
|
||||||
|
"""Run the machine with per-question engines keyed by question text."""
|
||||||
|
import floop.machine as M
|
||||||
|
q_text_to_engine = {k: cls for k, cls in engine_classes.items()}
|
||||||
|
captured = {}
|
||||||
|
|
||||||
|
class DispatchEngine:
|
||||||
|
name = "knowledge"
|
||||||
|
def __init__(self, modules, charge, expert_kind):
|
||||||
|
self.charge = charge
|
||||||
|
def run(self, qid, question, parent_question, table, answer_type, streams=None):
|
||||||
|
for key, cls in q_text_to_engine.items():
|
||||||
|
if key in question:
|
||||||
|
eng = cls(None, self.charge, "knowledge")
|
||||||
|
captured.setdefault(key, eng)
|
||||||
|
return eng.run(qid, question, parent_question, table,
|
||||||
|
answer_type, streams=streams)
|
||||||
|
# default: plain 'UNKNOWN' — the run must stay honest
|
||||||
|
self.charge()
|
||||||
|
return EvidenceRow(
|
||||||
|
qid=qid, answer_type=AnswerType.OPEN,
|
||||||
|
payload={"value": "UNKNOWN"}, engine="knowledge",
|
||||||
|
trace=[], provenance={}, verified=False, note="no engine")
|
||||||
|
|
||||||
|
real = M.LLMExpertEngine
|
||||||
|
M.LLMExpertEngine = DispatchEngine
|
||||||
|
try:
|
||||||
|
run = FloopRun("Who was the President before Pedro Sanchez?",
|
||||||
|
budget(), modules=fm, streams=streams)
|
||||||
|
rep = run.run()
|
||||||
|
return run, rep
|
||||||
|
finally:
|
||||||
|
M.LLMExpertEngine = real
|
||||||
|
|
||||||
|
|
||||||
|
def test_ambiguous_row_with_dependent_forks_and_renders_conditionally():
|
||||||
|
streams = RunStreams("fork test", verbose=False, runs_dir=tempfile.mkdtemp())
|
||||||
|
fm = FakeModules(
|
||||||
|
init_subs=[
|
||||||
|
{"text": "Which office does Pedro Sanchez hold as President?",
|
||||||
|
"deps": [], "answer_type": "OPEN"},
|
||||||
|
{"text": "Who held that office immediately before Pedro Sanchez?",
|
||||||
|
"deps": [1], "answer_type": "OPEN"},
|
||||||
|
],
|
||||||
|
route_fn=lambda q: "knowledge")
|
||||||
|
# Q1 (the office question) -> AMBIGUOUS: PM of Spain (picked) + SI (alt).
|
||||||
|
# Q2 (inside each branch world) -> the answer the BOUND reading implies:
|
||||||
|
# PM of Spain -> Rajoy; Socialist International -> Papandreou.
|
||||||
|
run, rep = _run_machine(fm, streams, {
|
||||||
|
"Which office": make_ambiguous_engine(
|
||||||
|
"Prime Minister of Spain",
|
||||||
|
[{"value": "President of Socialist International",
|
||||||
|
"quote": "quote for SI", "url": "http://y"}]),
|
||||||
|
"Who held that office": branch_answer_engine({
|
||||||
|
"Prime Minister of Spain": "Mariano Rajoy",
|
||||||
|
"Socialist International": "George Papandreou",
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
# FORK fired: two branches over the two readings
|
||||||
|
assert len(run.branches.specs) == 2, run.branches.specs
|
||||||
|
# the shared table: Q1's ambiguous row + 2 branch rows (one per branch)
|
||||||
|
br_rows = [r for r in run.table.rows() if r.provenance.get("branch")]
|
||||||
|
assert len(br_rows) == 2, [r.eid for r in run.table.rows()]
|
||||||
|
assert sorted(r.provenance["branch"] for r in br_rows) == ["B1", "B2"]
|
||||||
|
# the CONDITIONAL answer, composed by fixed code: both readings
|
||||||
|
assert "if you meant" in rep.final_answer, rep.final_answer
|
||||||
|
assert "Rajoy" in rep.final_answer, rep.final_answer
|
||||||
|
assert "the picked reading" in rep.final_answer, rep.final_answer
|
||||||
|
# store-unchanged law: the original ambiguous row keeps BOTH readings
|
||||||
|
q1_rows = [r for r in run.table.rows() if r.qid == "Q1"]
|
||||||
|
assert len(q1_rows) == 1 and q1_rows[0].payload.get("alternatives"), q1_rows
|
||||||
|
print("ok: ambiguous row + dependent -> 2 branches, conditional answer")
|
||||||
|
|
||||||
|
|
||||||
|
def test_ambiguous_row_without_dependent_does_not_fork():
|
||||||
|
streams = RunStreams("no fork test", verbose=False, runs_dir=tempfile.mkdtemp())
|
||||||
|
fm = FakeModules(
|
||||||
|
init_subs=[
|
||||||
|
{"text": "Which office does Pedro Sanchez hold as President?",
|
||||||
|
"deps": [], "answer_type": "OPEN"},
|
||||||
|
],
|
||||||
|
route_fn=lambda q: "knowledge")
|
||||||
|
run, rep = _run_machine(fm, streams, {
|
||||||
|
"Which office": make_ambiguous_engine(
|
||||||
|
"Prime Minister of Spain",
|
||||||
|
[{"value": "President of Socialist International",
|
||||||
|
"quote": "q", "url": "u"}]),
|
||||||
|
})
|
||||||
|
# LAZY: no dependent -> no fork; the ambiguity is a note, the pick rides
|
||||||
|
assert not run.branches.specs, run.branches.specs
|
||||||
|
assert any("AMBIGUOUS" in n for n in rep.notes)
|
||||||
|
assert "if you meant" not in rep.final_answer
|
||||||
|
print("ok: ambiguous row with no dependent -> no fork (lazy law)")
|
||||||
|
|
||||||
|
|
||||||
|
def test_dead_branch_renders_nothing():
|
||||||
|
streams = RunStreams("dead branch test", verbose=False, runs_dir=tempfile.mkdtemp())
|
||||||
|
fm = FakeModules(
|
||||||
|
init_subs=[
|
||||||
|
{"text": "Which office does Pedro Sanchez hold as President?",
|
||||||
|
"deps": [], "answer_type": "OPEN"},
|
||||||
|
{"text": "Who held that office immediately before Pedro Sanchez?",
|
||||||
|
"deps": [1], "answer_type": "OPEN"},
|
||||||
|
],
|
||||||
|
route_fn=lambda q: "knowledge")
|
||||||
|
# Q2 answers UNKNOWN in EVERY branch world -> both branches die honestly
|
||||||
|
run, rep = _run_machine(fm, streams, {
|
||||||
|
"Which office": make_ambiguous_engine(
|
||||||
|
"Prime Minister of Spain",
|
||||||
|
[{"value": "President of Socialist International",
|
||||||
|
"quote": "q", "url": "u"}]),
|
||||||
|
"Who held that office": plain_engine("UNKNOWN"),
|
||||||
|
})
|
||||||
|
assert len(run.branches.specs) == 2, run.branches.specs
|
||||||
|
assert all(run.branches.results[s.id].status == "dead"
|
||||||
|
for s in run.branches.specs)
|
||||||
|
assert rep.final_answer and "No reading" in rep.final_answer, rep.final_answer
|
||||||
|
print("ok: dead branches render an honest empty, never a clause")
|
||||||
|
|
||||||
|
|
||||||
|
def test_natural_merge_renders_once():
|
||||||
|
streams = RunStreams("merge test", verbose=False, runs_dir=tempfile.mkdtemp())
|
||||||
|
fm = FakeModules(
|
||||||
|
init_subs=[
|
||||||
|
{"text": "Which office does Pedro Sanchez hold as President?",
|
||||||
|
"deps": [], "answer_type": "OPEN"},
|
||||||
|
{"text": "Who held that office immediately before Pedro Sanchez?",
|
||||||
|
"deps": [1], "answer_type": "OPEN"},
|
||||||
|
],
|
||||||
|
route_fn=lambda q: "knowledge")
|
||||||
|
# both branch worlds conclude the SAME answer (the synthesis script is
|
||||||
|
# shared) -> one clause, the second merge-recorded
|
||||||
|
class SameAnswerEngine:
|
||||||
|
name = "knowledge"
|
||||||
|
def __init__(self, modules, charge, expert_kind):
|
||||||
|
self.charge = charge
|
||||||
|
def run(self, qid, question, parent_question, table, answer_type, streams=None):
|
||||||
|
self.charge()
|
||||||
|
return EvidenceRow(
|
||||||
|
qid=qid, answer_type=AnswerType.OPEN,
|
||||||
|
payload={"value": "Mariano Rajoy", "quote": "q"},
|
||||||
|
engine="knowledge", trace=[], provenance={}, verified=False, note="")
|
||||||
|
|
||||||
|
import floop.machine as M
|
||||||
|
real = M.LLMExpertEngine
|
||||||
|
M.LLMExpertEngine = SameAnswerEngine
|
||||||
|
fm_synth = fm
|
||||||
|
orig_synth = fm.synthesize
|
||||||
|
try:
|
||||||
|
run = FloopRun("Who was the President before Pedro Sanchez?",
|
||||||
|
budget(), modules=fm, streams=streams)
|
||||||
|
rep = run.run()
|
||||||
|
finally:
|
||||||
|
M.LLMExpertEngine = real
|
||||||
|
# both branches answered 'Rajoy' (their synthesis sees the same table
|
||||||
|
# shape) -> natural merge: one clause
|
||||||
|
statuses = {s.id: run.branches.results[s.id].status
|
||||||
|
for s in run.branches.specs}
|
||||||
|
assert set(statuses.values()) <= {"answered", "merged"}, statuses
|
||||||
|
if len(run.branches.specs) == 2:
|
||||||
|
merged = [s for s, st in statuses.items() if st == "merged"]
|
||||||
|
assert len(merged) <= 1, statuses
|
||||||
|
print("ok: convergent branches merge; the answer renders once")
|
||||||
|
|
||||||
|
|
||||||
|
def test_nested_ambiguity_forks_subbranches():
|
||||||
|
"""An ambiguous row answered INSIDE a branch (its own dependent) opens
|
||||||
|
sub-branches under it; the branch carries its children's conditional
|
||||||
|
as its answer — nesting composes."""
|
||||||
|
streams = RunStreams("nested test", verbose=False, runs_dir=tempfile.mkdtemp())
|
||||||
|
fm = FakeModules(
|
||||||
|
init_subs=[
|
||||||
|
{"text": "Which office does Pedro Sanchez hold as President?",
|
||||||
|
"deps": [], "answer_type": "OPEN"},
|
||||||
|
{"text": "Who held that office immediately before Pedro Sanchez?",
|
||||||
|
"deps": [1], "answer_type": "OPEN"},
|
||||||
|
{"text": "In what year did that predecessor leave office?",
|
||||||
|
"deps": [2], "answer_type": "OPEN"},
|
||||||
|
],
|
||||||
|
route_fn=lambda q: "knowledge")
|
||||||
|
# Q1 ambiguous (PM/SI); the predecessor question ALSO answers ambiguously
|
||||||
|
# (Rajoy | Papandreou) INSIDE every branch — and Q3 depends on it, so the
|
||||||
|
# inner ambiguity has its own dependent: sub-branches open under B1/B2.
|
||||||
|
run, rep = _run_machine(fm, streams, {
|
||||||
|
"Which office": make_ambiguous_engine(
|
||||||
|
"Prime Minister of Spain",
|
||||||
|
[{"value": "President of Socialist International",
|
||||||
|
"quote": "q", "url": "u"}]),
|
||||||
|
"Who held that office": make_ambiguous_engine(
|
||||||
|
"Mariano Rajoy",
|
||||||
|
[{"value": "George Papandreou", "quote": "q2", "url": "u2"}]),
|
||||||
|
"In what year": branch_answer_engine({
|
||||||
|
"Mariano Rajoy": "2018",
|
||||||
|
"George Papandreou": "2015",
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
outer = [s for s in run.branches.specs if not s.origin]
|
||||||
|
inner = [s for s in run.branches.specs if s.origin]
|
||||||
|
assert len(outer) == 2, [s.id for s in run.branches.specs]
|
||||||
|
assert inner, "nested ambiguity must open sub-branches"
|
||||||
|
for s in inner:
|
||||||
|
assert s.origin in {o.id for o in outer}, s
|
||||||
|
assert rep.final_answer and "if you meant" in rep.final_answer, rep.final_answer
|
||||||
|
print(f"ok: nested ambiguity -> {len(inner)} sub-branches under {len(outer)} parents")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
test_ambiguous_row_with_dependent_forks_and_renders_conditionally()
|
||||||
|
test_ambiguous_row_without_dependent_does_not_fork()
|
||||||
|
test_dead_branch_renders_nothing()
|
||||||
|
test_natural_merge_renders_once()
|
||||||
|
test_nested_ambiguity_forks_subbranches()
|
||||||
|
print("\nbranching tests passed")
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
"""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": ["PM 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,113 @@
|
|||||||
|
"""The per-signature LM router tests (lm[<SignatureName>] config blocks).
|
||||||
|
|
||||||
|
Law: any dspy.Signature may carry its own settings block in config.yaml —
|
||||||
|
`lm[ExtractSignature]:` — inheriting its provider's transport ceiling and
|
||||||
|
overriding model/max_tokens/temperature. The factory `floop.llm.predict()`
|
||||||
|
applies the block at CONSTRUCTION: no call-site if's; a signature can
|
||||||
|
change model by editing config alone, forever after (his ask, 26/10: one
|
||||||
|
general function so no more config edits mid-code as the pipeline grows).
|
||||||
|
|
||||||
|
Pinned:
|
||||||
|
1. The config block parses and carries only the intended overrides.
|
||||||
|
2. predict() with no block -> plain dspy.Predict (defaults, untouched).
|
||||||
|
3. predict() with a settings-only block -> Predict whose config carries
|
||||||
|
the overrides (dspy merges self.config as lm_kwargs per call —
|
||||||
|
verified against dspy 3.4.1 _forward_preprocess).
|
||||||
|
4. predict() with a model: override -> Predict bound to a DEDICATED
|
||||||
|
cached dspy.LM (same provider base_url/ceiling, its own model); a
|
||||||
|
second predict() returns the SAME LM object (no rebuild per call).
|
||||||
|
5. A block for a signature that is never constructed breaks nothing.
|
||||||
|
6. signature_overrides() lists the active blocks for the run.log line.
|
||||||
|
|
||||||
|
Run: .venv/bin/python tests/lm_signature_router.py
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
|
|
||||||
|
import floop.llm as llm
|
||||||
|
from floop.llm import predict, signature_overrides
|
||||||
|
from knowledge.extract import ExtractSignature
|
||||||
|
from floop.dspy_modules import InitSignature
|
||||||
|
|
||||||
|
|
||||||
|
def test_config_block_parses():
|
||||||
|
"""config.yaml carries lm[ExtractSignature] with the intended override."""
|
||||||
|
import yaml
|
||||||
|
cfg = yaml.safe_load((Path(__file__).resolve().parent.parent
|
||||||
|
/ "config.yaml").read_text())
|
||||||
|
assert "lm[ExtractSignature]" in cfg, (
|
||||||
|
"the per-signature block must be a top-level key `lm[<SigName>]`")
|
||||||
|
block = cfg["lm[ExtractSignature]"]
|
||||||
|
assert block.get("max_tokens") == 1800, block
|
||||||
|
assert "model" not in block, "no model override yet (his call: default)"
|
||||||
|
assert "lm[NoSuchSignature]" not in cfg
|
||||||
|
print("ok: config.yaml carries the lm[ExtractSignature] block, model-free")
|
||||||
|
|
||||||
|
|
||||||
|
def test_no_block_means_plain_predict():
|
||||||
|
"""A signature without a block gets the defaults, untouched."""
|
||||||
|
p = predict(InitSignature)
|
||||||
|
assert type(p).__name__ == "Predict"
|
||||||
|
assert not p.config, f"no overrides expected, got {p.config}"
|
||||||
|
assert p.lm is None, "no dedicated LM without a model override"
|
||||||
|
print("ok: no block -> plain dspy.Predict, defaults untouched")
|
||||||
|
|
||||||
|
|
||||||
|
def test_settings_block_becomes_predict_config():
|
||||||
|
"""Settings-only block -> per-call lm_kwargs (dspy honors self.config)."""
|
||||||
|
p = predict(ExtractSignature)
|
||||||
|
assert p.config.get("max_tokens") == 1800, p.config
|
||||||
|
assert p.lm is None, "settings-only block must not build a new LM"
|
||||||
|
print("ok: lm[ExtractSignature].max_tokens -> Predict config (lm_kwargs)")
|
||||||
|
|
||||||
|
|
||||||
|
def test_model_override_builds_dedicated_cached_lm():
|
||||||
|
"""A model: override binds a dedicated LM; the factory caches it."""
|
||||||
|
orig_load = llm._load_yaml
|
||||||
|
llm._load_yaml = lambda: { # noqa: E731 — monkeypatch, test-only
|
||||||
|
"lm": {"default": "local",
|
||||||
|
"local": {"base_url": "http://127.0.0.1:11435/v1",
|
||||||
|
"model": "qwen3.8-27b-uc-64k:latest",
|
||||||
|
"max_tokens": 4096, "temperature": 0.0,
|
||||||
|
"read_timeout_s": 1800, "num_retries": 1}},
|
||||||
|
"lm[InitSignature]": {"provider": "local", "model": "qwen3.8:27b",
|
||||||
|
"max_tokens": 1024},
|
||||||
|
}
|
||||||
|
llm._SIGNATURE_LMS.clear()
|
||||||
|
try:
|
||||||
|
p = predict(InitSignature)
|
||||||
|
assert p.lm is not None, "model override must bind a dedicated LM"
|
||||||
|
assert p.lm.model == "openai/qwen3.8:27b", p.lm.model
|
||||||
|
assert p.lm.kwargs["timeout"] == 1800, "inherits provider ceiling"
|
||||||
|
assert p.lm.kwargs["max_tokens"] == 1024, "block max_tokens on the LM"
|
||||||
|
assert not p.config, "dedicated LM carries the settings, not config"
|
||||||
|
# cached: a second construction reuses the SAME LM object
|
||||||
|
p2 = predict(InitSignature)
|
||||||
|
assert p2.lm is p.lm, "the factory must cache LMs per provider+model"
|
||||||
|
finally:
|
||||||
|
llm._load_yaml = orig_load
|
||||||
|
llm._SIGNATURE_LMS.clear()
|
||||||
|
print("ok: model override -> dedicated cached LM (provider ceiling inherited)")
|
||||||
|
|
||||||
|
|
||||||
|
def test_signature_overrides_lists_active_blocks():
|
||||||
|
ov = signature_overrides()
|
||||||
|
block = ov.get("ExtractSignature")
|
||||||
|
assert block and block.get("max_tokens") == 1800 and block.get("provider") == "local", ov
|
||||||
|
assert "NoSuchSignature" not in ov
|
||||||
|
print(f"ok: signature_overrides lists active blocks: {list(ov)}")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
test_config_block_parses()
|
||||||
|
test_no_block_means_plain_predict()
|
||||||
|
test_settings_block_becomes_predict_config()
|
||||||
|
test_model_override_builds_dedicated_cached_lm()
|
||||||
|
test_signature_overrides_lists_active_blocks()
|
||||||
|
print("\nlm_signature_router: 5/5 ok")
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
"""The LM transport ceiling tests (fix: EXTRACT hangs on slow local models).
|
||||||
|
|
||||||
|
Law: a provider's transport ceiling (read timeout + retries) is
|
||||||
|
CONFIG, not code — a 27b model on a busy home GPU can legitimately
|
||||||
|
take >600s for a long structured output, and the silent-ollama proxy
|
||||||
|
in front of it cuts at its own READ_TIMEOUT. dspy 3.4.1 routes
|
||||||
|
openai/... through lm15 whose default read timeout is 600s — the
|
||||||
|
wall every attempt of your 2407.3s EXTRACT call died on.
|
||||||
|
|
||||||
|
Pinned here:
|
||||||
|
1. config.yaml may set per-provider `read_timeout_s` and `num_retries`;
|
||||||
|
configure_lm forwards them (timeout= -> lm15 Timeouts(read=),
|
||||||
|
num_retries -> the dspy retry loop, LMTransportError IS retryable).
|
||||||
|
2. Defaults stay honest: nothing configured -> dspy defaults
|
||||||
|
(read 600s, retries 3), unchanged behavior for cloud.
|
||||||
|
3. The first run.log line reports the ceiling (no more silent 600s
|
||||||
|
walls — you SEE the read timeout that will kill a slow call).
|
||||||
|
4. The run dies at startup on an impossible ceiling (retries<0,
|
||||||
|
timeout<=0) rather than mid-run.
|
||||||
|
|
||||||
|
Run: .venv/bin/python tests/lm_transport.py
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
|
|
||||||
|
import floop.llm as llm
|
||||||
|
from floop.llm import configure_lm
|
||||||
|
|
||||||
|
|
||||||
|
CFG = Path(__file__).resolve().parent.parent / "config.yaml"
|
||||||
|
|
||||||
|
|
||||||
|
def test_config_carries_ceiling():
|
||||||
|
"""config.yaml supports read_timeout_s + num_retries per provider."""
|
||||||
|
import yaml
|
||||||
|
cfg = yaml.safe_load(CFG.read_text())["lm"]
|
||||||
|
local = cfg["local"]
|
||||||
|
assert local.get("read_timeout_s") == 1800, (
|
||||||
|
"local provider should declare read_timeout_s=1800 (30min — the "
|
||||||
|
"silent-ollama cut is 600s and the 27b EXTRACT runs longer)")
|
||||||
|
assert local.get("num_retries") == 1, (
|
||||||
|
"local provider should declare num_retries=1 (a hung call retries "
|
||||||
|
"once more, not 3 — each attempt costs up to read_timeout_s)")
|
||||||
|
cloud = cfg["ollama-cloud"]
|
||||||
|
assert cloud.get("read_timeout_s") == 300, (
|
||||||
|
"cloud provider should declare read_timeout_s=300 (glm-5.3-flash "
|
||||||
|
"answers EXTRACT in ~3s; 300s bounds a wedged call)")
|
||||||
|
print("ok: config.yaml declares per-provider read_timeout_s + num_retries")
|
||||||
|
|
||||||
|
|
||||||
|
def test_configure_lm_forwards_ceiling():
|
||||||
|
"""configure_lm builds the LM with timeout=/num_retries from config."""
|
||||||
|
import dspy
|
||||||
|
os.environ["FLOOP_LM"] = "local"
|
||||||
|
info = configure_lm()
|
||||||
|
assert info["provider"] == "local"
|
||||||
|
lm = llm._ACTIVE
|
||||||
|
assert lm.kwargs.get("timeout") == 1800, lm.kwargs.get("timeout")
|
||||||
|
assert getattr(lm, "num_retries", None) == 1, getattr(lm, "num_retries", None)
|
||||||
|
# the cloud provider, in the same config, carries its own ceiling
|
||||||
|
os.environ["FLOOP_LM"] = "ollama-cloud"
|
||||||
|
info2 = configure_lm()
|
||||||
|
assert info2["provider"] == "ollama-cloud"
|
||||||
|
lm2 = llm._ACTIVE
|
||||||
|
assert lm2.kwargs.get("timeout") == 300
|
||||||
|
assert getattr(lm2, "num_retries", None) == 2
|
||||||
|
del os.environ["FLOOP_LM"]
|
||||||
|
print("ok: configure_lm forwards timeout= + num_retries per provider")
|
||||||
|
|
||||||
|
|
||||||
|
def test_defaults_unchanged_when_unset():
|
||||||
|
"""No ceiling declared -> dspy defaults (600s read, retries 3)."""
|
||||||
|
import yaml
|
||||||
|
src = CFG.read_text()
|
||||||
|
assert "read_timeout_s" in src, "config.yaml must carry the new keys"
|
||||||
|
# simulate: build an LM from a config WITHOUT the keys — the loader
|
||||||
|
# must not invent values (None -> dspy default)
|
||||||
|
cfg = yaml.safe_load(src)["lm"]
|
||||||
|
stripped = {k: ({kk: vv for kk, vv in v.items()
|
||||||
|
if kk not in ("read_timeout_s", "num_retries")}
|
||||||
|
if isinstance(v, dict) else v)
|
||||||
|
for k, v in cfg.items()}
|
||||||
|
orig_load = llm._load_yaml
|
||||||
|
llm._load_yaml = lambda: {"lm": stripped} # noqa: E731 — monkeypatch, test-only
|
||||||
|
try:
|
||||||
|
os.environ["FLOOP_LM"] = "local"
|
||||||
|
configure_lm()
|
||||||
|
lm = llm._ACTIVE
|
||||||
|
assert "timeout" not in lm.kwargs, (
|
||||||
|
f"unset ceiling must not reach the LM (got {lm.kwargs.get('timeout')})")
|
||||||
|
assert getattr(lm, "num_retries", None) is None or lm.num_retries == 3, (
|
||||||
|
"dspy default num_retries=3 must survive untouched")
|
||||||
|
finally:
|
||||||
|
llm._load_yaml = orig_load
|
||||||
|
del os.environ["FLOOP_LM"]
|
||||||
|
print("ok: no ceiling declared -> dspy defaults, nothing invented")
|
||||||
|
|
||||||
|
|
||||||
|
def test_run_log_first_line_reports_ceiling():
|
||||||
|
"""The provider dict carries the ceiling for the run.log provenance."""
|
||||||
|
os.environ["FLOOP_LM"] = "local"
|
||||||
|
info = configure_lm()
|
||||||
|
assert info.get("read_timeout_s") == 1800, info
|
||||||
|
assert info.get("num_retries") == 1, info
|
||||||
|
del os.environ["FLOOP_LM"]
|
||||||
|
print("ok: configure_lm returns read_timeout_s/num_retries for the log line")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
test_config_carries_ceiling()
|
||||||
|
test_configure_lm_forwards_ceiling()
|
||||||
|
test_defaults_unchanged_when_unset()
|
||||||
|
test_run_log_first_line_reports_ceiling()
|
||||||
|
print("\nlm_transport: 4/4 ok")
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
"""Live wire check: does config timeout= actually bound the HTTP read?
|
||||||
|
|
||||||
|
Starts a local server that NEVER answers (a socket that accepts and
|
||||||
|
hangs), points the LM at it with a tiny timeout, and asserts the call
|
||||||
|
dies in ~timeout (not dspy's default 600s, not forever). This is the
|
||||||
|
one-hop proof that the ceiling travels configure_lm -> dspy.LM ->
|
||||||
|
lm15 engine -> the wire. Offline (127.0.0.1), one call, seconds.
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import socket
|
||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||||
|
|
||||||
|
HOST, PORT = "127.0.0.1", 0 # ephemeral
|
||||||
|
|
||||||
|
|
||||||
|
def hang_server(stop: threading.Event, port_box: list):
|
||||||
|
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||||
|
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||||
|
srv.bind((HOST, PORT))
|
||||||
|
srv.listen(4)
|
||||||
|
port_box.append(srv.getsockname()[1])
|
||||||
|
srv.settimeout(1.0)
|
||||||
|
while not stop.is_set():
|
||||||
|
try:
|
||||||
|
conn, _ = srv.accept()
|
||||||
|
# read nothing more; just hold the connection open forever
|
||||||
|
conn.settimeout(5.0)
|
||||||
|
try:
|
||||||
|
conn.recv(65536)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
except socket.timeout:
|
||||||
|
continue
|
||||||
|
srv.close()
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
port_box: list = []
|
||||||
|
stop = threading.Event()
|
||||||
|
t = threading.Thread(target=hang_server, args=(stop, port_box), daemon=True)
|
||||||
|
t.start()
|
||||||
|
while not port_box:
|
||||||
|
time.sleep(0.05)
|
||||||
|
port = port_box[0]
|
||||||
|
|
||||||
|
import dspy
|
||||||
|
import floop.llm as llm
|
||||||
|
orig_load = llm._load_yaml
|
||||||
|
llm._load_yaml = lambda: {"lm": {
|
||||||
|
"default": "hang",
|
||||||
|
"hang": {"base_url": f"http://127.0.0.1:{port}/v1",
|
||||||
|
"model": "test-model", "max_tokens": 8,
|
||||||
|
"temperature": 0.0,
|
||||||
|
"read_timeout_s": 3, "num_retries": 0},
|
||||||
|
}}
|
||||||
|
try:
|
||||||
|
os.environ["FLOOP_LM"] = "hang"
|
||||||
|
llm.configure_lm()
|
||||||
|
lm = llm._ACTIVE
|
||||||
|
assert lm.kwargs["timeout"] == 3.0, lm.kwargs
|
||||||
|
t0 = time.monotonic()
|
||||||
|
try:
|
||||||
|
lm(messages=[{"role": "user", "content": "hi"}])
|
||||||
|
print("FAIL: the hang server answered?!")
|
||||||
|
return 1
|
||||||
|
except Exception as e:
|
||||||
|
dt = time.monotonic() - t0
|
||||||
|
# the call must die at ~3s (+ handshake slack), NOT 600s
|
||||||
|
assert dt < 10, f"timeout did not bound the read: {dt:.1f}s"
|
||||||
|
print(f"ok: read died at {dt:.1f}s (timeout=3 honored on the wire; "
|
||||||
|
f"exception={type(e).__name__})")
|
||||||
|
return 0
|
||||||
|
finally:
|
||||||
|
stop.set()
|
||||||
|
llm._load_yaml = orig_load
|
||||||
|
os.environ.pop("FLOOP_LM", None)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
rc = main()
|
||||||
|
print("WIRE CHECK:", "PASS" if rc == 0 else "FAIL")
|
||||||
|
sys.exit(rc)
|
||||||
+94
-1
@@ -70,7 +70,11 @@ def test_user_expert_fails_question():
|
|||||||
rep = FloopRun("goal?", budget(), modules=fm).run()
|
rep = FloopRun("goal?", budget(), modules=fm).run()
|
||||||
assert rep.questions[1][1] == "failed"
|
assert rep.questions[1][1] == "failed"
|
||||||
assert any("needs_user_input" in e for e in rep.evidence_rows)
|
assert any("needs_user_input" in e for e in rep.evidence_rows)
|
||||||
assert rep.final_answer == "ANSWER(goal?)" # synthesis still happens, honestly
|
# the 23/10 law: a run that ASKED ends IN THE QUESTION (fixed code),
|
||||||
|
# never a synthesis prompt swallowing the ask — 'the evidence does
|
||||||
|
# not identify...' is the rejected behaviour
|
||||||
|
assert rep.final_answer.startswith("I need to ask you:"), rep.final_answer
|
||||||
|
assert any("clarification requested" in n for n in rep.notes)
|
||||||
|
|
||||||
|
|
||||||
def test_recursion_depth_cap():
|
def test_recursion_depth_cap():
|
||||||
@@ -264,6 +268,95 @@ def test_fanout_respects_top_n_slice():
|
|||||||
print("ok test_fanout_respects_top_n_slice")
|
print("ok test_fanout_respects_top_n_slice")
|
||||||
|
|
||||||
|
|
||||||
|
def test_seed_warning_is_emitted():
|
||||||
|
"""The mask seed auto-answering a question must WARN (his 23/10 ask):
|
||||||
|
on the log as WARNING, on screen even non-verbose — self-improvement
|
||||||
|
signal, not silent evidence."""
|
||||||
|
import tempfile
|
||||||
|
from floop.stream import RunStreams
|
||||||
|
streams = RunStreams("seed warn test", verbose=False,
|
||||||
|
runs_dir=tempfile.mkdtemp())
|
||||||
|
fm = FakeModules(
|
||||||
|
init_subs=[
|
||||||
|
{"text": "Who is Pedro Sanchez?", "deps": [],
|
||||||
|
"answer_type": "OPEN", "known_answer": "Pedro Sanchez"},
|
||||||
|
{"text": "What office did Pedro Sanchez hold?", "deps": [1],
|
||||||
|
"answer_type": "OPEN"},
|
||||||
|
],
|
||||||
|
route_fn=lambda q: "knowledge", expert_value="President")
|
||||||
|
run = FloopRun("Who is Pedro Sanchez and what office does he hold?",
|
||||||
|
budget(), modules=fm, streams=streams)
|
||||||
|
run.run()
|
||||||
|
log = streams.log_path.read_text(encoding="utf-8")
|
||||||
|
assert "WARNING SEED auto-answered Q1" in log, log[-400:]
|
||||||
|
assert "mask map; zero expert calls" in log
|
||||||
|
assert any("seeded from anonymization" in n for n in run.notes)
|
||||||
|
print("ok: seed WARNING lands in run.log (auto-answer is loud)")
|
||||||
|
|
||||||
|
|
||||||
|
def test_route_to_user_ends_in_the_question():
|
||||||
|
"""His 23/10 run: ROUTE deferred a subquestion to the user (the
|
||||||
|
evidence only flagged ambiguity) — and the final ANSWER prompt
|
||||||
|
swallowed the ask, inventing 'the evidence does not identify...'.
|
||||||
|
A run that ASKED ends IN THE QUESTION, composed by fixed code: the
|
||||||
|
instantiated question, what the machine holds as context, zero
|
||||||
|
synthesis calls. (The ambiguity+dependent shape now forks branches —
|
||||||
|
tested in branches.py; this covers every OTHER honest defer.)"""
|
||||||
|
import tempfile
|
||||||
|
from floop.stream import RunStreams
|
||||||
|
from floop.state import AnswerType, EvidenceRow
|
||||||
|
streams = RunStreams("clarify test", verbose=False,
|
||||||
|
runs_dir=tempfile.mkdtemp())
|
||||||
|
|
||||||
|
class PlainEngine:
|
||||||
|
def __init__(self, modules, charge, expert_kind):
|
||||||
|
self.charge = charge
|
||||||
|
def run(self, qid, question, parent_question, table, answer_type, streams=None):
|
||||||
|
self.charge()
|
||||||
|
return EvidenceRow(
|
||||||
|
qid=qid, answer_type=AnswerType.OPEN,
|
||||||
|
payload={"value": "Paris", "quote": "q"},
|
||||||
|
engine="knowledge", trace=[], provenance={},
|
||||||
|
verified=False, note="")
|
||||||
|
|
||||||
|
import floop.machine as M
|
||||||
|
real = M.LLMExpertEngine
|
||||||
|
M.LLMExpertEngine = PlainEngine
|
||||||
|
try:
|
||||||
|
# FakeModules.route_question returns (route_fn(question), "fake") —
|
||||||
|
# our route must return the ATTENDANT string alone, not a tuple
|
||||||
|
def route(q):
|
||||||
|
if "district" in q:
|
||||||
|
return "user"
|
||||||
|
return "knowledge"
|
||||||
|
|
||||||
|
fm = FakeModules(
|
||||||
|
init_subs=[
|
||||||
|
{"text": "What is the capital of France?", "deps": [],
|
||||||
|
"answer_type": "OPEN"},
|
||||||
|
{"text": "Which specific district of that capital does the user mean?",
|
||||||
|
"deps": [1], "answer_type": "OPEN"},
|
||||||
|
],
|
||||||
|
route_fn=route)
|
||||||
|
# the generic FakeModules.missing_decompose would inject a fallback
|
||||||
|
# question after the defer, reopening the loop and reaching a plain
|
||||||
|
# synthesis — this test isolates the defer path (missing adds nothing)
|
||||||
|
fm.missing_decompose = lambda goal, evidence: []
|
||||||
|
run = FloopRun("What is the capital of France and which district do you mean?",
|
||||||
|
budget(), modules=fm, streams=streams)
|
||||||
|
rep = run.run()
|
||||||
|
finally:
|
||||||
|
M.LLMExpertEngine = real
|
||||||
|
# the run ends IN THE QUESTION to the user, by fixed code
|
||||||
|
assert rep.final_answer.startswith("I need to ask you:"), rep.final_answer
|
||||||
|
assert "district" in rep.final_answer, rep.final_answer
|
||||||
|
assert "(so far: Paris)" in rep.final_answer, rep.final_answer
|
||||||
|
# the synthesis NEVER ran: the ask is not invented from the table
|
||||||
|
assert "synthesize" not in fm.calls, fm.calls
|
||||||
|
assert any("clarification requested" in n for n in rep.notes), rep.notes
|
||||||
|
print("ok: a run that asks ends in the question (fixed code, no synthesis)")
|
||||||
|
|
||||||
|
|
||||||
# keep a handle to restore the real engine after monkeypatching
|
# keep a handle to restore the real engine after monkeypatching
|
||||||
from floop.engine import LLMExpertEngine as _restore_llm_engine
|
from floop.engine import LLMExpertEngine as _restore_llm_engine
|
||||||
|
|
||||||
|
|||||||
@@ -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