needlepath-litellm 0.2.2__tar.gz → 0.2.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,6 +2,32 @@
2
2
 
3
3
  All notable changes to the `needlepath-litellm` Python package are documented here.
4
4
 
5
+ ## 0.2.3 — 2026-11-05
6
+
7
+ ### Fixed
8
+
9
+ - **A protected record the length guard would keep is withheld, never kept.**
10
+ Under workspace protection (the engine's `governance` forbids raw-context
11
+ fallback) and a verdict that is not blocked, `apply_selection` kept an
12
+ individual original whenever its excerpt or placeholder was empty or not
13
+ shorter, and the guardrail only declined when the aggregate rewrite showed
14
+ no saving, so a larger saving elsewhere masked the per-record refusal and
15
+ the protected original reached the model. Such a record now collapses to
16
+ the withheld notice; the aggregate no-saving decline does not apply under
17
+ protection, since the rewrite holds no original. The engine's own stop
18
+ conditions (an empty or unusable protected response) still raise.
19
+ - **Shadow never restores a protected original.** The adapter's own shadow
20
+ guard exempted only a blocked verdict, so a protected engaged or sanitized
21
+ delivery (the core keeps it applied in a shadow run) was discarded and the
22
+ original forwarded. The guard now exempts every protected result
23
+ (`SelectionResult.protected`). Shadow still forwards the original for every
24
+ unprotected delivery.
25
+ - **A defect while installing a protected result stops the call.** Selection
26
+ and installation shared one fail-open handler, so a failure after a
27
+ protected result had been returned restored the original. The install step
28
+ now runs under `SelectionResult.applying()`: under protection it raises
29
+ `NeedlepathGuardrailError`; otherwise it fails open as before.
30
+
5
31
  ## 0.2.2 — 2026-11-04
6
32
 
7
33
  ### Fixed
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: needlepath-litellm
3
- Version: 0.2.2
3
+ Version: 0.2.3
4
4
  Summary: Needlepath context selection as a LiteLLM proxy CustomGuardrail.
5
5
  Project-URL: Homepage, https://nextmoca.com
6
6
  Author: Next Moca Global, Inc.
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "needlepath-litellm"
7
- version = "0.2.2"
7
+ version = "0.2.3"
8
8
  description = "Needlepath context selection as a LiteLLM proxy CustomGuardrail."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.9"
@@ -11,6 +11,11 @@ while keeping its ``tool`` reply (or the reverse) is rejected by every provider,
11
11
  and rewriting content in place makes the pairing unbreakable by construction.
12
12
 
13
13
  **Invariant 2 — a rewrite never grows a message and never empties one.**
14
+ Refusing a rewrite keeps the original, which is the right degradation for an
15
+ ordinary selection and the wrong one under workspace protection: when the
16
+ engine's ``governance`` forbids raw-context fallback, a refused rewrite
17
+ collapses to the withheld notice instead (``protected_notice``), because the
18
+ original is the one thing that may not be installed.
14
19
  """
15
20
 
16
21
  from __future__ import annotations
@@ -199,14 +204,22 @@ def apply_selection(
199
204
  index_by_id: Dict[str, int],
200
205
  placeholder: str,
201
206
  withhold: bool = False,
207
+ protected_notice: Optional[str] = None,
202
208
  ) -> Tuple[List[Dict[str, Any]], int, int]:
203
209
  """Rewrite selected and unselected messages. Returns (messages, before, after).
204
210
 
205
- ``withhold`` is the one exception to the length guards below, for a
206
- ``blocked`` verdict: every record collapses to ``placeholder`` (the
207
- withheld notice) whatever its length, because the original is the thing
208
- that must not be kept. ``excerpts`` is ignored; a blocked response
209
- carries none.
211
+ Two exceptions to the length guards below, both for a response under
212
+ workspace protection, where the original is the thing that must not be
213
+ kept:
214
+
215
+ * ``withhold``, for a ``blocked`` verdict: every record collapses to
216
+ ``placeholder`` (the withheld notice) whatever its length. ``excerpts``
217
+ is ignored; a blocked response carries none.
218
+ * ``protected_notice``, for any other protected delivery: a record whose
219
+ rewrite the guards refuse collapses to this notice instead of keeping
220
+ the original. The refusal is per record, and a caller that only checks
221
+ the aggregate saving cannot see it — a large saving elsewhere would mask
222
+ one kept original and send it to the model.
210
223
 
211
224
  Every rewritten message is a **new dict**. The caller's own message objects
212
225
  are never mutated: on a proxy they can be shared with logging, with a retry
@@ -225,28 +238,17 @@ def apply_selection(
225
238
  original_text = content_text(original.get("content"))
226
239
  before += approx_tokens(original_text)
227
240
  if withhold:
228
- replacement = dict(original)
229
- replacement["content"] = placeholder
230
- out[index] = replacement
231
- after += approx_tokens(placeholder)
232
- continue
233
- excerpt = excerpts.get(record_id)
234
- if excerpt is None and not placeholder.strip():
235
- # Invariant 2, at the mutation boundary. A blank custom placeholder
236
- # would rewrite a non-empty message to nothing — the pairing
237
- # survives, the content does not. Refused rather than trusted.
238
- after += approx_tokens(original_text)
239
- continue
240
- if excerpt is None:
241
- new_text = placeholder
242
- elif not excerpt.strip() or len(excerpt) >= len(original_text):
243
- after += approx_tokens(original_text)
244
- continue
241
+ new_text: Optional[str] = placeholder
245
242
  else:
246
- new_text = excerpt
247
- if len(new_text) >= len(original_text):
248
- after += approx_tokens(original_text)
249
- continue
243
+ new_text = _rewrite_for(excerpts.get(record_id), original_text, placeholder)
244
+ if new_text is None and protected_notice is None:
245
+ # Invariant 2 refused the rewrite: the original stays.
246
+ after += approx_tokens(original_text)
247
+ continue
248
+ if new_text is None:
249
+ # Under workspace protection the original is the one thing
250
+ # that may not be installed. Withheld, with the notice.
251
+ new_text = protected_notice
250
252
  replacement = dict(original)
251
253
  replacement["content"] = new_text
252
254
  out[index] = replacement
@@ -254,6 +256,24 @@ def apply_selection(
254
256
  return out, before, after
255
257
 
256
258
 
259
+ def _rewrite_for(excerpt: Optional[str], original_text: str, placeholder: str) -> Optional[str]:
260
+ """What replaces a message, or ``None`` to refuse the rewrite.
261
+
262
+ Invariant 2, at the mutation boundary. Every ``None`` here is a rewrite
263
+ that would grow the message or empty it: a blank custom placeholder (the
264
+ pairing would survive, the content would not), a placeholder or an
265
+ excerpt that is not shorter than the message, an excerpt with nothing in
266
+ it.
267
+ """
268
+ if excerpt is None:
269
+ if not placeholder.strip() or len(placeholder) >= len(original_text):
270
+ return None
271
+ return placeholder
272
+ if not excerpt.strip() or len(excerpt) >= len(original_text):
273
+ return None
274
+ return excerpt
275
+
276
+
257
277
  def withheld_notice(result: SelectionResult) -> str:
258
278
  """The model-facing text installed for records workspace policy withheld.
259
279
 
@@ -292,6 +292,17 @@ class NeedlepathGuardrail(CustomGuardrail):
292
292
  selection_strategy=self.selection_strategy,
293
293
  support_contract=self.support_contract,
294
294
  )
295
+ with result.applying():
296
+ return self._apply(data, messages, records, index_by_id, result)
297
+
298
+ def _apply(
299
+ self,
300
+ data: dict,
301
+ messages: list,
302
+ records: list,
303
+ index_by_id: Dict[str, int],
304
+ result: SelectionResult,
305
+ ) -> Optional[dict]:
295
306
  # The raw engine receipt, exactly as returned — see the class
296
307
  # docstring's "Two stats objects, two truths" note. `.stats` is
297
308
  # recorded separately below, once, with the ACTUAL before/after this
@@ -301,11 +312,13 @@ class NeedlepathGuardrail(CustomGuardrail):
301
312
  # `self.shadow` is belt and braces — the core client already declines a
302
313
  # shadow result — but a proxy operator running this over production
303
314
  # traffic was promised that measuring changes nothing, and that promise
304
- # is enforced at the point of mutation rather than inherited. A blocked
305
- # verdict is the one delivery shadow does not suppress: shadow never
306
- # restores a withheld record, so it is installed below, shadow or not.
315
+ # is enforced at the point of mutation rather than inherited. What
316
+ # shadow does not suppress is a protected delivery (a blocked verdict,
317
+ # or a selection under workspace protection): shadow never restores a
318
+ # withheld record or a protected original, so it is installed below,
319
+ # shadow or not.
307
320
  blocked = result.reason == Reason.BLOCKED
308
- if not result.applied or (self.shadow and not blocked):
321
+ if not result.applied or (self.shadow and not result.protected):
309
322
  # Nothing is installed on this path, so the ACTUAL before/after is
310
323
  # the size of what was considered, unchanged — not the engine's own
311
324
  # numbers, which describe a selection that was never applied.
@@ -316,6 +329,11 @@ class NeedlepathGuardrail(CustomGuardrail):
316
329
  write_metadata(data, result.metadata(prefix=""))
317
330
  return None
318
331
 
332
+ # Workspace protection: the engine's `governance` forbids raw-context
333
+ # fallback (a blocked verdict is one case of it). Nothing of the
334
+ # caller's original may be installed, per record or in aggregate.
335
+ protected = not result.raw_context_fallback_allowed
336
+ notice = withheld_notice(result) if protected else None
319
337
  selected, before, after = apply_selection(
320
338
  messages,
321
339
  excerpts=result.excerpts,
@@ -325,11 +343,15 @@ class NeedlepathGuardrail(CustomGuardrail):
325
343
  # categories, rather than to the selection placeholder.
326
344
  placeholder=withheld_notice(result) if blocked else self.placeholder,
327
345
  withhold=blocked,
346
+ # Any other protected delivery: a record whose rewrite the length
347
+ # guards refuse is withheld with the notice, never kept.
348
+ protected_notice=notice,
328
349
  )
329
- if after >= before and not blocked:
330
- # The guard refuses a rewrite that saves nothing. A withheld
331
- # record is not a saving, and refusing on length would keep the
332
- # original — exactly what a blocked verdict forbids.
350
+ if after >= before and not protected:
351
+ # The guard refuses a rewrite that saves nothing. Under protection
352
+ # it does not apply: the rewrite holds no original, a withheld
353
+ # record is not a saving, and declining would raise and stop a
354
+ # request the engine did not stop.
333
355
  declined = result.declined(Reason.NO_SAVING)
334
356
  # Nothing is installed here either: `selected` is computed but
335
357
  # never written to `data["messages"]`, so actual after == before.
@@ -1,3 +1,3 @@
1
- __version__ = "0.2.2"
1
+ __version__ = "0.2.3"
2
2
 
3
3
  __all__ = ["__version__"]
@@ -770,3 +770,110 @@ async def test_aclose_releases_only_the_client_it_built():
770
770
  assert injected._owns_client is False
771
771
  await injected.aclose()
772
772
  assert transport.inner.closed is False, "somebody else's client was closed"
773
+
774
+
775
+ # --------------------------------------------------------------------------- #
776
+ # Workspace protection on a delivery that is not blocked (NEXPE-620)
777
+ # --------------------------------------------------------------------------- #
778
+
779
+ PROTECTED_GOVERNANCE = {
780
+ "enabled": True,
781
+ "policies_applied": 1,
782
+ "raw_context_fallback_allowed": False,
783
+ "category_counts": {},
784
+ }
785
+
786
+
787
+ @pytest.mark.asyncio
788
+ async def test_a_protected_record_the_length_guard_would_keep_is_withheld():
789
+ """Raw-context fallback forbidden, verdict not blocked. One tool result is
790
+ shorter than its excerpt, so the per-message guard would keep the
791
+ original; the other saves enough to mask that in the aggregate. Under
792
+ protection the kept original is the leak: the record is withheld with the
793
+ notice and the request proceeds."""
794
+ g, _ = guardrail([echoing(governance=dict(PROTECTED_GOVERNANCE))])
795
+ data = two_tool_body()
796
+ data["messages"][3]["content"] = "SSN 123-45-6789"
797
+ out = await call(g, data)
798
+ assert out is not None
799
+ text = out["messages"][3]["content"]
800
+ assert "123-45-6789" not in text
801
+ assert "withheld" in text.lower()
802
+ assert out["messages"][5]["content"].startswith("EXCERPT:")
803
+ assert g.stats.applied == 1 and g.stats.reasons == {Reason.OK: 1}
804
+
805
+
806
+ @pytest.mark.asyncio
807
+ @pytest.mark.parametrize("stream", [False, True])
808
+ @pytest.mark.parametrize(
809
+ "service",
810
+ [
811
+ pytest.param(echoing(governance=dict(PROTECTED_GOVERNANCE)), id="ok"),
812
+ pytest.param(
813
+ echoing(outcome="sanitized_fallback", governance=dict(PROTECTED_GOVERNANCE)),
814
+ id="sanitized",
815
+ ),
816
+ ],
817
+ )
818
+ async def test_shadow_never_restores_a_protected_tool_result(service, stream):
819
+ """The guardrail's own shadow flag is belt and braces for every delivery
820
+ the model could have had anyway. A protected delivery is not one of
821
+ those: the core client keeps it applied in a shadow run, and so does the
822
+ guardrail, on a streamed request too (same pre-call body)."""
823
+ g, transport = guardrail([service], shadow=True)
824
+ data = chat_body(stream=True) if stream else chat_body()
825
+ out = await call(g, data)
826
+ assert len(transport.calls) == 1
827
+ assert out is not None
828
+ assert out["messages"][3]["content"].startswith("EXCERPT:")
829
+ assert BIG not in out["messages"][3]["content"]
830
+ assert data["metadata"][METADATA_KEY]["applied"] is True
831
+ assert data["metadata"][METADATA_KEY]["shadow"] is True
832
+ assert g.stats.applied == 1
833
+
834
+
835
+ @pytest.mark.asyncio
836
+ async def test_shadow_still_restores_an_unprotected_delivery():
837
+ g, _ = guardrail([echoing()], shadow=True)
838
+ data = chat_body()
839
+ assert await call(g, data) is None
840
+ assert data["metadata"][METADATA_KEY]["reason"] == Reason.SHADOW
841
+
842
+
843
+ @pytest.mark.asyncio
844
+ async def test_a_failure_installing_a_protected_selection_stops_instead_of_failing_open(
845
+ monkeypatch,
846
+ ):
847
+ import needlepath_litellm.guardrail as module
848
+
849
+ def boom(*args, **kwargs):
850
+ raise RuntimeError("rewrite failed")
851
+
852
+ monkeypatch.setattr(module, "apply_selection", boom)
853
+ g, _ = guardrail([echoing(governance=dict(PROTECTED_GOVERNANCE))])
854
+ with pytest.raises(NeedlepathGuardrailError):
855
+ await call(g, chat_body())
856
+ g, _ = guardrail([echoing()])
857
+ data = chat_body()
858
+ assert await call(g, data) is None
859
+ assert data["metadata"][METADATA_KEY]["reason"] == Reason.UNEXPECTED_ERROR
860
+
861
+
862
+ @pytest.mark.asyncio
863
+ async def test_a_contradictory_blocked_body_installs_the_notice_and_nothing_else():
864
+ g, _ = guardrail(
865
+ [
866
+ echoing(
867
+ outcome="blocked",
868
+ rendered_context="LEAKED RENDER",
869
+ governance=dict(PROTECTED_GOVERNANCE),
870
+ )
871
+ ]
872
+ )
873
+ data = chat_body()
874
+ out = await call(g, data)
875
+ assert out is not None
876
+ text = out["messages"][3]["content"]
877
+ assert "withheld" in text.lower()
878
+ assert "EXCERPT:" not in text and "LEAKED" not in text and BIG not in text
879
+ assert data["metadata"][METADATA_KEY]["reason"] == Reason.BLOCKED