# How Memory Retrieval Works in TencentDB Agent Memory: SQLite Store Architecture Explained

> Understand TencentDB Agent Memory retrieval with this SQLite store architecture explanation. Learn how tenant-scoped requests flow through HTTP to SQLite for efficient data access.

- Repository: [Tencent Cloud/TencentDB-Agent-Memory](https://github.com/TencentCloud/TencentDB-Agent-Memory)
- Tags: architecture
- Published: 2026-08-29

---

**Memory retrieval in TencentDB Agent Memory follows a layered HTTP-to-SQLite flow where the Memory Proxy validates tenant-scoped requests and invokes `SqliteKnowledgeStore` methods that execute tenant-isolated `SELECT` queries against a per-tenant SQLite database.**

The TencentCloud/TencentDB-Agent-Memory repository implements a secure, multi-tenant memory system designed for LLM agents. Memory retrieval operates through a strict isolation model that ensures code-graph and wiki assets remain accessible only to authorized service and team contexts, utilizing Drizzle ORM with SQLite for data access.

## The Memory Retrieval Architecture

The retrieval pipeline consists of four distinct layers designed to enforce security while maintaining performance. Incoming requests traverse from external LLM agents through the Memory Proxy service before executing against the SQLite-backed storage layer.

### HTTP Entry Point and Proxy Validation

External agents such as WorkBuddy initiate memory retrieval by issuing HTTP requests to the Memory Proxy service. The request payload must include `service_id`, `team_id`, and the specific asset identifier (`code_graph_id` or `wiki_id`).

The [`MemoryProxy/src/workbuddyHandler.ts`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/MemoryProxy/src/workbuddyHandler.ts) file handles these incoming requests, validating parameters before forwarding authorized calls to the knowledge store. This handler acts as the gatekeeper, ensuring only properly scoped requests reach the storage layer.

### SQLite Store Query Execution

Once validated, the proxy invokes methods on the `SqliteKnowledgeStore` class implemented in [`MemoryKnowledge/src/store/sqlite-store.ts`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/MemoryKnowledge/src/store/sqlite-store.ts). This store implements the `IKnowledgeStore` interface and manages all read operations using Drizzle ORM with SQLite.

The store executes simple `SELECT … FROM … WHERE …` statements filtered by `service_id` and `deleted_at IS NULL` soft-delete markers. This design guarantees that retrieval operations never return data from other tenants or deleted records.

## Core Retrieval Methods in SqliteKnowledgeStore

The store exposes specific methods for different retrieval patterns, each enforcing tenant isolation through mandatory `service_id` and `team_id` parameters.

### Single Asset Retrieval

For targeted lookups, the store provides two primary methods:

- **`getCodeGraph(serviceId, teamId, codeGraphId)`** – Retrieves a single code-graph row from [`MemoryKnowledge/src/store/sqlite-store.ts`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/MemoryKnowledge/src/store/sqlite-store.ts). Returns the asset as a `CodeGraphRow` DTO or `null` if the tenant does not own the asset.
- **`getWiki(serviceId, teamId, wikiId)`** – Fetches a specific wiki entry, returning a `WikiRow` DTO or `null` for unauthorized access attempts.

Both methods include `team_id` validation to prevent cross-team data leaks within the same service.

### Batch and Listing Operations

When agents need to browse available memories rather than fetch specific assets, the store supports paginated listings:

- **`listCodeGraphs`** – Returns paginated code-graph collections scoped to the requesting tenant.
- **`listWikis`** – Provides paginated wiki listings with tenant isolation.

These methods enable agents to discover available context without loading entire datasets into memory.

## Data Transformation and DTO Mapping

Raw database rows undergo normalization before returning to clients. The private helper functions `mapCgRow` and `mapWikiRow` in the sqlite-store module convert internal column names (such as `code_graph_id`, `wiki_id`, `status`, `summary`) into clean public DTOs.

This mapping layer abstracts database schema details from API consumers, ensuring consistent JSON responses regardless of underlying SQLite schema evolution.

## Security Model and Tenant Isolation

The memory retrieval system implements defense-in-depth for multi-tenant security.

**Service and Team Scoping**

Every read operation filters by `service_id`, ensuring complete isolation between different services. When applicable, `team_id` provides additional segmentation within service boundaries.

**Id-Only Accessors**

The store provides `getCodeGraphById` and `getWikiById` methods that bypass `team_id` validation while maintaining `service_id` scoping. These utilities support internal operations and recovery scenarios without compromising tenant boundaries.

**Soft-Delete Enforcement**

All queries include `WHERE deleted_at IS NULL` clauses, ensuring that soft-deleted assets never appear in retrieval results. This allows for safe cleanup operations without risking data resurrection.

**Crash Recovery Consistency**

The `markInterruptedAsFailed` method (lines 542-560 in [`MemoryKnowledge/src/store/sqlite-store.ts`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/MemoryKnowledge/src/store/sqlite-store.ts)) ensures retrieval state consistency after server restarts. By marking pending assets as failed during initialization, the system prevents stale lock states from blocking legitimate retrievals.

## Implementation Examples

### Using the TypeScript SDK

The `memory-core/typescript` SDK encapsulates the HTTP proxy layer, providing convenient methods for agent integration:

```typescript
import { MemoryClient } from "memory-core";

const client = new MemoryClient({ 
  baseUrl: "https://memory-proxy.mycompany.com" 
});

async function fetchWiki(serviceId: string, teamId: string, wikiId: string) {
  // Internally calls Memory Proxy "/v3/wiki/get" endpoint
  const wiki = await client.getWiki({ 
    service_id: serviceId, 
    team_id: teamId, 
    wiki_id: wikiId 
  });
  
  console.log("Wiki title:", wiki.name);
  console.log("Summary:", wiki.summary);
  return wiki;
}

```

### Direct Store Access

For internal proxy handlers or server-side logic, instantiate the store directly:

```typescript
import { SqliteKnowledgeStore } from "./store/sqlite-store.js";

export async function handleGetWiki(req) {
  const { service_id, team_id, wiki_id } = req.body;
  const store = new SqliteKnowledgeStore(db); // db = Drizzle SQLite instance
  
  const wiki = store.getWiki(service_id, team_id, wiki_id);
  if (!wiki) {
    throw new Error("404 – Wiki not found or not owned by tenant");
  }
  
  return { data: wiki };
}

```

## Summary

- **Memory retrieval** in TencentDB Agent Memory uses a two-step HTTP-to-SQLite architecture: the Memory Proxy validates requests and forwards them to `SqliteKnowledgeStore`.
- **Tenant isolation** enforces strict boundaries through mandatory `service_id` and `team_id` parameters in every query.
- **Core retrieval methods** include `getCodeGraph`, `getWiki`, `listCodeGraphs`, and `listWikis`, all implemented in [`MemoryKnowledge/src/store/sqlite-store.ts`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/MemoryKnowledge/src/store/sqlite-store.ts).
- **Security features** encompass soft-delete filtering, id-only accessors for internal use, and crash recovery via `markInterruptedAsFailed`.
- **Data normalization** occurs through `mapCgRow` and `mapWikiRow` helpers that convert database rows to public DTOs.

## Frequently Asked Questions

### How does TencentDB Agent Memory prevent cross-tenant data leaks during retrieval?

Every retrieval method in `SqliteKnowledgeStore` requires `service_id` and validates `team_id` ownership before returning data. The SQL queries generated by Drizzle ORM include `WHERE service_id = ? AND team_id = ?` clauses, ensuring rows from other tenants are filtered at the database level. Even id-only accessors like `getCodeGraphById` maintain `service_id` scoping to prevent cross-service leaks.

### What happens to memory retrieval after a server crash?

The system includes restart recovery logic in [`MemoryKnowledge/src/store/sqlite-store.ts`](https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/main/MemoryKnowledge/src/store/sqlite-store.ts) (lines 542-560) via the `markInterruptedAsFailed` method. During initialization, this function marks any assets stuck in a pending state as failed, preventing inconsistent lock states that could block legitimate retrieval operations.

### Can agents retrieve soft-deleted memory assets?

No. The `SqliteKnowledgeStore` automatically appends `deleted_at IS NULL` filters to all `SELECT` statements. This soft-delete mechanism ensures that deleted code-graphs and wikis remain in the database for audit purposes while being permanently excluded from active memory retrieval operations.

### What is the difference between `getWiki` and `getWikiById`?

`getWiki(serviceId, teamId, wikiId)` performs a strict tenant check using both service and team identifiers, suitable for external API calls. `getWikiById` provides internal access using only the `serviceId` and asset ID, bypassing team validation for administrative or recovery scenarios while still maintaining service-level isolation.