From 0df67822152e9e4361f4fa1abfd0599851cd8f0a Mon Sep 17 00:00:00 2001 From: TARS Date: Sat, 17 Oct 2026 02:08:37 +0000 Subject: [PATCH] docs(langchain): document that bare-LLM cache hits are not scanned LangChain (langchain-core 1.6.12) looks up the LLM cache before firing on_llm_start, and a full cache hit returns the cached generations without start or end events. A callback handler therefore cannot scan the prompt or the cached output of such a call, and no BLOCK or fail_closed error can stop it. Narrow the documented contract in the README, CHANGELOG (Known limitation) and the integration's module docstring: set cache=False on LLMs whose calls must be scanned, or scan outside the model call. Chat models fire on_chat_model_start before their cache lookup, so cached chat calls still have their input scanned. Add regression tests with real FakeListLLM / FakeListChatModel and InMemoryCache, sync and async: - bare LLM cache hit: first call scans llm_input and llm_output (ALLOW); the identical second call with BLOCK mocked returns the cached reply with zero scan requests and no raise - bare LLM with cache=False: the second call raises ContentBlockedError on llm_input - chat model with the same cache: the second call raises ContentBlockedError on chat_input No runtime behaviour changes. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 +++ README.md | 14 +++- src/shieldcortex/integrations/langchain.py | 9 +++ tests/integrations/test_langchain.py | 85 ++++++++++++++++++++++ 4 files changed, 115 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 11268b1..cf12fa2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,6 +39,15 @@ unless you opt in with the new options below. ### Known limitation +- LangChain answers a bare (non-chat) LLM call that is fully served from its + LLM cache without firing `on_llm_start` or `on_llm_end`, so neither the + prompt nor the cached output is scanned and no block can stop that call. + The 0.4.0 bare-LLM prompt scanning applies only to calls that reach the + model. Set `cache=False` on LLMs whose calls must be scanned (the default, + `cache=None`, uses any cache set with `set_llm_cache`), or scan outside the + model call. Chat models fire their start callback before the cache lookup, + so cached chat calls still have their input scanned. Regression tests pin + this behaviour. - With the async handler, a sync-only tool (no coroutine) called through `ainvoke` runs in a worker thread where LangChain logs and swallows every exception the handler raises. Neither BLOCK verdicts nor `fail_closed` diff --git a/README.md b/README.md index 4d65fe8..91569e5 100644 --- a/README.md +++ b/README.md @@ -114,8 +114,9 @@ except MemoryBlockedError as e: ## LangChain Integration The callbacks scan chain inputs, LLM prompts, text in chat messages, tool inputs, -LLM outputs, and tool outputs. Use the async handler for `ainvoke` and -`astream`, or the sync handler for `invoke`: +LLM outputs, and tool outputs, whenever LangChain fires the matching callback +(see **LLM cache** below for a case where it does not). Use the async handler +for `ainvoke` and `astream`, or the sync handler for `invoke`: ```python from langchain_openai import ChatOpenAI # or any LangChain chat model / LLM @@ -161,6 +162,15 @@ from `invoke`. a string `text` (for example `{"payload": "..."}`), are dropped rather than JSON-encoded, so their contents are not scanned. `None` and non-string outputs that reduce to empty text are not scanned. +- **LLM cache:** a bare (non-chat) LLM call answered entirely from a + LangChain LLM cache fires no callbacks: LangChain checks the cache before + `on_llm_start` and returns the cached text without `on_llm_end`. Neither + the prompt nor the cached output is scanned, and no block or `fail_closed` + error can stop that call. Set `cache=False` on LLMs whose calls must be + scanned (the default, `cache=None`, uses any cache set with + `set_llm_cache`), or scan outside the model call. Chat models fire + `on_chat_model_start` before their cache lookup, so a cached chat call + still has its input scanned. - **Sync-only tools under `ainvoke`:** LangChain runs a tool that has no coroutine in a worker thread and logs and swallows every exception the async handler raises there. Neither a `BLOCK` verdict nor a `fail_closed` diff --git a/src/shieldcortex/integrations/langchain.py b/src/shieldcortex/integrations/langchain.py index 64ebbc6..830b1b8 100644 --- a/src/shieldcortex/integrations/langchain.py +++ b/src/shieldcortex/integrations/langchain.py @@ -33,6 +33,15 @@ errors, are not caught: with ``raise_on_block=True`` they stop the run, otherwise LangChain logs them. +LLM cache: LangChain answers a bare (non-chat) LLM call that is served +entirely from its LLM cache without firing ``on_llm_start`` or +``on_llm_end``, so neither the prompt nor the cached output is scanned and no +block can stop that call. Set ``cache=False`` on LLMs whose calls must be +scanned (the default, ``cache=None``, uses any cache set with +``set_llm_cache``), or scan outside the model call. Chat models fire +``on_chat_model_start`` before their cache lookup, so a cached chat call still +has its input scanned. + Exception: with the async handler, a tool without a coroutine (a sync-only tool) called through ``ainvoke`` runs in a worker thread, and LangChain logs and swallows every exception the async handler raises there. Neither a block diff --git a/tests/integrations/test_langchain.py b/tests/integrations/test_langchain.py index c18ec06..daec13a 100644 --- a/tests/integrations/test_langchain.py +++ b/tests/integrations/test_langchain.py @@ -626,3 +626,88 @@ async def test_connection_error_propagates_unwrapped(is_sync: bool, hook: str) - is_sync, make_runnable(), value, raise_on_block=True, fail_closed=True, **options ) assert len(route.calls) == 1 + + +# --- LLM cache hits (documented limitation) --- + + +async def invoke_twice( + is_sync: bool, runnable: Any, route: respx.Route, first_scans: list[str] +) -> Any: + """Invoke ``runnable`` twice with one handler; the second call sees BLOCK. + + The first call's scan identifiers are appended to ``first_scans`` and the + route's call log is then cleared, so ``route.calls`` holds only the second + call's scans. + """ + if is_sync: + with ShieldCortex(api_key="sc_test_abc") as client: + handler = integration.ShieldCortexSyncCallbackHandler(client, raise_on_block=True) + runnable.invoke("prompt", config={"callbacks": [handler]}) + first_scans.extend(item["source"]["identifier"] for item in scan_requests(route)) + route.mock(return_value=httpx.Response(200, json=BLOCKED_RESPONSE)) + route.reset() + return runnable.invoke("prompt", config={"callbacks": [handler]}) + async with AsyncShieldCortex(api_key="sc_test_abc") as aclient: + ahandler = ShieldCortexCallbackHandler(aclient, raise_on_block=True) + await runnable.ainvoke("prompt", config={"callbacks": [ahandler]}) + first_scans.extend(item["source"]["identifier"] for item in scan_requests(route)) + route.mock(return_value=httpx.Response(200, json=BLOCKED_RESPONSE)) + route.reset() + return await runnable.ainvoke("prompt", config={"callbacks": [ahandler]}) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("is_sync", [False, True], ids=["async", "sync"]) +@respx.mock +async def test_bare_llm_cache_hit_is_not_scanned(is_sync: bool) -> None: + # LangChain answers a full LLM cache hit without firing on_llm_start or + # on_llm_end, so neither the prompt nor the cached output is scanned. If + # this starts failing, LangChain now fires callbacks on cache hits: update + # the docs. + from langchain_core.caches import InMemoryCache + + route = respx.post(f"{BASE}/v1/scan").mock( + return_value=httpx.Response(200, json=ALLOWED_RESPONSE) + ) + llm = FakeListLLM(responses=["cached reply"], cache=InMemoryCache()) + first_scans: list[str] = [] + result = await invoke_twice(is_sync, llm, route, first_scans) + assert first_scans == ["langchain:llm_input", "langchain:llm_output"] + assert result == "cached reply" + assert len(route.calls) == 0 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("is_sync", [False, True], ids=["async", "sync"]) +@respx.mock +async def test_bare_llm_without_cache_rescans_and_blocks(is_sync: bool) -> None: + route = respx.post(f"{BASE}/v1/scan").mock( + return_value=httpx.Response(200, json=ALLOWED_RESPONSE) + ) + llm = FakeListLLM(responses=["reply", "reply"], cache=False) + first_scans: list[str] = [] + with pytest.raises(integration.ContentBlockedError) as exc_info: + await invoke_twice(is_sync, llm, route, first_scans) + assert first_scans == ["langchain:llm_input", "langchain:llm_output"] + assert exc_info.value.source_identifier == "langchain:llm_input" + assert len(route.calls) == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("is_sync", [False, True], ids=["async", "sync"]) +@respx.mock +async def test_chat_model_cache_hit_still_scans_input(is_sync: bool) -> None: + # Chat models fire on_chat_model_start before the cache lookup. + from langchain_core.caches import InMemoryCache + + route = respx.post(f"{BASE}/v1/scan").mock( + return_value=httpx.Response(200, json=ALLOWED_RESPONSE) + ) + chat = FakeListChatModel(responses=["cached reply"], cache=InMemoryCache()) + first_scans: list[str] = [] + with pytest.raises(integration.ContentBlockedError) as exc_info: + await invoke_twice(is_sync, chat, route, first_scans) + assert first_scans == ["langchain:chat_input", "langchain:llm_output"] + assert exc_info.value.source_identifier == "langchain:chat_input" + assert len(route.calls) == 1