Skip to content
Agent Field Notes
Course contentsExpand a topic to choose a lesson.

SYSTEMATIC LEARNING / FOUR-LEVEL COURSE

Hard filters, value ranking, and causal evaluation in memory retrieval

Examining memory retrieval stratification, relevance, authority, temporality, and counterfactual assessment.

Learning objectives: First use authorization, revocation and validity period to determine the memory that can be used, and then select a small amount of content based on task benefits. Hit rates describe recall behavior, and only task comparisons can prove that memory creates value.

Content checked: 2026-10-03 · Each level has independent explanations, tasks and inspections

Choose a starting point based on your familiarity with this topic. Current level: Design · Explain the trade-offs. After completing the task, continue to the next level. Reading and self-checks alone do not establish mastery.

On this level

Review the prerequisites

Suitable for: Backend developers learning Agent applications.

Hard filters, value ranking, and causal evaluation in memory retrieval
First use authorization, revocation and validity period to determine the memory that can be used, and then select a small amount of content based on task benefits. Hit rates describe recall behavior, and only task comparisons can prove that memory creates value.

How does the mechanism work?

Step-by-step explanation
  1. What should I do if the revocation record still remains in the vector index?

    As scale grows, index consistency becomes a practical limit on validity filtering.

  2. How to use high similarity and low credibility?

    Candidates that pass hard filters can still differ in trustworthiness.

  3. How to prove that the memory module is really useful?

    Move evaluation from internal retrieval metrics back to user-task outcomes.

Design · Explain the trade-offs

Changed constraints and integration decision

Objectives of this level: current memory eligibility, key precedence and context fitting — Apply a changed constraint and scope the proposed platform adapter.

Visual guide · Eligibility before memory ranking

Eligibility before memory ranking

Greedy score ordering is this lab’s policy, not a global optimum. Retrieval hits do not prove task benefit, and remembered preferences grant no approval. Select the figure to open it at full size.

Changed constraints and integration decision

Hold the scores fixed and change principal.epoch to3: all epoch2 records disappear. Mark a high-score style duplicate revoked: the lower authorized m-style can still be selected. Compare no memory/current structured constraints/this selected set on the same future task corpus with business success,wrong personalization and cost denominators; these fixtures alone do not measure memory benefit. Deliver a new-input JSON/result pair, an adapter boundary sketch and a short ADR comparing two alternatives, rejection/reconciliation behavior, ownership and reversal conditions. State implemented_local versus planned; connect to the same after-sales proposal/approval/merchant/receipt chain without inventing existing runtime features. Save the following block as memory_retrieval_budget_variants.py beside your student module, then run it after implementation. It imports your own function, reads the public complete inputs and changes the declared fields; these two rule-visible variants are not unseen assessment.

import copy, json
from pathlib import Path
from memory_retrieval_budget_student import select_memory

checks = json.loads(Path("cases/memory-retrieval-budget.json").read_text())["checks"]

payload = copy.deepcopy(checks[0]["input"])
payload["principal"]["epoch"] = 3
before = copy.deepcopy(payload)
try:
    actual = select_memory(payload)
except ValueError as exc:
    actual = "ValueError:" + str(exc)
assert payload == before, "input_mutation"
expected = {'ids': [], 'used': 0, 'remaining': 5}
assert actual == expected, (actual, expected)
print(json.dumps({"variant":1,"input":payload,"actual":actual}, sort_keys=True))

payload = copy.deepcopy(checks[9]["input"])
payload["records"][-1]["revoked"] = True
before = copy.deepcopy(payload)
try:
    actual = select_memory(payload)
except ValueError as exc:
    actual = "ValueError:" + str(exc)
assert payload == before, "input_mutation"
expected = {'ids': ['m-style', 'm-locale'], 'used': 5, 'remaining': 0}
assert actual == expected, (actual, expected)
print(json.dumps({"variant":2,"input":payload,"actual":actual}, sort_keys=True))
python3 memory_retrieval_budget_variants.py

Starting point and evidence

Download the source-only ZIP, extract it, and work in extended-agent-practice-v1 with lab_runner.py beside cases/. Python3.9+ standard library; no model, cloud, network or business request is made. Scaffold once in a fresh directory; it refuses overwrite. Reuse your module in later tracks. The empty template must exit1 on grade; scaffold exits0, overwrite exits2. Grade exits0 only when every fixed case passes and otherwise exits1.

  • https://ai.lwkjob.com/downloads/extended-agent-practice-v1.zip
  • https://ai.lwkjob.com/lab/extended-practice/lab_runner.py
  • https://ai.lwkjob.com/lab/extended-practice/cases/memory-retrieval-budget.json
python3 lab_runner.py scaffold --course memory-retrieval-budget --out memory_retrieval_budget_student.py
python3 lab_runner.py grade --course memory-retrieval-budget --module memory_retrieval_budget_student.py --out memory_retrieval_budget_before.json

This course has12 public fixed cases. Each calls your select_memory(payload), records input/expected/actual/error, strict JSON types, input immutability and no output-container aliases, plus module/runner/cases SHA and Python version. Inputs are complete JSON fixtures. Unknown or missing keys, null outside explicitly allowed fields, wrong types, duplicate IDs/list members where uniqueness is required raise ValueError:input_shape; booleans are not integers. Exceptions match exact class:message. Return fresh JSON values without mutating input.

Trusted identity, approvals, receipts and policy/index metadata are fixtures assembled by the exercise. In a real service the server must obtain them from authenticated/current authority sources; accepting client JSON with these labels does not authenticate it. The function is a decision over that trusted snapshot, not the adapter or race-proof enforcement.

Local function contract

payload exactly principal/now/budget/current_keys/records. principal exactly tenant/user/project(nonempty str),epoch(strict positive int),enabled(strict bool). now/budget strict nonnegative int; current_keys is a unique nonempty str list, possibly empty. records may be empty; each exactly id/tenant/user/project/key(nonempty str),epoch/tokens(strict positive int),score(strict nonnegative int),confirmed/revoked(strict bool),expires_at(None or strict nonnegative int); IDs unique globally. Shape errors first. Keep only enabled principal,same tenant/user/project/epoch,confirmed=True,revoked=False,expires_at>now or None,key absent from current_keys. Sort score descending then id ascending. Keep only the first eligible row per key BEFORE fitting budget; if it is too large, skip that key, not fall back to a weaker duplicate. Continue to other keys that fit. Return exactly ids(in selection order),used(sum teaching token units),remaining(budget-used). Empty/disabled/zero-budget returns empty IDs,used0,unchanged remaining. No tokenization or knapsack optimization is performed.

def select_memory(payload):
    raise NotImplementedError("Implement the public local contract")

Three reviewable inputs

exact-budget

{
  "principal": {
    "tenant": "acme",
    "user": "alice",
    "project": "after-sales",
    "epoch": 2,
    "enabled": true
  },
  "now": 10,
  "budget": 5,
  "current_keys": [],
  "records": [
    {
      "id": "m-style",
      "tenant": "acme",
      "user": "alice",
      "project": "after-sales",
      "epoch": 2,
      "key": "style",
      "tokens": 3,
      "score": 80,
      "confirmed": true,
      "revoked": false,
      "expires_at": null
    },
    {
      "id": "m-locale",
      "tenant": "acme",
      "user": "alice",
      "project": "after-sales",
      "epoch": 2,
      "key": "locale",
      "tokens": 2,
      "score": 70,
      "confirmed": true,
      "revoked": false,
      "expires_at": null
    }
  ]
}

Expected / 预期: {"ids": ["m-style", "m-locale"], "remaining": 0, "used": 5}

revoked-high-score

{
  "principal": {
    "tenant": "acme",
    "user": "alice",
    "project": "after-sales",
    "epoch": 2,
    "enabled": true
  },
  "now": 10,
  "budget": 5,
  "current_keys": [],
  "records": [
    {
      "id": "m-style",
      "tenant": "acme",
      "user": "alice",
      "project": "after-sales",
      "epoch": 2,
      "key": "style",
      "tokens": 3,
      "score": 80,
      "confirmed": true,
      "revoked": false,
      "expires_at": null
    },
    {
      "id": "m-locale",
      "tenant": "acme",
      "user": "alice",
      "project": "after-sales",
      "epoch": 2,
      "key": "locale",
      "tokens": 2,
      "score": 70,
      "confirmed": true,
      "revoked": false,
      "expires_at": null
    },
    {
      "id": "m-revoked",
      "tenant": "acme",
      "user": "alice",
      "project": "after-sales",
      "epoch": 2,
      "key": "style",
      "tokens": 3,
      "score": 100,
      "confirmed": true,
      "revoked": true,
      "expires_at": null
    }
  ]
}

Expected / 预期: {"ids": ["m-style", "m-locale"], "remaining": 0, "used": 5}

small-budget-skip-costly

{
  "principal": {
    "tenant": "acme",
    "user": "alice",
    "project": "after-sales",
    "epoch": 2,
    "enabled": true
  },
  "now": 10,
  "budget": 2,
  "current_keys": [],
  "records": [
    {
      "id": "m-style",
      "tenant": "acme",
      "user": "alice",
      "project": "after-sales",
      "epoch": 2,
      "key": "style",
      "tokens": 3,
      "score": 80,
      "confirmed": true,
      "revoked": false,
      "expires_at": null
    },
    {
      "id": "m-locale",
      "tenant": "acme",
      "user": "alice",
      "project": "after-sales",
      "epoch": 2,
      "key": "locale",
      "tokens": 2,
      "score": 70,
      "confirmed": true,
      "revoked": false,
      "expires_at": null
    }
  ]
}

Expected / 预期: {"ids": ["m-locale"], "remaining": 0, "used": 2}

Responsibility and limits

Junior implements authorized selection with exact budget boundaries. Intermediate would recheck metadata at body release and cache reads and measure ablation on unchanged tasks. Senior owns current-source dependencies, index lag/copy invalidation and workload/retention policies. These integer costs are authored units, not provider token usage, model relevance or production effectiveness. The four tracks are learning activities, not job ranks. Fixed authored examples and known repairs cannot prove independent diagnosis, real-world security or hiring readiness. Keep source, initial failure, personal diff, same-input rerun and a declared changed-condition result. A reviewer-new complete contract and observed personal work are separate; disclose assistance. The five-second worker guard is not a performance SLO or hostile-code sandbox.

code example

Changed constraints and integration decision — small-budget-skip-costly

Additional review: explain why this case follows the contract and which single-field change would alter the branch. Public case: small-budget-skip-costly Expected / 预期: {"ids": ["m-locale"], "remaining": 0, "used": 2} https://ai.lwkjob.com/lab/extended-practice/cases/memory-retrieval-budget.json

Acceptance task for this level

current memory eligibility, key precedence and context fitting — Execute the declared changed inputs and deliver result pairs plus an adapter/ADR with implemented versus planned boundaries.

Acceptance self-checks

Reading this browser’s record…

Hide the answer and check your understanding

Can the twelve local selection cases prove memory improves tasks?

Further explanations and practice

When encountering unfamiliar principles, first read the implementation, continuous questioning and migration cases, and then independently explain the premise and boundaries. Answers and notes are saved to the original account record.

All linked explanations and exercises (1 )

Sources and verification scope

The principles are based on public information; the numbers, cases and tasks are the teaching design of this website. Offline experiments verify the range noted on this page, and the learning effect still needs to be judged through independent tasks and feedback.