Skip to content

DSPy retrievers over Loom knowledge and memory search - #1049

Merged
zlareb1 merged 1 commit into
ClickHouse:mainfrom
rahulsjha:feat/dspy-retriever
Nov 20, 2026
Merged

zlareb1 merged 1 commit into
ClickHouse:mainfrom
rahulsjha:feat/dspy-retriever

Conversation

@rahulsjha

Copy link
Copy Markdown
Contributor

Closes: #716
Related: #650

Changelog category (leave one):

  • New Feature

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):

The Python SDK has DSPy retrievers: loom.integrations.dspy.LoomKnowledgeRetriever and LoomMemoryRetriever search Loom documents and memories and return a dspy.Prediction whose passages come with their sources, and as_tool() hands the same search to dspy.ReAct. Install with pip install 'clickhouse-loom[dspy]'.

Why

Loom has adapters for LangChain, LlamaIndex, Haystack and others, but none for DSPy. A DSPy program had to call the SDK inside its own module and rebuild the passages and citations by hand.

Which DSPy interface, and why (the issue's first acceptance item; also posted on the issue). I checked DSPy 3.5.0, the current release:

  • dspy.configure(rm=...) read through dspy.Retrieve still exists, but Retrieve.forward keeps only each passage's long_text. The sources would be dropped.
  • DSPy's own retriever, dspy.retrievers.Embeddings, is a plain class whose __call__(query) returns dspy.Prediction(passages=..., indices=...). Programs call it in forward or hand it to dspy.ReAct as a dspy.Tool.

So both retrievers are plain callables in that shape:

with SyncAgent(org="acme", namespace="support") as agent:
    found = LoomKnowledgeRetriever(agent, k=3)("refund policy for annual plans")
    found.passages  # ["Annual plans refund pro rata.", ...]
    found.sources   # ["support/doc://refunds#2", ...]
    react = dspy.ReAct("question -> answer", tools=[LoomMemoryRetriever(agent, user_id="alice").as_tool()])
  • Output. A dspy.Prediction with passages (the texts), sources, scores (similarity, 4 places) and metadata, in the same order. The metadata dicts hold the same keys as the LangChain retrievers' Document.metadata.
    • A knowledge source is <namespace>/<source_uri>#<chunk_idx>, the same as the LangChain document id.
    • A memory source is <namespace>/<memory_key>.
  • Fields. The same as the LangChain retrievers (k, search_tags, uri_prefix, namespace_scope, search_kwargs; memory_type, user_id, session_id, run_id, agent_id, honour_abstain), and they are sent the same way. namespace_scope is always sent. Memory search asks for bodies="full" and explain=False, and keeps Loom's abstain and below-floor handling. k can be overridden for one call, and it must be a positive int.
  • Sync and async. A call needs a SyncAgent, and the error message points to acall when given an Agent. await acall(query) takes either. With a SyncAgent the blocking call runs off the event loop.
  • ReAct. as_tool(name=None) returns a dspy.Tool named loom_search_documents or loom_search_memories. It returns one [source] passage line per hit, so the model sees what to cite. With an Agent the tool is async, for ReAct.acall.
  • Errors. A search error is raised, not turned into an empty result. An empty search is an empty prediction.
  • Session protection. Retained the same way as in the LangChain retrievers (_CallbackProtection, automatic or observing per call).

Scope and risk

  • New: sdk/python/loom/integrations/dspy.py and sdk/python/tests/test_dspy.py.
  • Registration:
    • The dspy extra (dspy>=3.5,<3.6).
    • dspy in SDK_ADAPTER_EXTRAS.
    • dspy and dspy.* in the root mypy ignore_missing_imports list for framework adapters.
  • Docs:
    • A row and a ## DSPy section in frameworks.md.
    • The framework list in integrations/index.md. Prettier re-aligned that table, which accounts for most of the file's diff.
    • A bullet in python-sdk.md.
    • The [dspy] extra in the adapters sentence of sdk/python/README.md.
  • Unchanged: server code, wire ops, the SDK clients and the other adapters. The module only reads through agent.knowledge.search and agent.memory.search.
  • Lock files: uv.lock is unchanged; it doesn't lock the SDK's adapter extras.

Compatibility, rollout and rollback

  • Wire: none. No op, field or default changes.
  • Operator steps: none. Users install the [dspy] extra.
  • Rollback: reverting removes the module, the extra and the docs. Nothing is stored.

Tests

Run on Linux (Ubuntu 22.04, uv 0.11.26):

  • make test-sdk-adapter-dspy (Python 3.12, dspy 3.5.0, highest resolution): 39 passed. mypy --strict passes for dspy.py, __init__.py, langgraph.py and strands.py.
  • make test-sdk-adapter-dspy SDK_ADAPTERS_PYTHON=3.11 SDK_ADAPTERS_RESOLUTION=lowest-direct: 39 passed, and mypy --strict passes.
  • pytest tests/unit/test_sdk_extra_requirements.py tests/unit/test_doc_links.py tests/unit/test_public_copy.py: 252 passed.
  • python -m scripts.codegen.docs_reference --check: current.
  • scripts/gates/sdk_wheel_smoke.py on a freshly built wheel in a clean venv: clickhouse-loom 1.3.0 ok on Python 3.12.13.
  • ruff format --check and ruff check (0.16.9): clean. Function-length gate: 54, at its baseline. mypy --strict sdk/python/loom: no issues in 70 files.
  • [email protected] --check on the four Markdown files and taplo format --check: clean.

What test_dspy.py covers:

  • The passages, sources, scores and metadata for knowledge and memory hits, including a fanned-out hit named by its own namespace.
  • The exact search fields sent, with optional fields only when set.
  • A per-call k, and a non-int, zero, negative or bool k refused.
  • Abstain and below-floor rows, with honour_abstain on and off.
  • An empty result, and an error raised.
  • Call versus acall on both agent types.
  • Use inside a dspy.Module.
  • as_tool() metadata, sync and async.
  • A full dspy.ReAct run with DSPy's DummyLM: one turn calls loom_search_documents, the next submits. It checks that the tool was called once and that the cited passage came back without error.
  • The ImportError naming clickhouse-loom[dspy].
  • Real Agent and SyncAgent clients with only the HTTP boundary stubbed: the knowledge.search and memory.search bodies.
  • Session protection: contributors retained across a client rebind for both retrievers in async, sync and thread modes, and explicit retrieval staying explicit.

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. I checked the interface against the installed DSPy 3.5.0 source (dspy/retrievers/retrieve.py, embeddings.py, predict/react.py, adapters/types/tool.py), matched every field and the abstain handling to the LangChain retrievers, and ran every check above myself.

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

Checklist

  • make format-check, make lint, make typecheck and make test-unit pass; the integration suite passes if server behaviour changed. (Run locally: ruff format and check, Prettier and Taplo on the changed files, the function-length gate, mypy --strict sdk/python/loom, and the unit tests the issue names. Not run locally: the full test-unit suite and the repo-wide mypy gate, which cover server code this PR doesn't touch; CI runs both. No server behaviour changed.)
  • Generated files are regenerated in this PR, not by hand: docs_reference --check is current; no SDK op tables change.
  • A new migration is additive and numbered after the latest on main; no merged migration is edited. (None.)
  • A behaviour change to any file a plugin ships bumps both plugin manifests' version. (None.)
  • The frontend builds 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 (tests/unit/test_public_copy.py passes).
  • Commits are signed off (git commit -s), as CONTRIBUTING.md asks.

Copilot AI balanced review requested due to automatic review settings November 20, 2026 14:06
@vercel

vercel Bot commented Nov 20, 2026

Copy link
Copy Markdown

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

A member of the Team first needs to authorize it.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@zlareb1 zlareb1 self-assigned this Nov 20, 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.

No blocking findings on e429256. Checked search arguments, abstention, namespace attribution, sync and async calls, tool output, and session protection against the existing SDK paths.

Validation: make test-sdk-adapter-dspy passes all 39 tests and strict type checks. CI remains a separate merge gate.

@zlareb1

zlareb1 commented Nov 20, 2026

Copy link
Copy Markdown
Member

The unit part 6 failure in test_timely_actual_http_reply_keeps_local_phase_bounds[success] reproduces with a controlled 80 ms scheduling pause on this head, its base, and clean main. Existing repair #1039 gives the exchange a private clock; the same test passes with the same pause. Reusing that repair avoids a duplicate.

@zlareb1
zlareb1 merged commit 721ed13 into ClickHouse:main Nov 20, 2026
53 of 55 checks passed
zlareb1 added a commit that referenced this pull request Nov 20, 2026
* Close preparation spends the shared session-end deadline

Signed-off-by: zlareb1 <[email protected]>

* Drive placement deadline tests with a private clock

Use one idle-driven clock for the mock exchange timers and owned close. Keep the six cases and their bounds, with a private-loop task census at teardown.

Signed-off-by: zlareb1 <[email protected]>
(cherry picked from commit e1f47e6)

* Drive directory cleanup checks with one private clock

Signed-off-by: zlareb1 <[email protected]>

* Docs: serve documentation from the docs subpath (#1042)

* Serve documentation from the docs subpath

The documentation build keeps its links, assets, and discovery files below the configured path.

Signed-off-by: Shaun Struwig <[email protected]>

* Trigger documentation preview

Signed-off-by: Shaun Struwig <[email protected]>

* Redirect documentation preview root

Preview deployments open the documentation path when their root URL is requested.

Signed-off-by: Shaun Struwig <[email protected]>

* Placement deadline tests use one simulated clock

Work deadlines, cleanup, and the elapsed-time assertion use one private clock.
The selector advances it when the loop waits, so scheduler pauses cannot expire
a simulated reply or consume its cleanup allowance. Keep all six cases and
their duration bounds, and fail teardown if the private loop retains a task.

Signed-off-by: Lareb Zafar <[email protected]>

---------

Signed-off-by: Shaun Struwig <[email protected]>
Signed-off-by: Lareb Zafar <[email protected]>
Co-authored-by: Lareb Zafar <[email protected]>

* DSPy retrievers over Loom knowledge and memory search (#1049)

* memory.ask matches bridge slugs literally (#1037)

* memory.ask matches bridge slugs literally

Escape LIKE metacharacters so slug underscores cannot select another subject.

Signed-off-by: Lareb Zafar <[email protected]>

* Expect literal bridge slugs in the governed-conflict test

The namespace regression must assert the escaped pattern used by the subject filter.

Signed-off-by: Lareb Zafar <[email protected]>

---------

Signed-off-by: Lareb Zafar <[email protected]>

* Record worker context after linear-cost assertions fail (#1058)

Selected durations alone omit worker allocation and collection state. Attach numeric context after the original assertion fails so the cost calls and decision remain unchanged.

Signed-off-by: zlareb1 <[email protected]>

* Document memory selection for coding agents and software factories (#1021)

* Document memory selection for coding agents and software factories

Give the existing use-case pages distinct search titles and concrete recall, isolation and evidence-handoff checks without claiming comparative results.

Signed-off-by: zlareb1 <[email protected]>

* Format coding-agent and factory memory selection tables

Signed-off-by: zlareb1 <[email protected]>

---------

Signed-off-by: zlareb1 <[email protected]>

* Document memory write and worker progress regression tests (#1043)

* Document memory write and worker progress regression tests

Exercise derived effects, stored cursors and complete SQL rows so regression checks observe the boundaries they claim to protect.

Signed-off-by: Lareb Zafar <[email protected]>

* Test warm worker passes beside cursor restarts

A restart can recover a missed boundary event through cold reconciliation, so the guide must retain warm continuation regressions.

Signed-off-by: Lareb Zafar <[email protected]>

* Concurrency tests cover changed content at an equal version

Signed-off-by: Lareb Zafar <[email protected]>

* Document committed-write cleanup and private cache regression tests

Cancellation during fence release must not skip effects owed by an acknowledged
write. Caches of private strings need retention and erasure coverage as well as
result checks.

Signed-off-by: Lareb Zafar <[email protected]>

---------

Signed-off-by: Lareb Zafar <[email protected]>

* Framework examples select matching SDK artifacts (#1064)

* Framework examples select matching SDK artifacts

Signed-off-by: zlareb1 <[email protected]>

* Framework examples install matching published SDKs

Select available stable artifacts and their native peers, keeping DSPy on its matching checkout. Give the invalid-identity fixture its own product clock so semantic closure assertions do not spend real phase time. Preserve all real deadline and cancellation cases.

Signed-off-by: zlareb1 <[email protected]>

---------

Signed-off-by: zlareb1 <[email protected]>

* Pin retriever installation to available SDK packages (#1061)

* Pin retriever installation to available SDK packages

Signed-off-by: zlareb1 <[email protected]>

* LangChain examples select published SDK artifacts

Install the matching stable SDKs and the declared native peer. Validation fixtures establish a post-exec witness and completed backend termination before checking successor ownership.

Reuses the complete published witness repair from 9ffae96 (#1046).

Signed-off-by: zlareb1 <[email protected]>

---------

Signed-off-by: zlareb1 <[email protected]>

* Cell checks share topology and catalog helpers (#906)

Related: #776

### Changelog category

- Improvement

### Changelog entry

Cell checks share topology, catalog and synchronization helpers across command and server code.

### Why

Complete cell reads depend on topology validation, the caller's effective privileges, replica identity and synchronization. These implementations live in CLI modules, which server code cannot import. Shared owners let both layers use the same checks without copying them.

### Scope and risk

The complete topology module moves to `server/core/cell_ch.py`. Catalog, grant, default-role, row-policy and replica checks move to `server/insights/store/cell_catalog.py`; synchronization and budget helpers move to `server/core/cell_sync.py`. Callers and test patch points use those owners, and the old topology module is deleted.

SQL, query settings and tags, defaults, refusal conditions, exception identity, row interpretation and ordinary update behavior remain unchanged. A missed caller import or patch point is the main risk. Bounded participant and observation joins remain unimplemented; this extraction adds no later-cell activation or readiness result.

The configuration and placement foundation is merged. Its raw connection ownership, retirement admission, typed configuration refusal, deadlines and cleanup remain intact when the shared imports compose with it.

### Compatibility, rollout and rollback

- Wire and defaults: unchanged; no operations, arguments, settings, tables or stored encodings are added.
- Operator steps: none.
- Rollback: reverting restores the former internal owners and callers; there is no stored data transition.
- The English architecture page names the shared topology owner. Existing translated code references await the normal translation workflow; translated files are unchanged.

### Tests

- Static bindings retain all 37 moved definitions, all 574 audited test assertions and the single unique moved topology assertion. The merged foundation's 577 assertions in the audited test modules remain in source order, with only the sixteen existing shared-owner reference substitutions. Production assertion relocations retain their conditions and multiplicity. The older reported total counted the moved topology assertion in both source images; no assertion was removed.
- The local attempt to run sixteen directly related pure selectors is refused before a test child starts because admission detects an unknown test process. No current test pass is claimed. Source and Git state match before and after the refusal. The same selectors historically pass as 34 parameterized cases on the earlier source, covering complete replica union, topology and synchronization refusal, privileges, caller identity, row policies, extra replicas, streaming failures and budget behavior. Those passes retain their original source attribution.
- Current scoped Ruff checks and formatting checks pass for all 25 changed Python files, and the concern diff passes whitespace checks. The earlier focused attempt lacking its complete source snapshot remains invalid; its passing output is not used as evidence. Historical focused passes retain their original source attribution.
- The actual merged-parent adoption resolves one import conflict while retaining both shared refusal owners and the existing retirement implementation. Static comparison with the later target finds no concern-path overlap or new production coupling; unrelated target advancement alone does not require a source refresh.
- Final-head hosted CI reports 54 successful checks and two expected documentation publication skips. Both Postgres versions complete the native, standby, authenticated-isolation and ordered-reconciliation phases. Mixed-version checks pass. Cell acceptance passes the unchanged latency and throughput requirements, with provenance and cleanup receipts. Fresh independent entire pushed-source review reports no findings or nits. These results apply to this extraction; bounded census joins remain separate work.

### AI assistance in the code

- AI-generated: Codex wrote this change. Independent final-source review and required hosted gates remain mandatory.

- [x] I can explain every line of this diff and how it interacts with the rest of Loom.

### Checklist

- [x] Scoped static checks pass; the refused local test attempt is recorded as unrun.
- [x] Required final-head GitHub CI and fresh whole-source review pass.
- [x] Documentation names the shared owner; generated translations are unchanged.
- [x] No migration or stored data change is introduced.
- [x] Commits are signed off.

* Live MCP results protect the SDK before automatic capture (#1067)

Compose rendering and transport observation so the privacy marker reaches protection before the next automatic write.

Signed-off-by: zlareb1 <[email protected]>

* Drive directory cleanup checks with one private clock (#1054)

Signed-off-by: zlareb1 <[email protected]>

---------

Signed-off-by: zlareb1 <[email protected]>
Signed-off-by: Shaun Struwig <[email protected]>
Signed-off-by: Lareb Zafar <[email protected]>
Co-authored-by: Shaun Struwig <[email protected]>
Co-authored-by: Rahul <[email protected]>
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.

A DSPy retriever over Loom search

3 participants