66 / VECTOR DB · EMBEDDINGS / KNOWLEDGE-RESEARCH ENGINE
66 / PRODUCTION / SEMANTIC INDEX · DENSE RETRIEVAL · FILTERS · VERSIONING

VECTOR DB
& EMBEDDINGS.

Embedding — числовое представление объекта в векторном пространстве, где геометрическая близость приблизительно отражает семантическую похожесть. Vector DB / Vector Index — инфраструктура, которая хранит эти векторы и быстро ищет ближайшие объекты по similarity, обычно вместе с metadata filters.

Главный принцип: Vector DB — не «память ИИ» и не весь RAG. Это retrieval index. Он помогает найти кандидатов, но не гарантирует, что найденный chunk релевантен, свеж, разрешён пользователю, действительно поддерживает claim или вообще является лучшим источником.
00. ARCHITECTURAL STATUS

НУЖЕН, КОГДА SEMANTIC RETRIEVAL ДАЁТ ЦЕННОСТЬ, А НЕ ПОТОМУ ЧТО «У AI ДОЛЖНА БЫТЬ VECTOR DB»

Для небольшого корпуса PostgreSQL + pgvector-подобный extension или даже exact brute-force search может быть достаточно. Отдельная specialized vector database оправдана масштабом, latency, filtering, multi-tenancy, replication или operational requirements.
TYPEPRODUCTIONRetrieval infrastructure.
DEFAULTCONDITIONALТолько если semantic similarity реально нужна.
ENABLE WHENDENSE RETRIEVAL HELPSMeaning > exact keyword match.
SEPARATE COMPONENTYESLogical index capability.
LIVES INKNOWLEDGE / RESEARCH ENGINER06 retrieval infrastructure.
COMPLEXITYLOW → HIGHExact/Postgres first; ANN at scale.
IMPLEMENT: WHEN RETRIEVAL NEEDS IT
Минимум 80% ценности: versioned embedding pipeline, canonical chunk IDs, content hashes, metadata/ACL filters, model/dimension version, index namespace, exact deletion/update semantics, top-k retrieval with scores, hybrid lexical+dense option, reranking boundary, provenance to source chunks and offline retrieval evals. Не делать Vector DB source of truth.
01A. ARCHITECTURE BOUNDARIES & OPERATIONS

EXPLICIT SYSTEM CONTRACT

A. BOUNDARY WITH NEIGHBORS

№08 RAG владеет всей retrieval-augmented generation architecture; №66 — только dense embeddings/index/search mechanics. №27 Agentic RAG решает, когда/как adaptive retrieval повторять, переписывать запрос и reroute; №66 выполняет конкретный dense/hybrid search. №55 Ingestion доставляет source versions; №56 Parsing создаёт structured blocks/chunks inputs; №66 индексирует уже подготовленные units. №61 Provenance владеет source/derivation graph; vector index хранит refs/hash/version, но не становится lineage system. №67 Knowledge Graph & GraphRAG владеет explicit entities/relations/graph traversal; vector similarity ≠ graph relation.

B. PREREQUISITES / CROSS-REFERENCES

Prerequisites: №08 RAG, №25 Evidence-First, №27 Agentic RAG, №46 Observability, №50 Contracts, №55 Ingestion, №56 Parsing, №61 Provenance, №62 Caching. Forward references: №67 Knowledge Graph & GraphRAG, №76 Data Governance & Privacy.

C. PLANE PLACEMENT

REQUEST-TIME: query embedding + search + filter/rerank. CONTROL PLANE: embedding model/version, metric, index type, namespaces, filter schema, recall/latency targets. DATA PLANE: vectors, chunk refs, metadata, index structures. OFFLINE: embedding generation, index build/rebuild, migration, retrieval evals, compaction and deletion reconciliation.

D. FAILURE & OPERATIONS CONTRACT

Success: search returns authorized, version-compatible candidate refs from intended corpus/index. Retryable: transient index/network failure. Permanent: dimension mismatch, unsupported namespace, invalid filters, missing index generation. Idempotency: upsert by stable chunk/vector identity + embedding version. Persist: chunk_ref, source/version/hash, embedding model/version/dimensions, vector, metadata, tenant/access scope, index generation. Trace: query→embedding→filter→search→rank→rerank. Security: ACL/tenant filter enforced at retrieval boundary, not after generation.

E. WHAT THIS TOPIC DOES NOT OWN

№66 не владеет document parsing, chunking semantics as a whole, RAG orchestration, answer generation, evidence verification, memory, graph traversal or source of truth. Она владеет EMBEDDING REPRESENTATION, VECTOR INDEXING AND SIMILARITY-BASED CANDIDATE RETRIEVAL.

01. WHAT AN EMBEDDING IS

SEMANTIC COORDINATES, НЕ «СЖАТЫЙ ТЕКСТ»

INPUT

Object representation

Text chunk, title, query, image, audio or multimodal object depending on embedding model.

OUTPUT

Dense numeric vector

Например, hundreds/thousands of floating-point dimensions. Coordinates individually usually have no human-readable meaning.

Embedding is useful because similar objects tend to occupy nearby regions. But similarity is learned approximation: close ≠ true, relevant, authoritative or safe.
02. DOCUMENT AND QUERY EMBEDDINGS

QUERY И CORPUS ДОЛЖНЫ БЫТЬ В СОВМЕСТИМОМ VECTOR SPACE

DOCUMENT CHUNK

«Условия концессии...»

embedding_model=v3 → vector D

SAME EMBEDDING SPACE

Vectors are comparable under the model's intended similarity metric.

QUERY

«Какие обязательства у концессионера?»

embedding_model=v3 → vector Q

Нельзя индексировать documents model A, а query model B и ожидать meaningful distance, если модели специально не совместимы.
03. EMBEDDING CONTRACT

VECTOR БЕЗ VERSION И SOURCE REF БЫСТРО СТАНОВИТСЯ НЕУПРАВЛЯЕМЫМ

{
  "vector_id": "VEC-...",
  "object_ref": "chunk://doc123/v7/ch42",
  "tenant_id": "tenant_A",
  "content_hash": "sha256:...",
  "embedding": {
    "model": "embed-v3",
    "dimensions": 1536,
    "normalization": "L2",
    "version": "2026-08"
  },
  "index": {
    "namespace": "knowledge-prod",
    "generation": "g17",
    "metric": "COSINE"
  },
  "metadata": {
    "document_id": "doc123",
    "source_version": "v7",
    "language": "ru",
    "acl_group": "project-X"
  }
}
MINIMUM

Always know what was embedded

  • stable object/chunk ref;
  • content hash;
  • embedding model/version;
  • dimension count;
  • metric/normalization assumptions;
  • tenant/access scope;
  • source version;
  • index namespace/generation.
04. SIMILARITY METRICS

«БЛИЖАЙШИЙ» ЗАВИСИТ ОТ ТОГО, КАК МЫ ИЗМЕРЯЕМ РАССТОЯНИЕ

MetricMeaningNotes
COSINE SIMILARITYAngle/direction similarity.Very common for normalized text embeddings.
DOT PRODUCTVector alignment weighted by magnitude.Often used when model is trained for it; normalization matters.
EUCLIDEAN / L2Geometric distance.Useful depending on model/index assumptions.
Metric должен соответствовать embedding model guidance/training. Не менять cosine на L2 просто потому, что база это поддерживает.
05. EXACT VS ANN SEARCH

НЕ ВСЕГДА НУЖЕН APPROXIMATE NEAREST NEIGHBOR

MODE
RECALL
LATENCY
SCALE
COMPLEXITY
USE
EXACT
maximal
grows with N
small/medium
LOW
MVP / eval oracle
ANN
approximate
fast
large
MED-HIGH
production scale
Exact search полезен не только для маленькой базы, но и как offline oracle для измерения recall ANN index.
06. ANN INDEX

INDEX УСКОРЯЕТ ПОИСК ЦЕНОЙ ПРИБЛИЖЕНИЯ И НАСТРОЕК

GRAPH-BASED ANN

HNSW-like

High recall/low latency, memory-heavy, popular general-purpose option.

IVF-LIKE

Cluster / partition search

Search subset of vector space; tunable probes vs recall.

QUANTIZED INDEX

Compression

Lower memory/storage, possible recall loss; useful at very large scale.

Index algorithm is implementation detail behind retrieval contract. Нельзя описывать RAG архитектуру словом «HNSW» — это только index-level choice.
07. RECALL VS LATENCY

ЧЕМ БОЛЬШЕ SEARCH EFFORT, ТЕМ ВЫШЕ ШАНС НАЙТИ НАСТОЯЩИХ СОСЕДЕЙ

LOW SEARCH EFFORT

Fast

Lower CPU/latency, potentially misses relevant vectors.

HIGH SEARCH EFFORT

Better recall

More graph exploration/probes, higher latency.

TOP-K

Candidate width

Larger K improves coverage but adds reranking/context cost.

RERANK

Recover precision

Retrieve broader candidate set, rerank with stronger lexical/cross-encoder/LLM judge.

Tune ANN and K using end-to-end retrieval metrics, not arbitrary defaults copied from examples.
08. CHUNKING IMPACT

VECTOR DB НЕ МОЖЕТ ИСПРАВИТЬ ПЛОХОЙ UNIT OF RETRIEVAL

TOO SMALL

Context lost

Chunk matches keyword/phrase but lacks enough surrounding meaning.

TOO LARGE

Semantic blur

One vector represents many unrelated concepts; retrieval becomes vague.

STRUCTURAL

Prefer document units

Headings/paragraphs/tables/sections often beat blind fixed-token slicing.

PARENT CONTEXT

Small search, larger read

Retrieve child chunk but expand to parent section/page for answer context.

Chunking belongs mainly to №56 Parsing / RAG pipeline, but its quality directly bounds vector retrieval quality.
09. EMBEDDING TITLE + BODY

REPRESENTATION МОЖЕТ ВКЛЮЧАТЬ STRUCTURAL CONTEXT, КОТОРОГО НЕТ В ЛОКАЛЬНОМ PARAGRAPH

BODY ONLY

Simple

Good when chunk is self-contained.

TITLE + BODY

Common improvement

Heading/document title can disambiguate short local passages.

SYNTHETIC CONTEXT

Advanced

Add bounded generated/structured context only if evals show uplift; retain source provenance.

Whatever text is embedded must be versioned/hashable. Otherwise index cannot be reproduced when embedding representation changes.
10. DENSE VS LEXICAL

SEMANTIC SEARCH И KEYWORD SEARCH ДОПОЛНЯЮТ ДРУГ ДРУГА

DENSE

Meaning similarity

Good for paraphrases, conceptual similarity and natural-language queries.

LEXICAL / BM25-LIKE

Exact term strength

Good for names, codes, numbers, rare terms, exact legal/technical phrases.

Hybrid retrieval is often stronger than «vector only», especially in enterprise/document corpora full of identifiers, acronyms, article numbers and exact names.
11. HYBRID SEARCH

FUSE DENSE + LEXICAL CANDIDATES, THEN RERANK

QUERYNatural language + filters.
DENSE SEARCHSemantic candidates.
+
LEXICAL SEARCHExact-term candidates.
FUSIONRRF/weighted/union.
RERANKBetter relevance model/rules.
TOP EVIDENCEAuthorized candidate refs.
Hybrid search не обязательно должен жить в одной database. Архитектурно важен общий candidate contract и deterministic fusion/rerank stage.
12. FILTERING BEFORE / DURING SEARCH

ACL И TENANT FILTER НЕ ДОЛЖНЫ БЫТЬ POST-FILTER ПОСЛЕ TOP-5

BAD

Search everything, then remove forbidden

Can leak through scores/logs and destroys recall if most top hits are inaccessible.

GOOD

Filter candidate domain

Tenant/source/access/language/date filters participate in retrieval execution.

DEFENSE IN DEPTH

Verify again on materialization

Retrieved ref is re-authorized before content is loaded into model context.

Pre-filter vs in-index filter implementation varies, but security invariant is simple: unauthorized objects are not eligible retrieval candidates.
13. METADATA SCHEMA

VECTOR БЕЗ FILTERABLE METADATA СЛИШКОМ СЛАБ ДЛЯ PRODUCTION

IDENTITY

Refs

chunk_id, document_id, source_ref, tenant_id.

VERSION

Freshness

source_version, content_hash, index_generation.

ACCESS

Security

ACL groups, classification, project/team scope.

STRUCTURE

Document location

page, section, heading path, block type.

TIME

Temporal filters

created_at, valid_from/to, published_at where meaningful.

LANGUAGE

Routing

Language/locale can improve model/query routing.

SOURCE TYPE

Authority routing

internal, official, user-uploaded, web, generated.

DELETE STATE

No zombies

Deleted/retracted versions cannot remain retrievable.

14. RERANKING

VECTOR SCORE — ЭТО CANDIDATE SCORE, НЕ FINAL EVIDENCE QUALITY

StagePurpose
ANN / DENSE SEARCHCheaply retrieve broad semantically plausible candidates.
LEXICAL / FILTER FUSIONRecover exact matches and business constraints.
RERANKEREvaluate query-document relevance more precisely over 20–100 candidates.
EVIDENCE CHECKDetermine whether top material actually supports requested fact/claim.
Reranker may be cross-encoder, specialized model, rules, LLM or combination. The vector DB itself should not be asked to solve claim verification.
15. QUERY TRANSFORMATION

QUERY EMBEDDING КАЧЕСТВЕНЕН ТОЛЬКО НАСКОЛЬКО КАЧЕСТВЕННО СФОРМУЛИРОВАН ПОИСКОВЫЙ INTENT

DIRECT QUERY

Default

Embed user/task query as-is after light normalization.

REWRITE

Conditional

Resolve references, remove conversational noise, add domain terms when needed.

MULTI-QUERY

Hard recall cases

Generate several distinct retrieval queries, union candidates, dedupe, rerank.

№27 Agentic RAG owns adaptive rewrite/retry logic. №66 just consumes one or more normalized search requests.
16. UPDATE / UPSERT

DOCUMENT UPDATE ДОЛЖЕН СОЗДАВАТЬ ПОНЯТНУЮ INDEX VERSION TRANSITION

SOURCE v8Ingestion detects new version.
PARSEBuild new structured blocks/chunks.
DIFF / HASHReuse unchanged chunks where possible.
EMBED CHANGEDModel/version pinned.
UPSERTNew refs/version metadata.
RETIRE OLDRemove/tombstone old chunk generation.
Не «обновлять vector по месту» без source version. Search result должен указывать, из какой exact document version пришёл chunk.
17. DELETION

УДАЛЁННЫЙ SOURCE НЕ ДОЛЖЕН ОСТАТЬСЯ В VECTOR INDEX

DELETE SOURCE

Trigger

Ingestion/governance marks source deleted or access revoked.

DESCENDANTS

Lineage

Find chunks/embeddings/index entries derived from source version.

REMOVE / TOMBSTONE

Index hygiene

Make entries immediately ineligible; physical compaction can happen later.

Deletion correctness важнее physical cleanup latency. Tombstone/filter can stop retrieval immediately while background index maintenance catches up.
18. INDEX GENERATIONS

REBUILD БЕЗ DOWNTIME ЧЕРЕЗ VERSIONED NAMESPACE

knowledge_index:
  generation g17  ← ACTIVE
  generation g18  ← BUILDING

BUILD g18:
  new embedding model
  new chunking profile
  new metadata schema
  full / incremental load
  retrieval eval
  ACL checks
  count/hash reconciliation

PROMOTE:
  active_generation = g18

ROLLBACK:
  active_generation = g17

RETIRE:
  delete g17 later after safety window
Blue/green index generations упрощают migration embedding model, dimensions, chunking and schema without partial mixed state.
19. EMBEDDING MODEL MIGRATION

НОВЫЙ EMBEDDING MODEL = НОВОЕ VECTOR SPACE

DUAL INDEX

Safe migration

Build new vectors/index generation in parallel, evaluate, then switch.

NO MIX

Space incompatibility

Do not casually combine vectors from model v2 and v3 in one nearest-neighbor space.

CACHE BUST

Query/result caches

Embedding/query/retrieval cache keys include model/index generation.

Migration is not merely «re-embed eventually». Until rebuild is complete, route queries to a coherent generation.
20. DEDUPLICATION

DUPLICATE CHUNKS МОГУТ ЗАНЯТЬ ВЕСЬ TOP-K

CONTENT HASH

Exact dup

Detect identical normalized chunk content.

SOURCE CLUSTER

Near dup

Same press release copied across many pages can dominate semantic results.

DIVERSIFY

Result policy

Limit per document/source/domain before final rerank where useful.

PROVENANCE

Keep origin

Dedup physically/logically without losing source authority/version metadata.

Высокий similarity score из пяти копий одного текста не означает пять независимых evidence sources.
21. MULTI-TENANCY

TENANT ISOLATION ДОЛЖНА БЫТЬ ЧАСТЬЮ INDEX CONTRACT

SHARED INDEX + FILTER

Simple operations

Tenant_id mandatory in every row/query; robust filter enforcement required.

NAMESPACE PER TENANT

Stronger logical isolation

Operational overhead grows with tenant count.

PHYSICAL SEPARATION

High assurance

Separate DB/cluster/index for strict regulatory or enterprise isolation.

Выбор зависит от threat model и scale. Но «tenant_id optional metadata» — не isolation.
22. VECTOR DB ≠ MEMORY

СХОЖЕЕ API RETRIEVAL НЕ ОЗНАЧАЕТ ОДИНАКОВУЮ SEMANTICS

LayerWhat is stored/retrievedPurpose
VECTOR INDEXVectors + refs + metadata.Approximate semantic candidate retrieval.
RAG KNOWLEDGEExternal/source-backed corpus.Bring relevant knowledge into current context.
MEMORYRetained facts/preferences/episodes/procedures.Persist experience/user/system knowledge over time.
Memory implementation may use vectors as one retrieval method, but Vector DB itself does not define memory retention, verification, consolidation or forgetting semantics.
23. VECTOR DB ≠ KNOWLEDGE GRAPH

«ПОХОЖЕ» И «СВЯЗАНО ОПРЕДЕЛЁННЫМ ОТНОШЕНИЕМ» — РАЗНЫЕ ВЕЩИ

VECTOR

Implicit geometry

Find semantically similar chunks/entities without explicit relation type.

№67 GRAPH

Explicit structure

Company A OWNS Project B, person C WORKS_FOR organization D, project CONNECTS city X→Y.

GraphRAG can use vector search to seed graph traversal, but graph semantics are not derivable from cosine similarity alone.
24. RETRIEVAL EVALS

ОЦЕНИВАТЬ НУЖНО НЕ «КРАСИВО ЛИ ИЩЕТ», А НАХОДИТ ЛИ НУЖНОЕ

RECALL@K

Coverage

Did top-K contain at least one truly relevant item?

MRR

First relevant rank

How early does first relevant item appear?

NDCG

Graded ranking

Useful when relevance has levels, not binary label.

PRECISION@K

Noise

How many returned items are actually relevant?

ACL ERR

Security

Unauthorized result rate. Target 0.

STALE ERR

Freshness

Retrieval of superseded/deleted versions.

LAT

Search latency

p50/p95 under realistic filters and corpus size.

COST

End-to-end

Embedding + search + rerank + context token cost.

Retriever eval set should include exact identifiers, semantic paraphrases, negatives, ambiguous queries, access filters, stale versions and multi-hop cases.
25. END-TO-END RAG QUALITY

ХОРОШИЙ RETRIEVER МОЖЕТ ДАТЬ ПЛОХОЙ ANSWER, И НАОБОРОТ

RETRIEVAL

Did evidence enter candidate set?

Measure independently with relevance labels.

CONTEXT SELECTION

Was best evidence retained?

Reranker/context builder can drop useful candidates.

GENERATION / VERIFY

Was evidence used correctly?

Answer may hallucinate despite perfect retrieval.

Это важно для диагностики: не «RAG плохо работает», а конкретно retrieval recall, reranking, context or generation failed.
26. CACHING

EMBEDDINGS — ОДИН ИЗ ЛУЧШИХ CANDIDATES ДЛЯ CACHE

DOC EMBEDDING

Hash + model version

Same content hash and embedding config → reuse vector.

QUERY EMBEDDING

Exact query cache

Useful for repetitive workloads; scope by embedding model/version.

RETRIEVAL RESULT

Conditional

Cache only with tenant/filter/index generation in key.

№62 Caching владеет cache policy; №66 provides stable hashes/versions that make safe reuse possible.
27. OBSERVABILITY

СМОТРЕТЬ НА INDEX КАК НА PIPELINE, А НЕ ТОЛЬКО QPS

VEC

Vector count

By namespace/tenant/model/generation.

AGE

Index freshness

Lag source update → searchable vector.

P95

Search latency

With realistic filters/top-K.

REC

Recall

Offline Recall@K by query segment.

MISS

Zero-hit / low-score

Queries with poor candidate coverage.

STALE

Stale results

Superseded/deleted versions returned.

ACL

Access errors

Unauthorized candidate/result rate.

IDX

Build health

Embedding failures, dimension mismatch, orphan vectors, generation completeness.

28. FAILURE MODES

КАК VECTOR SEARCH ДЕЛАЕТ RAG ХУЖЕ

VECTOR DB = RAG
Retrieval index is mistaken for full evidence/generation architecture.
KEEP RAG LAYERS SEPARATE
VECTOR DB = MEMORY
No retention/consolidation semantics, only similarity lookup.
SEPARATE MEMORY
NO MODEL VERSION
Mixed/incompatible vector spaces after embedding upgrade.
VERSIONED GENERATIONS
NO ACL FILTER
Private chunks become retrieval candidates for wrong principal.
FILTER AT RETRIEVAL
VECTOR ONLY
Exact identifiers/numbers/legal terms are missed.
HYBRID SEARCH
TOP-5 FOREVER
Arbitrary K becomes hidden recall bottleneck.
EVAL K + RERANK
NO DELETE SYNC
Deleted/revoked data remains retrievable.
TOMBSTONE + RECONCILE
CHUNK BLINDLY
Index faithfully retrieves semantically poor units.
STRUCTURAL CHUNKING
SCORE = TRUTH
Similarity is treated as evidence support or authority.
RERANK + VERIFY
29. METRICS

ЧТО ИЗМЕРЯТЬ

R@K

Recall@K

Share of queries where relevant evidence is present in top-K.

MRR

Mean Reciprocal Rank

How high the first relevant result appears.

P@K

Precision@K

Noise level among top results.

P95

Search Latency

Filtered ANN/hybrid latency at production scale.

FRESH

Index Freshness Lag

Source update → searchable new vector delay.

ACL

Unauthorized Result Rate

Target: zero.

STALE

Stale Vector Rate

Superseded/deleted entries still retrievable.

ROI

Retrieval Value

Answer/eval uplift versus lexical-only/no-retrieval baselines.

30. MVP IMPLEMENTATION

POSTGRES + VECTOR EXTENSION / EXACT SEARCH ЧАСТО ДОСТАТОЧНЫ ДЛЯ СТАРТА

vector_index/
├── embeddings.py
├── repository.py
├── search.py
├── filters.py
├── hybrid.py
├── rerank.py
├── migrations.py
├── reconcile.py
└── tests/

vector_entries(
  vector_id          uuid primary key,
  chunk_ref          text,
  tenant_id          text,
  source_ref         text,
  source_version     text,
  content_hash       text,
  embedding_model    text,
  embedding_version  text,
  dimensions         int,
  index_generation   text,
  vector             vector(...),
  metadata_json      jsonb,
  deleted            boolean,
  created_at         timestamptz,
  unique(
    chunk_ref,
    embedding_version,
    index_generation
  )
)

search(query, ctx):
  embed query with matching model
  apply tenant/ACL/source filters
  dense top_k = 30
  lexical top_k = 30
  fuse/dedupe
  rerank
  return refs + scores + provenance
80% VALUE MVP

Simple, versioned retrieval

  • One embedding model.
  • One coherent index generation.
  • Stable chunk refs + source versions.
  • Content-hash embedding cache.
  • Tenant/ACL metadata filters.
  • Exact or simple ANN search.
  • Lexical + dense hybrid.
  • Rerank top 20–50.
  • Deletion/tombstone reconciliation.
  • Recall@K eval set.
  • Blue/green index rebuild procedure.

Не нужен отдельный vector cluster, если corpus/load comfortably fits PostgreSQL and latency target.

31. WHEN TO UPGRADE

СПЕЦИАЛИЗИРОВАННАЯ VECTOR INFRA ПОЯВЛЯЕТСЯ ИЗ ИЗМЕРЕННОЙ НАГРУЗКИ

SignalPotential upgrade
Millions/billions of vectors + strict latencyDedicated ANN engine/vector database.
High concurrent filtered searchDistributed/sharded vector index with robust metadata filtering.
Memory pressureQuantized/compressed index or disk-oriented ANN.
Complex hybrid retrievalDedicated search stack / coordinated lexical+dense engine.
Frequent index migrationsAutomated generation build/canary/promote/rollback pipeline.
Entity/relation reasoning becomes importantAdd №67 Knowledge Graph / GraphRAG rather than forcing vectors to represent explicit relationships.
32. PRACTICAL DECISION

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

ВопросОтвет
Стоит ли реализовывать?Да, если dense semantic retrieval показывает uplift. Не нужен автоматически для любой AI-системы.
Separate Component?YES логически. Физически MVP может жить в PostgreSQL рядом с corpus metadata.
Минимум 80% ценности?Versioned embeddings, stable chunk refs, ACL filters, coherent index generations, hybrid retrieval, reranking, deletion sync, retrieval evals.
Когда overkill?Dedicated vector cluster для тысяч chunks, которые exact/Postgres search находит за milliseconds.
Trigger?Keyword retrieval misses paraphrases/conceptual matches, corpus scale/search latency requires dense index, or evals prove semantic retrieval uplift.
Как измерить uplift?Recall@K, MRR, answer quality uplift, retrieval latency, stale/ACL error rate, end-to-end cost and context efficiency.
Можно ли rule/tool/code вместо LLM-agent?Да. Embedding/index/search are deterministic infrastructure. LLM may rewrite queries or rerank, but Vector DB itself requires no agent.
33. DESIGN RULES

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

RULE 01

Vector DB is an index

Source of truth remains source/artifact/document stores.

RULE 02

Version the vector space

Embedding model/version/dimensions/index generation are mandatory.

RULE 03

Filter before exposure

Tenant/ACL/data scope belongs in retrieval eligibility.

RULE 04

Hybrid beats dogma

Use lexical + dense when exact identifiers and semantic paraphrases both matter.

RULE 05

Retrieve broad, rerank narrow

ANN is candidate generation, not final evidence judgment.

RULE 06

Chunk quality bounds index quality

Garbage units in → faithfully retrieved garbage out.

RULE 07

Deletion is part of indexing

Revoked/deleted sources become ineligible immediately.

RULE 08

Evaluate retrieval independently

Recall/rank/security/freshness before blaming generation.

RULE 09

Scale infra last

Use specialized vector DB only after Postgres/exact baseline stops meeting requirements.

34. FINAL MAP

SEMANTIC SEARCH IS ONE RETRIEVAL MECHANISM INSIDE A LARGER KNOWLEDGE SYSTEM

INGESTED SOURCE
        ↓
PARSED STRUCTURE
        ↓
CHUNKS / RETRIEVAL UNITS
  chunk_ref
  source_ref
  source_version
  content_hash
  ACL / tenant
        ↓
EMBEDDING PIPELINE
  exact representation text
  embedding model
  embedding version
  dimensions
        ↓
VECTOR
        ↓
VECTOR INDEX
  namespace
  generation
  metric
  ANN structure
  metadata filters
        ↓
QUERY
        ↓
QUERY NORMALIZATION
        ↓
QUERY EMBEDDING
  SAME VECTOR SPACE
        ↓
FILTER ELIGIBLE CORPUS
  tenant
  ACL
  source
  date
  language
  type
        ↓
DENSE SEARCH
        +
LEXICAL SEARCH
        ↓
FUSION / DEDUPE
        ↓
RERANK
        ↓
TOP EVIDENCE CANDIDATES
  refs
  scores
  provenance
        ↓
RAG CONTEXT BUILDER
        ↓
GENERATION
        ↓
VERIFICATION

UPDATE PATH:
  source v8
    ↓
  parse/chunk
    ↓
  embed changed content
    ↓
  upsert new generation/version
    ↓
  retire old entries

DELETE PATH:
  source revoked/deleted
    ↓
  lineage descendants
    ↓
  tombstone vector entries
    ↓
  physical compaction later

MIGRATION:
  g17 ACTIVE
  g18 BUILDING
    ↓
  eval
    ↓
  PROMOTE g18
    ↓
  rollback if needed

BOUNDARIES:

VECTOR DB
  = semantic candidate index

RAG
  = retrieval-augmented answering pipeline

MEMORY
  = retained knowledge/experience semantics

KNOWLEDGE GRAPH
  = explicit entities + typed relations

CORE PRINCIPLE:

VECTOR SIMILARITY MEANS:

"THESE OBJECTS LOOK
SEMANTICALLY CLOSE
IN THIS MODEL'S SPACE."

IT DOES NOT MEAN:

"THIS IS TRUE."
"THIS IS AUTHORIZED."
"THIS IS FRESH."
"THIS SUPPORTS THE CLAIM."
"THIS IS THE BEST SOURCE."

THOSE DECISIONS BELONG
TO THE LARGER RETRIEVAL,
POLICY, PROVENANCE
AND VERIFICATION SYSTEM.

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 №66 Vector DB & Embeddings.

B–E. Existing boundary and placement. The existing conceptual boundary, class SPECIALIZED, default CONDITIONAL 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.