Knowledge base¶
KnowledgeBase(shdata, name) is the research store: every source, every model output, every verification and
link decision, the graph built from them and its versioned consensus, on ordinary SharedData tables. Any agent can
add to it and read from it. It calls no LLM: producers (an agent, a script, any model lane) run the canonical
prompts in SharedData.KnowledgeContract and hand the raw output back; the store validates it, resolves entities
deterministically, writes the graph and publishes one consensus commit per batch.
Retrieval¶
For recorded answers, forecasts, scenarios and evaluations use the lazy
kb.research workflow. kb.research.ask(...) retrieves
and pins evidence in a replayable run (awaiting_synthesis until an external
agent or respond supplies a synthesis); kb.query(...) remains the read-only
evidence lookup.
The configured SharedData database folders and credentials are used as usual. Opening a store does not call a
model or ingest anything. Existing callers can continue to pass KnowledgeBase(shdata, name).
from SharedData.KnowledgeBase import KnowledgeBase
kb = KnowledgeBase('RESEARCH', read_only=True)
result = kb.query('Marco Rubio', related_to='oil', last_hours=24)
result['status'] # linked | topic_only | no_coverage (or ok | sources_only | no_match without related_to)
result['sources'] # matching original publications, including text, timestamps and URLs
result['claims'] # stored verified claims, with quotes, source hashes and URLs when available
result['paths'] # stated causal chains from the matching entities to oil; possibly empty
result['related_context'] # stored causes/effects of oil, without asserting a connection to Rubio
result['coverage'] # observed source dates, requested UTC interval and missing source days
result['truncated'] # explicit result/path limits
result['elapsed_ms']
Use start and end for an absolute UTC interval, or last_hours with an optional now for repeatable relative
queries. All new query windows are [start, end); an end date at midnight excludes that day. Paths, source
mentions and claims use the same window. limit=20 bounds each returned collection; causal traversal has a
200-path budget and depth is bounded to 0–3. Reaching a limit is reported, so an empty bounded path search does
not prove that no longer path exists.
Claims labelled match='entity' directly name a resolved entity as subject/object. match='source' means the
claim occurs in a publication mentioning the query. This is contextual evidence, not attribution to that
person. Source co-occurrence never creates a causal path, and unresolved surname-only identities are never
silently merged. The store does not infer an oil forecast from disconnected facts.
sources_only means matching publications exist without matching structured claims. no_match means there is
no matching evidence in this store/window. no_coverage means the requested interval has no observed source
coverage. Observed dates do not certify complete ingestion: coverage['completeness'] is always unknown.
An empty structured query does not establish that the original sources never said something.
Coverage also reports claim dates separately, so XBRL facts without a registered source record remain queryable
(coverage['status'] == 'claims_only'); missing source URLs remain null rather than being invented.
For narrower lookups use find(text), search_sources(text, start=..., end=...), context(text) or the existing
effects, causes, walk and financial answer methods. No caller needs to decode BSON or scan graph tables.
Lookup maintenance¶
register_sources maintains the source index and build maintains node and claim indexes. Call kb.prepare()
once on the single writer when opening a store loaded by an earlier version; an unprepared first lookup also
performs that migration. Subsequent processes reuse the persisted indexes. A ready query reads matching
postings/payloads and does not decode the entire node, source or claim corpus.
As with the graph and consensus store, one writer per store name is required. Prepare a legacy store on that
writer before serving concurrent readers; queries against ready stores do not write indexes. Interrupted index
updates resume from published block watermarks and are safe to retry. If records were edited through low-level
table APIs, call kb.prepare(rebuild=True) on the writer to publish a fresh lookup generation. Old generations
are retained; preparation does not delete sources or prior evidence.
Confirmed identity groups are also persisted in bounded chunks and reused by new processes. Updating a link or
its second-check verdict refreshes those groups, including when an existing verdict is replaced in place.
Use read_only=True for serving readers: mutation methods reject writes, and a missing/stale index reports that
the single writer must prepare the store. A reader never takes over an in-progress index update. Producers use
the default writable constructor. This API guard does not change the underlying operating-system file permissions.
Postings are stored as BSON integer lists bounded to 4,096 record positions per term/block. They do not use fixed-width JSON strings or replace prior batches' matches. Text lookup preserves normalized substring matches, including accents and short words, and indexes the complete stored source text.
Table (under <user>/<db>/D1/<name>/) |
Key | Holds |
|---|---|---|
Hashs/.../KGSOURCES |
source hash | kind, uid, date, route, content hash, text, file / CIK / accession (re-routable) |
Hashs/.../KGCONTENT |
content hash | first source with that exact text; copies reuse its extraction and verdicts |
Hashs/.../KGEXTRACT |
(source, extractor) | raw model output for one item |
Hashs/.../KGVERDICTS |
key | verification, link and same-check decisions with their version |
Hashs/.../KGFILERS |
cik:<10 digits> |
ticker, names, fiscal focus, verified against the filing cover |
Hashs/.../KGFACTS |
fact key | deterministic inline-XBRL facts |
Hashs/.../KGLOOKUP |
(version, generation, kind, term, record block) | bounded node/source text and claim subject/object/source postings |
Hashs/.../KGLOOKUPSTATE |
(version, kind) | published index watermark and observed source dates |
| + knowledge graph and consensus graph tables |
from SharedData.KnowledgeBase import KnowledgeBase
from SharedData import KnowledgeContract as K
kb = KnowledgeBase(shdata, 'RESEARCH')
st = kb.register_sources([dict(kind='rss', uid=link, date=published, source=feed, text=title_and_summary)])
todo = kb.pending('gen') # routed to general extraction, not yet extracted
body = kb.prompt_items(todo[:8]) # numbered items for K.GEN_PROMPT (K.FIN_PROMPT for 'fin')
kb.add_extractions([dict(source=r['hash'], extractor=K.GEN_VERSION, output=item) for r, item in zip(todo, items)])
checks = kb.unverified([r['hash'] for r in todo]) # statements + quotes for K.VERIFY_PROMPT
kb.add_verdicts([dict(key=c['key'], ok=ok) for c, ok in zip(checks, answers)])
kb.add_filing_folder('/archive/earnings/CVX/0000093410/EVT-...') # filer + XBRL facts, no model
kb.build([s['hash'] for s in st], fact_keys) # graph + one consensus commit; repeatable
kb.answer('cik:0000093410', 'eps_diluted', basis='adjusted', period='2026Q3') # consensus + evidence
kb.context('refinery strike') # matching nodes with stated causes and effects, outlets and quotes
kb.walk(node, depth=2, min_outlets=2, direction='in') # causal paths stated by >= 2 outlets per hop
Routing (K.route_of, versioned by K.ROUTE_V):
- earnings releases, decks, and news or tweets with earnings figures go to fin;
- other news, tweets and 10-Q prose go to gen;
- 10-Q tables and 8-K covers go to xbrl (facts only);
- SEC notice feeds go to filing-discovery;
- legal exhibits go to archive.
Changing the rules and bumping ROUTE_V re-routes known sources on their next registration, using their stored
text and metadata. Repeated rows in a registration batch retain one source and never become their own duplicate.
Contract (K.validate, K.validate_rel): an assertion that fails is kept with its problems but never votes.
Typical failures:
- quote not in the source, or number not in the quote;
- metric not named;
- table column contradicting the period, or a table without its header;
- guidance range stored as a point;
- unit, scale or currency mismatch;
- unresolved entity or period;
- relation with the wrong subject/object kind, a self-cause, or a non-prose quote.
Verification: relational claims enter the graph only with a positive verdict (K.VERIFY_PROMPT; causal claims
are meant for a reasoning-mode check). Copies of a text share the first copy's verdicts when they reuse its extraction. A copy with its own extraction
requires its own verdict. Copies routed to a different extraction stream remain eligible for that stream.
Links: concept_labels() gives every concept with its definition. The caller proposes pairs (embeddings,
shared words, shared causal targets) and asks K.LINK_PROMPT. Rules for publishing:
- a same link needs a second, independent K.SAME_PROMPT check (add_same_checks), and label similarity
= 0.78 when
cosis given; - hierarchy is published only when lexically certain (narrower label = broader label + modifiers, same head noun); - decisions stay inKGVERDICTS, so edges can be republished under new rules (write_links).
Queries return what sources stated, never an inference. Each answer carries:
- independent outlets (family), claim counts and modalities;
- up to three quotes with source class and time.
An empty answer means no matching structured evidence is stored. Incoming and outgoing causal queries include all stated
modalities and denials; a denial has sign=0 and never becomes an opposite causal effect or a walk hop.
Confirmed same-as groups can be queried from either endpoint.
Source timestamps are normalized to UTC, preserving their precision. Graph valid records publication time;
known records ingestion time, including for future-dated publications. A build retry repairs missing edges and
publishes evidence left by an interruption before consensus. An unchanged build publishes no new commit.
Source and contract keys encode component boundaries so embedded separators cannot alias another key.
XBRL duplicate concepts use expanded namespaces; INF precision requires exact equality.
Scale (two earnings days, 73k sources, from cached model output on one host):
- load 201 s;
- 52k claims, 30k consensus questions, 368k XBRL facts;
- Historical timings before persistent lookup: answer 0.4 s, context 2 s (lexical node scan).
Index preparation is a separate migration/ingestion cost. Benchmark prepared retrieval separately from first opening/JIT compilation; do not treat historical scan timings as current latency guarantees.
Prepared retrieval measured on the existing two-day store (70,017 nodes, 72,911 sources, 51,781 claims), median
of five calls in a newly opened process: find('Rubio') 0.7 ms, context('oil price') 19 ms, and the complete
Rubio/oil query 59 ms. A missing last-24-hours interval returned no_coverage in 0.7 ms. These are local
observations, not latency guarantees. Legacy text/claim index preparation took about 110 seconds once and added
about 545 MB of lookup data; subsequent processes reused it without updating the index.
lxml is needed only to read filings (KnowledgeXBRL).