chunk-invariance

io.github.ninadphalak由 GitHub 帳號 ninadphalak 發布v0.2.0更新於 Oct 26, 2026

Checks whether your streaming redactor leaks a secret split across chunks; writes a pytest for it.

已驗證STDIO僅桌面開發者工具安全與監控

概覽

AI 產生的概覽

檢查串流脫敏器或護欄是否會在分塊邊界洩漏被切開的敏感值,並產生對應的 pytest 回歸測試。

可以做什麼
  • 檢查串流過濾器:從專案匯入函式,對樣本輸入嘗試每一種兩段切分,並指出最小的失敗切分。
  • 產生以 assert_chunk_invariant 為基礎的 pytest 檔案,讓檢查留在 CI 中。
  • 用一段話說明逐塊過濾為何會洩漏被切分的值。
  • 使用預設的假樣本(電子郵件、SSN、卡號、幾種 API 金鑰格式),也可傳入自編樣本。
適用情境
適合在維護串流脫敏器、護欄或改寫器時使用,用來確認串流輸出與整份輸入過濾的結果在任意分塊下都一致,並把這項檢查留作專案中的回歸測試。
執行需求
本機 stdio 程序,從 PyPI 安裝並加上 mcp 附加項目(Python 3.10 以上),透過 chunk-invariance-mcp 指令啟動。目標函式必須是 project_dir 下原始碼檔案中的 Python 函式;若專案有 .venv 則會使用它。未宣告需要帳號、金鑰或網路存取。
安裝前請注意
檢查函式會在本機以獨立程序執行你的程式碼,且環境變數經過精簡,因此只應對自己的專案核准呼叫。切勿把真實密鑰或個人資料當作樣本:樣本、洩漏值、例外訊息和產生的測試檔都會回傳給助理,並隨對話傳送給其模型供應商。伺服器本身不連網、不寫檔,但它執行的程式碼可以。

安裝

在 SourceWeft 中

  1. 開啟 儀表板中的 chunk-invariance,將其新增到工作區。
  2. 為需要使用其工具的對話啟用該服務。

Desktop only,透過 STDIO。 STDIO 服務會啟動本機處理程序,因此需要 SourceWeft 桌面主機。

其他 MCP 客戶端

參照 儲存庫 中的啟動說明。

README

chunk-invariance

A streaming filter (a redactor, a guardrail, a rewriter) is correct only if, for every way of splitting an input into chunks, the concatenated streamed output equals the output of filtering the whole input at once. This package turns that rule into one assertion.

python
from chunk_invariance import assert_chunk_invariant
def redact(text):                 # your filter on the whole input    return text.replace("sk-AbCd1234", "[KEY]")
def redact_stream(chunks):        # your filter on a stream: takes chunks, yields chunks    for chunk in chunks:        yield redact(chunk)       # redacts each chunk alone
def test_streaming_redaction():    assert_chunk_invariant(redact_stream, redact, "use sk-AbCd1234 now")

That test fails, and names the smallest split that breaks it:

chunk_invariance.core.ChunkInvarianceError: stream filter is not chunk-invariant  input:    'use sk-AbCd1234 now'  split:    ['use s', 'k-AbCd1234 now'] (cut at 5)  whole:    'use [KEY] now'  streamed: 'use sk-AbCd1234 now'  split #6 in the order tried; generated splits run fewest parts first
bash
pip install chunk-invariancepip install "chunk-invariance[hypothesis]"   # optional Hypothesis strategiespip install "chunk-invariance[mcp]"          # optional MCP server for AI assistants

What it catches

  • A filter that evaluates each chunk alone, so a value cut across two chunks matches neither half.
  • A filter that prepends a fixed carryover from the previous chunk. The match fires, but the start of the value was already emitted with the previous chunk.
  • A hold-back that is shorter than the pattern, a missing end-of-stream flush, and output that is corrupted rather than leaked (any difference from the whole-input output fails).

chunk_invariance.examples has one correct filter (hold_back) and the two wrong designs (design_a, design_b) for the same pattern, as a worked comparison.

What it does not catch

It tests a filter you can call in-process. It does not test a running gateway, where the chunks are decided by an upstream model, a network and an SSE parser. For that, use pii-leak-benchmark, which sends fragmented responses through the gateway and checks what reaches the client.

It checks the splits you ask for. The default is the whole input plus every single cut, which catches a value cut in two. splits="all" tries every split of a short input (up to 16 characters); splits=3 tries every split into at most three parts; an explicit list of chunk lists runs exactly those. It cannot prove a filter correct for inputs you did not give it.

Use it from your AI assistant

Do you use Claude Code, Cursor or Claude Desktop? The package has an optional MCP server. With it you can ask the assistant to run the every-split check on your own streaming function, and then to add the test to your repo.

bash
pip install "chunk-invariance[mcp]"      # Python 3.10 or laterclaude mcp add chunk-invariance -- chunk-invariance-mcp

For Claude Desktop, add this to claude_desktop_config.json (give the full path to the command if Claude Desktop cannot find it on your PATH):

json
{  "mcpServers": {    "chunk-invariance": { "command": "chunk-invariance-mcp" }  }}

Then ask, for example: "Check whether redact_stream in myapp/filters.py leaks values split across chunks, and add a regression test for it."

There are three tools. check_stream_filter imports your function (myapp.filters:redact_stream), streams each sample through it in every two-part split and tells you which split broke it, for example that 'sk-AbCd1234' came out unredacted when the input was cut into 'use s' and 'k-AbCd1234 now'. write_regression_test returns a pytest file built on assert_chunk_invariant, so the check stays in your CI. explain is one paragraph on why per-chunk filtering leaks.

The default samples (an email, an SSN, a card number and a few API-key shapes) are all fake. Pass your own made-up samples in the formats your filter redacts, such as a key you typed yourself in your provider's format. A sample the filter does not change tests nothing, and the tool says so.

Never pass a real secret or real personal data as a sample. The samples, and any value your filter leaks, come back in the tool's result, and your assistant sends that result to its model provider like the rest of the conversation. So does the message of any exception your code raises, but nothing your code prints. The same samples also end up in the generated test file.

Checking a function runs your code. The server imports your module on your own machine, in a separate process that is stopped after a timeout (60 seconds by default). If your project has a .venv (or venv), that is the Python it uses; the python argument accepts only that interpreter or the server's own. The target, flush_target and whole_target must be Python functions defined in source files under project_dir: built-ins, the standard library and installed packages (anything in the interpreter's site-packages, including your .venv's) are refused, and so is a project_dir that is or contains the interpreter's own library. The check process gets a minimal environment (PATH, HOME, temp and locale variables), not the server's, so a filter that reads its configuration from other environment variables will not see them. project_dir is chosen by the assistant's tool call, so whatever code lives under it is what can run: approve calls only for your own project. The server itself makes no network calls, sends no telemetry and writes no files, though the code it runs can do whatever that code does. Saving the test file is up to you and your assistant.

API

NameDoes
assert_chunk_invariant(stream_filter, whole_filter, text, *, splits="all-two-part")Raises ChunkInvarianceError (an AssertionError) on the first failing split, fewest parts first. Returns the number of splits checked. Works on str and bytes.
assert_chunk_invariant_async(...)The same, for an async generator filter, inside an async test.
two_part_splits(text)Every split into two non-empty parts.
all_splits(text, max_parts=None)Every split into at most max_parts non-empty parts, the whole input first.
per_chunk(process, *, state=dict, flush=None)Adapts process(chunk, state) -> output and flush(state) -> output, with fresh state per stream.
from_async(async_stream_filter)Adapts an async generator filter for the synchronous assertion.
strategies.splits_of(text, max_parts=None)Hypothesis strategy: random splits of text, shrinking toward fewer cuts.
strategies.text_and_splits(texts, max_parts=None)Hypothesis strategy: (text, chunks) pairs. texts is itself a strategy, such as st.sampled_from([...]), not a list.

stream_filter is called once per split, so it must start from fresh state each time.

Background

The invariant and the two wrong designs are described in Phalak, N. (2026), Split-Boundary Leaks in Streaming Guardrails, Zenodo, 10.5281/zenodo.22909585.

Standard library only (the mcp extra adds the MCP SDK, for the server alone). Apache-2.0. A TypeScript version with the same API is published on npm as chunk-invariance.

來源:chunk-invariance/README.md,提交 f95ba91

工具

0
SourceWeft 尚未在沙箱中啟動過該軟體包,因此其工具未知。

版本歷史

1
  1. v0.2.0最新Oct 19, 2026

評分

已滿足適用檢查項的 50%

該評分衡量此收錄條目的完整程度,依據註冊中心條目、端點與公開來源計算得出。它不是對伺服器本身的評價,也不表示伺服器安全或目前可用:可連通性是帶日期的檢查結果,評分也不包含安裝量或使用者評價。

  • 近 30 天內可連通25 分

    請保持端點能夠回應 MCP 握手;SourceWeft 每 30 天探測一次。

  • 已宣告認證方式10 分

    請在註冊中心條目中宣告憑證請求標頭,或保持端點能夠回應探測,以便判定其認證方式。

  • 已列出工具15 分

    請讓伺服器在無憑證時回應 tools/list,或發布可在沙箱中無憑證啟動的軟體包。

  • 描述必需15 分
  • 圖示10 分
  • 文件15 分
  • 授權條款10 分