Agent Application DevelopmentAccount
Knowledge catalogChoose core direction and segmented content
knowledge unit 25IntermediateSystem designAbout 12 minutes

Understand → Implement → Debug → Design

Memory scopes and trusted authorization context

Design memory scope, authenticity, permissions and recall order as data contracts, and vector similarity is only responsible for sorting.

memorynamespacemulti-tenantPermissionsrecall

Knowledge content check2026-10-03 · Check the source of the original question2026-10-02

Which step do you want to learn from this knowledge point?

Select the starting point based on the current basis, or you can go deeper one by one. When you encounter an unfamiliar concept, go back to the core principles first; use the knowledge exercises to check your understanding when you are finished.

Understand first

New to this knowledge point

Complete the prerequisite concepts, read the principles and counterexamples, and then explain why in your own words.

Start with core principles →

Realize again

Prepare to write the principles into code

Understand implementation steps and boundaries, complete small tasks, and check results against acceptance requirements.

View the code example →

Will troubleshoot

Need to handle failures and changes in conditions

Follow the continuous questioning to locate the failure premise, and then compare the migration cases to explain how the plan should be adjusted.

Continue to delve deeper into the problem →

Able to choose

Need to design or review plans

Combine engineering deductions and senior self-evaluation standards to explain the applicable conditions, costs and alternatives of the plan.

Analyze engineering scenarios →
Knowledge unit directory

LEARN · PRACTICE · REFLECT

Knowledge learning and personal records

My notes and review ↗

First read along the principles, Q&A and migration cases. When you need to check your understanding, switch to reinforcement exercises or start personal recording.

Answers and personal notes

Each modified commit will be kept as an independent history. Your level of mastery is up to you to evaluate yourself against the standards.

Core concept · Memory scopes and trusted authorization context

Understand the core principles first

Preparatory concepts:Tenant and subject identity, Short-term state vs. long-term storage, Namespaces and ACLs

The relevance, life cycle and visibility range of memory are three independent dimensions. Threads or namespaces provide organization, and real authorization is still determined by trusted identities and current resource relationships.

Scope identifies whose memory is being used

Thread state holds current-task messages and intermediate results. Long-term storage holds reusable facts and preferences. Personal, project, and organizational scopes differ: short-answer preferences cannot remove organizational approval, and one project’s PostgreSQL choice does not apply everywhere.

Define a resource hierarchy such as tenant, project, principal, and memory type, with owner, source, and validity. The framework does not establish permission to read a namespace. Derive tenant identity from authentication and allowed scopes from membership. Models propose information needs without selecting arbitrary identities.

Namespaces do not enforce authorization

LangGraph store searches can match namespace prefixes and descendants. A full prefix may still return deeper records. Verify returned paths; string startsWith can confuse tenant-a with tenant-admin. Exact queries, structured path comparison, and item-level authorization serve different purposes. Naming conventions do not authenticate users.

Authorization changes during a run

A user leaving a project can lose access to memory available at task start. Recheck membership during recovery and before sending, remove private historical context, and prevent stale writeback. Organizational rules come from trusted configuration; personal preferences are lower-priority data. “I am an administrator” in memory is not a credential.

Check understanding with a question

How does Agent memory divide thread, user, project and organization scopes to avoid tenant stringing?

Keep session state in thread checkpoints and cross-session facts in long-term storage, scoped by tenant, user, project, or organization. Derive identity and allowed scopes from trusted authorization, never model-selected tenant_id. Retain source, version, validity, confidence, and deletion status. Only authorized current facts enter context; similarity determines relevance, not access.

Realization and trade-offs

First model according to usage and visible range

Thread memory is used for current task progress, recent conversations, and temporary evidence; user memory stores cross-session preferences; project memory stores repository constraints, decisions, and shared terms; and organizational memory stores rules that allow everyone to use them. LangGraph separates thread-scoped checkpoints from cross-thread stores, and the store namespace is designed by the application. Don't put all your stuff into one user vector library, and don't put all your long-term content permanently into prompt. Progress status is part of an executable task, while project facts can be reused by multiple tasks. They are updated and deleted at different frequencies.

Namespace is not an automatically implemented authorization system

It is recommended to locate records by tenant_id, scope_type, scope_id, memory_id. Before reading user, project or organization content, the server calculates the allowed range from authentication identity and membership. Fields input by the client or generated by the model can only be used as requests and cannot be used as authorization basis. LangGraph's namespace search supports prefix matching, so passing in a shorter prefix may read multiple subspaces; paging and precise ranges must also be designed separately. The vector backend must support authorization pre-filtering, or verify candidates with a trusted master database; it cannot first pass other tenant fragments to the model and then let the model "ignore" them.

Memory must carry evidence and update rules

Each memory adds source_id, source_version, created_at, expires_at, confidence and status. Explicit user preferences can be recorded directly; the project facts extracted by the model should retain their sources and be verified by rules or manually. In the event of a conflict, the current trusted source will be given priority, and expired preferences will wait for confirmation; when project rules conflict with user preferences, the authorized project rules will be followed, and selection cannot be based solely on vector scores. Hot path writing tends to increase response delays, while background writing needs to handle duplicate messages, source changes, and authorization changes after the task ends. Writes must also match scope permissions.

Use cross-tenant and cross-project counterexamples for acceptance

Prepare two tenants with the same user name and the same text; check that search, reading by ID, paging, export, cache and logs do not cross the boundary. Retest users exiting the project, preferences expiring, sources being modified, memory conflicts, and prefix searches. The code example uses trusted server parameters to perform precise SQL filtering, and only shows that the allowed range must be determined first; it does not provide real login, project member management or semantic sorting. Adding database row-level policies in production can form an additional line of defense, but the application layer and database layer must share the same tenant semantics.

code example

Minimal example of authorized scope recall

The Python standard library works. The trusted parameter must come from server-side authentication; the example does not have login capabilities, nor does it demonstrate project authorization or vector database.

import sqlite3
c = sqlite3.connect(':memory:')
c.execute('CREATE TABLE memory(tenant TEXT, scope TEXT, owner TEXT, body TEXT)')
c.executemany('INSERT INTO memory VALUES (?,?,?,?)', [('t1','user','u1','prefer Chinese'), ('t2','user','u1','private finance'), ('t1','project','p2','private repository')])
def recall(trusted_tenant, trusted_user):
    return [r[0] for r in c.execute('SELECT body FROM memory WHERE tenant=? AND scope=? AND owner=?', (trusted_tenant, 'user', trusted_user))]
print(recall('t1', 'u1'))
assert recall('t1','u1') == ['prefer Chinese']

expected output

['prefer Chinese']

Engineering deduction

scene
Hypothetical engineering scenario: The same developer participates in the Agent projects of two companies at the same time.
design decisions
Establish precise scope with tenants and projects, verify membership relationships before recalling, and save source versions of project facts.
Verify target
The acceptance goal is that Company A's rules and code summaries do not enter Company B's task context.
applicable boundary
Sample filtering is not a substitute for full authentication, row-level policies, cache isolation, and export permissions.

Continuous questions and answers

Continue reading along with the premises and constraints of the problem. Understand the reference answers first, then try to put away the answers and explain the cause and effect and trade-offs in your own words.

Draw inferences from one example: If the conditions change, how to deduce it?

First find out the conditions for change, and then determine which premises in the original plan still hold true. The following cases are teaching deductions to facilitate the transfer of principles to new problems.

Shared device switching user

Changing conditions:The same browser logs in to different subjects successively

Extended question:Can I continue to read history by retaining the thread ID after changing accounts?

Derivation and reference solutions

The thread ID is just a locator, the reading thread and its checkpoint must verify the current principal and tenant. When switching accounts, clear the local private cache and re-authenticate. Do not treat "knowing the ID" as access capabilities. Shared threads require independent ACLs, and long-term memory is still constrained on a per-source basis.

The principles that remain unchanged:Data location and authorization are independent mechanisms, and interface continuity cannot expand the visible range.

Project transferred to new organization

Changing conditions:Resource ownership changes, and historical memory remains on the old path

Extended question:Is the migration completed by just modifying the namespace prefix?

Derivation and reference solutions

First re-confirm whether the source data and member authorization are transferred with the project, and then migrate the allowed records and source relationships. Organizational rules and personal privacy preferences probably shouldn't be transferred; old paths and caches need to be revoked or cleaned. When verifying cross-organization reads after migration, you cannot default to all historical facts being owned by the new organization.

The principles that remain unchanged:The memory scope expresses the current ownership, and the migration needs to verify the authorization and life cycle of each data.

Easy to make mistakes

  • The model generates tenant_id, which is directly queried
  • Treat similarity scores as permission judgments
  • Only the main library is isolated, cache and logs are not isolated
  • Permanently storing an unsupported fact inferred by the model

References

It is designed based on public technical information; the reference materials support the technical mechanism, and the scenarios and scoring standards are designed by this website and do not represent the original interview questions of a certain company. New Q&A and migration cases are added for principle explanation, and source verification and case operation verification are recorded separately.

Check how far you understand

After reading, you can explain the principles, boundaries, and trade-offs against these standards. It is up to you to evaluate your mastery; if further verification is needed, complete the small tasks below.

Basic standards met
Distinguish between threads, users, projects, and organizational memory.
Intermediate and advanced signals
Construct a namespace from trusted identities and restrict retrieval and writing.
Senior Signal
Ability to check for cross-scope inheritance, conflicts, caching and deletion propagation.

View verification records for independent examples

Continue to do advanced research experiments

Why can’t the old context continue to be used after the policy changes?

Transferring pre-retrieval filtered ideas to memory versions and recovery. Observe how existing drafts become invalid after cancellation.

Read full text and fault analysis → · Download Reliability Experiment v3 ↓

python3 cli.py memory-put --db memory.sqlite
python3 cli.py submit --db memory.sqlite
python3 cli.py run --db memory.sqlite --lease-seconds 2 --fault after_draft
python3 cli.py memory-forget --db memory.sqlite
# 等待至少 2 秒后分别执行
python3 cli.py run --db memory.sqlite
python3 cli.py inspect --db memory.sqlite

Keep evidence and check item by item

  • The draft checkpoint already exists after the first exit.
  • Recovery after memory-forget gets failed with memory_changed_or_expired.
  • No publish checkpoint; explain the difference between fail blocking and complete deletion.

Verify local scope, version, and undo blocking; old checkpoints remain, no complete deletion of logs, backups, or checkpoints is provided.

Hands-on verificationComplete on demand · Suggestions15 minutes

Draw the memory keys and read permissions for two users, two projects.

Expand acceptance requirements and checkpoints
  • Unauthorized records are not shared between different tenants
  • Project temporary status does not become global preference
  • Identity cannot be forged by model parameters

Key inspections

  • Able to distinguish between thread state and cross-thread long-term memory
  • Ability to define write authorization and sharing methods for different scopes
  • Ability to place permission filtering after retrieval instead of answer
  • Able to handle conflicting facts and lapsed memories