67 / KNOWLEDGE GRAPH · GRAPHRAG / KNOWLEDGE-RESEARCH ENGINE
67 / PRODUCTION / ENTITIES · TYPED RELATIONS · GRAPH RETRIEVAL · EVIDENCE

KNOWLEDGE GRAPH
& GRAPHRAG.

Knowledge Graph — структурированное представление сущностей и явных отношений между ними. Вместо «эти два текста семантически похожи» граф умеет выражать: компания A ВЛАДЕЕТ объектом B, проект C РАСПОЛОЖЕН_В регионе D, документ E ОТНОСИТСЯ_К проекту C.

GraphRAG использует этот граф как retrieval substrate: находит стартовые сущности, проходит по разрешённым связям, собирает локальное подграфовое evidence и передаёт его в генерацию. Это особенно полезно для вопросов про связи, зависимости, ownership, цепочки, impact analysis и multi-hop facts.
00. ARCHITECTURAL STATUS

GRAPH НУЖЕН, КОГДА ЯВНЫЕ RELATIONS ДАЮТ ИЗМЕРИМУЮ ЦЕННОСТЬ

Не строить knowledge graph «потому что AI». Если большинство вопросов решаются обычным RAG/SQL/vector search, граф может быть лишней сложностью. Он оправдан, когда relation-aware retrieval, entity-centric aggregation, path queries или dependency/impact analysis заметно улучшают результат.
TYPEPRODUCTIONStructured knowledge / retrieval infrastructure.
DEFAULTCONDITIONALНе является обязательным слоем любой AI-системы.
ENABLE WHENRELATIONS MATTEREntity/path/dependency queries show uplift.
SEPARATE COMPONENTYESLogical graph store + retrieval service.
LIVES INKNOWLEDGE / RESEARCH ENGINER06 structured knowledge substrate.
COMPLEXITYMEDIUM → HIGHSchema + entity resolution are harder than storage.
IMPLEMENT: ONLY WITH A GRAPH USE CASE
Минимум 80% ценности: stable entity IDs, small explicit relation schema, source-backed edges, entity resolution, version/freshness fields, tenant/ACL constraints, one-hop/two-hop/path queries, vector/lexical entity seeding, bounded neighborhood expansion, provenance on every material edge, graph retrieval evals and rebuild/reconciliation. PostgreSQL tables can be enough initially.
01A. ARCHITECTURE BOUNDARIES & OPERATIONS

EXPLICIT SYSTEM CONTRACT

A. BOUNDARY WITH NEIGHBORS

№66 Vector DB & Embeddings владеет similarity-based candidate retrieval; №67 — explicit entities/typed relations/traversal. №08 RAG владеет full retrieval-augmented answer pipeline; GraphRAG — один retrieval pattern внутри неё. №26 Multi-Hop Research владеет исследовательской стратегией, где следующий вопрос зависит от найденного evidence; graph traversal может быть одним из инструментов такого исследования. №17 Reasoning Search ищет по reasoning states/partial solutions; это не knowledge graph traversal. №61 Provenance хранит origin/derivation graph system objects; knowledge graph описывает domain entities/relations. №55–56 доставляют и парсят source data, из которой graph facts извлекаются.

B. PREREQUISITES / CROSS-REFERENCES

Prerequisites: №08 RAG, №25 Evidence-First, №26 Multi-Hop Research, №27 Agentic RAG, №45 Verification, №46 Observability, №50 Contracts, №55 Ingestion, №56 Parsing, №61 Provenance, №66 Vector DB & Embeddings. Forward references: №76 Data Governance & Privacy, №77 Production AI Architecture.

C. PLANE PLACEMENT

REQUEST-TIME: entity resolution, graph lookup, neighborhood/path retrieval. CONTROL PLANE: ontology/schema, relation types, confidence thresholds, extraction policies, traversal limits. DATA PLANE: entities, edges, properties, aliases, evidence refs, temporal/access metadata. OFFLINE: graph extraction, entity linking, dedup, consistency checks, community summaries, rebuild and evals.

D. FAILURE & OPERATIONS CONTRACT

Success: graph query returns bounded authorized entities/relations with source-backed evidence and exact versions. Retryable: transient graph/index/network failure. Permanent: invalid schema relation, unresolved entity, forbidden traversal, missing graph generation. Idempotency: upsert by stable entity/edge identity + source fact version. Persist: entity IDs, aliases, relation type, source/evidence refs, confidence/status, temporal validity, access scope, graph generation. Security: path expansion cannot traverse through hidden nodes and leak their existence/relations.

E. WHAT THIS TOPIC DOES NOT OWN

№67 не владеет general RAG, vector similarity, reasoning-tree search, provenance graph, workflow dependencies or arbitrary database joins. Она владеет DOMAIN ENTITY/RELATION MODELING AND GRAPH-BASED KNOWLEDGE RETRIEVAL.

01. KNOWLEDGE GRAPH CORE

ENTITY + RELATION + EVIDENCE

COMPANY entity://A PROJECT entity://B REGION entity://C DOCUMENT entity://D INVESTS_IN LOCATED_IN DESCRIBES Each edge must carry evidence_ref + source version + status/confidence + validity + access scope.
Графовой связью является не «текст A похож на текст B», а domain assertion с конкретным типом: INVESTS_IN, LOCATED_IN, OWNS, PART_OF, DEPENDS_ON.
02. PROPERTY GRAPH VS RDF-LIKE MODEL

ДВА ОСНОВНЫХ СПОСОБА ДУМАТЬ О GRAPH DATA

PROPERTY GRAPH

Nodes + typed edges + properties

Практичен для product/operational graph queries. Node/edge can carry arbitrary properties: dates, status, evidence, tenant, confidence.

RDF / TRIPLES

Subject → predicate → object

Полезен при semantic-web/ontology/interoperability requirements. Can support formal vocabularies and reasoning layers.

Для большинства прикладных AI-систем property-graph-like mental model проще. Выбор physical database не должен определять business ontology prematurely.
03. ENTITY CONTRACT

СУЩНОСТЬ ДОЛЖНА ИМЕТЬ STABLE ID, А НЕ ЖИТЬ КАК СТРОКА ИМЕНИ

{
  "entity_ref": "entity://project/01J...",
  "entity_type": "PROJECT",
  "canonical_name": "...",
  "aliases": [
    "...",
    "..."
  ],
  "tenant_id": "tenant_A",
  "status": "ACTIVE",
  "properties": {
    "region": "...",
    "project_type": "..."
  },
  "source_refs": [
    "source://..."
  ],
  "valid_from": "...",
  "valid_to": null,
  "graph_generation": "g12"
}
IDENTITY RULE

Name is not identity

  • same entity can have many names;
  • same name can refer to different entities;
  • names change;
  • legal entity and brand may differ;
  • project phase/name may change.

Stable entity_ref separates identity from labels.

04. RELATION CONTRACT

EDGE — ЭТО ASSERTION, КОТОРОЕ НУЖНО УМЕТЬ ДОКАЗАТЬ

{
  "edge_id": "EDGE-...",
  "subject_ref": "entity://company/A",
  "predicate": "INVESTS_IN",
  "object_ref": "entity://project/B",
  "status": "VERIFIED",
  "confidence": 0.98,
  "evidence": [
    {
      "ref": "block://doc77/v4/page2/b9",
      "source_ref": "source://official/..."
    }
  ],
  "valid_from": "2026-01-01",
  "valid_to": null,
  "extracted_by": {
    "pipeline": "relation-extract-v3"
  },
  "tenant_id": "tenant_A"
}
EDGE IS NOT A GUESS

Source-backed relation

Для material domain facts полезны статусы:

  • CANDIDATE
  • VERIFIED
  • DISPUTED
  • RETRACTED
  • SUPERSEDED

LLM extraction may create CANDIDATE, not automatic truth.

05. ONTOLOGY / SCHEMA

НЕ НАЧИНАТЬ СО СХЕМЫ НА 400 ENTITY TYPES

ENTITY TYPES

Small explicit set

Company, Person, Project, Location, Document, Product, Regulation...

RELATION TYPES

Meaningful verbs

OWNS, FUNDS, LOCATED_IN, PART_OF, WORKS_FOR, DEPENDS_ON.

CONSTRAINTS

Allowed shapes

COMPANY —OWNS→ PROJECT; PROJECT —LOCATED_IN→ LOCATION.

EVOLUTION

Versioned schema

Add/rename/deprecate relation types with migration rules.

Ontology should emerge from retrieval/questions/business use cases. Too-generic RELATED_TO is useless; too-detailed ontology becomes unmaintainable.
06. ENTITY EXTRACTION

ТЕКСТ → CANDIDATE ENTITIES, НО НЕ СРАЗУ KNOWLEDGE

SOURCE BLOCKParsed text/table/metadata.
DETECT MENTIONSRules/NER/LLM extraction.
NORMALIZENames, legal forms, dates, IDs.
ENTITY RESOLVEExisting entity or create candidate?
RELATION EXTRACTCandidate typed edges.
VERIFYSchema + evidence + confidence.
UPSERT GRAPHVersioned source-backed facts.
Extraction pipeline должен сохранять exact evidence span/table cell/source version, чтобы позже можно было проверить edge и переизвлечь graph при улучшении extractor-а.
07. ENTITY RESOLUTION

САМЫЙ ТРУДНЫЙ ВОПРОС: «ЭТО ТОТ ЖЕ ОБЪЕКТ ИЛИ ДРУГОЙ?»

EXACT ID

Strongest signal

Tax ID, registry ID, internal project ID, canonical external identifier.

ALIASES

Name normalization

Legal form, punctuation, transliteration, abbreviations.

CONTEXT

Disambiguation

Region, parent org, date, address, role, neighboring entities.

SEMANTIC MATCH

Candidate generation

Embeddings/LLM can suggest same-entity candidates, but high-risk merges need deterministic evidence/review.

Wrong merge is often worse than duplicate nodes: two different companies/projects become one entity and contaminate every downstream path. Prefer uncertain duplicate over aggressive merge when confidence is low.
08. CANONICAL ENTITY VS SOURCE MENTION

НЕ ТЕРЯТЬ ТО, КАК SOURCE НАЗЫВАЛ ОБЪЕКТ

MENTION

Source-local observation

Text span «Омск-Фёдоровка», page 3, source v4, exact spelling and context.

CANONICAL ENTITY

Resolved identity

Stable project entity with canonical name and aliases, linked to all mentions.

Так можно менять canonicalization/entity resolution later, не перепарсивая исходный документ и не теряя evidence.
09. TEMPORAL GRAPH

RELATIONS МЕНЯЮТСЯ СО ВРЕМЕНЕМ

VALID TIME

When fact is true

CEO role valid 2025–2027; concession status changed in 2026.

OBSERVED TIME

When system learned it

Fetched/extracted at a particular timestamp/source version.

SUPERSESSION

New fact replaces old

Keep history instead of silently overwriting relation/property.

Вопрос «кто владеет сейчас?» и «кто владел в 2024 году?» требуют temporal semantics. Без valid_from/valid_to graph быстро становится смесью фактов разных эпох.
10. SOURCE PROVENANCE ON EVERY EDGE

GRAPH БЕЗ EVIDENCE ПРЕВРАЩАЕТСЯ В БАЗУ СЛУХОВ

EDGE → SOURCE

Exact evidence

Relation references block/table/record that supports it.

SOURCE VERSION

Reproducible

Link points to exact source version/hash used during extraction.

TRANSFORM

How extracted

Extractor/parser/model/config version captured via №61 lineage.

Knowledge graph and provenance graph are separate logical graphs, but every domain fact should have a bridge into provenance/evidence.
11. WHAT GRAPHRAG DOES

QUERY → ENTITY SEED → GRAPH EXPANSION → EVIDENCE SUBGRAPH → ANSWER

QUERYQuestion/task.
ENTITY / INTENTResolve mentioned entities and relation need.
SEEDExact ID, lexical, vector or metadata search.
EXPANDAllowed relation types, 1–N hops.
PRUNEAccess, time, relevance, degree, budget.
MATERIALIZE EVIDENCELoad source-backed facts/docs.
GENERATE + VERIFYAnswer from bounded subgraph.
GraphRAG не означает «загрузить весь граф в prompt». Главная задача — собрать маленький релевантный подграф и material evidence behind it.
12. SEED RETRIEVAL

ГРАФУ НУЖНА ТОЧКА ВХОДА

EXACT ID

Best

Known project/company/person identifier.

LEXICAL

Name / code

Alias index, exact name, rare identifier.

VECTOR

Semantic entity retrieval

№66 can find seed entities/chunks from natural-language description.

STRUCTURED FILTER

Known attributes

Type=PROJECT + region=... + year=...

Vector search and graph search are often complementary: vector finds where to enter; graph follows explicit relationships from there.
13. NEIGHBORHOOD EXPANSION

НЕ ДЕЛАТЬ «ВСЕ СОСЕДИ ДО 5 HOPS»

RELATION ALLOWLIST

Task-specific

Ownership question follows OWNS/PART_OF, not every available relation.

HOP LIMIT

Bounded depth

Usually 1–3 hops, deeper only with explicit need/evals.

DEGREE CAP

Control supernodes

Limit neighbors from high-degree entities such as country/topic.

BUDGET

Node/edge ceiling

Max expanded nodes, paths and materialized evidence items.

Graph traversal without pruning explodes combinatorially and returns generic hubs instead of useful evidence.
14. PATH QUERIES

СИЛЬНАЯ СТОРОНА GRAPH — EXPLICIT CONNECTION CHAINS

OWNERSHIP PATH

A → owns → B → owns → C

Useful for beneficial ownership / organizational hierarchy.

DEPENDENCY PATH

System → depends_on → service → provider

Useful for impact analysis and architecture queries.

PROJECT PATH

Company → invests_in → project → located_in → region

Useful for cross-document structured research.

Path existence is not automatically causal proof. Relation semantics must justify interpretation of the path.
15. MULTI-HOP GRAPH RETRIEVAL

GRAPH HOP И RESEARCH HOP — НЕ ОДНО И ТО ЖЕ

GRAPH HOP

Traversal over known edge

PROJECT —LOCATED_IN→ REGION. The relation already exists in graph.

№26 RESEARCH HOP

New evidence-gathering step

First source reveals operator name; next search queries external registry for operator ownership.

GraphRAG accelerates multi-hop when relations are already structured. If graph lacks the needed fact, research engine must retrieve new evidence rather than hallucinate an edge.
16. LOCAL VS GLOBAL GRAPHRAG

ДВА ПОЛЕЗНЫХ RETRIEVAL MODES

LOCAL / ENTITY-CENTRIC

Question about specific entities

Resolve one company/project/person, expand immediate relations, collect source evidence, answer bounded question.

GLOBAL / THEMATIC

Question about corpus-wide structure

Use communities/clusters/aggregate summaries to answer «какие основные группы/темы/связи?» without traversing every raw edge at runtime.

Global summaries are derived artifacts, not ground truth. They require provenance to underlying nodes/edges and regeneration when graph changes.
17. COMMUNITY SUMMARIES

СЖАТЬ БОЛЬШОЙ GRAPH ДО HIERARCHICAL MAP — ОПЦИОНАЛЬНЫЙ ADVANCED PATTERN

GRAPHMany entities/edges.
COMMUNITY DETECTCluster structurally related nodes.
SUMMARIZECreate source-backed community artifact.
INDEX SUMMARYLexical/vector lookup.
GLOBAL QUERYRetrieve relevant communities first.
Не делать community pipeline в MVP, если обычные entity/path queries already solve real tasks. Это advanced acceleration/aggregation layer.
18. VECTOR + GRAPH HYBRID

ЧАСТО ЛУЧШИЙ GRAPH RAG НАЧИНАЕТСЯ С VECTOR/LEXICAL, А НЕ С GRAPH QUERY PARSER

SEMANTIC / LEXICAL SEED

Find likely entities/documents from natural-language query.

GRAPH EXPANSION

Follow explicit typed relations and filters from seeds.

RERANK / EVIDENCE

Rank graph facts + source chunks and build answer context.

Это снимает проблему «как превратить любой natural-language query в идеальный graph query» и использует strengths обоих retrieval modes.
19. GRAPH QUERY CONTRACT

MODEL НЕ ДОЛЖЕН ПОЛУЧАТЬ БЕЗГРАНИЧНЫЙ RAW GRAPH QUERY ACCESS

{
  "seed_entities": [
    "entity://project/B"
  ],
  "allowed_relations": [
    "INVESTS_IN",
    "OWNS",
    "LOCATED_IN"
  ],
  "direction": "BOTH",
  "max_hops": 2,
  "max_nodes": 100,
  "max_edges": 200,
  "time": {
    "as_of": "2026-08-31"
  },
  "filters": {
    "tenant_id": "tenant_A"
  },
  "include_evidence_refs": true
}
SAFE QUERY LAYER

Prefer bounded templates

Вместо unrestricted query language model получает:

  • approved query templates;
  • relation allowlists;
  • hop/node/edge limits;
  • tenant/time filters;
  • schema validation;
  • result size limits.

Advanced analysts/tools may use direct graph query language under separate permissions.

20. GRAPH MATERIALIZATION

В PROMPT НУЖНЫ НЕ ID РЁБЕР, А ЧИТАЕМОЕ EVIDENCE

FACT TABLE

Compact triples

Company A —INVESTS_IN→ Project B [source: ...].

SOURCE PASSAGES

Evidence text

Load the exact source blocks behind material edges.

PATH SUMMARY

Bounded explanation

For long path, show sequence + relation semantics + citations, not raw graph dump.

Graph facts speed retrieval; source material is still needed for evidence-first answer where claims are externally verifiable.
21. RELATION EXTRACTION WITH LLM

LLM — EXTRACTOR, НЕ ORACLE

SCHEMA-CONSTRAINED

Allowed predicates

Model chooses only from explicit entity/relation types.

EVIDENCE SPAN

Must point back

Every extracted edge includes exact supporting text/table source.

CONFIDENCE

Candidate status

Uncertain relation remains candidate and may require verification.

NO IMPLIED EDGE

Don't infer beyond source silently

«Works with» must not become OWNS unless evidence explicitly supports ownership.

Relation extraction eval should emphasize precision. Hallucinated edges contaminate many future graph queries and are expensive to unwind.
22. FACT VS INFERENCE

ЯВНО РАЗДЕЛЯТЬ SOURCE FACT И DERIVED INFERENCE

Graph itemStatusExample
DIRECT FACTSource explicitly states relation.«Company A owns 60% of B» → A OWNS B.
NORMALIZED FACTDeterministic normalization.60 percent → ownership_share=0.6.
DERIVED INFERENCEComputed from several facts.A controls C through B.
HYPOTHESISPossible relation needing confirmation.Likely same project entity from ambiguous alias.
Derived relations can be useful, but must carry derivation path and should not masquerade as directly sourced facts.
23. CONFLICTS

ДВА SOURCE МОГУТ ДАТЬ РАЗНЫЕ FACTS

DON'T OVERWRITE

Keep competing assertions

Store separate edge/fact records with source/version/time rather than silently choosing latest.

RESOLUTION POLICY

Authority/time/context

Official source, newer valid time, trusted internal registry or human review may determine active fact.

DISPUTED

Expose uncertainty

Graph retrieval can return conflict metadata so answer does not present contested relation as certain.

Graph consistency does not mean forcing reality into one value when sources genuinely disagree.
24. SUPER-NODES

ПОПУЛЯРНЫЕ ENTITIES МОГУТ ВЗОРВАТЬ RETRIEVAL

COUNTRY

Huge degree

Thousands of projects/companies linked to one country.

TOPIC

Generic hubs

«Infrastructure» or «AI» nodes create noisy neighborhoods.

DEGREE CAP

Bound expansion

Sample/filter/rank neighbors before following them.

RELATION PRIORITY

Task fit

For ownership question, ignore broad TOPIC edges entirely.

High degree is not relevance. Traversal policy must control hubs explicitly.
25. GRAPH CYCLES

ЦИКЛЫ НОРМАЛЬНЫ ДЛЯ DOMAIN GRAPH, НО RETRIEVAL НЕ ДОЛЖЕН ХОДИТЬ ПО НИМ БЕСКОНЕЧНО

VISITED SET

No repeated node expansion

Track node/path states during bounded traversal.

MAX HOPS

Hard stop

Traversal depth has explicit ceiling.

PATH DEDUPE

Equivalent paths

Deduplicate repeated fact chains before materialization.

Это graph traversal engineering, не №17 Reasoning Graph Search: здесь nodes are domain entities, not reasoning states.
26. SECURITY & ACCESS PROPAGATION

GRAPH МОЖЕТ УТЕЧЬ ЧЕРЕЗ САМ ФАКТ СВЯЗИ

NODE EXISTENCE

Metadata leak

Hidden project/customer name can leak even without source text.

EDGE LEAK

Relationship sensitive

«Company A works with confidential Client B» may itself be protected.

FILTER BEFORE TRAVERSAL

Eligible graph only

Traversal engine must apply tenant/ACL constraints at every expansion.

MATERIALIZE RECHECK

Defense in depth

Source/evidence refs re-authorized before loading into context.

Нельзя search global graph → find private intermediate node → hide its name but use it to infer public answer, если policy запрещает knowledge leakage through existence/relationships.
27. DELETE / RETRACT / UPDATE

GRAPH ДОЛЖЕН СИНХРОНИЗИРОВАТЬСЯ С SOURCE LIFECYCLE

SOURCE CHANGENew version / delete / revoke.
LINEAGE LOOKUPFind mentions/entities/edges derived from source.
RETRACT FACTSDisable source-dependent assertions.
RE-EXTRACTBuild candidates from new version.
RE-RESOLVEEntity/edge consistency.
PROMOTENew active graph generation/facts.
Если edge supported by 3 sources and one source deleted, edge may remain valid through remaining evidence. Поэтому delete semantics should operate on assertions/evidence links, not blindly delete canonical relation.
28. GRAPH GENERATIONS

МАССОВЫЙ RE-EXTRACTION ЛУЧШЕ ДЕЛАТЬ BLUE/GREEN

graph g11  ← ACTIVE
graph g12  ← BUILDING

g12 changes:
  ontology v4
  entity resolver v7
  relation extractor v5
  new source snapshot
  dedupe rules v3

BUILD
  ↓
consistency checks
  ↓
entity/edge counts
  ↓
precision/recall evals
  ↓
ACL tests
  ↓
sample path verification
  ↓
PROMOTE g12

ROLLBACK:
  active_generation = g11
Для small graph per-fact versioning достаточно. Generations особенно полезны при массовой смене ontology/entity-resolution/extractor logic.
29. STORAGE: GRAPH DB OR POSTGRES?

GRAPH DATABASE — НЕ ОБЯЗАТЕЛЬНО ПЕРВЫЙ ШАГ

POSTGRES TABLES

Excellent MVP

entities, edges, alias tables, recursive CTEs. Good for small/medium graphs, strong transactional integration and familiar operations.

DEDICATED GRAPH DB

Upgrade when traversal dominates

Useful for very large/deep interactive traversals, graph-native analytics, path-heavy workloads or specialized graph algorithms.

Выбор store should follow query workload. «Knowledge Graph» — data model and architecture, not a requirement to run a graph database.
30. MVP STORAGE MODEL

ДВЕ ОСНОВНЫЕ TABLES + EVIDENCE LINKS УЖЕ ДОСТАТОЧНЫ

kg_entities(
  entity_ref        text primary key,
  entity_type       text,
  canonical_name    text,
  tenant_id         text,
  status            text,
  valid_from        timestamptz,
  valid_to          timestamptz,
  generation        text,
  properties_json   jsonb
)

kg_aliases(
  alias             text,
  entity_ref        text,
  alias_type        text,
  source_ref        text
)

kg_edges(
  edge_id           uuid primary key,
  subject_ref       text,
  predicate         text,
  object_ref        text,
  tenant_id         text,
  status            text,
  confidence        numeric,
  valid_from        timestamptz,
  valid_to          timestamptz,
  generation        text,
  metadata_json     jsonb
)

kg_edge_evidence(
  edge_id           uuid,
  evidence_ref      text,
  source_ref        text,
  source_version    text
)
KEY INDEXES

Support real queries

  • entity_type + canonical_name;
  • alias normalized text;
  • subject_ref + predicate;
  • object_ref + predicate;
  • tenant_id;
  • status + valid time;
  • generation;
  • source/evidence refs.

Recursive CTEs cover bounded 1–3 hop MVP traversal surprisingly well.

31. GRAPH QUERY EXAMPLES

СНАЧАЛА ПОНЯТНЫЕ PRODUCT QUERIES

Q1:
"Какие проекты связаны с Company A?"
  seed Company A
  follow INVESTS_IN / OWNS
  filter status=ACTIVE
  return projects + evidence

Q2:
"В каких регионах находятся проекты,
в которые инвестирует Company A?"
  Company A
    --INVESTS_IN→ Project
    --LOCATED_IN→ Region

Q3:
"Какие опубликованные отчёты зависят
от источника, который был отозван?"
  NOTE:
  this is primarily №61 provenance/lineage,
  NOT domain Knowledge Graph.

Q4:
"Найди цепочку владения A → C"
  A --OWNS/PART_OF→ ... --OWNS→ C
  max_hops=4
  verify every edge evidence
Очень важно отличать domain graph query от provenance/workflow/dependency graph queries. Не складывать все типы графов в одну giant universal graph без причины.
32. GRAPH RETRIEVAL EVALS

GRAPHRAG НУЖНО ИЗМЕРЯТЬ ОТДЕЛЬНО ОТ VECTOR RAG

ENTITY RESOLUTION

Accuracy

Correct canonical entity selected from mention/query.

EDGE PRECISION

Truthfulness

Extracted relation is actually supported by evidence.

EDGE RECALL

Coverage

Important supported relations are present in graph.

PATH RECALL

Answerability

Graph contains a valid relation path needed for target questions.

GRAPH P@K

Retrieval relevance

Returned nodes/edges are relevant to query intent.

ACL

Security

Unauthorized node/edge exposure rate. Target 0.

ANSWER UPLIFT

Graph value

Quality gain vs vector/lexical RAG baseline on relation-heavy tasks.

COST / LAT

Operational

Traversal + materialization + generation overhead.

Для graph extraction precision часто важнее максимального recall: один ложный edge может contaminate hundreds of downstream path answers.
33. GRAPH QUALITY CHECKS

OFFLINE CONSISTENCY TESTS ЛОВЯТ МНОГО ОШИБОК БЕЗ LLM

TYPE

Schema constraints

PERSON cannot LOCATED_IN a document if ontology forbids that relation shape.

DANGLING

Missing endpoints

Every active edge resolves to existing active entities.

EVIDENCE

Resolvable support

Every VERIFIED edge has at least one accessible evidence ref.

TEMPORAL

Date consistency

valid_from ≤ valid_to; impossible overlapping states flagged.

DUPLICATE

Entity merge candidates

High-similarity aliases/identifiers flagged for review.

SUPER-NODE

Degree anomaly

Sudden degree explosion may indicate bad extraction/schema mapping.

SOURCE

Stale/retracted

Facts from superseded source versions handled correctly.

ACL

Propagation

Edge/node access is not weaker than protected source evidence by accident.

34. FAILURE MODES

КАК KNOWLEDGE GRAPH СТАНОВИТСЯ ДОРОГОЙ ГАЛЛЮЦИНАЦИЕЙ

GRAPH FOR EVERYTHING
Simple SQL/vector retrieval use cases gain no value but incur ontology/entity-resolution cost.
GRAPH ONLY WHERE RELATIONS MATTER
LLM EDGE = TRUTH
Hallucinated relation contaminates all future paths.
CANDIDATE + EVIDENCE + VERIFY
NAME = ENTITY ID
Aliases split same entity; collisions merge different ones.
STABLE ENTITY REF
RELATED_TO
Graph stores vague connections with no usable semantics.
TYPED RELATIONS
NO SOURCE ON EDGE
Cannot verify/correct/retract graph fact.
EVIDENCE-BACKED ASSERTIONS
UNBOUNDED TRAVERSAL
Supernodes/cycles explode nodes, latency and context.
HOPS + RELATION + DEGREE BUDGET
POST-FILTER ACL
Private nodes participate in paths and leak relationships.
ACCESS DURING EXPANSION
GRAPH = PROVENANCE
Domain relations and data-derivation relationships get conflated.
SEPARATE GRAPH SEMANTICS
GRAPH DB TOO EARLY
Operational complexity before query needs justify it.
POSTGRES FIRST
35. OBSERVABILITY

СМОТРЕТЬ НА GRAPH КАК НА ЖИВУЮ KNOWLEDGE PIPELINE

ENT

Entity Count

Active entities by type/tenant/generation.

EDG

Edge Count

Verified/candidate/disputed edges by relation type.

PREC

Edge Precision

Verified extraction precision on labeled samples.

ER

Entity Resolution Accuracy

Correct merge/link rate and false-merge rate.

HOPS

Traversal Depth

Actual hops/nodes/edges expanded per query.

P95

Graph Retrieval Latency

Entity resolve + traversal + materialization.

ACL

Access Violations

Unauthorized node/edge/path exposure. Target 0.

UP

GraphRAG Uplift

Quality gain vs simpler retrieval baseline on graph-suitable tasks.

36. MVP IMPLEMENTATION

ОДИН DOMAIN GRAPH, 5–15 RELATIONS, POSTGRES И ЯВНЫЕ QUERY TEMPLATES

knowledge_graph/
├── schema.py
├── entities.py
├── aliases.py
├── resolver.py
├── relations.py
├── extraction.py
├── verification.py
├── traversal.py
├── materialize.py
├── reconcile.py
└── tests/

MVP PIPELINE:

source blocks
  ↓
mention extraction
  ↓
entity resolution
  ↓
relation candidates
  ↓
schema validation
  ↓
evidence check
  ↓
verified graph facts

MVP RETRIEVAL:

query
  ↓
resolve seed entity
  ↓
choose approved relation template
  ↓
max_hops <= 2
  ↓
max_nodes <= 50
  ↓
tenant/ACL/time filter
  ↓
load evidence
  ↓
answer + verify
80% VALUE MVP

Small graph, strong evidence

  • One narrow domain/use case.
  • 5–15 entity/relation types.
  • Stable entity IDs + alias table.
  • Source-backed verified edges.
  • LLM extraction only into CANDIDATE status.
  • Deterministic schema checks.
  • PostgreSQL entities/edges/evidence tables.
  • 1–2 hop bounded traversal.
  • Vector/lexical seed lookup.
  • Tenant/ACL filters during traversal.
  • GraphRAG eval set vs vector-only baseline.

No enterprise ontology, no graph DB cluster, no autonomous graph-building agent required.

37. WHEN TO UPGRADE

GRAPH СТАНОВИТСЯ СЛОЖНЕЕ ТОЛЬКО ПОСЛЕ ДОКАЗАННОГО GRAPH WORKLOAD

SignalPotential upgrade
Large/deep path-heavy interactive queriesDedicated graph database / graph-native query engine.
Huge corpus-wide structural questionsCommunity detection + hierarchical graph summaries.
Many ambiguous entitiesStronger entity-resolution pipeline, review queue, registry integration.
Ontology grows across domainsSchema registry, compatibility/versioning, domain ownership.
High extraction volumeBatch workers, confidence calibration, active-learning/eval pipelines.
Graph + vector both criticalUnified hybrid retrieval orchestration, not necessarily a single physical database.
38. PRACTICAL DECISION

СТОИТ ЛИ ДЕЛАТЬ ОТДЕЛЬНЫЙ КОМПОНЕНТ?

ВопросОтвет
Стоит ли реализовывать?Только если relation-aware use cases действительно важны. Для обычного document QA сначала RAG + vector/lexical retrieval.
Separate Component?YES логически. Физически MVP может быть PostgreSQL tables + retrieval library.
Минимум 80% ценности?Stable entities, typed relations, evidence-backed edges, entity resolution, temporal/access metadata, bounded traversal, graph retrieval evals.
Когда overkill?Enterprise ontology, graph DB cluster, community hierarchy и autonomous extraction для маленького корпуса без graph-specific questions.
Trigger?Questions repeatedly require ownership/dependencies/paths/entity aggregation or vector RAG misses relation structure.
Как измерить uplift?GraphRAG answer quality vs vector-only baseline, entity resolution accuracy, edge precision/recall, path recall, retrieval latency, ACL violations.
Можно ли rule/tool/code вместо LLM-agent?Да для storage/query/schema. LLM useful for extraction/entity linking/query interpretation, but verified graph truth must remain source-backed and constrained.
39. DESIGN RULES

ПРАВИЛА ДЛЯ РЕАЛЬНОЙ СИСТЕМЫ

RULE 01

Graph only for explicit relations

Use vectors for similarity; graph for typed domain connections.

RULE 02

Stable entity identity

Names are aliases, not primary keys.

RULE 03

Every important edge has evidence

Source/version/provenance are part of graph fact contract.

RULE 04

LLM extraction creates candidates

Schema/evidence/verification decide what becomes trusted graph knowledge.

RULE 05

Bound traversal

Relation allowlist, hop limit, degree cap and graph budget are mandatory.

RULE 06

Vector + graph can cooperate

Semantic seed → graph expansion → evidence materialization is a strong pattern.

RULE 07

Temporal facts stay temporal

Don't overwrite history when ownership/status changes.

RULE 08

Access applies during traversal

Hidden nodes/edges cannot participate in unauthorized paths.

RULE 09

Postgres before graph cluster

Upgrade storage only after path/query workload proves it necessary.

40. FINAL MAP

GRAPH TURNS KNOWLEDGE FROM «SIMILAR TEXT» INTO EXPLICIT RELATIONSHIPS

SOURCES
  documents
  tables
  APIs
  registries
        ↓
INGEST / PARSE
        ↓
MENTIONS
        ↓
ENTITY RESOLUTION
  stable entity_ref
  aliases
  identifiers
  context
        ↓
RELATION EXTRACTION
  schema-constrained
  evidence span required
        ↓
CANDIDATE FACTS
        ↓
VERIFY
  type constraints
  evidence support
  temporal consistency
  access scope
        ↓
KNOWLEDGE GRAPH
  entities
  typed relations
  properties
  valid time
  status
  evidence refs
        ↓

GRAPHRAG QUERY:

USER QUESTION
        ↓
RESOLVE INTENT / ENTITIES
        ↓
SEED RETRIEVAL
  exact ID
  lexical alias
  vector search
  metadata
        ↓
BOUNDED GRAPH EXPANSION
  allowed relations
  max hops
  max nodes
  degree cap
  time filter
  tenant / ACL
        ↓
PRUNE / RANK
        ↓
MATERIALIZE SOURCE EVIDENCE
        ↓
RAG CONTEXT
        ↓
GENERATE
        ↓
VERIFY CLAIMS

HYBRID:

VECTOR
  finds semantically plausible entry points

GRAPH
  follows explicit domain relations

PROVENANCE
  explains where graph facts came from

VERIFICATION
  checks whether evidence supports answer

BOUNDARIES:

№66 VECTOR SEARCH
  "WHAT IS SEMANTICALLY SIMILAR?"

№67 KNOWLEDGE GRAPH
  "WHAT IS EXPLICITLY RELATED, AND HOW?"

№17 REASONING SEARCH
  "WHICH REASONING STATE SHOULD WE EXPLORE?"

№61 PROVENANCE
  "WHERE DID THIS SYSTEM OBJECT / FACT COME FROM?"

№26 MULTI-HOP RESEARCH
  "WHAT NEW EVIDENCE SHOULD WE FIND NEXT?"

CORE PRINCIPLE:

A KNOWLEDGE GRAPH
IS NOT A COLLECTION
OF LLM-GENERATED CONNECTIONS.

IT IS A VERSIONED,
SOURCE-BACKED MODEL
OF DOMAIN ENTITIES
AND TYPED RELATIONS.

GRAPHRAG IS USEFUL
WHEN THE QUESTION DEPENDS
ON THOSE RELATIONS.

IF THE QUESTION ONLY NEEDS
RELEVANT TEXT—

NORMAL RAG MAY BE
SIMPLER, CHEAPER
AND BETTER.

ECC RETROFIT / PRACTICAL HARNESS INTEGRATION

A. Related ECC ideas. Context-as-cache, scoped memory, lifecycle hooks, selective capabilities, feature flags, deterministic enforcement, provider-neutral adapters and eval-gated learning are applied only where relevant to №67 Knowledge Graph & GraphRAG.

B–E. Existing boundary and placement. The existing conceptual boundary, class ADVANCED, default OFF and owner Knowledge / Research Engine remain authoritative. Runtime/control/data/offline placement is unchanged; durable state stays outside model context.

F–H. Hooks and contracts. Use bounded PRE_MODEL/POST_MODEL, PRE_TOOL/POST_TOOL, CHECKPOINT and TASK_COMPLETED events as applicable. Illustrative fields and canonical contracts are defined in NEW_CONTRACTS_SPEC.md; no universal schema is implied.

I–J. Security and evaluation. Host-side schema, permission, secret, budget, idempotency and audit checks take precedence over LLM output. Optional mechanisms require a feature flag and WITH/WITHOUT ablation; measure quality, acceptance, correction, latency, cost, escalations and severe errors.

K–L. Task profiles and cross-references. A TaskProfile selects the relevant skill, tool/context slice, memory scope and enforcement profile independently from FAST/STANDARD/DEEP. See cross-reference map, hook spec and ablation plan. Provider adapters remain outside the core.