Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions docs/architecture/document-sources.md
Original file line number Diff line number Diff line change
Expand Up @@ -1066,6 +1066,9 @@ the public fallback. No reranking provider receives the provisional pools.
and `agent`;
- a marked request writes no recall credit or exposure row, so the usage signals
(`recall_count`, `last_recalled_at`, the usage totals) leave out every marked read;
- a marked request, and a call made inside one, records no
[knowledge-gap miss](knowledge-gaps.md#recording-misses), so the gaps of a namespace
with an active mirrored source form from the `memory.search` calls a caller invokes;
- the assistant's support check reads a marked call as unknown, so a memory it cites
from one gets the reason that the check could not run (`unchecked`), not
`unsupported`;
Expand Down Expand Up @@ -2171,6 +2174,7 @@ Each implementing pull request lists its own; these pin the model:
- A request a mirror leg answered keeping no argument or result-side field the leg
shaped in its `agent_events` row.
- A marked request's trace and exposure rows unchanged by a hidden mirrored hit.
- A marked request, and a call made inside one, recording no knowledge-gap miss.
- A follow-up query a mirror leg shaped leaving the embedding cache untouched.
- A generation over a mirrored chunk capturing no text.
- The sync's audit rows, status, pass notes and log lines naming no mirrored file id
Expand Down
11 changes: 11 additions & 0 deletions docs/architecture/knowledge-gaps.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,14 @@ No miss is recorded:
`single-user`), or for a request without a token, since a gap needs several askers;
- by a search another op runs on a caller's behalf: only the op the caller invoked records
one;
- by a request marked as touching a mirror, or by a call made inside one
(`request_work.mirror_marked()` and `public_diagnostics()`, read first in `record_miss`):
nothing such a request writes outside the mirror depends on what the mirror holds
([document sources: the mirror](document-sources.md#the-mirror)), and a miss is judged
on the answer. With auth on, a `knowledge.search` or `loom_search` over a namespace with
an active `mirrored` source, a `loom_search` whose live leg ran, and a search the
assistant runs for an answer in such a namespace record none, so gaps there form from
the `memory.search` calls a caller invokes. A mark that cannot be read records none;
- for an agent sign-up's service account (registry `kind = 'agent'`), which stands for no
person;
- for a later page (a call with a `page` handle);
Expand Down Expand Up @@ -248,6 +256,8 @@ between.
form.
- A miss is recorded only when the operator opted in and the request's capture level is
not `off`; its asker comes from the token, never the body.
- A request marked as touching a mirror records no miss, and neither does a call made
inside one.

## Source entry points

Expand All @@ -259,5 +269,6 @@ between.
## Related

- [Curation loop design](../development/curation-loop-design.md)
- [Document sources: the mirror](document-sources.md#the-mirror)
- [Rolling upgrades](rolling-upgrades.md)
- [Memory architecture: erasure saga](memory-architecture.md#erasure-saga)
4 changes: 0 additions & 4 deletions docs/development/curation-loop-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -154,10 +154,6 @@ and is not part of this design.
Recording misses, grouping them and `knowledge.gaps.list` are built: [knowledge
gaps](../architecture/knowledge-gaps.md). What the later parts add to them follows.

Once a document can be hidden from some readers (the `mirrored` access of [document
sources](../architecture/document-sources.md)), a `knowledge.search` or `loom_search` that
left out a document its reader may not see records no miss.

### Drafting, query history and review

These paths are implemented in [definition drafts](../architecture/definition-drafts.md),
Expand Down
4 changes: 4 additions & 0 deletions docs/features/knowledge.md
Original file line number Diff line number Diff line change
Expand Up @@ -2331,6 +2331,10 @@ groups the last 7. Once a day the `knowledge_gaps` worker groups a namespace's m
their normalised text, drops every query fewer than `LOOM_KNOWLEDGE_GAPS_MIN_ASKERS`
askers asked in that form, and merges the alike ones.

With auth on, a `knowledge.search` or `loom_search` over a namespace with an active source
whose access follows the store's permissions records no miss, so gaps there form from
`memory.search`.

```bash
curl -s localhost:7777/v1/knowledge.gaps.list -H "Authorization: Bearer $LOOM_API_KEY" \
-H 'content-type: application/json' -d '{"org":"dev","namespace":"local"}'
Expand Down
6 changes: 6 additions & 0 deletions server/knowledge/app/gaps.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
from dataclasses import dataclass
from typing import Any

from server.core import request_work
from server.core.diagnostics import public_diagnostics
from server.knowledge.api.models_gaps import (
KnowledgeGapsListInput,
KnowledgeGapsListOutput,
Expand Down Expand Up @@ -63,6 +65,10 @@ def record_miss(
"""Record one miss of `op` in the background, when gaps are on, `op` is the op the
caller invoked and the token names an asker. Never raises."""
try:
# Nothing a request that touched a mirror writes outside it may depend on what the
# mirror holds, and a miss is judged on the answer: such a request records none.
if request_work.mirror_marked() or not public_diagnostics():
return
if (
not settings.knowledge_gaps_enabled
or len(query) > _MAX_QUERY_CHARS
Expand Down
74 changes: 74 additions & 0 deletions tests/unit/test_knowledge_gaps.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,15 @@

from __future__ import annotations

from collections.abc import Iterator
from contextlib import contextmanager
from datetime import datetime
from typing import Any

import pytest

from server.core import request_work
from server.core.diagnostics import private_work
from server.knowledge.app import gaps as gaps_app
from server.knowledge.domain.gaps import Group, gap_id, merge_groups, normalize_query, ranked
from server.knowledge.store import gaps as gaps_store
Expand Down Expand Up @@ -319,6 +323,58 @@ def test_nothing_is_recorded_while_an_older_replica_serves(
assert scheduled == []


@contextmanager
def _joined_mirror(kind: str, monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:
"""One way a request stands once it joined a per-reader mirror."""
if kind == "marked":
with request_work.bind(request_work.RequestWork()):
assert request_work.mark_mirrored()
yield
elif kind == "private_work":
with private_work():
yield
elif kind == "http_owner":
# The mark sits on the HTTP owner; the call runs under a later bag of its own.
with request_work.http_owner({"type": "http"}):
with request_work.bind(request_work.RequestWork()):
assert request_work.mark_mirrored()
with request_work.bind(request_work.RequestWork()):
yield
else:

def unreadable(scope: Any = None) -> bool:
raise RuntimeError("the mark cannot be read")

with monkeypatch.context() as patch:
patch.setattr(request_work, "http_mirror_marked", unreadable)
yield


@pytest.mark.parametrize("kind", ["marked", "private_work", "http_owner", "unreadable"])
def test_a_request_that_joined_a_mirror_records_no_miss(
scheduled: list[dict[str, Any]], monkeypatch: pytest.MonkeyPatch, kind: str
) -> None:
held: list[str] = []

def hold(coro: Any, *, name: str, scope: Any = None) -> object:
coro.close() # the insert never runs, so a slot it took stays taken
held.append(name)
return object()

bound = settings.knowledge_gaps_max_in_flight
with _joined_mirror(kind, monkeypatch), monkeypatch.context() as patch:
patch.setattr("server.memory.app.after_write.schedule", hold)
patch.setattr(settings, "knowledge_gaps_max_in_flight", 0)
_record()
assert gaps_app.recordings.dropped == 0 # refused ahead of the in-flight bound
patch.setattr(settings, "knowledge_gaps_max_in_flight", bound)
_record()
assert held == [] and gaps_app.recordings.in_flight == 0
# The same call outside the request records its miss.
_record()
assert [r["normalized"] for r in scheduled] == ["what is arr"]


def _cap(name: str) -> int:
field = type(settings).model_fields[name]
[cap] = [m.le for m in field.metadata if getattr(m, "le", None) is not None]
Expand Down Expand Up @@ -593,6 +649,24 @@ def test_loom_search_records_no_miss_under_a_narrowed_token_or_while_disabled(
assert misses == []


def test_a_loom_search_that_joined_a_mirror_records_no_miss(
scheduled: list[dict[str, Any]], monkeypatch: pytest.MonkeyPatch
) -> None:
from server.memory.api.models_loom_search import SearchInput
from server.memory.app.loom_search import handler

monkeypatch.setattr(gaps_app, "current_operation", lambda: "search.query")
monkeypatch.setattr(gaps_app, "reads_whole_namespace", lambda: True)
q = SearchInput(org="o", namespace="ns", query="what is arr")
with request_work.bind(request_work.RequestWork()):
assert request_work.mark_mirrored()
with private_work():
handler._record_gap_miss(q, dict(_EMPTY), "")
assert scheduled == []
handler._record_gap_miss(q, dict(_EMPTY), "")
assert [r["normalized"] for r in scheduled] == ["what is arr"]


def test_knowledge_search_misses_only_with_no_close_keyed_or_lexical_hit(
misses: list[dict[str, Any]],
) -> None:
Expand Down
Loading