Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

docs(examples): add one-call pii redaction example (#703)

svonava2b3f7d2ed6d7
diff --git a/examples/redact/README.md b/examples/redact/README.md
index 493791ab2..ca4f81daa 100644
--- a/examples/redact/README.md
+++ b/examples/redact/README.md
@@ -1,5 +1,9 @@
# Mask personal data before it reaches a log, a prompt or a vendor
+For a complete document sent through `superlinked/pii-redact` in one SDK
+operation, see the [one-call example](one-call/README.md). This directory retains
+the recorded two-model study, its callers and scoring below.
+
## What this shows
This example holds the recorded run behind
diff --git a/examples/redact/one-call/README.md b/examples/redact/one-call/README.md
new file mode 100644
index 000000000..887ce9ad2
--- /dev/null
+++ b/examples/redact/one-call/README.md
@@ -0,0 +1,126 @@
+# Mask one complete document with `superlinked/pii-redact`
+
+This caller sends one complete text item through `sie_sdk.SIEClient.extract`,
+then masks the union of the returned intervals. The served model composes two
+detectors internally, including score filtering, overlapping server windows and
+name propagation. The caller only validates offsets and applies masks.
+
+The example includes a complete synthetic trade confirmation, index `240`, uid
+`gretel-en-34966`. It contains `Alejandra Santamaría-Castilla`, so the input itself
+exercises non-ASCII offsets. [input.txt](input.txt) is copied unchanged: **962
+Unicode code points, 963 UTF-8 bytes**, SHA-256
+`94ec9f7160c81390866958d9b33c2c5a9e98f854782eafc938f4e57418adfc62`.
+No newline, normalization, stripping or caller windows are added.
+
+## Run from the repository root
+
+Use the root frozen Python workspace and its current SDK, version `0.10.0`:
+
+```sh
+mise exec -- uv run --frozen --project . --package sie-sdk python examples/redact/one-call/run.py --show
+mise exec -- uv run --frozen --project . --package sie-sdk python examples/redact/one-call/run.py --saved-composition
+mise exec -- uv run --frozen --project . --package sie-sdk python examples/redact/one-call/run.py --url "$SIE_URL"
+```
+
+`--show` prints the logical request and dispatches nothing. `--saved-composition`
+renders the included reference spans offline. Both modes also work with plain
+`python3` and the standard library.
+
+For a live request, supply a Cloud or self-hosted URL through `--url` or `SIE_URL`.
+If the endpoint needs authentication, set `SIE_API_KEY`; the caller passes it
+explicitly to the SDK for that chosen endpoint. `--no-auth` suppresses it. Keys
+and authentication headers are never printed. URLs must have no embedded
+credentials, query or fragment. The example does not choose an endpoint for you.
+
+The request contains the whole input and `options={"profile": "default"}`;
+it omits `labels` to use the server's configured 36 defaults. The SDK sends
+MessagePack to `/v1/extract/superlinked/pii-redact`. The JSON from `--show` is a
+logical-body display, not the actual wire encoding.
+
+Ordinary mode makes one SDK extract operation and keeps normal SDK handling of
+a cold deployment and transient capacity failures; that operation can send more
+than one HTTP request. For an explicit illustration requiring **at most one
+extract POST**, add `--single-attempt`. It disables transport retries, blocks a
+second POST before transport, and stops on the first HTTP error before SDK retry
+logic runs. A loading response therefore ends that attempt. Supported SDK
+same-origin GET completion polling can still retrieve the submitted result.
+`--timeout-seconds` sets the SDK provision budget and HTTP phase timeouts
+(default 900 seconds); HTTP phase timeouts are not a hard whole-call deadline.
+
+## Read the output
+
+Output includes the evidence type, returned entity spans, merged intervals and
+masked text. Integer `start` and `end` must satisfy
+`0 <= start < end <= len(text)`, and each entity's text must equal exactly
+`text[start:end]`. A mismatch fails; the caller never searches for another
+occurrence or changes the input to repair offsets.
+
+Python string offsets count Unicode code points. UTF-8 bytes, UTF-16 code units
+and displayed graphemes can have different lengths: an astral character occupies
+one Python offset, while a base letter followed by a combining mark occupies
+two. The tests exercise these cases alongside the input's accented name.
+
+Duplicate, nested, partial-overlap and touching intervals merge before masking.
+Each covered code point becomes one `█`, preserving the original Python string
+length and every unmasked substring. The caller does not filter scores or
+recreate the model composition. Returned errors, malformed wire responses,
+missing entity lists, invalid spans and uncertain transport outcomes exit
+nonzero without masked output. A genuine empty list says **no spans returned**;
+it does not establish that the text is free of personal data.
+
+## Source and evidence
+
+[source.json](source.json) records the complete request, input identity, the full
+36-label list and expected configuration from public SIE source
+`9f9eaa3d74684c081fce45386ec91ac137f3ac1a`:
+
+- [Model configuration](https://github.com/superlinked/sie/blob/9f9eaa3d74684c081fce45386ec91ac137f3ac1a/packages/sie_server/models/superlinked__pii-redact.yaml),
+ SHA-256 `7637549f4036cc91dc342fcfd19abb8218cb444673b5091968f80f993ea06f57`.
+- `urchade/gliner_multi_pii-v1` at `1fcf13e85f4eef5394e1fcd406cf2ca9ea82351d` and
+ `numind/NuNER_Zero` at `c90187673f464518dca09f41689184ed6976242c`, with
+ `merge_adjacent_entities=true` for NuNER.
+- Tokenizer dependencies `microsoft/mdeberta-v3-base` at
+ `a0484667b22365f84929a935b5e50a51f71f159d` and
+ `microsoft/deberta-v3-large` at `64a8c8eab3e352a784c658aef62be1662607476f`.
+- The default profile runs both members with score floor `0.6`, server windows
+ of 300 GLiNER words and overlap 50, and case-sensitive whole-word propagation
+ of `person` tokens containing at least three letters. GLiNER's word counting
+ includes punctuation; it differs from `text.split()`.
+
+The adapter retains overlaps and differently labelled spans, deduplicating
+identical `(start, end, label)` spans at the maximum score. It returns original
+document offsets. Usage counts each detector and each overlapping server window.
+These pins describe the expected source configuration; they do not prove what
+an arbitrary URL serves. Deployment, installed runtime, device, checkpoint-load
+receipts and returned revision metadata remain unknown until observed. A returned
+configuration digest is not a checkpoint revision or proof of device parity.
+
+The complete text and reference spans come from the immutable
+[public fixture](https://github.com/superlinked/sie/blob/9f9eaa3d74684c081fce45386ec91ac137f3ac1a/packages/sie_server/tests/adapters/fixtures/gliner_union/redact-documents.json),
+whose SHA-256 is
+`27a46485552385b096933d05eb4e96722e0914becae5261645c2ad9daea42677`.
+The retained input is in
+[superlinked/sie-task-evidence](https://huggingface.co/datasets/superlinked/sie-task-evidence/blob/31383ae9986d9dc9edd4e3a06ee9fb40b223d6fb/redact/inputs/gretel-main.jsonl)
+at `31383ae9986d9dc9edd4e3a06ee9fb40b223d6fb`, derived from
+[Gretel's synthetic financial dataset](https://huggingface.co/datasets/gretelai/synthetic_pii_finance_multilingual),
+attributed as Apache 2.0 in the [recorded study](../README.md).
+
+**No real one-call HTTP exchange is retained here.** The fixture's `expected`
+spans compose two saved model responses from that study; propagated spans can
+have `score: null`. Offline output explicitly says
+`saved composition replay; not a one-call HTTP recording`. It retains overlapping
+phone/email spans and unnecessary masks, including the car description and
+placeholder text. It illustrates masking and provenance, not a new inference,
+accuracy estimate or comparison. A live run needs a reachable endpoint serving
+the model; a local CPU server also needs both pinned checkpoints and tokenizers.
+
+## Check without credentials or weights
+
+```sh
+mise exec -- uv run --frozen --project . --package sie-sdk pytest examples/redact/one-call/test_one_call.py
+```
+
+The tests use the real SDK with HTTPX MockTransport to inspect its MessagePack
+request, optional authentication, cold-deployment handling, strict failure
+behavior and validation before the SDK can default a missing entities field to
+an empty list. No model is loaded and no inference request is sent.
diff --git a/examples/redact/one-call/input.txt b/examples/redact/one-call/input.txt
new file mode 100644
index 000000000..c30881e65
--- /dev/null
+++ b/examples/redact/one-call/input.txt
@@ -0,0 +1,33 @@
+------------------------------------------------------------------------------------------------------------------
+
+Trade Confirmation
+
+Trade Date: 05/12/2023
+Portfolio: Vintage Cars
+Confirmation: 123456789
+
+Securities: 1 x 1963 Chevrolet Corvette Stingray (Restored)
+Quantity: 1
+Price: $50,000.00
+Settlement Date: 10/08/2024
+
+Swift BIC Code: FRZIUSNZ985
+SSN: 324-78-5893
+Name: Alejandra Santamaría-Castilla
+Street Address: 6074 Chaney Dam, Apt. 293
+
+Delivery Instructions:
+- Securities will be delivered to the above mentioned address
+- Funds will be remitted to the bank specified in the Swift BIC Code
+
+------------------------------------------------------------------------------------------------------------------
+
+Please contact us if you have any questions or concerns regarding this trade confirmation.
+
+Sincerely,
+
+[Trading Firm Name]
+[Trading Firm Address]
+[Trading Firm City, State, Zip Code]
+[Trading Firm Phone Number]
+[Trading Firm Email Address]
\ No newline at end of file
diff --git a/examples/redact/one-call/run.py b/examples/redact/one-call/run.py
new file mode 100644
index 000000000..49bed9c46
--- /dev/null
+++ b/examples/redact/one-call/run.py
@@ -0,0 +1,247 @@
+"""Send one complete text item to pii-redact and mask the returned span union."""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import math
+import os
+import sys
+from pathlib import Path
+from typing import TYPE_CHECKING, Any
+from urllib.parse import urlsplit
+
+if TYPE_CHECKING:
+ import httpx
+
+MODEL = "superlinked/pii-redact"
+PROFILE = "default"
+DIRECTORY = Path(__file__).resolve().parent
+SAVED_EVIDENCE = "saved composition replay; not a one-call HTTP recording"
+EXTRACT_PATH = f"/v1/extract/{MODEL}"
+
+
+class ExampleError(Exception):
+ """An incomplete or invalid result must never become masked output."""
+
+
+class SingleAttemptError(ExampleError):
+ """The optional one-POST illustration has stopped."""
+
+
+def load_input() -> str:
+ source = json.loads((DIRECTORY / "source.json").read_text(encoding="utf-8"))
+ data = (DIRECTORY / "input.txt").read_bytes()
+ if hashlib.sha256(data).hexdigest() != source["input"]["sha256"]:
+ raise ExampleError("input.txt does not match the pinned complete input")
+ text = data.decode("utf-8")
+ if len(data) != source["input"]["utf8_bytes"] or len(text) != source["input"]["code_points"]:
+ raise ExampleError("input.txt has an unexpected length")
+ return text
+
+
+def logical_request(text: str) -> dict[str, Any]:
+ return {
+ "method": "POST",
+ "path": EXTRACT_PATH,
+ "body": {"items": [{"text": text}], "params": {"options": {"profile": PROFILE}}},
+ }
+
+
+def validate_entities(text: str, result: Any) -> list[dict[str, Any]]:
+ if not isinstance(result, dict) or result.get("error") is not None:
+ raise ExampleError("extraction returned an error or an invalid item")
+ entities = result.get("entities")
+ if not isinstance(entities, list):
+ raise ExampleError("extraction did not return an entities list")
+ for index, entity in enumerate(entities):
+ if not isinstance(entity, dict):
+ raise ExampleError(f"entity {index} is not an object")
+ start, end = entity.get("start"), entity.get("end")
+ if type(start) is not int or type(end) is not int or not 0 <= start < end <= len(text):
+ raise ExampleError(f"entity {index} has invalid code-point offsets")
+ if entity.get("text") != text[start:end]:
+ raise ExampleError(f"entity {index} does not match the original text at its offsets")
+ if not isinstance(entity.get("label"), str) or not entity["label"]:
+ raise ExampleError(f"entity {index} has no label")
+ return entities
+
+
+def merged_intervals(entities: list[dict[str, Any]]) -> list[list[int]]:
+ intervals: list[list[int]] = []
+ for start, end in sorted((entity["start"], entity["end"]) for entity in entities):
+ if intervals and start <= intervals[-1][1]:
+ intervals[-1][1] = max(intervals[-1][1], end)
+ else:
+ intervals.append([start, end])
+ return intervals
+
+
+def render_result(text: str, result: Any, evidence: str) -> dict[str, Any]:
+ entities = validate_entities(text, result)
+ intervals = merged_intervals(entities)
+ pieces: list[str] = []
+ cursor = 0
+ for start, end in intervals:
+ pieces.extend((text[cursor:start], "█" * (end - start)))
+ cursor = end
+ pieces.append(text[cursor:])
+ return {
+ "evidence": evidence,
+ "span_status": "spans returned" if entities else "no spans returned",
+ "entities": entities,
+ "merged_intervals": intervals,
+ "masked_text": "".join(pieces),
+ }
+
+
+def validate_url(url: str) -> str:
+ try:
+ parts = urlsplit(url)
+ _ = parts.port
+ except ValueError as exc:
+ raise ExampleError("--url / SIE_URL must be an absolute HTTP(S) URL") from exc
+ if parts.scheme not in {"http", "https"} or not parts.hostname:
+ raise ExampleError("--url / SIE_URL must be an absolute HTTP(S) URL")
+ if parts.username is not None or parts.password is not None or parts.query or parts.fragment:
+ raise ExampleError("put authentication in SIE_API_KEY; the URL must have no credentials, query or fragment")
+ return url.rstrip("/")
+
+
+class SingleAttempt:
+ def __init__(self, url: str) -> None:
+ parts = urlsplit(url)
+ self.expected_path = parts.path + EXTRACT_PATH
+ self.origin = (parts.scheme, parts.hostname, parts.port or (443 if parts.scheme == "https" else 80))
+ self.posts = 0
+ self.last_status: int | None = None
+
+ def on_request(self, request: httpx.Request) -> None:
+ parts = urlsplit(str(request.url))
+ origin = (parts.scheme, parts.hostname, parts.port or (443 if parts.scheme == "https" else 80))
+ if origin != self.origin:
+ raise SingleAttemptError("single-attempt blocked a request to another origin")
+ if request.method == "GET" and self.posts == 1:
+ return # The SDK may retrieve an already submitted result on this origin.
+ if request.method != "POST" or parts.path != self.expected_path or parts.query or self.posts:
+ raise SingleAttemptError("single-attempt blocked an unexpected request or second POST")
+ self.posts += 1
+
+ def on_response(self, response: httpx.Response) -> None:
+ self.last_status = response.status_code
+ if response.status_code >= 400:
+ # Raising here preserves the known status before any SDK retry branch.
+ raise SingleAttemptError(f"single-attempt stopped at HTTP {response.status_code}; no resend")
+
+
+def live_extract(
+ text: str,
+ url: str,
+ *,
+ timeout_s: float = 900,
+ no_auth: bool = False,
+ single_attempt: bool = False,
+ transport: httpx.BaseTransport | None = None,
+) -> dict[str, Any]:
+ # Optional dependencies: --show and --saved-composition use only the standard library.
+ import httpx
+ import msgpack
+ from sie_sdk import Item, SIEClient
+
+ url = str(httpx.URL(validate_url(url))).rstrip("/")
+ if not math.isfinite(timeout_s) or timeout_s <= 0:
+ raise ExampleError("timeout must be a finite positive number of seconds")
+
+ def check_wire_response(response: httpx.Response) -> None:
+ if response.status_code != 200:
+ return
+ try:
+ envelope = msgpack.unpackb(response.read(), raw=False)
+ except (ValueError, msgpack.UnpackException) as exc:
+ raise ExampleError("extraction returned malformed MessagePack") from exc
+ if not isinstance(envelope, dict) or envelope.get("error") is not None:
+ raise ExampleError("extraction returned an invalid envelope")
+ items = envelope.get("items")
+ if not isinstance(items, list) or len(items) != 1:
+ raise ExampleError("extraction did not return exactly one item")
+ validate_entities(text, items[0])
+
+ guard = SingleAttempt(url) if single_attempt else None
+ request_hooks = [guard.on_request] if guard else []
+ response_hooks = ([guard.on_response] if guard else []) + [check_wire_response]
+ with httpx.Client(
+ base_url=url,
+ follow_redirects=False,
+ transport=transport if transport is not None else httpx.HTTPTransport(retries=0),
+ timeout=httpx.Timeout(timeout_s),
+ event_hooks={"request": request_hooks, "response": response_hooks},
+ ) as http_client:
+ with SIEClient(
+ url,
+ api_key="" if no_auth else os.environ.get("SIE_API_KEY", ""),
+ timeout_s=timeout_s,
+ http_client=http_client,
+ ) as client:
+ if single_attempt:
+ result = client.extract(
+ MODEL,
+ Item(text=text),
+ options={"profile": PROFILE},
+ wait_for_capacity=False,
+ max_oom_retries=0,
+ provision_timeout_s=timeout_s,
+ )
+ else:
+ result = client.extract(
+ MODEL, Item(text=text), options={"profile": PROFILE}, provision_timeout_s=timeout_s
+ )
+ validate_entities(text, result)
+ return result
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ modes = parser.add_mutually_exclusive_group()
+ modes.add_argument("--show", action="store_true", help="print the logical request without dispatch")
+ modes.add_argument("--saved-composition", action="store_true", help="mask the saved composition reference offline")
+ parser.add_argument("--url", default=os.environ.get("SIE_URL"), help="SIE Cloud or self-hosted URL (or SIE_URL)")
+ parser.add_argument("--no-auth", action="store_true", help="do not send the optional SIE_API_KEY")
+ parser.add_argument(
+ "--single-attempt", action="store_true", help="stop at the first HTTP failure; at most one POST"
+ )
+ parser.add_argument(
+ "--timeout-seconds", type=float, default=900, help="SDK provision budget and HTTP phase timeout"
+ )
+ args = parser.parse_args(argv)
+ try:
+ text = load_input()
+ if args.show:
+ output = {"evidence": "logical request display; no HTTP request sent", **logical_request(text)}
+ elif args.saved_composition:
+ source = json.loads((DIRECTORY / "source.json").read_text(encoding="utf-8"))
+ output = render_result(text, {"entities": source["saved_composition"]["entities"]}, SAVED_EVIDENCE)
+ else:
+ if not args.url:
+ raise ExampleError("provide --url or SIE_URL for a live request")
+ result = live_extract(
+ text,
+ args.url,
+ timeout_s=args.timeout_seconds,
+ no_auth=args.no_auth,
+ single_attempt=args.single_attempt,
+ )
+ output = render_result(text, result, "live SDK response")
+ except ExampleError as exc:
+ print(f"Failure: {exc}. No masked output produced.", file=sys.stderr)
+ return 1
+ except Exception as exc:
+ # SDK/server/transport exception text can contain credential-bearing context.
+ print(f"Failure: {type(exc).__name__}; no valid extraction result. No masked output produced.", file=sys.stderr)
+ return 1
+ print(json.dumps(output, ensure_ascii=False, indent=2))
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/examples/redact/one-call/source.json b/examples/redact/one-call/source.json
new file mode 100644
index 000000000..7d9737b4f
--- /dev/null
+++ b/examples/redact/one-call/source.json
@@ -0,0 +1,249 @@
+{
+ "input": {
+ "file": "input.txt",
+ "index": 240,
+ "uid": "gretel-en-34966",
+ "sha256": "94ec9f7160c81390866958d9b33c2c5a9e98f854782eafc938f4e57418adfc62",
+ "utf8_bytes": 963,
+ "code_points": 962,
+ "copy_policy": "Complete original text; no final newline added, normalization, stripping or caller windows."
+ },
+ "sources": {
+ "fixture": {
+ "repository": "https://github.com/superlinked/sie",
+ "revision": "9f9eaa3d74684c081fce45386ec91ac137f3ac1a",
+ "path": "packages/sie_server/tests/adapters/fixtures/gliner_union/redact-documents.json",
+ "sha256": "27a46485552385b096933d05eb4e96722e0914becae5261645c2ad9daea42677",
+ "url": "https://github.com/superlinked/sie/blob/9f9eaa3d74684c081fce45386ec91ac137f3ac1a/packages/sie_server/tests/adapters/fixtures/gliner_union/redact-documents.json"
+ },
+ "retained_study": {
+ "dataset": "superlinked/sie-task-evidence",
+ "revision": "31383ae9986d9dc9edd4e3a06ee9fb40b223d6fb",
+ "input_path": "redact/inputs/gretel-main.jsonl",
+ "url": "https://huggingface.co/datasets/superlinked/sie-task-evidence/blob/31383ae9986d9dc9edd4e3a06ee9fb40b223d6fb/redact/inputs/gretel-main.jsonl"
+ },
+ "upstream": {
+ "dataset": "gretelai/synthetic_pii_finance_multilingual",
+ "url": "https://huggingface.co/datasets/gretelai/synthetic_pii_finance_multilingual",
+ "description": "Synthetic financial text; Apache-2.0 attribution from the public recorded study.",
+ "full_upstream_revision": null
+ }
+ },
+ "expected_model_configuration": {
+ "sie_id": "superlinked/pii-redact",
+ "source_revision": "9f9eaa3d74684c081fce45386ec91ac137f3ac1a",
+ "path": "packages/sie_server/models/superlinked__pii-redact.yaml",
+ "sha256": "7637549f4036cc91dc342fcfd19abb8218cb444673b5091968f80f993ea06f57",
+ "url": "https://github.com/superlinked/sie/blob/9f9eaa3d74684c081fce45386ec91ac137f3ac1a/packages/sie_server/models/superlinked__pii-redact.yaml",
+ "first_checkpoint": {
+ "model": "urchade/gliner_multi_pii-v1",
+ "revision": "1fcf13e85f4eef5394e1fcd406cf2ca9ea82351d"
+ },
+ "members": [
+ {
+ "model": "numind/NuNER_Zero",
+ "revision": "c90187673f464518dca09f41689184ed6976242c",
+ "options": {
+ "merge_adjacent_entities": true
+ }
+ }
+ ],
+ "tokenizer_dependencies": {
+ "microsoft/mdeberta-v3-base": "a0484667b22365f84929a935b5e50a51f71f159d",
+ "microsoft/deberta-v3-large": "64a8c8eab3e352a784c658aef62be1662607476f"
+ },
+ "profile": "default",
+ "adapter": "sie_server.adapters.gliner_union.adapter:GLiNERUnionAdapter",
+ "runtime": {
+ "score_floor": 0.6,
+ "window_words": 300,
+ "window_overlap": 50,
+ "propagate_label": "person",
+ "name_min_letters": 3,
+ "default_labels": [
+ "person",
+ "street address",
+ "city",
+ "county",
+ "postal code",
+ "gps coordinates",
+ "date of birth",
+ "phone number",
+ "fax number",
+ "email address",
+ "url",
+ "ip address",
+ "mac address",
+ "social security number",
+ "national id number",
+ "tax id number",
+ "medical record number",
+ "health plan beneficiary number",
+ "account number",
+ "credit card number",
+ "cvv",
+ "pin",
+ "password",
+ "api key",
+ "http cookie",
+ "username",
+ "customer id",
+ "employee id",
+ "certificate or license number",
+ "license plate",
+ "vehicle identification number",
+ "device identifier",
+ "biometric identifier",
+ "unique identifier",
+ "passport number",
+ "driver's license number"
+ ]
+ },
+ "word_counting": "GLiNER splitter, including punctuation; not text.split().",
+ "composition": "Both detectors run in server windows. Identical (start,end,label) spans keep the maximum score; differently labelled and overlapping spans remain. Case-sensitive whole-word person tokens of at least three letters propagate. Offsets refer to the original document.",
+ "usage": "Input tokens count each detector and each overlapping server window."
+ },
+ "sdk": {
+ "source_project_version": "0.10.0",
+ "source_revision": "9f9eaa3d74684c081fce45386ec91ac137f3ac1a",
+ "dependency_contract": "Root Python workspace uv.lock"
+ },
+ "logical_request": {
+ "method": "POST",
+ "path": "/v1/extract/superlinked/pii-redact",
+ "body": {
+ "items": [
+ {
+ "text": "------------------------------------------------------------------------------------------------------------------\n\nTrade Confirmation\n\nTrade Date: 05/12/2023\nPortfolio: Vintage Cars\nConfirmation: 123456789\n\nSecurities: 1 x 1963 Chevrolet Corvette Stingray (Restored)\nQuantity: 1\nPrice: $50,000.00\nSettlement Date: 10/08/2024\n\nSwift BIC Code: FRZIUSNZ985\nSSN: 324-78-5893\nName: Alejandra Santamaría-Castilla\nStreet Address: 6074 Chaney Dam, Apt. 293\n\nDelivery Instructions:\n- Securities will be delivered to the above mentioned address\n- Funds will be remitted to the bank specified in the Swift BIC Code\n\n------------------------------------------------------------------------------------------------------------------\n\nPlease contact us if you have any questions or concerns regarding this trade confirmation.\n\nSincerely,\n\n[Trading Firm Name]\n[Trading Firm Address]\n[Trading Firm City, State, Zip Code]\n[Trading Firm Phone Number]\n[Trading Firm Email Address]"
+ }
+ ],
+ "params": {
+ "options": {
+ "profile": "default"
+ }
+ }
+ },
+ "wire_format": "MessagePack; this JSON is a logical display."
+ },
+ "saved_composition": {
+ "evidence": "saved composition replay; not a one-call HTTP recording",
+ "origin": "The public fixture expected spans: caller composition of two saved model responses from the recorded study.",
+ "score_note": "Propagated reference spans can have score null; no live score equality is implied.",
+ "entities": [
+ {
+ "start": 224,
+ "end": 267,
+ "label": "license plate",
+ "score": 0.62744140625,
+ "text": "1963 Chevrolet Corvette Stingray (Restored)"
+ },
+ {
+ "start": 360,
+ "end": 371,
+ "label": "social security number",
+ "score": 0.99560546875,
+ "text": "324-78-5893"
+ },
+ {
+ "start": 372,
+ "end": 376,
+ "label": "person",
+ "score": null,
+ "text": "Name"
+ },
+ {
+ "start": 378,
+ "end": 407,
+ "label": "person",
+ "score": 0.99609375,
+ "text": "Alejandra Santamaría-Castilla"
+ },
+ {
+ "start": 424,
+ "end": 449,
+ "label": "street address",
+ "score": 0.990234375,
+ "text": "6074 Chaney Dam, Apt. 293"
+ },
+ {
+ "start": 826,
+ "end": 844,
+ "label": "person",
+ "score": 0.66162109375,
+ "text": "[Trading Firm Name"
+ },
+ {
+ "start": 847,
+ "end": 854,
+ "label": "person",
+ "score": null,
+ "text": "Trading"
+ },
+ {
+ "start": 855,
+ "end": 859,
+ "label": "person",
+ "score": null,
+ "text": "Firm"
+ },
+ {
+ "start": 870,
+ "end": 877,
+ "label": "person",
+ "score": null,
+ "text": "Trading"
+ },
+ {
+ "start": 878,
+ "end": 882,
+ "label": "person",
+ "score": null,
+ "text": "Firm"
+ },
+ {
+ "start": 896,
+ "end": 904,
+ "label": "postal code",
+ "score": 0.85498046875,
+ "text": "Zip Code"
+ },
+ {
+ "start": 907,
+ "end": 932,
+ "label": "phone number",
+ "score": 0.88525390625,
+ "text": "Trading Firm Phone Number"
+ },
+ {
+ "start": 920,
+ "end": 932,
+ "label": "phone number",
+ "score": 0.93212890625,
+ "text": "Phone Number"
+ },
+ {
+ "start": 934,
+ "end": 961,
+ "label": "email address",
+ "score": 0.7255859375,
+ "text": "[Trading Firm Email Address"
+ },
+ {
+ "start": 935,
+ "end": 961,
+ "label": "email address",
+ "score": 0.93212890625,
+ "text": "Trading Firm Email Address"
+ }
+ ]
+ },
+ "live_recording": null,
+ "deployment_runtime": {
+ "served_configuration": "unknown until observed",
+ "runtime_version": "unknown",
+ "installed_distribution_version": "unknown",
+ "device": "unknown",
+ "returned_revision_metadata": "unknown",
+ "checkpoint_load_receipts": "unknown"
+ }
+}
diff --git a/examples/redact/one-call/test_one_call.py b/examples/redact/one-call/test_one_call.py
new file mode 100644
index 000000000..e60f12777
--- /dev/null
+++ b/examples/redact/one-call/test_one_call.py
@@ -0,0 +1,249 @@
+"""Weightless checks of complete-input, masking and actual SDK wire behavior."""
+
+import hashlib
+import importlib.util
+import json
+from pathlib import Path
+from typing import Any
+
+import httpx
+import msgpack
+import pytest
+
+DIRECTORY = Path(__file__).resolve().parent
+SPEC = importlib.util.spec_from_file_location("redact_one_call", DIRECTORY / "run.py")
+assert SPEC is not None and SPEC.loader is not None
+example = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(example)
+BASE = "https://sie.example.test/prefix"
+
+
+def entity(text: str, start: int, end: int, label: str = "person") -> dict[str, Any]:
+ return {"start": start, "end": end, "text": text[start:end], "label": label, "score": 0.9}
+
+
+def response(items: Any) -> httpx.Response:
+ return httpx.Response(
+ 200,
+ content=msgpack.packb({"model": example.MODEL, "items": items}, use_bin_type=True),
+ headers={"Content-Type": "application/msgpack"},
+ )
+
+
+def test_complete_input_and_pins() -> None:
+ data = (DIRECTORY / "input.txt").read_bytes()
+ text = example.load_input()
+ assert hashlib.sha256(data).hexdigest() == "94ec9f7160c81390866958d9b33c2c5a9e98f854782eafc938f4e57418adfc62"
+ assert (len(data), len(text)) == (963, 962)
+ assert "Alejandra Santamaría-Castilla" in text
+ fixture = DIRECTORY.parents[2] / "packages/sie_server/tests/adapters/fixtures/gliner_union/redact-documents.json"
+ documents = json.loads(fixture.read_bytes())["documents"]
+ original = next(row for row in documents if row["index"] == 240)
+ assert data == original["text"].encode("utf-8")
+ source = json.loads((DIRECTORY / "source.json").read_text(encoding="utf-8"))
+ assert source["input"]["uid"] == "gretel-en-34966"
+ assert source["logical_request"]["body"] == example.logical_request(text)["body"]
+ assert "labels" not in source["logical_request"]["body"]["params"]
+ assert len(source["expected_model_configuration"]["runtime"]["default_labels"]) == 36
+
+
[email protected]("mode", ["--show", "--saved-composition"])
+def test_offline_modes_do_not_dispatch(mode: str, monkeypatch: pytest.MonkeyPatch, capsys: Any) -> None:
+ def fail_if_called(*args: Any, **kwargs: Any) -> None:
+ pytest.fail("offline mode attempted extraction")
+
+ monkeypatch.setattr(example, "live_extract", fail_if_called)
+ assert example.main([mode]) == 0
+ output = json.loads(capsys.readouterr().out)
+ if mode == "--show":
+ assert output["evidence"] == "logical request display; no HTTP request sent"
+ assert output["body"]["items"] == [{"text": example.load_input()}]
+ else:
+ assert output["evidence"] == example.SAVED_EVIDENCE
+ assert len(output["entities"]) == 15
+ assert len(output["merged_intervals"]) == 13
+ assert len(output["masked_text"]) == len(example.load_input())
+
+
+def test_unicode_overlap_union_preserves_original_code_points() -> None:
+ text = "A😀e\u0301 Santamaría Z!"
+ spans = [entity(text, 5, 10), entity(text, 1, 3), entity(text, 2, 4), entity(text, 1, 3)]
+ spans += [entity(text, 6, 8), entity(text, 9, 12), entity(text, 12, 14)]
+ output = example.render_result(text, {"entities": spans}, "test")
+ assert output["merged_intervals"] == [[1, 4], [5, 14]]
+ assert output["masked_text"] == "A███ █████████a Z!"
+ assert len(output["masked_text"]) == len(text)
+ assert len(text.encode("utf-8")) != len(text)
+ assert len(text.encode("utf-16-le")) // 2 != len(text)
+ # The combining mark is its own code point, even beside the masked base letter.
+ assert (
+ example.render_result(text, {"entities": [entity(text, 2, 3)]}, "test")["masked_text"]
+ == "A😀█\u0301 Santamaría Z!"
+ )
+
+
+ "bad",
+ [
+ {"start": True, "end": 2},
+ {"start": 0, "end": False},
+ {"start": -1, "end": 2},
+ {"start": 0, "end": 4},
+ {"start": 2, "end": 2},
+ {"start": 2, "end": 1},
+ {"start": 0.0, "end": 1},
+ {"start": None, "end": 1},
+ {"start": 0, "end": 1, "text": "z"},
+ {"start": 0, "end": 1, "label": None},
+ ],
+)
+def test_invalid_span_fails(bad: dict[str, Any]) -> None:
+ with pytest.raises(example.ExampleError):
+ example.render_result("abc", {"entities": [{**entity("abc", 0, 1), **bad}]}, "test")
+
+
+ "item",
+ [{}, {"entities": None}, {"entities": {}}, {"entities": [None]}, {"entities": [], "error": {"code": "FAILED"}}],
+)
+def test_incomplete_or_failed_item_is_not_clean(item: Any) -> None:
+ with pytest.raises(example.ExampleError):
+ example.render_result("abc", item, "test")
+
+
+def test_genuine_empty_entities_are_explicit() -> None:
+ output = example.render_result("abc", {"entities": []}, "test")
+ assert output["span_status"] == "no spans returned"
+ assert output["masked_text"] == "abc"
+ assert output["merged_intervals"] == []
+
+
[email protected]("single_attempt", [False, True])
[email protected]("no_auth", [False, True])
+def test_actual_sdk_one_post_msgpack_default_profile_and_auth(
+ single_attempt: bool, no_auth: bool, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ text = example.load_input()
+ calls = []
+ monkeypatch.setenv("SIE_API_KEY", "test-only-key")
+
+ def handle(request: httpx.Request) -> httpx.Response:
+ calls.append(request)
+ return response([{"entities": [entity(text, 378, 407)]}])
+
+ result = example.live_extract(
+ text, BASE, single_attempt=single_attempt, no_auth=no_auth, transport=httpx.MockTransport(handle)
+ )
+ assert len(calls) == 1
+ assert calls[0].method == "POST"
+ assert str(calls[0].url) == BASE + example.EXTRACT_PATH
+ assert calls[0].headers["Content-Type"] == "application/msgpack"
+ assert msgpack.unpackb(calls[0].content, raw=False) == example.logical_request(text)["body"]
+ assert ("Authorization" in calls[0].headers) is not no_auth
+ if not no_auth:
+ assert calls[0].headers["Authorization"] == "Bearer test-only-key"
+ output = example.render_result(text, result, "live SDK response")
+ assert output["entities"][0]["text"] == "Alejandra Santamaría-Castilla"
+ assert "test-only-key" not in json.dumps(output)
+
+
[email protected]("code", ["MODEL_LOADING", "QUEUE_FULL", "RESOURCE_EXHAUSTED"])
+def test_single_attempt_known_failure_is_retained_without_retry(code: str) -> None:
+ calls = []
+
+ def handle(request: httpx.Request) -> httpx.Response:
+ calls.append(request)
+ return httpx.Response(
+ 503, json={"error": {"code": code, "message": "retry later"}}, headers={"Retry-After": "0"}
+ )
+
+ with pytest.raises(example.SingleAttemptError, match="HTTP 503; no resend"):
+ example.live_extract("abc", BASE, single_attempt=True, transport=httpx.MockTransport(handle))
+ assert len(calls) == 1
+
+
+def test_transport_uncertainty_has_no_resend_or_masked_output(monkeypatch: pytest.MonkeyPatch, capsys: Any) -> None:
+ calls = []
+
+ def handle(request: httpx.Request) -> httpx.Response:
+ calls.append(request)
+ raise httpx.ReadError("test-only-secret")
+
+ original = example.live_extract
+
+ def extract(text: str, url: str, **kwargs: Any) -> Any:
+ return original(text, url, transport=httpx.MockTransport(handle), **kwargs)
+
+ monkeypatch.setattr(example, "live_extract", extract)
+ assert example.main(["--url", BASE, "--single-attempt"]) == 1
+ captured = capsys.readouterr()
+ assert captured.out == ""
+ assert "No masked output produced" in captured.err
+ assert "test-only-secret" not in captured.err
+ assert len(calls) == 1
+
+
+ "item", [{}, {"entities": {}}, {"entities": [], "error": {"code": "FAILED", "message": "failed"}}]
+)
+def test_missing_entities_or_item_error_on_actual_wire_fails(item: Any) -> None:
+ with pytest.raises(example.ExampleError):
+ example.live_extract("abc", BASE, transport=httpx.MockTransport(lambda request: response([item])))
+
+
+def test_ordinary_mode_keeps_cold_model_handling(monkeypatch: pytest.MonkeyPatch) -> None:
+ calls = []
+
+ def handle(request: httpx.Request) -> httpx.Response:
+ calls.append(request)
+ if len(calls) == 1:
+ return httpx.Response(
+ 503, json={"error": {"code": "MODEL_LOADING", "message": "loading"}}, headers={"Retry-After": "0"}
+ )
+ return response([{"entities": []}])
+
+ monkeypatch.setattr("sie_sdk.client.sync.time.sleep", lambda delay: None)
+ assert example.live_extract("abc", BASE, transport=httpx.MockTransport(handle))["entities"] == []
+ assert len(calls) == 2
+
+
+def test_single_attempt_blocks_second_post_before_transport() -> None:
+ calls = []
+ guard = example.SingleAttempt(BASE)
+ with httpx.Client(
+ transport=httpx.MockTransport(lambda request: calls.append(request) or response([{"entities": []}])),
+ event_hooks={"request": [guard.on_request]},
+ ) as client:
+ client.post(BASE + example.EXTRACT_PATH)
+ with pytest.raises(example.SingleAttemptError, match="second POST"):
+ client.post(BASE + example.EXTRACT_PATH)
+ assert len(calls) == 1
+
+
+def test_single_attempt_normalizes_url_and_allows_sdk_completion_get() -> None:
+ calls = []
+
+ def handle(request: httpx.Request) -> httpx.Response:
+ calls.append(request)
+ if request.method == "POST":
+ return httpx.Response(303, headers={"Location": "/result?__modal_attempt_token=test-only-token"})
+ return response([{"entities": []}])
+
+ result = example.live_extract(
+ "abc",
+ "HTTPS://SIE.EXAMPLE.TEST:443/prefix/",
+ single_attempt=True,
+ transport=httpx.MockTransport(handle),
+ )
+ assert result["entities"] == []
+ assert [request.method for request in calls] == ["POST", "GET"]
+ assert str(calls[0].url) == BASE + example.EXTRACT_PATH
+ assert all(request.url.host == "sie.example.test" for request in calls)
+
+
+ "url", ["localhost:8080", "http://user:[email protected]", "https://example.test?key=secret"]
+)
+def test_invalid_or_credential_bearing_url_is_rejected(url: str) -> None:
+ with pytest.raises(example.ExampleError):
+ example.validate_url(url)