KoreaDevKNOWLEDGE SHARING

Content typeLearn

AI SOFTWARE DEVELOPMENT · 05 / 10

Databases in the age of AI

Study relational constraints, JSON, vector search, and RAG not as substitutes for one another but as answers to different questions with different failure paths.

Difficulty
Beginner · Practical
Structure
Lessons 8 · Labs 2 · Assessment

CORE UNIT 1 / 1

Databases in the age of AI

Study relational constraints, JSON, vector search, and RAG not as substitutes for one another but as answers to different questions with different failure paths.

Difficulty
Beginner · Practical
Structure
Lessons 8 · Labs 2 · Assessment

Diagrams and tables: composed by the author using each lesson's official primary sources. Find the originals and review dates at the end of that lesson.

NEW HIRE ONBOARDING

Start in the order you would receive your first assignment

So that even a new hire with no prior IT background can follow along, we start with the situation, the task, the evidence, and when to report, before difficult definitions.

  1. 01

    Read the situation in one sentence

    Documents for all employees were placed in one vector index, and unauthorized documents are hidden in the application after retrieval. If unauthorized documents fill the Top-k results, no authorized documents remain.

  2. 02

    Today's assignment

    Distinguish the questions answered by relational, document, and vector search approaches.

  3. 03

    Evidence that shows the work is complete

    Verify initial existence, inject cache failure, then check zero old-revision entries and preservation of the current revision.

  4. 04

    When to stop and ask a senior colleague

    Costs include migrations, locks, scaling topology, and rigorous modeling.

Unpack unfamiliar terms first

Relational models and consistency
The strength of the relational model lies less in its tabular shape than in separating logical relationships and constraints from physical storage.
The emergence of NoSQL and the re-evaluation of PostgreSQL
Rather than a simple RDB→NoSQL→RDB round trip, workloads specialized and operational complexity was reassessed.
Embedding and vector search
Vector search finds representations that are close to one another, while metadata filters and source evidence complement it with meaning and authorization.

Questions for this course

Why did it change, and what must be verified?

Do not merely memorize a technology's advantages; check the conditions under which they hold and the new failure boundaries they introduce.

OBSERVABLE OUTCOMES

What you can do after this course

  1. Distinguish the questions answered by relational, document, and vector search approaches.
  2. Compare recall, speed, and build tradeoffs between Exact search and HNSW or IVFFlat.
  3. Isolate RAG failure stages from ingest through citation, and apply permission filters.

PREREQUISITE CHECK

Three things to check before reading

This is not a test of memorized answers. Think about each question first, then open the explanation to review the foundational concepts used in this course.

1How is a database different from a file?

Provides concurrent users, queries, constraints, transactions, recovery, and access control within a consistent management boundary.

2Does a vector store the truth of a sentence?

An embedding vector is a numeric coordinate in the representation space a model has learned. Closeness signals semantic similarity; it is not evidence of factual accuracy or authorization.

3Does RAG retrain the model?

External documents are usually retrieved at query time and supplied as context; model weights are not changed.

TEXTBOOK GUIDE

Main text that covers each concept from its background to the criteria for judging it

We explain the material section by section so readers new to IT can connect causes and effects without memorizing terms.

CONCEPT FLOW

How the chapters connect

The chapters are not isolated short answers to memorize. Follow them from left to right to see how each chapter's concepts support the next decision.

  1. 1.Relational models and consistency
  2. 2.The emergence of NoSQL and the re-evaluation of PostgreSQL
  3. 3.Embedding and vector search
  4. 4.RAG is a pipeline, not a single feature
  5. 5.Agent data access and safety
  6. 6.Constrain concurrent reservations with database rules
  7. 7.Diagnose retrieval results lost after permission filtering
  8. 8.Trace source deletion through vectors and caches
Databases in the age of AI: the overall map. If you lose track while reading the detailed explanations and chapters below, return to this sequence.
Figure 5-1. Databases in the age of AI: concept developmentShows how each chapter’s choices and limits lead to the problems of the next chapter.
  1. 1
    Relational models and consistency

    The strength of the relational model lies less in its tabular shape than in separating logical relationships and constraints from physical storage.

  2. 2
    The emergence of NoSQL and the re-evaluation of PostgreSQL

    Rather than a simple RDB→NoSQL→RDB round trip, workloads specialized and operational complexity was reassessed.

  3. 3
    Embedding and vector search

    Vector search finds representations that are close to one another, while metadata filters and source evidence complement it with meaning and authorization.

  4. 4
    RAG is a pipeline, not a single feature

    If retrieval results are poor, identify the failed ingest, chunk, embedding, filter, or rerank stage before focusing on the model.

  5. 5
    Agent data access and safety

    An Agent should invoke allowed business operations within an authorized row scope, not receive database credentials.

  6. 6
    Constrain concurrent reservations with database rules

    A duplicate check in the UI cannot prevent conflicts between two concurrent writes.

  7. 7
    Diagnose retrieval results lost after permission filtering

    Distance-search candidate count can differ from the valid result count after authorization filtering.

  8. 8
    Trace source deletion through vectors and caches

    Deleting a source and preventing its further use in retrieval or answers are different states.

CONTROLLED EXPLANATION

Compare retrieval of five tenant-A sources

Current state: Tenant-A query

Compare retrieval of five tenant-A sources

Compare exact and approximate search within the same authorization scope while blocking permission-weakening shortcuts.

Fix authorization scopeSame questionCompare omissionsIsolate causeRemeasure identical workload1Tenant-A query2Exact baseline3Approximate results4Revalidate search5Independent approval conditions
  1. Tenant-A query

    Same vector and distance function

  2. Exact baseline

    5 authorized sources

  3. Approximate results

    2 results after filtering

  4. Revalidate search

    Compare settings, plan and latency

  5. Independent approval conditions

    Recall met · 0 unauthorized returns

1 → 2
Fix authorization scope
1 → 3
Same question
2 → 4
Compare omissions
3 → 4
Isolate cause
4 → 5
Remeasure identical workload

The counts of five and two are teaching fixtures. Do not pad the count with another tenant’s documents.

CONCRETE CASES

Selection criteria for all courses

TABLE 5-1

Selection criteria for all courses

Compare the technology in each chapter by how it works, the new costs it adds, and the evidence to check, not by its name.

Table 5-1. Databases in the age of AI: design decision criteria
.Core mechanismCosts to watchEvidence to check
1. Relational models and consistencyDeclarative queries, constraints, and transactions enforce data relationships and consistency in the database.Costs include migrations, locks, scaling topology, and rigorous modeling.Inject invalid rows that attempt to bypass constraints and concurrent transactions, then verify rejection and rollback.
2. The emergence of NoSQL and the re-evaluation of PostgreSQLCombines diverse data types and indexes with relational transactions and a query planner.Relying solely on general-purpose capability without measuring scale and latency for specialized workloads can create bottlenecks.Compare query pattern, consistency, volume, operator skill, and failure domain in a table.
3. Embedding and vector searchThe distance metric and index return candidate IDs close to the query vector.Approximation, model drift, memory costs, filter interactions, and relevance misjudgments arise.Using a ground-truth set, measure recall@k, latency, and omissions after filtering together.
4. RAG is a pipeline, not a single featurePreserve evidence identity from ingest to answer citation to trace the failing stage.Index freshness, retrieval latency, authorization, token costs, and evaluation operations are added.Pin the source span for a known question and compare candidate IDs and citation support at each stage.
5. Agent data access and safetyDomain tools and database policies convert natural-language intent into restricted queries and transactions.Risks include policy drift, excessive queries, sensitive data exposure, and duplicate changes.Verify that prohibited tables, other tenants, bulk queries, and duplicate writes are rejected at each boundary.
6. Constrain concurrent reservations with database rulesUniqueness on business identity and transactions over related changes produce consistent concurrent-write outcomes.An incorrect uniqueness scope blocks valid work; conflict responses and retry policy also need design.Run same-session contention alongside valid bookings for other sessions, and verify the final rows and quantities.
7. Diagnose retrieval results lost after permission filteringCompare an exact baseline within identical authorization scope against approximate execution plans to isolate omissions.Broader scans and partitioning change latency and operational cost, requiring workload-wide remeasurement.Compare recall and latency with the same tenant and distance function, and separately verify zero unauthorized returns.
8. Trace source deletion through vectors and cachesUse source/revision lineage and per-stage deletion state to detect data remaining in active paths.Asynchronous index and cache failures require handling; aggregate counts cannot establish completion.Verify initial existence, inject cache failure, then check zero old-revision entries and preservation of the current revision.

CHAPTER 1 / 8

Relational models and consistency

The strength of the relational model lies less in its tabular shape than in separating logical relationships and constraints from physical storage.

Why this concept became necessary

Primary keys, foreign keys, and constraints let multiple applications share the same data rules. A transaction commits or rolls back related changes as a single unit, controlling the exposure of intermediate states.

A schema does not obstruct change; it reveals which changes break the existing contract. However, a fixed schema and joins are not optimal for every access pattern, so measure workloads and scaling conditions.

Figure 5-2. Relational models and consistency: decision flowThe chain from the problem conditions through the working principle to verification evidence.
Problems and selection criteria

The strength of the relational model lies less in its tabular shape than in separating logical relationships and constraints from physical storage.

How it works

Declarative queries, constraints, and transactions enforce data relationships and consistency in the database.

Verification evidence

Inject invalid rows that attempt to bypass constraints and concurrent transactions, then verify rejection and rollback.

Follow it through a concrete system

In an order system, a foreign key that prevents `orders.customer_id` from referencing a nonexistent customer is a stronger shared rule than validation on a single screen. The constraint applies consistently even when admin tools, batch jobs, and new mobile APIs all use the same database. A unique constraint prevents duplicate storage of the same payment identifier, while a check constraint enforces allowed quantity or status values close to the data.

A transaction defines externally visible state transitions rather than merely grouping queries for speed. If order creation fails after inventory is reduced, both changes must roll back. When two users order the last item in stock at the same time, you must understand which outcomes the isolation level and locking strategy permit. Using a transaction alone does not eliminate every concurrency problem.

Schema migration does not end with adding a column. In a rolling deployment where old and new application versions coexist, you may need to add a compatible column, backfill data, switch the read path, and strengthen constraints last. Validation and index builds on large tables can introduce locks and I/O, so measure duration and blocking scope at realistic data volumes.

There are also conditions where a relational model is not the right choice. If most access reads and writes an entire aggregate rather than focusing on relationships and transactions, if the schema changes rapidly, or if cross-region availability is a strong priority, another storage model may be simpler. However, compare query plans, cardinality, consistency requirements, and recovery approaches on the same workload rather than splitting storage based only on an assumption that joins are slow.

Selection criteria and failure boundaries

Costs include migrations, locks, scaling topology, and rigorous modeling.

Misconceptions to avoid: It is incorrect to assume that an RDB is merely a spreadsheet and cannot scale.

Verify it yourself

Inject invalid rows that attempt to bypass constraints and concurrent transactions, then verify rejection and rollback.

What to judgeDeclarative queries, constraints, and transactions enforce data relationships and consistency in the database.

To summarize this chapter

The strength of the relational model lies less in its tabular shape than in separating logical relationships and constraints from physical storage.

Official sources for this chapter

The technical facts in the text were reviewed against the following primary sources. The author reconstructed the diagrams and comparisons using these materials.

  1. IBM Research, 「A Relational Model of Data for Large Shared Data BanksReview date 2026-08-28 · Scope Original 1970 paper
  2. PostgreSQL Global Development Group, 「ConstraintsReview date 2026-08-28 · Scope PostgreSQL 18 / current
  3. PostgreSQL Global Development Group, 「Concurrency Control: IntroductionReview date 2026-08-28 · Scope PostgreSQL 18 / current

CHAPTER 2 / 8

The emergence of NoSQL and the re-evaluation of PostgreSQL

Rather than a simple RDB→NoSQL→RDB round trip, workloads specialized and operational complexity was reassessed.

Why this concept became necessary

Large-scale distributed key-value access, flexible documents, and specific latency requirements drove the growth of document, wide-column, and key-value databases. These choices involve the tradeoff of moving some joins and transactions into the application.

PostgreSQL adds JSON operations, indexes, and an extension ecosystem, so it can handle relational data and some document requirements within a single transaction boundary. This does not mean it replaces every dedicated database; it widens the conditions under which you can reduce the number of services and the cost of consistency.

Figure 5-3. The emergence of NoSQL and the re-evaluation of PostgreSQL: decision flowThe chain from the problem conditions through the working principle to verification evidence.
Problems and selection criteria

Rather than a simple RDB→NoSQL→RDB round trip, workloads specialized and operational complexity was reassessed.

How it works

Combines diverse data types and indexes with relational transactions and a query planner.

Verification evidence

Compare query pattern, consistency, volume, operator skill, and failure domain in a table.

Follow it through a concrete system

A document database stores an object’s structure together in one record, which makes it easy to align the application model with the unit of reading. For services where large-scale key-value access and horizontal distribution matter, it reduces relational joins and lets a partition key predict where a request goes. In exchange, rules that span multiple documents, updates to duplicated data, and new query patterns can become the application’s responsibility.

PostgreSQL's JSON types, indexing, partitioning, and extensions make it possible to manage core data that needs relational constraints and flexible attributes within one operational boundary. That does not mean every workload belongs in one database. Compare polyglot persistence with unified operation, including the costs of failure domains, independent scaling, backup, and team ownership.

Selection criteria and failure boundaries

Relying solely on general-purpose capability without measuring scale and latency for specialized workloads can create bottlenecks.

Misconceptions to avoid: It is incorrect to assume that the NoSQL era is over and PostgreSQL alone is sufficient.

Verify it yourself

Compare query pattern, consistency, volume, operator skill, and failure domain in a table.

What to judgeCombines diverse data types and indexes with relational transactions and a query planner.

To summarize this chapter

Rather than a simple RDB→NoSQL→RDB round trip, workloads specialized and operational complexity was reassessed.

Official sources for this chapter

The technical facts in the text were reviewed against the following primary sources. The author reconstructed the diagrams and comparisons using these materials.

  1. IBM Research, 「A Relational Model of Data for Large Shared Data BanksReview date 2026-08-28 · Scope Original 1970 paper
  2. PostgreSQL Global Development Group, 「JSON Functions and OperatorsReview date 2026-08-28 · Scope PostgreSQL 18 / current

CHAPTER 3 / 8

Embedding and vector search

Vector search finds representations that are close to one another, while metadata filters and source evidence complement it with meaning and authorization.

Why this concept became necessary

An embedding model converts text or images into fixed-length numeric arrays. Candidates are found by distance between vectors produced with the same model and preprocessing, but a model revision changes the space, requiring regeneration and version management.

Exact search compares every vector to find the true nearest neighbors, while approximate indexes such as HNSW and IVFFlat trade some recall, build memory, and build time for faster search. You cannot pick an index by name alone without a dataset size and latency target.

Figure 5-4. Embedding and vector search: decision flowThe chain from the problem conditions through the working principle to verification evidence.
Problems and selection criteria

Vector search finds representations that are close to one another, while metadata filters and source evidence complement it with meaning and authorization.

How it works

The distance metric and index return candidate IDs close to the query vector.

Verification evidence

Using a ground-truth set, measure recall@k, latency, and omissions after filtering together.

Follow it through a concrete system

An embedding is not an answer key that perfectly stores the meaning of a sentence or image; it is the result of turning the model's learned representation into fixed-dimension numbers. Expressions with the same meaning may land close together, but numbers, negation, recent facts, and domain terms may be placed differently than expected. When the model or preprocessing changes, new vectors may not be directly comparable with existing ones in the same space.

Exact search computes distances to every vector to find the closest results under the current metric, but its cost increases with data size. Approximate indexes such as HNSW and IVFFlat gain speed by exploring only some candidates, trading off recall, memory, build cost, and update cost. Use representative queries and a ground-truth set to measure recall@k, tail latency, and index-build time together so index selection is evidence-based.

Selection criteria and failure boundaries

Approximation, model drift, memory costs, filter interactions, and relevance misjudgments arise.

Misconceptions to avoid: It is incorrect to assume that high cosine similarity proves correctness or factual accuracy.

Verify it yourself

Using a ground-truth set, measure recall@k, latency, and omissions after filtering together.

What to judgeThe distance metric and index return candidate IDs close to the query vector.

To summarize this chapter

Vector search finds representations that are close to one another, while metadata filters and source evidence complement it with meaning and authorization.

Official sources for this chapter

The technical facts in the text were reviewed against the following primary sources. The author reconstructed the diagrams and comparisons using these materials.

  1. pgvector, 「Exact and Approximate Nearest Neighbor SearchReview date 2026-08-28 · Scope Official repository README

CHAPTER 4 / 8

RAG is a pipeline, not a single feature

If retrieval results are poor, identify the failed ingest, chunk, embedding, filter, or rerank stage before focusing on the model.

Why this concept became necessary

Documents are parsed and chunked with their source ID, revision, owner, and permissions intact, then linked to the embedding index. A query passes through filtering, retrieval, and reranking, and only a limited set of source spans reaches the model context.

An answer must use citations to connect each claim to the supporting span. Missing retrieval, outdated revisions, answers distorted in context, and unsupported model conclusions are different failures, so metrics are needed for each stage.

Figure 5-5. RAG is a pipeline, not a single feature: decision flowThe chain from the problem conditions through the working principle to verification evidence.
Problems and selection criteria

If retrieval results are poor, identify the failed ingest, chunk, embedding, filter, or rerank stage before focusing on the model.

How it works

Preserve evidence identity from ingest to answer citation to trace the failing stage.

Verification evidence

Pin the source span for a known question and compare candidate IDs and citation support at each stage.

Follow it through a concrete system

RAG is not a single step of putting documents into a vector database and calling a model. It is a sequence of source collection, parsing, cleaning, chunking, embedding, indexing, query transformation, candidate retrieval, permission filtering, reranking, context packing, generation, and citation. When an answer is wrong, you cannot tell a prompt problem from a missing source unless you preserve the inputs and revision of each stage.

For example, if the latest HR policy is missing from an answer, check in order whether ingest read an older revision, the table parser lost a key row, the chunk used different wording from the question, or the ACL filter removed an allowed document. A citation must point to the span supporting the actual answer sentence and its source revision, not merely append a URL string.

Selection criteria and failure boundaries

Index freshness, retrieval latency, authorization, token costs, and evaluation operations are added.

Misconceptions to avoid: It is incorrect to assume that putting documents into a vector DB automatically produces grounded answers.

Verify it yourself

Pin the source span for a known question and compare candidate IDs and citation support at each stage.

What to judgePreserve evidence identity from ingest to answer citation to trace the failing stage.

To summarize this chapter

If retrieval results are poor, identify the failed ingest, chunk, embedding, filter, or rerank stage before focusing on the model.

Official sources for this chapter

The technical facts in the text were reviewed against the following primary sources. The author reconstructed the diagrams and comparisons using these materials.

  1. pgvector, 「Exact and Approximate Nearest Neighbor SearchReview date 2026-08-28 · Scope Official repository README

CHAPTER 5 / 8

Agent data access and safety

An Agent should invoke allowed business operations within an authorized row scope, not receive database credentials.

Why this concept became necessary

Converting natural language to SQL is convenient but carries risks of prompt injection, full table scans, and permission bypass. Limit capability with a read replica, allowlisted views, parameterized queries, row-level policies, and a query budget.

Writes need a preview, domain validation, transactions, idempotency, and an approval policy. Record the user's identity, agent and tool revisions, affected rows, and results in the audit trail while minimizing raw personal information and secrets.

Figure 5-6. Agent data access and safety: decision flowThe chain from the problem conditions through the working principle to verification evidence.
Problems and selection criteria

An Agent should invoke allowed business operations within an authorized row scope, not receive database credentials.

How it works

Domain tools and database policies convert natural-language intent into restricted queries and transactions.

Verification evidence

Verify that prohibited tables, other tenants, bulk queries, and duplicate writes are rejected at each boundary.

Follow it through a concrete system

When an Agent queries a database in natural language, giving the model raw SQL and administrator credentials can turn query mistakes and prompt injection directly into data exposure or modification. Put allowed views, row-level policies, and parameterized queries behind limited tools, and control result counts and sensitive fields on the server.

Apply authorization filters before generating candidates, not as post-processing that hides results after retrieval. If unauthorized vectors enter reranking or model context and are hidden only on screen, the information has already crossed the processing boundary. Record the tenant, subject, source revision, and policy decision in the retrieval trace, and verify how long revoked access takes to disappear from caches and indexes after a permission change.

Selection criteria and failure boundaries

Risks include policy drift, excessive queries, sensitive data exposure, and duplicate changes.

Misconceptions to avoid: It is incorrect to assume that an Agent may receive database-administrator privileges just because it can generate SQL.

Verify it yourself

Verify that prohibited tables, other tenants, bulk queries, and duplicate writes are rejected at each boundary.

What to judgeDomain tools and database policies convert natural-language intent into restricted queries and transactions.

To summarize this chapter

An Agent should invoke allowed business operations within an authorized row scope, not receive database credentials.

Official sources for this chapter

The technical facts in the text were reviewed against the following primary sources. The author reconstructed the diagrams and comparisons using these materials.

  1. PostgreSQL Global Development Group, 「ConstraintsReview date 2026-08-28 · Scope PostgreSQL 18 / current
  2. PostgreSQL Global Development Group, 「Concurrency Control: IntroductionReview date 2026-08-28 · Scope PostgreSQL 18 / current
  3. pgvector, 「Exact and Approximate Nearest Neighbor SearchReview date 2026-08-28 · Scope Official repository README

CHAPTER 6 / 8

Constrain concurrent reservations with database rules

A duplicate check in the UI cannot prevent conflicts between two concurrent writes.

Why this concept became necessary

Two booking screens can both observe the same seat as free. Another request can intervene between reading and saving, so application-only “check then create” logic can produce duplicate bookings.

Express business identities that must not duplicate, such as seat and session, with a database uniqueness constraint. UI prechecks improve guidance, but final consistency belongs at the storage boundary traversed by every writer.

Bind related booking and remaining-capacity updates in one transaction contract. Without defined rollback behavior, a failed check may leave reduced capacity without a booking.

Translate constraint violations into explicit domain results such as already booked rather than hiding them as success. Users need not see raw database errors, but conflicts and transient outages need different retry policies.

Figure 5-7. Constrain concurrent reservations with database rules: decision flowThe chain from the problem conditions through the working principle to verification evidence.
Problems and selection criteria

A duplicate check in the UI cannot prevent conflicts between two concurrent writes.

How it works

Uniqueness on business identity and transactions over related changes produce consistent concurrent-write outcomes.

Verification evidence

Run same-session contention alongside valid bookings for other sessions, and verify the final rows and quantities.

Follow it through a concrete system

A teaching fixture sends two simultaneous requests for seat A3 in session S1. Synchronize them so that both finish their prechecks before starting writes, creating contention that sequential tests do not expose. Distinguish this from running the requests sequentially and having only one succeed by chance. Record evidence that both prechecks saw an empty state to confirm that the contention condition actually occurred.

Verify not only one success and one conflict response, but also one final booking row and a single capacity decrement. Correct response statuses can still conceal duplicate internal changes. Query remaining capacity immediately after transaction failure. Cached UI counts can conceal stored errors, so verification must include authorized source-data reads.

Also verify that seat A3 in session S2 remains bookable. A uniqueness rule on seat number alone would block valid bookings across sessions, so the key must reflect the domain scope. Check rebooking after cancellation against policy. Restricting active reservations differs from restricting all historical records, so define the domain rule before choosing the data model.

Make agent tools use the same storage contract and inspect bypass write paths. Actual constraints and transaction outcomes establish conflict prevention more reliably than natural-language prohibitions. Inventory batch imports and administrative writers to verify they share the constraint. One safe API does not establish consistency when other writers can bypass the rule.

Selection criteria and failure boundaries

An incorrect uniqueness scope blocks valid work; conflict responses and retry policy also need design.

Misconceptions to avoid: Checking for duplicates before saving does not ensure safety under concurrency.

Verify it yourself

Run same-session contention alongside valid bookings for other sessions, and verify the final rows and quantities.

What to judgeUniqueness on business identity and transactions over related changes produce consistent concurrent-write outcomes.

To summarize this chapter

A duplicate check in the UI cannot prevent conflicts between two concurrent writes.

Official sources for this chapter

The technical facts in the text were reviewed against the following primary sources. The author reconstructed the diagrams and comparisons using these materials.

  1. PostgreSQL Global Development Group, 「ConstraintsReview date 2026-08-28 · Scope PostgreSQL 18 / current
  2. PostgreSQL Global Development Group, 「Concurrency Control: IntroductionReview date 2026-08-28 · Scope PostgreSQL 18 / current

CHAPTER 7 / 8

Diagnose retrieval results lost after permission filtering

Distance-search candidate count can differ from the valid result count after authorization filtering.

Why this concept became necessary

Searching nearby vectors globally and then applying a tenant filter can leave fewer results than requested. Before blaming missing documents or embeddings, inspect where index search and filtering occur.

With pgvector approximate indexes, inspect the interaction between filtering and search scope. Review iterative scans and scan limits supported by the deployed version, without treating broader search as permission to weaken authorization.

The accuracy baseline is exact search using the same tenant condition and distance function. Treating global unauthorized results as ground truth can misclassify correct exclusions as retrieval failures.

When changing search settings, record recall, returned count and latency together. Broader scans cost more, so assess whether they meet task minimums on the same workload.

Figure 5-8. Diagnose retrieval results lost after permission filtering: decision flowThe chain from the problem conditions through the working principle to verification evidence.
Problems and selection criteria

Distance-search candidate count can differ from the valid result count after authorization filtering.

How it works

Compare an exact baseline within identical authorization scope against approximate execution plans to isolate omissions.

Verification evidence

Compare recall and latency with the same tenant and distance function, and separately verify zero unauthorized returns.

Follow it through a concrete system

A fictional corpus stores tenants A and B together while an A user requests five documents. First build an exact baseline over authorized A documents to check that five relevant documents actually exist. Preserve expected document IDs and revisions so deleted or changed sources are not still expected. A stale baseline may require evaluation-data updates rather than index changes.

If the approximate path returns only two results, record search effort, filter conditions, and the actual execution plan. Removing the tenant condition to fill five results is an authorization violation, not a performance fix. Check whether the query plan actually used the approximate index. If a different plan was chosen after a settings change, the latency change cannot be attributed to the scan limit alone.

After changing scan settings or partitioning, recompare recall and latency for the same questions. One tenant may improve while another waits longer, so observe shared-index effects separately. Repeat with controlled query order and cache conditions. Running only one candidate warm confounds cache effects with index-design differences.

Keep zero unauthorized returns as an independent evaluation condition. Better recall cannot justify even one cross-tenant document; retrieval quality and access control must both hold. Excluded document IDs must not remain in public answers or suggestions. Hiding bodies can still expose titles or existence, so inspect the full return format.

Selection criteria and failure boundaries

Broader scans and partitioning change latency and operational cost, requiring workload-wide remeasurement.

Misconceptions to avoid: Receiving fewer than k results does not justify removing permission filters.

Verify it yourself

Compare recall and latency with the same tenant and distance function, and separately verify zero unauthorized returns.

What to judgeCompare an exact baseline within identical authorization scope against approximate execution plans to isolate omissions.

To summarize this chapter

Distance-search candidate count can differ from the valid result count after authorization filtering.

Official sources for this chapter

The technical facts in the text were reviewed against the following primary sources. The author reconstructed the diagrams and comparisons using these materials.

  1. pgvector, 「Exact and Approximate Nearest Neighbor SearchReview date 2026-08-28 · Scope Official repository README
  2. PostgreSQL Global Development Group, 「CREATE INDEXReview date 2026-08-28 · Scope PostgreSQL 18 / current

CHAPTER 8 / 8

Trace source deletion through vectors and caches

Deleting a source and preventing its further use in retrieval or answers are different states.

Why this concept became necessary

One document can produce multiple chunks, vectors and summary caches, leaving old content retrievable after the source file is deleted. Preserve source IDs and revisions on derived data to identify deletion scope.

Titles used as identifiers can mix revisions sharing the same name. Link content hashes, revisions and chunk IDs, and identify the active generation so results can be traced to current sources.

Record deletion progress for sources, active indexes and caches separately. Partial failure must remain incomplete, with outstanding targets retried and progress recoverable after restart.

In-use results and retention policy are separate concerns. Recovery artifacts must not reintroduce revoked content into new responses; distinguish active serving paths from restricted retention paths.

Figure 5-9. Trace source deletion through vectors and caches: decision flowThe chain from the problem conditions through the working principle to verification evidence.
Problems and selection criteria

Deleting a source and preventing its further use in retrieval or answers are different states.

How it works

Use source/revision lineage and per-stage deletion state to detect data remaining in active paths.

Verification evidence

Verify initial existence, inject cache failure, then check zero old-revision entries and preservation of the current revision.

Follow it through a concrete system

Use fictional policy document D7 revision 2 as the deletion fixture and freeze the list of its derived chunk IDs. Before deletion, verify that D7 is retrieved for the question so a document that was never present cannot produce a false pass. Also include another valid document containing the same sentences. This counterexample checks that deletion follows source identity rather than bulk removal of matching strings.

Inject successful index deletion but failed cache invalidation. Check that status remains partially failed and identifies the path still returning stale answers to the same question. Test that pending cache deletion survives restart. An in-memory completion list can lose failed targets after interruption and keep serving stale material.

After reprocessing, query the active index, result cache, and replicas separately to confirm zero entries for D7 revision 2. A total document count dropping by one does not prove removal of specific derived data. Record the queried revisions so the zero-count verdict identifies which generation it covers. Do not merge replica results from different points in time into a single completion state.

Keep the new revision 3 as a separate fixture to check that the deletion scope is not too broad. Correct deletion removes old evidence while preserving retrieval and source links for the valid current document. Apply the revocation list even when testing a switch to an older generation for recovery. If a rollback reactivates all past documents, it may resolve the outage while breaking the deletion commitment.

Selection criteria and failure boundaries

Asynchronous index and cache failures require handling; aggregate counts cannot establish completion.

Misconceptions to avoid: Deleting the source file does not automatically remove every vector and cache entry.

Verify it yourself

Verify initial existence, inject cache failure, then check zero old-revision entries and preservation of the current revision.

What to judgeUse source/revision lineage and per-stage deletion state to detect data remaining in active paths.

To summarize this chapter

Deleting a source and preventing its further use in retrieval or answers are different states.

Official sources for this chapter

The technical facts in the text were reviewed against the following primary sources. The author reconstructed the diagrams and comparisons using these materials.

  1. PostgreSQL Global Development Group, 「ConstraintsReview date 2026-08-28 · Scope PostgreSQL 18 / current
  2. pgvector, 「Exact and Approximate Nearest Neighbor SearchReview date 2026-08-28 · Scope Official repository README

INTERACTIVE LAB 1 / 2

Lab 1 · Diagnosing index and authorization issues in customer-support search

Documents for all employees were placed in one vector index, and unauthorized documents are hidden in the application after retrieval. If unauthorized documents fill the Top-k results, no authorized documents remain.

Choose how to improve recall and security together.

Choose an answer

Correct answer A

A. Apply tenant and ACL filters before generating search candidates, and evaluate recall@k and citations within the allowed slice.A decision that accounts for conditions, working principles, and failure boundaries together.

B. Increase top-k indefinitely and hide results only on the final screen.It considers only some benefits and omits prerequisites or newly introduced failure boundaries.

C. Skip the authorization check when cosine similarity is high.It treats the responsibilities of different layers as one and misses the actual verification points.

D. Make all documents public.It relies on technology names or trends, with no observable evidence from the current requirements.

INTERACTIVE LAB 2 / 2

Lab 2 · Recover vector search returning only two filtered results

Tenant A has five authorized relevant documents. Approximate search returns only two for the same question; mixing in another tenant's documents yields five.

Choose the next check that preserves both authorization and retrieval quality.

Choose an answer

Correct answer C

A. Remove the tenant filter to fill five results.This violates authorization to satisfy a result count.

B. Retrieval passes because even two results summarize naturally.Fluency does not detect missing required evidence.

C. Compare with the same-tenant exact baseline and test recall, latency and zero unauthorized returns across scan settings.Isolate and verify search-scope gaps without relaxing authorization.

D. Replace only the embedding model and discard prior results.This loses the baseline for comparing causes, so you cannot tell whether the problem lies in filtering or index search.

KEY TERMS

Key terms in this unit

Relational models and consistency
Declarative queries, constraints, and transactions enforce data relationships and consistency in the database.
The emergence of NoSQL and the re-evaluation of PostgreSQL
Combines diverse data types and indexes with relational transactions and a query planner.
Embedding and vector search
The distance metric and index return candidate IDs close to the query vector.
RAG is a pipeline, not a single feature
Preserve evidence identity from ingest to answer citation to trace the failing stage.
Agent data access and safety
Domain tools and database policies convert natural-language intent into restricted queries and transactions.
Constrain concurrent reservations with database rules
Uniqueness on business identity and transactions over related changes produce consistent concurrent-write outcomes.
Diagnose retrieval results lost after permission filtering
Compare an exact baseline within identical authorization scope against approximate execution plans to isolate omissions.
Trace source deletion through vectors and caches
Use source/revision lineage and per-stage deletion state to detect data remaining in active paths.

UNIT WORKBOOK

Exercises and worksheets for applying concepts to new situations

Start by checking basic principles, then expand to practical workplace decisions. After submitting an answer, you can see why every option is correct or incorrect, not just the correct answer.

THREE-LEVEL ASSESSMENT

From basic principles to operational decisions

After you submit an answer, you can see not only the correct answer but also why each option is right or wrong.

Basic Question 1

What does vector similarity directly tell you?

Choose an answer

Correct answer A

A. How close the two representations are under the chosen embedding and distance metric.A decision that accounts for conditions, working principles, and failure boundaries together.

B. That the sentence is legally true.It considers only some benefits and omits prerequisites or newly introduced failure boundaries.

C. The user’s permission to view the document.It treats the responsibilities of different layers as one and misses the actual verification points.

D. A successful database transaction.It relies on technology names or trends, with no observable evidence from the current requirements.

Apply Question 2

What should you measure alongside it when choosing an approximate index such as HNSW?

Choose an answer

Correct answer B

A. Look only at model response length.It relies on technology names or trends, with no observable evidence from the current requirements.

B. Recall@k on the ground-truth set, filter conditions, latency, memory, and build cost.A decision that accounts for conditions, working principles, and failure boundaries together.

C. The popularity of the index name.It considers only some benefits and omits prerequisites or newly introduced failure boundaries.

D. Table colors.It treats the responsibilities of different layers as one and misses the actual verification points.

Capstone Question 3

What is the first diagnostic step when a RAG answer is wrong?

Choose an answer

Correct answer C

A. Remove all permission filters.It treats the responsibilities of different layers as one and misses the actual verification points.

B. Make only the answer prompt longer.It relies on technology names or trends, with no observable evidence from the current requirements.

C. Separate the source revision, chunks, candidates, filters, reranking, and citations into per-stage evidence.A decision that accounts for conditions, working principles, and failure boundaries together.

D. Unconditionally switch to a larger model.It considers only some benefits and omits prerequisites or newly introduced failure boundaries.

PRIMARY SOURCES

Course references

This list collects the sources for each chapter. The text and author-created diagrams were prepared by directly reviewing the originals below.

PERSONAL WORKSHEET

A learning worksheet you adapt to your own environment

Your input remains only on the current browser screen and is not stored or transmitted externally. Use categories and pseudonyms instead of actual sensitive information.

OFFICIAL SOURCES

Verify against official sources

Technical, compatibility, and model information reviewed: August 2026

LEARNING RECORD

Have you reviewed the text, decision activities, and all explanations?

Completion status is stored only in this browser.