Skip to content

Example: retrieval scope chosen from the audience, for a private and a shared reply - #1402

Open
hskl18 wants to merge 3 commits into
ClickHouse:mainfrom
hskl18:feat/1181-audience-scoped-retrieval
Open

hskl18 wants to merge 3 commits into
ClickHouse:mainfrom
hskl18:feat/1181-audience-scoped-retrieval

Conversation

@hskl18

@hskl18 hskl18 commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

Closes: #1181

Changelog category (leave one):

  • Documentation (changelog entry is not required)

Changelog entry (one or two sentences a user of Loom can read without the diff; the release pull request collects these into the release notes):

None.

Why

A host that answers one person in a private conversation and in a shared one has no example of how to keep the shared reply to what its readers may see. The per-user support example keeps two users apart; here the user stays the same and the audience changes.

Scope and risk

No server change. New files: sdk/python/examples/audience_scoped_retrieval.py, docs/guides/audience-scoped-retrieval.md, a unit test and an integration test. Edits: the examples README, the Python SDK reference's example list, a link each from the guides index, the tokens guide and the sharing page, and the regenerated llms.txt.

  • The example plays the agent host with end-user tokens. The person is user:<id>, the private notes are @me, and two collections are granted to the person. A Destination is the host's own record of who reads a reply and which collections they share.
  • Scope of a request: the destination's collections that collection.list, called as the person, also returns. A private conversation gets everything the person reads. The host passes the scope to knowledge.search as namespace and namespaces, and never sends namespace_scope: "all_mine" for a shared destination.
  • The agent reaches Loom through two tools, search(query) and open_citation(handle). Any other tool name or argument is refused before a request is made.
  • Retrieved passages live in one state per person and destination, and deliver refuses a reply whose target is not the destination its context was chosen for.
  • A limit of the existing APIs, stated in the guide: an end-user token carries no namespace claim, so Loom checks that the person may read each collection a search names, and holding a shared request to the destination's collections is the host's choice of namespaces. A claim that caps an end-user token at named collections would move that check into Loom. I did not open an issue for it.
  • The guide also names the scoped token (--namespace-role) for a host that must hand a credential to the agent. On a local server, a scoped token whose subject held grants on two collections got 403 for the one its claim did not name.

Left out, as the issue says: messaging, agent execution, channel membership, and any model call.

Compatibility, rollout and rollback

  • Wire: none; the example calls existing ops.
  • Operator steps: none. Running the example needs an end-user issuer (LOOM_JWT_END_USER_ISSUERS_JSON), which the README section shows for a local server.
  • Rollback: reverting removes the four new files, the README section, the links and the llms.txt line.

Tests

Unit (tests/unit/test_sdk_example_audience_scoped_retrieval.py, 6 tests, a scripted server that keeps grants per signed-in user): every check passes and the run removes what it made; the shared request names the support collection alone; a refused tool call and an unknown destination send nothing; a server that returns a hit from outside the named collections stops the run; a grant that stays after the revoke fails it, and so does a collection that is not deleted. With the search line changed to namespace_scope="all_mine", four of the six fail.

Integration (tests/integration/test_sdk_example_audience_scoped_retrieval.py): the example against a live server with the test end-user issuer; it skips without one.

By hand against a local Loom (ClickHouse 26.10.4 in Docker from dev/ci_start_clickhouse.sh, migrations, one uvicorn server.main:app with auth on, the fake-ngram-1024 embedder): with the test issuer of tests/end_user_issuer.py, pytest tests/integration/test_sdk_example_audience_scoped_retrieval.py tests/integration/test_knowledge_sharing.py has 34 passed. With a key from openssl genrsa registered as the README shows, the README's command printed the run pasted there and exited 0.

Repository checks (Linux, Python 3.12): ruff format --check ., prettier@3.9.9 --check "**/*.{md,yml,yaml}", make lint (with docs_reference.py --check, after llms.txt was regenerated) and make typecheck pass; test_public_copy.py and test_doc_links.py pass; mkdocs build --strict builds the site with the new page. I did not run the biome, taplo and shfmt parts of make format-check; the diff has no file of theirs. pytest bench -q passes (251). pytest tests/unit -n 16, run before the last review fixes, had 46,978 passed and 2 failed, both in test_cross_replica_auth.py (retiring 'k1' would leave no key), which also fail with this change stashed, on the base commit; after those fixes I reran the new test file and the two doc tests (285 passed).

AI assistance in the code (leave one; writing this description with AI is fine):

  • AI-generated (an agent wrote most of the diff): Claude Code wrote the example, tests and guide, and Codex reviewed the diff. I checked each server behaviour the guide states against a local Loom (the search scope fields, the 403 on an unreadable collection, @me, the revoke, the scoped token), ran the example and both tests there, and broke the scope line to see the tests fail.

  • I can explain every line of this diff and how it interacts with the rest of Loom.

Checklist

  • Local format, lint, type checks and focused tests pass. The full make test-unit and applicable integration results are reported by CI; a full local run is not required before pushing. (ruff, prettier, lint, typecheck and the focused tests pass; the biome, taplo and shfmt format checks were not run, see Tests)
  • Generated files are regenerated in this PR, not by hand: the SDK op tables, docs/reference/configuration.md and the docs/reference/ tables (python scripts/codegen/docs_reference.py), the reach manifest, schemas/schema.sql (make schema-dump) and the Codex plugin copies (python3 scripts/codegen/agent_plugin_sync.py). (llms.txt regenerated by docs_reference.py; nothing else applies)
  • A new migration is additive and numbered after the latest on main; no merged migration is edited. (no migration)
  • A behaviour change to any file a plugin ships (hooks/, lib/, bin/, skills/, .mcp.json, the Codex plugin-defaults.json) bumps both plugin manifests' version, and no other open PR uses that version. (no plugin file)
  • The frontend builds (npm --prefix frontend run build) and its tests pass, if frontend/ changed. (not changed)
  • Docs under docs/ describe the system as it now is, and this description names any operator steps and wire changes.
  • Repository text has no dates, people, host names, internal namespaces, ticket or decision numbers; the history goes in this description (tests/unit/test_public_copy.py).
  • Commits are signed off (git commit -s), as CONTRIBUTING.md asks.

…a shared reply

A host that answers one person in a private conversation and in a shared
one had no example of keeping the shared reply to what its readers may
see. The example plays the host with end-user tokens: the scope of a
request is the destination's collections that the person may also read,
passed to knowledge.search as namespace and namespaces. The guide says
which checks Loom makes, which stay with the host, and that an end-user
token cannot be held to a destination's collections.

Closes: ClickHouse#1181
Signed-off-by: hskl18 <thb182003@gmail.com>
@vercel

vercel Bot commented Nov 25, 2026

Copy link
Copy Markdown

@hskl18 is attempting to deploy a commit to the ClickHouse Team on Vercel.

A member of the Team first needs to authorize it.

@cla-assistant

cla-assistant Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@vercel

vercel Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
loom-docs Ready Ready Preview Nov 25, 2026 9:05am UTC

Request Review

@zlareb1 zlareb1 self-assigned this Nov 25, 2026

@zlareb1 zlareb1 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Three focused probes reproduce defects in the example: a reply can outlive its permitted audience, a wide scope exceeds the search request limit, and a note deletion error skips collection cleanup.


def deliver(self, talk: Conversation, destination: str, reply: str) -> str:
"""The last check before a reply leaves: it goes where its context was chosen for."""
if destination != talk.destination:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 — A reply built before an audience change can still be delivered to the same channel. Retrieve a passage, replace the channel's destination record with one that adds a reader and removes the collection, then call deliver with the original conversation. A fresh search returns no passages, but delivery returns the old reply. Bind the draft to the audience and source scope it used, and discard it if that scope is no longer valid at delivery.

… change

Delivery now recomputes the scope and refuses a reply whose destination gained
a reader or lost a source since its passages were retrieved, also when the
record changes while the collections are listed. A scope wider than one
knowledge.search takes (namespace and 100 namespaces) is searched in batches.
Each cleanup delete is tried on its own, so a failed one leaves nothing else
behind.

Signed-off-by: hskl18 <thb182003@gmail.com>
@hskl18

hskl18 commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

All three are fixed in edb37d5.

P1, a reply outliving its audience. deliver now recomputes the scope and refuses the reply when the destination has a reader it did not have at the search, or when a passage's collection is no longer in scope. On that refusal the host drops the conversation's passages, so the next request starts over with the readers and sources the destination has then. Your probe (add a reader and remove the collection, then deliver the old reply) is a unit test, with a second case that adds the reader and keeps the collection. scope and deliver also read the destination record again after collection.list returns, so a record that changes during the listing is caught; that has two test cases, one adding a reader and one removing the source. deliver also refuses a destination the person is not in.

P2, more than 100 namespaces. I took the batch option. A scope wider than 101 collections is searched 101 at a time, and the example keeps the ten nearest passages across the batches by distance. Each batch still returns its top ten in Loom's own ranking, so this is an approximation of one search over the whole scope; the guide says so. The scripted server in the unit tests now answers 422 above 100 namespaces, and a test with 102 readable collections checks the two calls, their sizes, and which passage wins across batches.

P2, cleanup after a failed knowledge.delete. Each delete is tried on its own and every failure is reported after the others have run. A test injects a 400 on the note delete and checks that both collections are still removed and the run exits 1.

The example's run now also checks that a reply drafted before the revoke is not delivered. The guide's delivery section and the README's recorded run are updated to match.

Checks on Linux, Python 3.12, against a local Loom from source: the example's unit tests (12) and the doc tests pass, the live integration test and test_knowledge_sharing.py pass, and make format-check, make lint, make typecheck and mkdocs build --strict pass. I did not rerun the full unit suite for this round.

@zlareb1 zlareb1 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All 12 example unit tests pass, including the wide-scope and cleanup regressions. The delivery check still needs to bind the draft to the context that produced it.

new_reader = talk.readers is not None and not where.members <= talk.readers
if new_reader or any(p["namespace"] not in scope for p in talk.passages.values()):
talk.passages.clear()
talk.readers = None

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 — Clearing the conversation here also clears the evidence that made the draft invalid. The draft is a separate string, so a subsequent delivery attempt can accept that same draft after the passage list and reader snapshot have been cleared. Bind each draft to its context generation and reject drafts from a discarded generation. Cover a delivery retry after a reader joins or a source is removed.

if passage["namespace"] not in await self.scope(talk.person, talk.destination):
raise ScopeRefused(f"{handle} is no longer in scope")
async with self.as_person(talk.person, passage["namespace"]) as loom:
document = await loom.knowledge.get(passage["source_uri"])

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 — The example aborts when collection.list still includes a collection after its grant is revoked. The integration job reports zero passages after the revoke, then knowledge.get raises AuthInsufficient past the tool boundary. A focused probe reproduces that sequence with the collection still listed. Convert the citation read's AuthInsufficient to ScopeRefused and cover this ordering in the unit test. Failed integration job.

…ead is a refusal

A reply refused at delivery could be sent again and pass, because the refusal
cleared the passages and readers it was checked against. A conversation now
counts the contexts it dropped and delivery takes the count a draft was
written under. collection.list can still name a collection whose grant was
just revoked: a citation read or a search Loom answers 403 is now the host's
own refusal and drops the context too.

Signed-off-by: hskl18 <thb182003@gmail.com>
@hskl18

hskl18 commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

Both are fixed in f2d740d.

P1, the same draft sent again. A conversation now counts how many times its context was dropped, and deliver takes the count the draft was written under. A draft from an earlier count is refused, so a retry fails even though the passages and the reader snapshot are gone. The tests cover a reader joining (with the source kept and with it removed) and a source being removed: the first delivery is refused for the change, and each retry for the count, including a retry after a new search.

P2, a revoked collection that collection.list still names. open_citation now turns AuthInsufficient from knowledge.get into ScopeRefused. That read also drops the context, and so does a search Loom answers 403, because in this ordering the listing would still pass an old draft at delivery. A search that finds a held passage's collection out of scope drops it too. The scripted server in the unit tests can keep listing a collection after grants.revoke: one test covers the citation read and the search in that state, and another runs the whole example against it.

After the revoke, the example's run now refuses the old citation as one the conversation no longer holds, and the old draft by its count. The README's recorded run and the guide's delivery section are updated to match. The revoke step moved into its own function to stay under the function-length gate.

Checks on Linux, Python 3.12, against a local Loom from source: the example's unit tests (16) pass, the live integration test and test_knowledge_sharing.py pass (34), and make lint, make typecheck, ruff format --check, prettier and mkdocs build --strict pass. My local server is a single process and never showed the lagging listing, so that ordering is covered by the scripted server only. I did not rerun the full unit suite for this round.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Show how agents select knowledge for private and shared replies

2 participants