powermem icon indicating copy to clipboard operation
powermem copied to clipboard

feat(recall): persist aggregate RecallEffort metrics for bounded-context experiments

Open AlexStocks opened this issue 1 month ago • 3 comments

Feature description

Persist the existing coarse RecallEffort trace as a scope-local daily aggregate when the opt-in recall-sufficiency gate runs.

This is a narrow observability prerequisite for evaluating bounded-context policies. It borrows one portable lesson from Codex: context-management experiments need explicit cost and omission evidence before they change default retrieval behavior. It does not borrow Codex's user-global memory, file-backed authority, model-authored lifecycle citations, or read-path writes.

Related: #1426 (multi-resolution projections), #1698 (governance/diagnostics umbrella), and #1792 (portable Codex ideas).

Problem

RecallEffort is already computed by ScopedContextApplication._prepare and contains only coarse, privacy-safe values: policy ID, assessment, rounds, expansion actions, candidate-pool counts, search-reported additional inference calls, and final byte-budget omissions.

Today it is delivered only to an optional in-process RecallEffortSink. Normal relational Runtime composition passes no sink, so the trace is discarded. pc_recall_token_daily records a separate token-estimation measurement; it cannot answer:

  • how often an enabled recall gate executed one or more expansion rounds;
  • which coarse assessment/expansion path was used;
  • how many candidates the gate assessed across committed rounds;
  • how much additional embedding/rerank work expansion actually caused; or
  • how often final byte budgeting truncated or omitted items.

Without those aggregates, #1426 cannot compare a bounded projection policy with the current behavior using production-shaped cost evidence. A harness-only counter would not establish Runtime behavior; conversely, putting entry IDs, query text, or prompt bodies into production telemetry would violate the existing non-leakage design.

Proposed implementation

1. Keep RecallEffort as the source of truth

Do not duplicate recall-loop accounting in a host, an evaluation adapter, or a second search path.

  • Reuse the existing RecallEffort value assembled in builtin/runtime/recall_sufficiency.py.
  • Preserve its current semantics: rounds is committed search passes; candidates_by_round is the untruncated pool seen by the gate; added_embeddings and added_generation_calls are search-reported, not estimated; omission fields come from PreparedContextBuild.
  • Emit one aggregate observation per RecallEffort delivered to the sink. Do not synthesize observations when the gate is disabled, and do not change the existing disabled-gate behavior.
  • A failed statistics write must be best-effort: log a structured safe failure and still return the same prepare_context result. It must not retry inside the request's critical path, alter a Memory/Artifact revision, or turn a ready result into an error.

2. Add a dedicated aggregate, not per-entry telemetry

Add a new statistics relation, tentatively named pc_recall_effort_daily, and include it in the normal statistics table set. Do not overload pc_recall_token_daily: its estimator identity and baseline/recalled-token semantics are different.

The primary key must be bounded and scope-safe:

(scope_id, usage_date, policy_id, assessment)

Use the repository's validated Scope identity/column conventions. The row contains additive counters only:

preparations
rounds
expanded_preparations
admission_expansions
policy_floor_expansions
candidate_round_samples
candidates_assessed
final_candidate_pool
added_embeddings
added_generation_calls
truncated_items
dropped_items
dropped_below_min_bytes
dropped_no_fitting_truncation

Definitions:

  • expanded_preparations: number of efforts where rounds is greater than 1.
  • admission_expansions and policy_floor_expansions: total occurrences of the corresponding values in expansion_actions.
  • candidate_round_samples: sum of len(candidates_by_round).
  • candidates_assessed: sum of every value in candidates_by_round.
  • final_candidate_pool: last candidates_by_round value, or zero only if the existing type permits an empty sequence.
  • All omission counters preserve the existing RecallEffort meanings. dropped_items must remain the sum of its two subclasses.
  • All values are non-negative. No counter may represent a Memory entry, Artifact, Source, citation, prompt, query, vector, text body, or user identity beyond the existing scope_id.

Upsert atomically per daily key. The schema/open path must work for both SQLite and OceanBase existing deployments; use the repository's established additive-schema approach when an existing database needs a new relation. Do not introduce a second scheduler, a lease, a background worker, or an external service for this write.

3. Wire the recorder at the Runtime boundary

Provide a relational RecallEffortSink/recorder through the normal Runtime composition path, close to the existing recall-token estimator and statistics services.

Required properties:

  • The recorder receives the already-built RecallEffort; it must not query Memory, rerun search, reconstruct candidates, or inspect PreparedContext text.
  • It writes under the caller's validated scope and normal statistics connection/timeout discipline.
  • It is not exposed as an HTTP/MCP operation in this issue.
  • prepare_context HTTP/MCP schemas, Context Pack JSON, exact citations, host integration payloads, retrieval ordering, and default gate configuration stay byte-for-byte compatible.
  • A caller-supplied recall_effort_sink remains usable for tests/embedding. Define one composition rule and test it explicitly; do not silently double-record an effort.
  • Record only when the gate actually produces RecallEffort. A disabled gate must retain the existing zero-sink-call contract.

4. Harness boundary

The evaluation harness may consume this aggregate later, but it must not implement or define the feature.

  • No projection, reranking, compaction, source filtering, usage_count, or retention policy belongs in evaluation/ for this issue.
  • Do not add a new experiment arm, alter an existing LongMemEval/LoCoMo answer score, or claim task-quality improvement.
  • Production Runtime tests establish accounting and failure semantics. Evaluation work may only add a read-only consumer in a follow-up under #1426 after the stored metric contract exists.
  • The daily aggregate is operational/evaluation evidence, not a correctness gate: missing or failed telemetry must not block recall, artifact writes, or host injection.

Non-goals

  • No L0/L1/L2 projection implementation; that remains #1426.
  • No change to scope_id semantics or cross-Scope aggregation.
  • No user-global or project-global memory store.
  • No model-generated Memory extraction, consolidation agent, filesystem memory workspace, or Git-baseline mechanism.
  • No model-authored citation parsing and no read-path mutation.
  • No per-entry/per-source usage counters, provenance-ranking change, eviction/retention policy, or automatic forgetting.
  • No public statistics API, dashboard feature, OpenAPI change, MCP operation, or integration capability change in this issue.
  • No decision-model policy, new provider dependency, or new background scheduler.

Acceptance criteria

  • [ ] With the recall gate enabled, a preparation that yields RecallEffort creates or atomically increments exactly one matching daily aggregate row.
  • [ ] Aggregate values exactly match a constructed effort with both expansion actions, multiple committed rounds, nonzero added inference costs, truncation, and both drop subclasses.
  • [ ] The two drop subclasses always sum to dropped_items; invalid/inconsistent input is rejected before persistence rather than silently repaired.
  • [ ] A repeated preparation accumulates additive counters without duplicating or changing the primary-key dimensions.
  • [ ] Two Scopes with the same policy and assessment produce isolated rows; no query or aggregate exposes a Memory entry, Artifact, Source, prompt, query, or citation.
  • [ ] A disabled recall gate leaves no recall-effort row and preserves the existing RecallEffortSink non-invocation behavior.
  • [ ] An injected recorder/storage failure logs safely and does not change the public prepare_context outcome, prepared bytes, citations, omissions, retrieval order, or Artifact/Memory revision state.
  • [ ] Existing SQLite and OceanBase schema initialization/open tests cover the new relation. The implementation does not rely on a fresh database only.
  • [ ] Existing recall-sufficiency, prepared-context, statistics, and context e2e tests still pass.

Test placement

Use focused tests at the owning boundaries:

  • tests/builtin/runtime/test_recall_sufficiency.py: validate mapping/invariants from RecallEffort to the persistable aggregate; no database required.
  • tests/builtin/persistence/ and backend contract coverage: atomic upsert, daily-key isolation, zero-content schema, and SQLite/OceanBase compatibility.
  • tests/e2e/test_recall_sufficiency_gate.py: enabled recording, disabled no-op, cross-Scope isolation, and recorder failure preserving a ready preparation.
  • tests/builtin/runtime/test_statistics.py: include the new table in bounded statistics-read accounting only if the statistics overview is intentionally extended. Do not add a table scan merely because the table exists.

Do not replace these with a mock-only assertion that a sink callback happened. At least one e2e test must exercise open_builtin_runtime, a real preparation, and the real relational statistics store.

Verification

Run focused checks first, then the affected contract suite:

uv run pytest tests/builtin/runtime/test_recall_sufficiency.py tests/e2e/test_recall_sufficiency_gate.py tests/builtin/runtime/test_statistics.py -q
uv run pytest tests/builtin/persistence -k "statistic or schema or recall" -q
uv run prek run -a

Run the relevant SQLite and OceanBase persistence contract tests if the repository's existing test selection distinguishes them. Do not report a harness score or a production quality improvement as acceptance evidence for this issue.

Design references

  • src/powercontext/builtin/runtime/recall_sufficiency.py: coarse RecallEffort contract and non-leakage boundary.
  • src/powercontext/builtin/runtime/application.py: existing sink delivery and safe failure handling.
  • src/powercontext/builtin/runtime/composition.py and relational.py: Runtime wiring seam.
  • src/powercontext/builtin/persistence/statistics.py and tables.py: daily aggregate storage pattern.
  • RFC 1560: recall-sufficiency gate accounting and experimental/default-off constraints.
  • #1426: subsequent policy evaluation consumer, not implementation scope here.

AlexStocks avatar Oct 08 '26 13:10 AlexStocks

please assign for me

chenncy avatar Oct 08 '26 14:10 chenncy

ask for assign, but i see @chenncy wants to solve this, maybe we can like: who resolves this first, who done . that avoid the cost of time. everybody just push pr by theirself, no needs too much cares about the "assign"

AsperforMias avatar Oct 08 '26 14:10 AsperforMias

ask for assign, but i see @chenncy wants to solve this, maybe we can like: who resolves this first, who done . that avoid the cost of time. everybody just push pr by theirself, no needs too much cares about the "assign"

ok. I assign it to @chenncy

AlexStocks avatar Oct 08 '26 15:10 AlexStocks