Open-source inference server and production cluster for all the models your agent needs.
Python bgecolbertdata-pipelinedeep-learningembeddingsinferenceinference-serverinformation-retrievalllmmlmlopsnatural-language-processingnlppythonrerankingretrievalretrieval-augmented-generationsemantic-searchspladevector-search
release: v0.6.10
github-actions[bot]3cb1fd7277d4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 33562a820..efef53714 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,33 @@# Changelog+## v0.6.10++- chore(main): release 0.6.10+- fix: sync generation visibility api contract+- fix: improve generation failure observability+- feat(florence2): fix <OD> bbox conversion, re-task base-ft/large to COCO detection (#1347)+- feat(bench): floor measure-first dark models, retire donut-rvlcdip (#1347)+- fix(qwen3_vl_embedding): coalesce whitespace-only instruction to default+- test(qwen3_vl_embedding): pin empty/None instruction -> default contract+- fix(bench): align gliner label inputs+- fix(bench): align gliner v2.5 conll protocol+- fix(deploy): address payload-store review feedback+- feat(deploy): provision and enable the payload store by default+- fix(sie-cluster): address PR review findings on the self-host edge+- fix(sie-cluster): make AWS self-host turnkey (warm default + edge nits)+- fix(helm): let the MCP edge ingress drive cert-manager without a global gateway host+- fix(worker): preserve label order when batching extract requests+- fix(cluster): propagate --aws-region to terraform + standardize release name on 'sie'+- docs(sie_mcp): runbook must actively wait through cluster create/destroy+- docs(sie_mcp): clean-room AWS self-host runbook for a fresh agent+- refactor(sie_mcp): consolidate the offload skill into one surface-agnostic SKILL.md+- feat(helm): add sglang worker bundle to the AWS l4 pool+- docs(sie_mcp): local Cowork verification guide + example MCP client+- feat(helm): optional MCP-edge component for the sie-cluster chart+- feat(sie_mcp): containerize the MCP edge+- fix(qwen3_vl_embedding): pool post-RMSNorm last_hidden_state + normalize instruction (#1385)+- fix(sie-server): make transformers5 bundle reachable via pip (#826)+## v0.6.9- chore(main): release 0.6.9diff --git a/README.md b/README.mdindex f99714419..bc921e716 100644--- a/README.md+++ b/README.md@@ -10,8 +10,8 @@<h1>SIE: Superlinked Inference Engine</h1>-<p><strong>Open-source inference server and production cluster for embeddings, reranking, and extraction.</strong></p>-<p>85+ models. Three functions. From laptop to Kubernetes. All Apache 2.0.</p>+<p><strong>Self-hosted inference for agents. Every model your agents call, served from one open-source cluster in your cloud.</strong></p>+<p>85+ models: Stella, SPLADE, Qwen3, GLiNER, SigLIP, and more. One API. From laptop to Kubernetes. All Apache 2.0.</p><p><a href="https://superlinked.com/docs/">Docs</a> |@@ -28,7 +28,7 @@## About-SIE is an open-source inference engine that serves embeddings, reranking, and entity extraction through a single unified API. It replaces the patchwork of separate model servers with one system that handles 85+ models across dense, sparse, multi-vector, vision, and cross-encoder architectures.+SIE is an open-source inference engine that runs the models behind every agent task through one API: search and retrieval, document-to-markdown conversion, structured output, content safety, and the agent loop itself. It replaces the patchwork of a separate model server per task with one system that serves 85+ models, loading each on demand.- 85+ pre-configured models, hot-swappable, all quality-verified against MTEB in CI- Serves multiple models simultaneously with on-demand loading and LRU eviction@@ -36,6 +36,18 @@ SIE is an open-source inference engine that serves embeddings, reranking, and en- Integrates with LangChain, LlamaIndex, Haystack, DSPy, CrewAI, Chroma, Qdrant, and Weaviate- OpenAI-compatible `/v1/embeddings` endpoint for drop-in migration+## Tasks++One SIE cluster runs the inference behind a whole agent. Each task is a handful of swappable models; browse [`packages/sie_server/models/`](https://github.com/superlinked/sie/tree/main/packages/sie_server/models) for the full set.++| Task | What it does | Models |+|---|---|---|+| **Search** | Embed, match, and rerank to retrieve the right context. | `bge-m3`, `splade-v3`, `colbertv2`, `qwen3-reranker` |+| **Document to markdown** | PDFs, Office files, and scans become clean markdown. | `glm-ocr`, `mineru`, `paddleocr-vl`, `docling` |+| **Structured output** | Schema-valid JSON, extracted or generated. | `gliner2`, `nuner-zero`, `qwen3.6-27b` |+| **Guard content** | A safety verdict with a probability you threshold. | `granite-guardian-2b` |+| **Run the agent loop** | Plan steps and call tools with an open LLM, streaming included. | `qwen3.6-27b` |+## QuickstartSIE is a Docker container; your code calls it over HTTP. Start the container, install the SDK, run the example.@@ -66,7 +78,7 @@ pip install sie-sdk # Pythonpnpm add @superlinked/sie-sdk # TypeScript```-The entire API is three functions: `encode`, `score`, `extract`.+The same `SIEClient` talks to every model. Four of them, one call each:```pythonfrom sie_sdk import SIEClient@@ -76,11 +88,11 @@ client = SIEClient("http://localhost:8080")# First call to each model downloads weights from Hugging Face (seconds for# these tinies, longer for larger models). After that, calls are warm in ms.-# Encode: dense embeddings (all-MiniLM-L6-v2, ~90 MB)+# all-MiniLM-L6-v2: compact dense embeddings (~90 MB)result = client.encode("sentence-transformers/all-MiniLM-L6-v2", Item(text="Hello world"))print(result["dense"].shape) # (384,)-# Score: rerank documents by relevance (ms-marco MiniLM, ~80 MB)+# ms-marco-MiniLM: cross-encoder that reranks documents by relevance (~80 MB)scores = client.score("cross-encoder/ms-marco-MiniLM-L-6-v2",Item(text="What is machine learning?"),@@ -91,7 +103,7 @@ print(scores["scores"])# {'item_id': 'item-1', 'score': -11.048, 'rank': 1}]# (cross-encoder logits; relative order is what matters, not the absolute value)-# Extract: zero-shot named entity recognition, no training data+# GLiNER: zero-shot entity extraction with any labels, no training dataresult = client.extract("urchade/gliner_multi-v2.1",Item(text="Tim Cook is the CEO of Apple."),@@ -100,6 +112,24 @@ result = client.extract(print(result["entities"])# [{'text': 'Tim Cook', 'label': 'person', 'score': 0.991},# {'text': 'Apple', 'label': 'organization', 'score': 0.978}]++# Qwen3-0.6B: open-weight text generation (~1.2 GB). Generation needs a GPU and+# the generation image (latest-cuda12-sglang below), not the latest-cpu-default+# server above; SGLang has no CPU path.+result = client.generate(+ "Qwen/Qwen3-0.6B",+ "Reply with a single word: the capital of France.",+ max_new_tokens=16,+)+print(result["text"]) # 'Paris'+print(result["usage"]) # {'prompt_tokens': 12, 'completion_tokens': 1, 'total_tokens': 13}+```++`encode`, `score`, and `extract` run on the `latest-cpu-default` server above.+Generation ships in a separate GPU image (the `sglang` bundle); start it with:++```bash+docker run --gpus all -p 8080:8080 -v sie-hf-cache:/app/.cache/huggingface ghcr.io/superlinked/sie-server:latest-cuda12-sglang```For the equivalent TypeScript example, see the [TypeScript SDK docs](https://superlinked.com/docs/reference/typescript-sdk/). For more, see the [full quickstart guide](https://superlinked.com/docs/quickstart/) and [SDK reference](https://superlinked.com/docs/reference/sdk/).@@ -126,9 +156,8 @@ See the [deployment guide](https://superlinked.com/docs/deployment/).### Explore-[**85+ models**](https://superlinked.com/models): `Stella v5`, `BGE-M3`, `SPLADE v3`, `SigLIP`, `ColQwen2.5`, `BGE-reranker`, `GLiNER`, `Florence-2`, and [more](https://superlinked.com/models).-Dense, sparse, multi-vector, vision, rerankers, extractors. All pre-configured. All quality-verified against MTEB in CI.-Pass the full Hugging Face model ID to the SDK (e.g. `sentence-transformers/all-MiniLM-L6-v2`, `NovaSearch/stella_en_400M_v5`); see the [catalog](https://superlinked.com/models) for the complete list.+[**85+ models**](https://superlinked.com/models) across embedders, rerankers, extractors, and generators: dense, sparse, multi-vector, vision, cross-encoder, and generative architectures. All pre-configured, all quality-verified in CI.+Every model is a config in [`packages/sie_server/models/`](https://github.com/superlinked/sie/tree/main/packages/sie_server/models); pass its full Hugging Face ID to the SDK (e.g. `sentence-transformers/all-MiniLM-L6-v2`, `Qwen/Qwen3-4B-Instruct-2507`). Browse the rendered [catalog](https://superlinked.com/models) for the complete list.[**Integrations**](https://superlinked.com/docs/integrations/): LangChain, LlamaIndex, Haystack, DSPy, CrewAI, Chroma, Qdrant, Weaviate.diff --git a/deploy/helm/sie-cluster/Chart.yaml b/deploy/helm/sie-cluster/Chart.yamlindex cf32212c7..b741b695c 100644--- a/deploy/helm/sie-cluster/Chart.yaml+++ b/deploy/helm/sie-cluster/Chart.yaml@@ -4,8 +4,8 @@ description: >-SIE (Search Inference Engine) Kubernetes deployment with gateway, GPU workers,and observabilitytype: application-version: 0.6.9 # x-release-please-version-appVersion: v0.6.9 # x-release-please-version+version: 0.6.10 # x-release-please-version+appVersion: v0.6.10 # x-release-please-versionkeywords:- inference- embeddingdiff --git a/deploy/helm/sie-cluster/README.md b/deploy/helm/sie-cluster/README.mdindex 484fe2b45..da84e1f80 100644--- a/deploy/helm/sie-cluster/README.md+++ b/deploy/helm/sie-cluster/README.md@@ -63,7 +63,7 @@ Pre-populate shared object storage with model weights so worker pods don't re-do**AWS (Terraform-managed bucket):**```bash-# 1. Provision the bucket via the AWS Terraform module (opt-in via create_model_cache=true)+# 1. Provision the bucket via the AWS Terraform module (created by default; create_model_cache=true)cd deploy/terraform/aws/examples/dev-g6-spotterraform apply@@ -81,6 +81,32 @@ The Terraform output already includes the `/models` prefix, so the same URL is u**Other clouds / BYO bucket:** point `workers.common.clusterCache.url` at any `s3://...`, `gs://...`, `abfs://...`, or `abfss://...` URL the workload identity can read; populate it with the same `sie-admin cache weights sync --dest ...` command.+## Payload store++Work items larger than 1MB (for example images or long documents) are too big to put on the NATS queue inline, so the gateway offloads the payload to object storage and enqueues only a reference; workers fetch it back. **This is required for >1MB requests**: without a payload store the gateway cannot enqueue them and the request fails.++It is therefore **enabled by default** (`payloadStore.enabled=true`) and is **decoupled from the optional cluster cache** above. When the payload store is enabled, the chart resolves a store URL and **fails the install if none is found**, so a missing payload store surfaces at deploy time instead of silently failing >1MB requests at runtime.++URL resolution, in order:++1. `payloadStore.url`, if set: the terraform `payload_store_url` output (the `/payloads` prefix of the shared bucket), or any `s3://` / `gs://` / `abfs(s)://` URL the workload identity can read and write.+2. otherwise derived from `workers.common.clusterCache.url` by swapping the trailing `/models` prefix for `/payloads` (the same bucket).++```bash+# The terraform modules provision the bucket by default (create_model_cache=true)+# and expose its /payloads URL:+helm upgrade --install sie-cluster . \+ --set payloadStore.url=$(terraform output -raw payload_store_url)+```++To run without large-payload support (for example a local/dev cluster), opt out:++```bash+helm upgrade --install sie-cluster . --set payloadStore.enabled=false+```++> **Upgrade note:** the payload store is on by default. An existing queue-mode install with *no* payload store and *no* cluster cache will fail on upgrade until it either sets a URL (above) or `payloadStore.enabled=false`. Installs that already set `workers.common.clusterCache.url` keep working; the payload store derives its URL from it.+## AutoscalingKEDA-based autoscaling with scale-to-zero support:diff --git a/deploy/helm/sie-cluster/templates/_helpers.tpl b/deploy/helm/sie-cluster/templates/_helpers.tplindex 3655aff77..73c14ab01 100644--- a/deploy/helm/sie-cluster/templates/_helpers.tpl+++ b/deploy/helm/sie-cluster/templates/_helpers.tpl@@ -376,8 +376,16 @@ Runs from NOTES.txt so every install/upgrade is checked, regardless of which (or{{- fail (printf "Invalid configuration: ingress.tlsConfig.mode=%q. Must be one of: \"byo\", \"cert-manager\", \"self-signed\", \"disabled\"." $mode) }}{{- end }}{{- if eq $mode "cert-manager" }}-{{- if not $hosts }}-{{- fail "Invalid configuration: ingress.tlsConfig.mode=cert-manager requires ingress.host or ingress.hosts to be set (cert-manager has nothing to issue a certificate against without a hostname)." }}+{{- /* The MCP edge ingress (mcpEdge.ingress.host) is its own cert-manager-issued host on+ its own TLS secret, independent of the gateway ingress — so its hostname also+ satisfies this "cert-manager needs something to issue against" check. This lets the+ with-domain edge connector path enable cert-manager without forcing a global+ ingress.host (which would collide gateway + edge on the same host/path). */ -}}+{{- $mcpEdge := default (dict) .Values.mcpEdge }}+{{- $mcpEdgeIngress := default (dict) $mcpEdge.ingress }}+{{- $edgeHost := and $mcpEdge.enabled $mcpEdgeIngress.enabled (trim (default "" $mcpEdgeIngress.host)) }}+{{- if and (not $hosts) (not $edgeHost) }}+{{- fail "Invalid configuration: ingress.tlsConfig.mode=cert-manager requires ingress.host or ingress.hosts (gateway) or mcpEdge.ingress.host (MCP edge) to be set (cert-manager has nothing to issue a certificate against without a hostname)." }}{{- end }}{{- $certManager := default (dict) $tls.certManager }}{{- $kind := default "" $certManager.kind }}@@ -446,13 +454,15 @@ Templates that consume this should treat a non-empty result as "payloadstore enabled" and an empty result as "off".*/}}{{- define "sie-cluster.payloadStoreUrl" -}}+{{- if .Values.payloadStore.enabled -}}{{- if .Values.payloadStore.url -}}{{- .Values.payloadStore.url -}}-{{- else if and .Values.workers.common.clusterCache.enabled .Values.workers.common.clusterCache.url -}}+{{- else if .Values.workers.common.clusterCache.url -}}{{- $cache := trimSuffix "/" .Values.workers.common.clusterCache.url -}}{{- $base := trimSuffix "/models" $cache -}}{{- printf "%s/payloads" $base -}}{{- end -}}+{{- end -}}{{- end }}{{/*@@ -492,3 +502,49 @@ Returns a comma-joined, sorted list of distinct machine profiles.{{- end -}}{{- keys $profiles | sortAlpha | join "," -}}{{- end }}++{{/*+MCP edge (Req 12) — the hosted MCP server fronting the cluster's document jobs.+*/}}+{{- define "sie-cluster.mcpEdge.serviceName" -}}+{{- printf "%s-mcp" (include "sie-cluster.fullname" .) }}+{{- end }}++{{- define "sie-cluster.mcpEdge.labels" -}}+{{ include "sie-cluster.labels" . }}+app.kubernetes.io/component: mcp-edge+{{- end }}++{{- define "sie-cluster.mcpEdge.selectorLabels" -}}+{{ include "sie-cluster.selectorLabels" . }}+app.kubernetes.io/component: mcp-edge+{{- end }}++{{- define "sie-cluster.mcpEdge.image" -}}+{{- $tag := default .Chart.AppVersion .Values.mcpEdge.image.tag }}+{{- printf "%s:%s" .Values.mcpEdge.image.repository $tag }}+{{- end }}++{{/*+In-cluster URL the edge uses to reach the gateway (SIE_BASE_URL). Overridable+via mcpEdge.clusterBaseUrl; otherwise the in-namespace gateway Service.+*/}}+{{- define "sie-cluster.mcpEdge.clusterBaseUrl" -}}+{{- if .Values.mcpEdge.clusterBaseUrl -}}+{{- .Values.mcpEdge.clusterBaseUrl -}}+{{- else -}}+{{- printf "http://%s:%v" (include "sie-cluster.gateway.serviceName" .) .Values.gateway.service.port -}}+{{- end -}}+{{- end }}++{{/*+Name of the Secret holding the connector secrets. Uses an existing Secret when+mcpEdge.existingSecretName is set; otherwise the chart-managed one.+*/}}+{{- define "sie-cluster.mcpEdge.secretName" -}}+{{- if .Values.mcpEdge.existingSecretName -}}+{{- .Values.mcpEdge.existingSecretName -}}+{{- else -}}+{{- printf "%s-connector-secrets" (include "sie-cluster.mcpEdge.serviceName" .) -}}+{{- end -}}+{{- end }}diff --git a/deploy/helm/sie-cluster/templates/gateway-deployment.yaml b/deploy/helm/sie-cluster/templates/gateway-deployment.yamlindex c44e81a7c..d75d74319 100644--- a/deploy/helm/sie-cluster/templates/gateway-deployment.yaml+++ b/deploy/helm/sie-cluster/templates/gateway-deployment.yaml@@ -40,6 +40,12 @@Supported schemes: s3:// (AWS), gs:// (GCP), abfs:// + abfss:// (AzureData Lake Storage Gen2 / Blob via the hierarchical namespace). */}}{{- $payloadStoreUrl := include "sie-cluster.payloadStoreUrl" . }}+{{- /* Payload store is required for work items >1MB in queue mode. If it is+ enabled (default) but no URL resolves, fail loudly rather than silently+ dropping >1MB requests at runtime. Opt out with payloadStore.enabled=false. */}}+{{- if and (eq $routing "queue") .Values.payloadStore.enabled (not $payloadStoreUrl) }}+ {{- fail "payloadStore.enabled=true but no payload-store URL resolved. Work items >1MB will fail without it. Set payloadStore.url to the terraform `payload_store_url` output (or workers.common.clusterCache.url for the shared bucket), or set payloadStore.enabled=false to disable. See deploy/helm/sie-cluster/README.md" }}+{{- end }}{{- if $payloadStoreUrl }}{{- if not (or (hasPrefix "s3://" $payloadStoreUrl) (hasPrefix "gs://" $payloadStoreUrl) (hasPrefix "abfs://" $payloadStoreUrl) (hasPrefix "abfss://" $payloadStoreUrl)) }}{{- fail (printf "payloadStore.url must be an object-store URL (s3://bucket/prefix, gs://bucket/prefix, or abfs(s)://[email protected]/prefix), not a local path; got %q" $payloadStoreUrl) }}@@ -216,7 +222,7 @@ spec:{{- end }}{{- with .Values.queueRouting }}- name: SIE_STREAM_MAX_AGE_S- value: {{ .streamMaxAgeSec | default 120 | quote }}+ value: {{ .streamMaxAgeSec | default 1800 | quote }}{{- with .staticQueuePools }}- name: SIE_GATEWAY_STATIC_QUEUE_POOLSvalue: {{ toJson . | quote }}diff --git a/deploy/helm/sie-cluster/templates/mcp-edge-deployment.yaml b/deploy/helm/sie-cluster/templates/mcp-edge-deployment.yamlnew file mode 100644index 000000000..ec1427435--- /dev/null+++ b/deploy/helm/sie-cluster/templates/mcp-edge-deployment.yaml@@ -0,0 +1,97 @@+{{- if .Values.mcpEdge.enabled }}+apiVersion: apps/v1+kind: Deployment+metadata:+ name: {{ include "sie-cluster.mcpEdge.serviceName" . }}+ namespace: {{ include "sie-cluster.namespace" . }}+ labels:+ {{- include "sie-cluster.mcpEdge.labels" . | nindent 4 }}+spec:+ {{- /* Single replica: the OAuth authorization-code store is in-process. */}}+ replicas: {{ .Values.mcpEdge.replicas }}+ selector:+ matchLabels:+ {{- include "sie-cluster.mcpEdge.selectorLabels" . | nindent 6 }}+ template:+ metadata:+ labels:+ {{- with .Values.podLabels }}+ {{- toYaml . | nindent 8 }}+ {{- end }}+ {{- include "sie-cluster.mcpEdge.selectorLabels" . | nindent 8 }}+ {{- with .Values.mcpEdge.podAnnotations }}+ annotations:+ {{- toYaml . | nindent 8 }}+ {{- end }}+ spec:+ {{- include "sie-cluster.imagePullSecrets" . | nindent 6 }}+ serviceAccountName: {{ include "sie-cluster.serviceAccountName" . }}+ containers:+ - name: mcp-edge+ image: {{ include "sie-cluster.mcpEdge.image" . }}+ imagePullPolicy: {{ .Values.mcpEdge.image.pullPolicy }}+ ports:+ - name: http+ containerPort: {{ .Values.mcpEdge.service.port }}+ protocol: TCP+ env:+ - name: SIE_BASE_URL+ value: {{ include "sie-cluster.mcpEdge.clusterBaseUrl" . | quote }}+ {{- if or .Values.mcpEdge.connectorSecrets .Values.mcpEdge.existingSecretName }}+ - name: SIE_MCP_CONNECTOR_SECRETS+ valueFrom:+ secretKeyRef:+ name: {{ include "sie-cluster.mcpEdge.secretName" . }}+ key: connector-secrets+ {{- end }}+ {{- if .Values.mcpEdge.publicUrl }}+ - name: SIE_MCP_PUBLIC_URL+ value: {{ .Values.mcpEdge.publicUrl | quote }}+ {{- end }}+ {{- if not .Values.mcpEdge.oauthEnabled }}+ - name: SIE_MCP_OAUTH_ENABLED+ value: "0"+ {{- end }}+ {{- if .Values.mcpEdge.clusterApiKey.existingSecretName }}+ - name: SIE_API_KEY+ valueFrom:+ secretKeyRef:+ name: {{ .Values.mcpEdge.clusterApiKey.existingSecretName }}+ key: {{ .Values.mcpEdge.clusterApiKey.secretKey }}+ {{- end }}+ - name: SIE_LOG_LEVEL+ value: {{ .Values.logging.level | quote }}+ {{- if .Values.logging.json }}+ - name: SIE_LOG_JSON+ value: "true"+ {{- end }}+ startupProbe:+ httpGet:+ path: /healthz+ port: http+ {{- toYaml .Values.mcpEdge.probes.startup | nindent 12 }}+ livenessProbe:+ httpGet:+ path: /healthz+ port: http+ {{- toYaml .Values.mcpEdge.probes.liveness | nindent 12 }}+ readinessProbe:+ httpGet:+ path: /healthz+ port: http+ {{- toYaml .Values.mcpEdge.probes.readiness | nindent 12 }}+ resources:+ {{- toYaml .Values.mcpEdge.resources | nindent 12 }}+ {{- with .Values.mcpEdge.nodeSelector }}+ nodeSelector:+ {{- toYaml . | nindent 8 }}+ {{- end }}+ {{- with .Values.mcpEdge.affinity }}+ affinity:+ {{- toYaml . | nindent 8 }}+ {{- end }}+ {{- with .Values.mcpEdge.tolerations }}+ tolerations:+ {{- toYaml . | nindent 8 }}+ {{- end }}+{{- end }}diff --git a/deploy/helm/sie-cluster/templates/mcp-edge-ingress.yaml b/deploy/helm/sie-cluster/templates/mcp-edge-ingress.yamlnew file mode 100644index 000000000..b900893b1--- /dev/null+++ b/deploy/helm/sie-cluster/templates/mcp-edge-ingress.yaml@@ -0,0 +1,71 @@+{{- /* The MCP edge gets its OWN host (/ -> edge), separate from the gateway+ ingress (/ -> gateway), so the OAuth well-known/authorize/token paths and+ /mcp don't collide with the gateway. Reuses the chart's nginx ++ cert-manager machinery; the cert lands in a dedicated TLS secret. */}}+{{- if and .Values.mcpEdge.enabled .Values.mcpEdge.ingress.enabled }}+{{- $host := required "mcpEdge.ingress.host is required when mcpEdge.ingress.enabled" (trim (default "" .Values.mcpEdge.ingress.host)) }}+{{- /* The edge and gateway ingresses both serve path / on their host. If they+ share a host the two Ingress objects collide; fail fast with guidance. */ -}}+{{- if .Values.ingress.enabled }}+{{- $gatewayHosts := include "sie-cluster.ingress.hosts" . | fromJsonArray }}+{{- if has (trim $host) $gatewayHosts }}+{{- fail (printf "Invalid configuration: mcpEdge.ingress.host (%s) collides with a gateway ingress host; both Ingresses would serve path / on the same hostname. Give the MCP edge a distinct host (e.g. sie-mcp.example.com)." $host) }}+{{- end }}+{{- end }}+{{- $tls := include "sie-cluster.ingressTlsConfig" . | fromYaml }}+{{- $tlsSecret := printf "%s-tls" (include "sie-cluster.mcpEdge.serviceName" .) }}+apiVersion: networking.k8s.io/v1+kind: Ingress+metadata:+ name: {{ include "sie-cluster.mcpEdge.serviceName" . }}+ namespace: {{ include "sie-cluster.namespace" . }}+ labels:+ {{- include "sie-cluster.mcpEdge.labels" . | nindent 4 }}+ {{- $annotations := dict }}+ {{- /* base64 documents can be large; MCP streamable-HTTP needs unbuffered,+ long-lived responses. */ -}}+ {{- $nginxDefaults := dict+ "nginx.ingress.kubernetes.io/proxy-body-size" "100m"+ "nginx.ingress.kubernetes.io/proxy-read-timeout" "600"+ "nginx.ingress.kubernetes.io/proxy-send-timeout" "600"+ "nginx.ingress.kubernetes.io/proxy-buffering" "off"+ }}+ {{- $annotations = merge $annotations $nginxDefaults }}+ {{- if .Values.ingress.annotations }}+ {{- $annotations = merge $annotations .Values.ingress.annotations }}+ {{- end }}+ {{- /* The edge does its own auth (connector secret + OAuth bridge); never put+ oauth2-proxy in front of it — Claude can't traverse a second auth wall. */ -}}+ {{- if and $tls.enabled (eq (default "byo" $tls.mode) "cert-manager") }}+ {{- $certManager := default (dict) $tls.certManager }}+ {{- $issuerAnnotation := ternary "cert-manager.io/cluster-issuer" "cert-manager.io/issuer" (eq $certManager.kind "ClusterIssuer") }}+ {{- $issuerName := $certManager.name }}+ {{- if not $issuerName }}{{ $issuerName = printf "%s-letsencrypt-prod" (include "sie-cluster.fullname" .) }}{{ end }}+ {{- $annotations = merge $annotations (dict $issuerAnnotation $issuerName) }}+ {{- end }}+ {{- if $annotations }}+ annotations:+ {{- toYaml $annotations | nindent 4 }}+ {{- end }}+spec:+ {{- if .Values.ingress.className }}+ ingressClassName: {{ .Values.ingress.className }}+ {{- end }}+ {{- if $tls.enabled }}+ tls:+ - hosts:+ - {{ $host | quote }}+ secretName: {{ $tlsSecret }}+ {{- end }}+ rules:+ - host: {{ $host | quote }}+ http:+ paths:+ - path: /+ pathType: Prefix+ backend:+ service:+ name: {{ include "sie-cluster.mcpEdge.serviceName" . }}+ port:+ number: {{ .Values.mcpEdge.service.port }}+{{- end }}diff --git a/deploy/helm/sie-cluster/templates/mcp-edge-secret.yaml b/deploy/helm/sie-cluster/templates/mcp-edge-secret.yamlnew file mode 100644index 000000000..72bcefd28--- /dev/null+++ b/deploy/helm/sie-cluster/templates/mcp-edge-secret.yaml@@ -0,0 +1,14 @@+{{- /* Chart-managed connector-secret Secret. Skipped when the operator points+ mcpEdge.existingSecretName at a Secret they manage out-of-band. */}}+{{- if and .Values.mcpEdge.enabled .Values.mcpEdge.connectorSecrets (not .Values.mcpEdge.existingSecretName) }}+apiVersion: v1+kind: Secret+metadata:+ name: {{ include "sie-cluster.mcpEdge.secretName" . }}+ namespace: {{ include "sie-cluster.namespace" . }}+ labels:+ {{- include "sie-cluster.mcpEdge.labels" . | nindent 4 }}+type: Opaque+stringData:+ connector-secrets: {{ .Values.mcpEdge.connectorSecrets | quote }}+{{- end }}diff --git a/deploy/helm/sie-cluster/templates/mcp-edge-service.yaml b/deploy/helm/sie-cluster/templates/mcp-edge-service.yamlnew file mode 100644index 000000000..b2ab97563--- /dev/null+++ b/deploy/helm/sie-cluster/templates/mcp-edge-service.yaml@@ -0,0 +1,20 @@+{{- if .Values.mcpEdge.enabled }}+apiVersion: v1+kind: Service+metadata:+ name: {{ include "sie-cluster.mcpEdge.serviceName" . }}+ namespace: {{ include "sie-cluster.namespace" . }}+ labels:+ {{- include "sie-cluster.mcpEdge.labels" . | nindent 4 }}+spec:+ # Hardcoded ClusterIP: the edge is reached only via the TLS-terminating ingress;+ # a LoadBalancer/NodePort would expose it (and its bearer auth) without TLS.+ type: ClusterIP+ ports:+ - name: http+ port: {{ .Values.mcpEdge.service.port }}+ targetPort: http+ protocol: TCP+ selector:+ {{- include "sie-cluster.mcpEdge.selectorLabels" . | nindent 4 }}+{{- end }}diff --git a/deploy/helm/sie-cluster/templates/worker-statefulset.yaml b/deploy/helm/sie-cluster/templates/worker-statefulset.yamlindex 46af45e12..92087b8fe 100644--- a/deploy/helm/sie-cluster/templates/worker-statefulset.yaml+++ b/deploy/helm/sie-cluster/templates/worker-statefulset.yaml@@ -193,7 +193,7 @@ spec:- name: SIE_MAX_DELIVERvalue: {{ .maxDeliver | default 20 | quote }}- name: SIE_STREAM_MAX_AGE_S- value: {{ .streamMaxAgeSec | default 120 | quote }}+ value: {{ .streamMaxAgeSec | default 1800 | quote }}- name: SIE_NATS_FETCH_BUDGETvalue: {{ .natsFetchBudget | default 64 | quote }}{{- end }}@@ -369,7 +369,7 @@ spec:# Whoever creates the stream first wins, so both producers and# consumers must agree on max_age or retries race against purge.- name: SIE_STREAM_MAX_AGE_S- value: {{ .streamMaxAgeSec | default 120 | quote }}+ value: {{ .streamMaxAgeSec | default 1800 | quote }}{{- if .maxAckPending }}- name: SIE_MAX_ACK_PENDINGvalue: {{ .maxAckPending | quote }}diff --git a/deploy/helm/sie-cluster/values-aws.yaml b/deploy/helm/sie-cluster/values-aws.yamlindex 603d7df2e..99c60cb13 100644--- a/deploy/helm/sie-cluster/values-aws.yaml+++ b/deploy/helm/sie-cluster/values-aws.yaml@@ -134,9 +134,21 @@ workers:operator: Existseffect: NoSchedulebundles:+ # docs→markdown, describe_image, VL-OCR, encode/score/extract. Kept warm+ # (minReplicas: 1) — it serves the headline docs→markdown path, so a+ # dropped document converts immediately rather than waiting on a GPU+ # node + worker cold-start. Set to 0 to trade the always-on L4 for+ # scale-from-zero (cheaper, but the first request is slow).default:- minReplicas: 0+ minReplicas: 1maxReplicas: 10+ # Generation (Qwen3.5-4B via SGLang) — powers extract_structured /+ # generate_structured and answer_questions' answer step. Separate bundle+ # = its own worker (sie-worker-l4-sglang); scale-to-zero so it costs+ # nothing until a generation request arrives.+ sglang:+ minReplicas: 0+ maxReplicas: 4# ServiceAccount — Helm manages creation; IRSA annotation must be injected at deploy time.# NAMING CONTRACT: name must match module.sie_irsa_role namespace_service_accountsdiff --git a/deploy/helm/sie-cluster/values.yaml b/deploy/helm/sie-cluster/values.yamlindex 2a112876a..b3b8a79ac 100644--- a/deploy/helm/sie-cluster/values.yaml+++ b/deploy/helm/sie-cluster/values.yaml@@ -375,7 +375,12 @@ workers:# -- Model cache size limit (emptyDir - ephemeral, no zone-lock issues)cacheStorageSize: 300Gi- # -- Cluster cache (object storage) configuration+ # -- Cluster cache (object storage) for model WEIGHTS only. Optional+ # perf/offline feature (a cache miss falls back to HuggingFace), default+ # off. Decoupled from the payload store (top-level `payloadStore`), which+ # is required for >1MB work items and on by default. When clusterCache.url+ # is set, the payload store can derive its URL from the same bucket, but+ # the two toggle independently.clusterCache:enabled: false# -- Object-store URL with the /models prefix. Supported schemes:@@ -1104,8 +1109,9 @@ queueRouting:# Must be high enough to cover cold model downloads (10-60s+).maxDeliver: 20# -- Maximum age (seconds) for messages in the pool-level stream.- # Messages older than this are discarded. Set higher for slow model loads.- streamMaxAgeSec: 120+ # Keep above maxDeliver * 30s so failed work remains fetchable+ # after the retry/DLQ envelope for operator inspection.+ streamMaxAgeSec: 1800# -- Non-expiring pool objects synthesized by the gateway for Helm-declared# queue namespaces. Keys are queue pool names; names are normalized to# lowercase before gateway storage/routing. Use this when@@ -1142,41 +1148,41 @@ queueRouting:staleAfterSec: 30# -- Payload store for large work item payloads (images, long documents).-# When a work item exceeds 1MB, the payload is offloaded to this store.-# IMPORTANT: payloadStore.url must point to shared storage accessible by both-# gateway and worker pods. Supported schemes:-# - s3://<bucket>/<prefix> (AWS S3)-# - gs://<bucket>/<prefix> (GCP GCS)-# - abfs://<container>@<account>.dfs.core.windows.net/<prefix> (Azure ADLS Gen2)-# - abfss://... (same as abfs, TLS-only enforced by the SDK)-# Local filesystem paths (e.g., /tmp/payloads) will NOT work in queue mode-# because gateway and worker pods have different filesystems.+# When a work item exceeds 1MB, the gateway offloads the payload here and+# publishes only a reference to NATS; workers fetch it back. This is REQUIRED+# for >1MB requests in queue mode: with no payload store the gateway cannot+# offload, falls back to an inline publish, and NATS rejects it (1MB+# max_payload), so the request fails. It is therefore ENABLED BY DEFAULT and+# is decoupled from the optional model-weights cache+# (workers.common.clusterCache).#-# Auto-derivation: when workers.common.clusterCache.enabled=true and-# workers.common.clusterCache.url is set, the chart enables the payload store-# automatically and points it at the sibling /payloads prefix of the same-# bucket/container. By convention the terraform modules expose the cache URL as-# "<scheme>://<bucket-or-container>/models", and the chart strips a trailing-# "/models" segment before appending "/payloads" so the two features live at-# top-level sibling prefixes:-# <bucket>/models/... model weights (managed by sie-admin)-# <bucket>/payloads/... large work-item refs (managed by gateway)-# All three terraform modules (AWS, GCP, Azure) scope their workload IAM-# grants to these top-level prefixes, so the auto-derived URL aligns with the-# permissions out of the box. Set payloadStore.url explicitly only to override-# the default (e.g., a separate bucket); leaving it empty is the right call-# for most clusters.+# URL resolution (when enabled):+# 1. payloadStore.url, if set. Object storage only; local filesystem paths+# do NOT work in queue mode (gateway and workers have different+# filesystems) and are rejected.+# 2. else derived from workers.common.clusterCache.url by swapping a trailing+# "/models" prefix for "/payloads" (shared bucket, sibling prefixes:+# <bucket>/models/... model weights (managed by sie-admin)+# <bucket>/payloads/... large work-item refs (managed by gateway)).+# Supported schemes: s3:// (AWS), gs:// (GCP), abfs:// + abfss:// (Azure ADLS+# Gen2). All three terraform modules expose `payload_store_url` (the /payloads+# URL) and scope the workload IAM grant to that prefix, so the wiring aligns+# out of the box.+#+# If enabled and clusterRouting=queue but no URL resolves, the chart FAILS the+# install with guidance (see deploy/helm/sie-cluster/README.md). Set+# payloadStore.enabled=false to opt out and accept that >1MB requests will fail.payloadStore:- # -- Payload store URL. Supported schemes: s3://, gs://, abfs://, abfss://- # (s3://bucket/prefix, gs://bucket/prefix, or abfs(s)://[email protected]/prefix).- # Local paths are rejected when clusterRouting=queue (see gateway-deployment.yaml validation).- # Leave empty to auto-derive from workers.common.clusterCache.url (recommended).+ # -- Enable the payload store. Default true: required for >1MB work items.+ enabled: true+ # -- Payload store URL (object storage: s3://, gs://, abfs://, abfss://).+ # Empty derives from workers.common.clusterCache.url (the shared bucket's+ # /payloads sibling). Set explicitly to the terraform `payload_store_url`+ # output (or a separate bucket). Local paths are rejected in queue mode.url: ""- # -- TTL for stored payloads in seconds.- # For S3: configure via S3 lifecycle rules on the bucket.- # For GCS: configure via GCS lifecycle rules on the bucket.- # For Azure Blob: configure via lifecycle management rules on the storage account.- # This value is passed as SIE_PAYLOAD_STORE_TTL env var to the gateway.+ # -- TTL for stored payloads in seconds (passed to the gateway as+ # SIE_PAYLOAD_STORE_TTL). This is the runtime eviction hint; enforce actual+ # deletion via bucket lifecycle rules (S3 / GCS / Azure Blob).ttlSeconds: 300# =============================================================================@@ -1559,3 +1565,67 @@ kubernetes-event-exporter:limits:cpu: "100m"memory: "128Mi"++# =============================================================================+# MCP edge (Req 12) — hosted MCP server exposing the cluster's document jobs to+# Claude surfaces (Cowork / claude.ai / desktop app) over remote streamable-HTTP.+# A sie_sdk client of the gateway; holds no models. Default OFF so existing+# cluster deploys are unaffected.+# =============================================================================+mcpEdge:+ enabled: false+ image:+ repository: ghcr.io/superlinked/sie-mcp+ # Defaults to the chart appVersion when empty.+ tag: ""+ pullPolicy: IfNotPresent+ # Single replica: the OAuth authorization-code store is in-process, so a code+ # issued on one replica cannot be redeemed on another (see+ # packages/sie_mcp/plugin/superlinked.md operator notes). Keep at 1 until a+ # shared store lands with Req 10 (#1313).+ replicas: 1+ service:+ # type is hardcoded to ClusterIP in the template (security: the edge is only+ # reached via the TLS-terminating ingress), so it is intentionally not exposed here.+ port: 8088+ # Connector secrets (the per-user auth shim). Comma-separated `secret[:user_id]`.+ # Rendered into a chart-managed Secret when set; or point existingSecretName at+ # a Secret you manage (key: connector-secrets). NEVER commit a real secret here.+ connectorSecrets: ""+ existingSecretName: ""+ # SIE_MCP_PUBLIC_URL — the externally reachable https origin (e.g.+ # https://mcp.example.com). Pin it so OAuth metadata URLs are stable.+ publicUrl: ""+ # OAuth bridge for claude.ai / desktop connectors (#1312). Disable for+ # connector-secret-only (e.g. Cowork header) deployments.+ oauthEnabled: true+ # SIE_BASE_URL override; empty => the in-cluster gateway Service.+ clusterBaseUrl: ""+ # Optional cluster API key (SIE_API_KEY) from an existing Secret.+ clusterApiKey:+ existingSecretName: ""+ secretKey: api-key+ ingress:+ # The edge gets its OWN host (/ -> edge) to avoid colliding with the+ # gateway ingress (/ -> gateway). Reuses the chart's nginx + cert-manager.+ enabled: false+ host: ""+ resources:+ requests:+ cpu: "100m"+ memory: "256Mi"+ limits:+ cpu: "1"+ memory: "1Gi"+ probes:+ startup:+ periodSeconds: 5+ failureThreshold: 30+ liveness:+ periodSeconds: 10+ readiness:+ periodSeconds: 5+ podAnnotations: {}+ nodeSelector: {}+ affinity: {}+ tolerations: []diff --git a/integrations/sie_chroma/pyproject.toml b/integrations/sie_chroma/pyproject.tomlindex 04f42f162..5ede6f83c 100644--- a/integrations/sie_chroma/pyproject.toml+++ b/integrations/sie_chroma/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-chroma"-version = "0.6.9"+version = "0.6.10"description = "SIE integration for ChromaDB"readme = "README.md"requires-python = ">=3.10"diff --git a/integrations/sie_crewai/pyproject.toml b/integrations/sie_crewai/pyproject.tomlindex 06dcb383e..40bea516f 100644--- a/integrations/sie_crewai/pyproject.toml+++ b/integrations/sie_crewai/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-crewai"-version = "0.6.9"+version = "0.6.10"description = "SIE integration for CrewAI"readme = "README.md"requires-python = ">=3.10"diff --git a/integrations/sie_dspy/pyproject.toml b/integrations/sie_dspy/pyproject.tomlindex 8e550234d..bf1de361d 100644--- a/integrations/sie_dspy/pyproject.toml+++ b/integrations/sie_dspy/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-dspy"-version = "0.6.9"+version = "0.6.10"description = "SIE integration for DSPy"readme = "README.md"requires-python = ">=3.10"diff --git a/integrations/sie_haystack/pyproject.toml b/integrations/sie_haystack/pyproject.tomlindex 484ffc89e..4de266f27 100644--- a/integrations/sie_haystack/pyproject.toml+++ b/integrations/sie_haystack/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-haystack"-version = "0.6.9"+version = "0.6.10"description = "SIE integration for Haystack"readme = "README.md"requires-python = ">=3.10"diff --git a/integrations/sie_lancedb/pyproject.toml b/integrations/sie_lancedb/pyproject.tomlindex 5096f62cd..f5b375f86 100644--- a/integrations/sie_lancedb/pyproject.toml+++ b/integrations/sie_lancedb/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-lancedb"-version = "0.6.9"+version = "0.6.10"description = "SIE integration for LanceDB"requires-python = ">=3.12"dependencies = [diff --git a/integrations/sie_langchain/pyproject.toml b/integrations/sie_langchain/pyproject.tomlindex 6d6daea24..ff2db9ab8 100644--- a/integrations/sie_langchain/pyproject.toml+++ b/integrations/sie_langchain/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-langchain"-version = "0.6.9"+version = "0.6.10"description = "SIE integration for LangChain"requires-python = ">=3.10"dependencies = [diff --git a/integrations/sie_llamaindex/pyproject.toml b/integrations/sie_llamaindex/pyproject.tomlindex 5ccb69543..7b07b896c 100644--- a/integrations/sie_llamaindex/pyproject.toml+++ b/integrations/sie_llamaindex/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-llamaindex"-version = "0.6.9"+version = "0.6.10"description = "SIE integration for LlamaIndex"requires-python = ">=3.10"dependencies = [diff --git a/integrations/sie_qdrant/pyproject.toml b/integrations/sie_qdrant/pyproject.tomlindex a3f81689f..58e87cbbf 100644--- a/integrations/sie_qdrant/pyproject.toml+++ b/integrations/sie_qdrant/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-qdrant"-version = "0.6.9"+version = "0.6.10"description = "SIE integration for Qdrant"readme = "README.md"requires-python = ">=3.10"diff --git a/integrations/sie_ts_chroma/package.json b/integrations/sie_ts_chroma/package.jsonindex bc98635d5..e77dd5404 100644--- a/integrations/sie_ts_chroma/package.json+++ b/integrations/sie_ts_chroma/package.json@@ -1,6 +1,6 @@{"name": "@superlinked/sie-chroma",- "version": "0.6.9",+ "version": "0.6.10","description": "SIE embedding function for ChromaDB","type": "module","main": "./dist/index.cjs",diff --git a/integrations/sie_ts_lancedb/package.json b/integrations/sie_ts_lancedb/package.jsonindex b36a1b92d..342209c98 100644--- a/integrations/sie_ts_lancedb/package.json+++ b/integrations/sie_ts_lancedb/package.json@@ -1,6 +1,6 @@{"name": "@superlinked/sie-lancedb",- "version": "0.6.9",+ "version": "0.6.10","description": "SIE embedding function and reranker for LanceDB","type": "module","main": "./dist/index.cjs",diff --git a/integrations/sie_ts_langchain/package.json b/integrations/sie_ts_langchain/package.jsonindex bf17b994c..54e9697ae 100644--- a/integrations/sie_ts_langchain/package.json+++ b/integrations/sie_ts_langchain/package.json@@ -1,6 +1,6 @@{"name": "@superlinked/sie-langchain",- "version": "0.6.9",+ "version": "0.6.10","description": "SIE embeddings integration for LangChain.js","type": "module","main": "./dist/index.cjs",diff --git a/integrations/sie_ts_llamaindex/package.json b/integrations/sie_ts_llamaindex/package.jsonindex 728d7cc2a..91fcebc4d 100644--- a/integrations/sie_ts_llamaindex/package.json+++ b/integrations/sie_ts_llamaindex/package.json@@ -1,6 +1,6 @@{"name": "@superlinked/sie-llamaindex",- "version": "0.6.9",+ "version": "0.6.10","description": "SIE embeddings integration for LlamaIndex.TS","type": "module","main": "./dist/index.cjs",diff --git a/integrations/sie_weaviate/pyproject.toml b/integrations/sie_weaviate/pyproject.tomlindex 926224484..80d2f5d7e 100644--- a/integrations/sie_weaviate/pyproject.toml+++ b/integrations/sie_weaviate/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-weaviate"-version = "0.6.9"+version = "0.6.10"description = "SIE integration for Weaviate"readme = "README.md"requires-python = ">=3.10"diff --git a/packages/sie_gateway/Cargo.lock b/packages/sie_gateway/Cargo.lockindex ee58631db..dd947edeb 100644--- a/packages/sie_gateway/Cargo.lock+++ b/packages/sie_gateway/Cargo.lock@@ -2960,7 +2960,7 @@ checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"[[package]]name = "sie-gateway"-version = "0.6.9"+version = "0.6.10"dependencies = ["arc-swap","async-nats",diff --git a/packages/sie_gateway/Cargo.toml b/packages/sie_gateway/Cargo.tomlindex 78348d6bd..9815baa34 100644--- a/packages/sie_gateway/Cargo.toml+++ b/packages/sie_gateway/Cargo.toml@@ -1,6 +1,6 @@[package]name = "sie-gateway"-version = "0.6.9"+version = "0.6.10"edition = "2021"publish = falsediff --git a/packages/sie_gateway/docs/architecture-guide.md b/packages/sie_gateway/docs/architecture-guide.mdindex fc6ef04ea..1f6980887 100644--- a/packages/sie_gateway/docs/architecture-guide.md+++ b/packages/sie_gateway/docs/architecture-guide.md@@ -291,7 +291,7 @@ Per-subject transport:| Inference results | `_INBOX.{router_id}.{request_id}` | NATS Core | Gateway is waiting synchronously; a brief blip after publish but before delivery means the result is lost and the client retries (the gateway returns `503` with `X-SIE-Error-Code: MODEL_LOADING` and `Retry-After: 5` — see §2). Result payload is msgpack. || Config deltas | `sie.config.models.{bundle}`, `sie.config.models._all` | NATS Core | Lightweight fan-out. Gateway durability comes from the snapshot/export path (§4), not the bus. JSON payload (control plane, not hot path). The gateway subscribes on `_all`; worker-sidecar containers subscribe on their bundle subject and apply through Python IPC. || Worker health | `sie.health.>` | NATS Core | Ephemeral, last-heartbeat-wins. The gateway subscribes in `health_mode=nats` (see `discovery/nats_health.rs`) and supervises the subscriber task: reconnects normally resume in `async-nats`, but a terminated subscription stream is recreated with bounded backoff because there is no full-state health poller. Worker-sidecar containers publish this heartbeat and include the latest bundle hash after successful config apply; the **default `health_mode=ws`** still uses the Python WebSocket path. |-| DLQ advisories | `$JS.EVENT.ADVISORY.CONSUMER.MAX_DELIVERIES.>` | NATS Core (advisory) | JetStream emits these; the gateway subscribes in `queue/dlq.rs`. |+| DLQ advisories | `$JS.EVENT.ADVISORY.CONSUMER.MAX_DELIVERIES.>` | NATS Core (advisory) | JetStream emits these; gateway replicas subscribe in `queue/dlq.rs` and publish to `DEAD_LETTERS` with a deterministic `Nats-Msg-Id`, so JetStream dedupes replica fan-out. || DLQ storage | `sie.dlq.{model_token}` | JetStream | Single stream `DEAD_LETTERS` (Limits retention, memory storage, 24 h `max_age`) captures `sie.dlq.>`. `model_token` is derived from the advisory's original work subject by taking the model segment and replacing `/` with `_`. |### 8.2 Work-stream configuration and the model-ID constraint@@ -303,11 +303,11 @@ name: WORK_POOL_{pool}subjects: ["sie.work.{pool}.*.*.*"]retention: WorkQueuestorage: Memory-max_age: 60s (gateway-side)+max_age: 1800s (shared gateway/worker default)max_msgs: 100_000```-The worker-sidecar (`packages/sie_server_sidecar`, binary `sie-server-sidecar`) also calls `add_stream` with the **same** name but a default `max_age` of 120 s (`SIE_STREAM_MAX_AGE_S`). `get_or_create_stream` / `add_stream` does not update an existing stream's config, so whichever side races to the broker first wins. To avoid drift, pick one owner (either the gateway or the worker); the Helm values should set `SIE_STREAM_MAX_AGE_S` on workers to match the gateway's constant, or the gateway should read the same env.+max_age defaults to 1800 s on both the gateway (`SIE_STREAM_MAX_AGE_S`) and worker sidecar. The default intentionally stays above `max_deliver * 30s` for the pool consumer so the original work payload remains fetchable after the retry/DLQ envelope trips. `get_or_create_stream` / `add_stream` does not update an existing stream's config, so both gateway and sidecar reconcile existing stream `max_age` during stream ensure; keep the Helm value wired to both gateway and workers so they repair to the same target.When a gateway or sidecar observes an existing `WORK_POOL_{pool}` stream, itreconciles the stream subjects to exactly `sie.work.{pool}.*.*.*`. Legacydiff --git a/packages/sie_gateway/openapi.json b/packages/sie_gateway/openapi.jsonindex b7c2ae907..cf2a45dec 100644--- a/packages/sie_gateway/openapi.json+++ b/packages/sie_gateway/openapi.json@@ -1585,6 +1585,9 @@},"type": "array"},+ "pending_generation": {+ "$ref": "#/components/schemas/PendingGenerationSnapshot"+ },"status": {"type": "string"},@@ -1853,6 +1856,9 @@"no_bundles": {"type": "boolean"},+ "pending_generation": {+ "$ref": "#/components/schemas/PendingGenerationSnapshot"+ },"source": {"type": "string"}@@ -1950,6 +1956,9 @@},"type": "array"},+ "pending_generation": {+ "$ref": "#/components/schemas/PendingGenerationSnapshot"+ },"profiles": {"additionalProperties": {"$ref": "#/components/schemas/ProfileInfoWire"@@ -2289,6 +2298,75 @@],"type": "string"},+ "PendingGenerationGroup": {+ "properties": {+ "active_streams": {+ "format": "int64",+ "minimum": 0,+ "type": "integer"+ },+ "count": {+ "format": "int64",+ "minimum": 0,+ "type": "integer"+ },+ "display_model": {+ "type": "string"+ },+ "model": {+ "type": "string"+ },+ "oldest_request_age_ms": {+ "format": "int64",+ "minimum": 0,+ "type": "integer"+ },+ "pool": {+ "type": "string"+ },+ "republished": {+ "format": "int64",+ "minimum": 0,+ "type": "integer"+ },+ "waiting_first_chunk": {+ "format": "int64",+ "minimum": 0,+ "type": "integer"+ }+ },+ "required": [+ "model",+ "display_model",+ "pool",+ "count",+ "waiting_first_chunk",+ "active_streams",+ "republished",+ "oldest_request_age_ms"+ ],+ "type": "object"+ },+ "PendingGenerationSnapshot": {+ "properties": {+ "groups": {+ "items": {+ "$ref": "#/components/schemas/PendingGenerationGroup"+ },+ "type": "array"+ },+ "total": {+ "format": "int64",+ "minimum": 0,+ "type": "integer"+ }+ },+ "required": [+ "total",+ "groups"+ ],+ "type": "object"+ },"Pool": {"properties": {"spec": {@@ -2902,7 +2980,7 @@"url": "https://www.apache.org/licenses/LICENSE-2.0.html"},"title": "SIE Gateway",- "version": "0.6.9"+ "version": "0.6.10"},"openapi": "3.1.0","paths": {diff --git a/packages/sie_gateway/src/config.rs b/packages/sie_gateway/src/config.rsindex 7b4681604..313bb7d46 100644--- a/packages/sie_gateway/src/config.rs+++ b/packages/sie_gateway/src/config.rs@@ -342,7 +342,7 @@ impl Config {request_timeout: env_float("SIE_GATEWAY_REQUEST_TIMEOUT", 30.0),max_stream_pending: env_u64("SIE_GATEWAY_MAX_STREAM_PENDING", 50_000),- stream_max_age_s: env_u64("SIE_STREAM_MAX_AGE_S", 120),+ stream_max_age_s: env_u64("SIE_STREAM_MAX_AGE_S", 1_800),configured_gpus,gpu_profile_map,@@ -890,7 +890,7 @@ mod tests {fn test_stream_max_age_default_matches_worker_contract() {without_env(&["SIE_STREAM_MAX_AGE_S"], || {let cfg = Config::load();- assert_eq!(cfg.stream_max_age_s, 120);+ assert_eq!(cfg.stream_max_age_s, 1_800);});}diff --git a/packages/sie_gateway/src/handlers/config_api.rs b/packages/sie_gateway/src/handlers/config_api.rsindex a1eb5b7bf..8c46fb278 100644--- a/packages/sie_gateway/src/handlers/config_api.rs+++ b/packages/sie_gateway/src/handlers/config_api.rs@@ -191,6 +191,11 @@ async fn compute_model_status(// `all_bundles_acked` stays false.let mut all_acked = !model_info.bundles.is_empty();let model_pool = model_info.pool.as_deref().unwrap_or("default");+ let pending_generation = state+ .work_publisher+ .as_ref()+ .map(|publisher| publisher.pending_generation_for_model(&model_info.name))+ .unwrap_or_default();for bundle_id in &model_info.bundles {let expected = state@@ -247,6 +252,7 @@ async fn compute_model_status("all_bundles_acked": all_acked,"no_bundles": model_info.bundles.is_empty(),"bundles": bundles_out,+ "pending_generation": pending_generation,"source": "gateway-registry",})}@@ -463,7 +469,7 @@ mod tests {multi_router: false,request_timeout: 30.0,max_stream_pending: 50_000,- stream_max_age_s: 120,+ stream_max_age_s: 1_800,configured_gpus: Vec::new(),gpu_profile_map: HashMap::new(),static_queue_pools: Vec::new(),@@ -779,6 +785,7 @@ mod tests {serde_json::from_slice(&body_bytes(response).await).unwrap();assert_eq!(parsed["model_id"], "BAAI/bge-m3");assert_eq!(parsed["all_bundles_acked"], false);+ assert_eq!(parsed["pending_generation"]["total"], 0);let bundles = parsed["bundles"].as_array().unwrap();assert!(!bundles.is_empty());for bundle in bundles {@@ -956,6 +963,7 @@ mod tests {let status = compute_model_status(state.as_ref(), &entry).await;assert_eq!(status["all_bundles_acked"], false);assert_eq!(status["no_bundles"], true);+ assert_eq!(status["pending_generation"]["total"], 0);let bundles = status["bundles"].as_array().unwrap();assert!(bundles.is_empty());diff --git a/packages/sie_gateway/src/handlers/health.rs b/packages/sie_gateway/src/handlers/health.rsindex cc34591e3..ba674b70f 100644--- a/packages/sie_gateway/src/handlers/health.rs+++ b/packages/sie_gateway/src/handlers/health.rs@@ -119,6 +119,11 @@ pub async fn readyz() -> impl IntoResponse {)]pub async fn health(State(state): State<Arc<AppState>>) -> impl IntoResponse {let cluster = state.registry.get_cluster_status().await;+ let pending_generation = state+ .work_publisher+ .as_ref()+ .map(|publisher| publisher.pending_generation_snapshot())+ .unwrap_or_default();let status_str = if cluster.worker_count > 0 {"healthy"} else {@@ -142,6 +147,7 @@ pub async fn health(State(state): State<Arc<AppState>>) -> impl IntoResponse {},"workers": cluster.workers,"models": cluster.models,+ "pending_generation": pending_generation,})),)}@@ -164,6 +170,11 @@ async fn handle_cluster_status_ws(mut socket: WebSocket, state: Arc<AppState>) {loop {interval.tick().await;let status = state.registry.get_cluster_status().await;+ let pending_generation = state+ .work_publisher+ .as_ref()+ .map(|publisher| publisher.pending_generation_snapshot())+ .unwrap_or_default();// nested cluster sub-object in WS feedlet nested = serde_json::json!({"timestamp": status.timestamp,@@ -175,6 +186,7 @@ async fn handle_cluster_status_ws(mut socket: WebSocket, state: Arc<AppState>) {},"workers": status.workers,"models": status.models,+ "pending_generation": pending_generation,});let json = match serde_json::to_string(&nested) {Ok(j) => j,diff --git a/packages/sie_gateway/src/handlers/models.rs b/packages/sie_gateway/src/handlers/models.rsindex 261347c50..fedf879fe 100644--- a/packages/sie_gateway/src/handlers/models.rs+++ b/packages/sie_gateway/src/handlers/models.rs@@ -51,10 +51,12 @@ pub async fn get_models(State(state): State<Arc<AppState>>) -> impl IntoResponse.map(|name| {let worker_urls = model_workers.get(name).cloned().unwrap_or_default();let loaded = !worker_urls.is_empty();- match state.model_registry.get_model_info(name) {+ let mut body = match state.model_registry.get_model_info(name) {Some(entry) => entry.to_model_info_value(loaded),None => worker_only_model_info(name, loaded),- }+ };+ attach_pending_generation(&mut body, state.as_ref(), name);+ body}).collect();@@ -139,10 +141,22 @@ pub async fn get_model(Path(model): Path<String>, State(state): State<Arc<AppSta}}}+ attach_pending_generation(&mut body, state.as_ref(), &canonical_model);(StatusCode::OK, Json(body)).into_response()}+fn attach_pending_generation(body: &mut Value, state: &AppState, model: &str) {+ let pending_generation = state+ .work_publisher+ .as_ref()+ .map(|publisher| publisher.pending_generation_for_model(model))+ .unwrap_or_default();+ if let Some(map) = body.as_object_mut() {+ map.insert("pending_generation".to_string(), json!(pending_generation));+ }+}+fn canonical_worker_models(model_workers: HashMap<String, Vec<String>>,model_registry: &ModelRegistry,@@ -347,7 +361,7 @@ mod route_tests {multi_router: false,request_timeout: 30.0,max_stream_pending: 50_000,- stream_max_age_s: 120,+ stream_max_age_s: 1_800,configured_gpus: Vec::new(),gpu_profile_map: HashMap::new(),static_queue_pools: Vec::new(),@@ -588,6 +602,7 @@ mod route_tests {assert_eq!(models.len(), 1);assert_eq!(models[0]["name"], "BAAI/bge-m3");assert_eq!(models[0]["loaded"], false);+ assert_eq!(models[0]["pending_generation"]["total"], 0);}#[tokio::test]@@ -724,6 +739,7 @@ mod route_tests {assert_eq!(body["object"], "model");assert_eq!(body["owned_by"], "sie");assert!(body["created"].is_i64());+ assert_eq!(body["pending_generation"]["total"], 0);}#[tokio::test]diff --git a/packages/sie_gateway/src/openapi.rs b/packages/sie_gateway/src/openapi.rsindex 5ae67dda2..7fa9f4beb 100644--- a/packages/sie_gateway/src/openapi.rs+++ b/packages/sie_gateway/src/openapi.rs@@ -67,6 +67,8 @@ static OPENAPI_JSON: LazyLock<String> = LazyLock::new(|| {ConfigModelSummary,ConfigModelsResponse,crate::handlers::pools::CreatePoolRequest,+ crate::queue::publisher::PendingGenerationGroup,+ crate::queue::publisher::PendingGenerationSnapshot,ErrorDetailCore,StandardApiError,GpuNotConfiguredDetail,@@ -1928,6 +1930,8 @@ pub struct HealthResponse {pub cluster: ClusterSummary,pub workers: Vec<crate::types::worker::WorkerInfo>,pub models: Vec<crate::types::worker::ModelInfo>,+ #[serde(default)]+ pub pending_generation: crate::queue::publisher::PendingGenerationSnapshot,}#[derive(Debug, Serialize, Deserialize, ToSchema)]@@ -1966,6 +1970,8 @@ pub struct ModelInfoWire {/// ``capabilities.lora_adapters`` union summary.#[serde(skip_serializing_if = "Option::is_none")]pub capabilities: Option<ModelCapabilitiesWire>,+ #[serde(default)]+ pub pending_generation: crate::queue::publisher::PendingGenerationSnapshot,}/// Capability summary surfaced on each entry of ``GET /v1/models``.@@ -2092,6 +2098,8 @@ pub struct ModelConfigStatusResponse {pub all_bundles_acked: bool,pub no_bundles: bool,pub bundles: Vec<ModelAckBundleStatus>,+ #[serde(default)]+ pub pending_generation: crate::queue::publisher::PendingGenerationSnapshot,pub source: String,}diff --git a/packages/sie_gateway/src/queue/dlq.rs b/packages/sie_gateway/src/queue/dlq.rsindex 143606c41..1bbe2bea5 100644--- a/packages/sie_gateway/src/queue/dlq.rs+++ b/packages/sie_gateway/src/queue/dlq.rs@@ -2,7 +2,7 @@ use std::time::Duration;use async_nats::jetstream;use futures_util::StreamExt;-use tracing::{error, info, warn};+use tracing::{debug, error, info, warn};const DLQ_STREAM_NAME: &str = "DEAD_LETTERS";const DLQ_SUBJECT: &str = "sie.dlq.>";@@ -37,7 +37,11 @@ impl DlqListener {"dead letter queue stream ready");- // Subscribe to max-delivery advisory events+ // Subscribe every gateway replica to max-delivery advisories. The+ // publish into DEAD_LETTERS is stamped with a deterministic message id+ // below, so JetStream dedupes the fan-out while preserving HA: if one+ // replica sees the advisory but fails before publishing, another+ // replica can still persist it.let subscriber = client.subscribe(ADVISORY_SUBJECT.to_string()).await@@ -124,6 +128,7 @@ impl DlqListener {// Forward the advisory payload to the DLQ streamlet dlq_subject = format!("sie.dlq.{}", model_normalized);+ let message_id = dlq_message_id(&advisory, stream_name, consumer_name, stream_seq);// `jetstream.publish(...).await` returns a// `PublishAckFuture` once the client has queued the@@ -135,13 +140,29 @@ impl DlqListener {// per-message round-trip, which is acceptable here — DLQ// is a rare, degraded-state path, not the hot inference// loop.- let publish_result: Result<(), String> =- match jetstream.publish(dlq_subject.clone(), payload.into()).await {- Ok(ack_future) => ack_future.await.map(|_| ()).map_err(|e| e.to_string()),- Err(e) => Err(e.to_string()),- };+ let publish_result: Result<jetstream::publish::PublishAck, String> = match jetstream+ .send_publish(+ dlq_subject.clone(),+ jetstream::message::PublishMessage::build()+ .message_id(&message_id)+ .payload(payload.into()),+ )+ .await+ {+ Ok(ack_future) => ack_future.await.map_err(|e| e.to_string()),+ Err(e) => Err(e.to_string()),+ };match publish_result {- Ok(()) => {+ Ok(ack) if ack.duplicate => {+ debug!(+ subject = %dlq_subject,+ stream = %stream_name,+ seq = stream_seq,+ message_id = %message_id,+ "duplicate DLQ advisory publish deduped by JetStream"+ );+ }+ Ok(_) => {crate::metrics::DLQ_EVENTS.with_label_values(&[stream_name, consumer_name]).inc();@@ -169,9 +190,29 @@ impl DlqListener {}}+fn dlq_message_id(+ advisory: &serde_json::Value,+ stream_name: &str,+ consumer_name: &str,+ stream_seq: u64,+) -> String {+ advisory+ .get("id")+ .and_then(|v| v.as_str())+ .filter(|id| !id.is_empty())+ .map(|id| format!("dlq-advisory:{}", id))+ .unwrap_or_else(|| {+ format!(+ "dlq-advisory:{}:{}:{}",+ stream_name, consumer_name, stream_seq+ )+ })+}+#[cfg(test)]mod tests {use super::*;+ use serde_json::json;#[test]fn test_dlq_constants() {@@ -192,4 +233,31 @@ mod tests {let subject = format!("sie.dlq.{}", model_normalized);assert_eq!(subject, "sie.dlq.BAAI_bge-m3");}++ #[test]+ fn test_dlq_message_id_prefers_advisory_id() {+ let advisory = json!({"id": "abc-123"});+ assert_eq!(+ dlq_message_id(&advisory, "WORK_POOL_default", "consumer", 42),+ "dlq-advisory:abc-123"+ );+ }++ #[test]+ fn test_dlq_message_id_falls_back_to_stream_consumer_sequence() {+ let advisory = json!({});+ assert_eq!(+ dlq_message_id(&advisory, "WORK_POOL_default", "consumer", 42),+ "dlq-advisory:WORK_POOL_default:consumer:42"+ );+ }++ #[test]+ fn test_dlq_message_id_empty_string_falls_back_to_stream_consumer_sequence() {+ let advisory = json!({"id": ""});+ assert_eq!(+ dlq_message_id(&advisory, "WORK_POOL_default", "consumer", 42),+ "dlq-advisory:WORK_POOL_default:consumer:42"+ );+ }}diff --git a/packages/sie_gateway/src/queue/publisher.rs b/packages/sie_gateway/src/queue/publisher.rsindex 73fc6d1cc..024c05209 100644--- a/packages/sie_gateway/src/queue/publisher.rs+++ b/packages/sie_gateway/src/queue/publisher.rs@@ -1,3 +1,4 @@+use std::collections::BTreeMap;use std::sync::Arc;use std::time::{Duration, Instant};@@ -8,6 +9,7 @@ use futures_util::StreamExt;use serde::{Deserialize, Serialize};use tokio::sync::{broadcast, oneshot};use tracing::{debug, info, warn};+use utoipa::ToSchema;use rmp::decode::read_str_from_slice;use rmp::Marker;@@ -528,6 +530,78 @@ struct CachedStreamInfo {num_consumers: usize,}+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, ToSchema)]+pub struct PendingGenerationGroup {+ pub model: String,+ pub display_model: String,+ pub pool: String,+ pub count: u64,+ pub waiting_first_chunk: u64,+ pub active_streams: u64,+ pub republished: u64,+ pub oldest_request_age_ms: u64,+}++#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq, ToSchema)]+pub struct PendingGenerationSnapshot {+ pub total: u64,+ pub groups: Vec<PendingGenerationGroup>,+}++impl PendingGenerationSnapshot {+ pub fn for_model(&self, model_id: &str) -> Self {+ let groups: Vec<PendingGenerationGroup> = self+ .groups+ .iter()+ .filter(|group| group.display_model == model_id || group.model == model_id)+ .cloned()+ .collect();+ Self {+ total: groups.iter().map(|group| group.count).sum(),+ groups,+ }+ }+}++fn accumulate_pending_generation_group(+ grouped: &mut BTreeMap<(String, String, String), PendingGenerationGroup>,+ collector: &StreamCollector,+ now: Instant,+) {+ let key = (+ collector.model.clone(),+ collector.display_model.clone(),+ collector.pool.clone(),+ );+ let age_ms = now+ .saturating_duration_since(collector.published_at)+ .as_millis()+ .min(u128::from(u64::MAX)) as u64;++ let group = grouped+ .entry(key.clone())+ .or_insert_with(|| PendingGenerationGroup {+ model: key.0,+ display_model: key.1,+ pool: key.2,+ count: 0,+ waiting_first_chunk: 0,+ active_streams: 0,+ republished: 0,+ oldest_request_age_ms: 0,+ });+ group.count += 1;+ if collector.first_chunk_at.is_some() {+ group.active_streams += 1;+ } else {+ group.waiting_first_chunk += 1;+ }+ if collector.republished {+ group.republished += 1;+ }+ group.oldest_request_age_ms = group.oldest_request_age_ms.max(age_ms);+}+pub struct WorkPublisher {jetstream: jetstream::Context,router_id: String,@@ -1193,6 +1267,26 @@ impl WorkPublisher {"reconciled JetStream stream subjects to canonical queue lane routing");}+ let observed_max_age = stream.cached_info().config.max_age;+ if observed_max_age != self.stream_max_age {+ let mut updated = stream.cached_info().config.clone();+ updated.max_age = self.stream_max_age;+ self.jetstream+ .update_stream(updated)+ .await+ .map_err(|e| format!("update stream {} max_age: {}", name, e))?;+ stream = self+ .jetstream+ .get_stream(name.clone())+ .await+ .map_err(|e| format!("refresh stream {} after max_age update: {}", name, e))?;+ info!(+ stream = %name,+ observed_max_age_s = observed_max_age.as_secs(),+ desired_max_age_s = self.stream_max_age.as_secs(),+ "reconciled JetStream stream max_age"+ );+ }// Prime the backpressure cache so the very first request to// this pool sees real consumer/pending numbers instead of@@ -1801,6 +1895,26 @@ impl WorkPublisher {self.pending_streams.remove(request_id);}+ pub fn pending_generation_snapshot(&self) -> PendingGenerationSnapshot {+ let now = Instant::now();+ let mut grouped: BTreeMap<(String, String, String), PendingGenerationGroup> =+ BTreeMap::new();++ for entry in self.pending_streams.iter() {+ accumulate_pending_generation_group(&mut grouped, entry.value(), now);+ }++ let groups: Vec<PendingGenerationGroup> = grouped.into_values().collect();+ PendingGenerationSnapshot {+ total: groups.iter().map(|group| group.count).sum(),+ groups,+ }+ }++ pub fn pending_generation_for_model(&self, model_id: &str) -> PendingGenerationSnapshot {+ self.pending_generation_snapshot().for_model(model_id)+ }+/// Terminate an in-flight streaming request with a synthetic/// error outcome and fire the result sender so the HTTP handler/// returns immediately. Used by :meth:`handle_nak` when both the@@ -2852,6 +2966,51 @@ mod tests {);}+ #[test]+ fn test_pending_generation_snapshot_groups_collectors() {+ let now = Instant::now();+ let mut grouped: BTreeMap<(String, String, String), PendingGenerationGroup> =+ BTreeMap::new();++ let (tx1, _rx1) = oneshot::channel();+ let mut waiting = StreamCollector::new(tx1, "model-a:no-spec".into(), "default".into());+ waiting.display_model = "model-a".into();+ waiting.published_at = now.checked_sub(Duration::from_millis(250)).unwrap_or(now);+ accumulate_pending_generation_group(&mut grouped, &waiting, now);++ let (tx2, _rx2) = oneshot::channel();+ let mut active = StreamCollector::new(tx2, "model-a:no-spec".into(), "default".into());+ active.display_model = "model-a".into();+ active.first_chunk_at = Some(now);+ active.republished = true;+ active.published_at = now.checked_sub(Duration::from_millis(100)).unwrap_or(now);+ accumulate_pending_generation_group(&mut grouped, &active, now);++ let (tx3, _rx3) = oneshot::channel();+ let other = StreamCollector::new(tx3, "model-b".into(), "l4".into());+ accumulate_pending_generation_group(&mut grouped, &other, now);++ let groups: Vec<PendingGenerationGroup> = grouped.into_values().collect();+ let snapshot = PendingGenerationSnapshot {+ total: groups.iter().map(|group| group.count).sum(),+ groups,+ };++ assert_eq!(snapshot.total, 3);+ let model_a = snapshot.for_model("model-a");+ assert_eq!(model_a.total, 2);+ assert_eq!(model_a.groups.len(), 1);+ assert_eq!(model_a.groups[0].count, 2);+ assert_eq!(model_a.groups[0].waiting_first_chunk, 1);+ assert_eq!(model_a.groups[0].active_streams, 1);+ assert_eq!(model_a.groups[0].republished, 1);+ assert!(model_a.groups[0].oldest_request_age_ms >= 250);++ let model_b = snapshot.for_model("model-b");+ assert_eq!(model_b.total, 1);+ assert_eq!(model_b.groups[0].pool, "l4");+ }+#[test]fn test_normalize_model_id() {assert_eq!(normalize_model_id("BAAI/bge-m3"), "BAAI__bge-m3");diff --git a/packages/sie_mcp/Dockerfile b/packages/sie_mcp/Dockerfilenew file mode 100644index 000000000..e4659f6df--- /dev/null+++ b/packages/sie_mcp/Dockerfile@@ -0,0 +1,83 @@+# syntax=docker/dockerfile:1.6+# SIE MCP edge — hosted MCP server exposing SIE document jobs (Req 12).+# Lightweight image: a sie_sdk client, no GPU/model dependencies.+#+# Build (from repo root):+# docker build -t sie-mcp:latest -f packages/sie_mcp/Dockerfile .+#+# Run:+# docker run -p 8088:8088 \+# -e SIE_BASE_URL=https://your-gateway \+# -e SIE_MCP_CONNECTOR_SECRETS=your-secret \+# sie-mcp:latest++# =============================================================================+# Dependency builder: install the edge and its dependencies+# =============================================================================+FROM python:3.12-slim AS builder++WORKDIR /app++# Copy sie-sdk first (a dependency of sie-mcp); installing it editable satisfies+# the sie-sdk requirement so `pip install -e .` resolves without hitting PyPI.+COPY packages/sie_sdk /tmp/sie_sdk++# Copy sie-mcp files+COPY packages/sie_mcp/pyproject.toml ./+COPY packages/sie_mcp/src src/++# Create venv and install sie-sdk + sie-mcp (pulls mcp, starlette, uvicorn,+# typer, jsonschema, pypdfium2, pillow from PyPI).+RUN --mount=type=cache,target=/root/.cache/pip \+ python -m venv .venv \+ && .venv/bin/pip install --upgrade pip \+ && .venv/bin/pip install \+ -e /tmp/sie_sdk \+ -e "."++# Clean up to reduce image size+RUN find .venv -type d -name "__pycache__" -exec rm -rf {} + 2>/dev/null || true \+ && find .venv -type f -name "*.pyc" -delete 2>/dev/null || true \+ && find .venv -type d -name "tests" -exec rm -rf {} + 2>/dev/null || true \+ && find .venv -type d -name "test" -exec rm -rf {} + 2>/dev/null || true++# =============================================================================+# Runtime image: minimal MCP edge+# =============================================================================+FROM python:3.12-slim AS runtime++# Create non-root user+RUN useradd --create-home --shell /bin/bash sie++WORKDIR /app++# Copy virtual environment from builder+COPY --from=builder --chown=sie:sie /app/.venv /app/.venv++# Copy source code (pip -e creates editable installs with .pth pointing to src)+COPY --from=builder --chown=sie:sie /app/src /app/src++# Copy the plugin dir (SKILL.md etc.) so the in-container `sie-mcp skill-zip`+# helper can find it (cli.py resolves it at /app/plugin/SKILL.md).+COPY --chown=sie:sie packages/sie_mcp/plugin /app/plugin++# Copy sie-sdk source (installed as editable in /tmp)+COPY --from=builder --chown=sie:sie /tmp/sie_sdk/src /tmp/sie_sdk/src++ENV PATH="/app/.venv/bin:$PATH" \+ PYTHONUNBUFFERED=1 \+ PYTHONDONTWRITEBYTECODE=1++USER sie++# Default MCP edge port (sie_mcp.cli serve --port default)+EXPOSE 8088++# Health check — /healthz is unauthenticated and does not require the cluster.+HEALTHCHECK --interval=30s --timeout=5s --start-period=5s --retries=3 \+ CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8088/healthz')" || exit 1++# Default command — the connector-secret / cluster URL are supplied via env+# (SIE_BASE_URL, SIE_MCP_CONNECTOR_SECRETS, SIE_MCP_PUBLIC_URL, ...).+ENTRYPOINT ["sie-mcp", "serve"]+CMD ["--host", "0.0.0.0", "--port", "8088"]diff --git a/packages/sie_mcp/docs/examples/mcp_smoke.py b/packages/sie_mcp/docs/examples/mcp_smoke.pynew file mode 100644index 000000000..bc977fb41--- /dev/null+++ b/packages/sie_mcp/docs/examples/mcp_smoke.py@@ -0,0 +1,96 @@+# ruff: noqa: INP001 — standalone example script, not a package module.+"""End-to-end smoke for the SIE MCP edge, exactly as a Cowork connector calls it.++Connects to the remote streamable-HTTP MCP server with a connector-secret Bearer,+lists tools, and (optionally) calls docs_to_markdown on a local file.++Run it in the sie-mcp package env so the `mcp` client is importable:++ mise exec -- uv run --package sie-mcp python packages/sie_mcp/docs/examples/mcp_smoke.py \+ --url http://localhost:8088/mcp --secret <secret> --list++ mise exec -- uv run --package sie-mcp python packages/sie_mcp/docs/examples/mcp_smoke.py \+ --url http://localhost:8088/mcp --secret <secret> \+ --file packages/sie_mcp/docs/examples/sample.html --filename sample.html --engine docling+"""++import argparse+import asyncio+import base64+import json+import sys+from pathlib import Path+from typing import Any++from mcp import ClientSession+from mcp.client.streamable_http import streamablehttp_client+++def _unwrap(result: object) -> dict[str, Any]:+ """Return the tool's structured dict from a CallToolResult, tolerating shapes."""+ sc = getattr(result, "structuredContent", None)+ if sc:+ return sc+ for block in getattr(result, "content", []) or []:+ text = getattr(block, "text", None)+ if text:+ try:+ return json.loads(text)+ except json.JSONDecodeError:+ return {"_raw_text": text}+ return {"_repr": repr(result)}+++async def _run(args: argparse.Namespace, document_b64: str | None) -> int:+ headers = {"Authorization": f"Bearer {args.secret}"}+ async with (+ streamablehttp_client(args.url, headers=headers) as (read, write, _),+ ClientSession(read, write) as session,+ ):+ await session.initialize()+ tools = await session.list_tools()+ print("TOOLS:", [t.name for t in tools.tools])+ if document_b64 is None:+ return 0++ fname = args.filename or args.file.rsplit("/", 1)[-1]+ print(f"\nCALL docs_to_markdown(filename={fname!r}, engine={args.engine!r})")+ result = await session.call_tool(+ "docs_to_markdown",+ {"document_base64": document_b64, "filename": fname, "engine": args.engine},+ )+ if getattr(result, "isError", False):+ print("TOOL ERROR:")+ print(json.dumps(_unwrap(result), indent=2)[:4000])+ return 1+ payload = _unwrap(result)+ md = payload.get("markdown", "")+ print("\n--- METADATA ---")+ print(json.dumps(payload.get("metadata", {}), indent=2)[:3000])+ print("\n--- MARKDOWN (first 1500 chars) ---")+ print(md[:1500])+ print(f"\n--- markdown length: {len(md)} chars ---")+ return 0+++def main() -> int:+ ap = argparse.ArgumentParser()+ ap.add_argument("--url", default="http://localhost:8088/mcp")+ ap.add_argument("--secret", required=True)+ ap.add_argument("--list", action="store_true", help="list tools and exit")+ ap.add_argument("--file")+ ap.add_argument("--filename")+ ap.add_argument("--engine", default="docling")+ args = ap.parse_args()++ # Read the file synchronously here, outside the async client (avoids blocking+ # I/O inside the event loop).+ document_b64: str | None = None+ if args.file and not args.list:+ document_b64 = base64.b64encode(Path(args.file).read_bytes()).decode()++ return asyncio.run(_run(args, document_b64))+++if __name__ == "__main__":+ sys.exit(main())diff --git a/packages/sie_mcp/docs/examples/sample.html b/packages/sie_mcp/docs/examples/sample.htmlnew file mode 100644index 000000000..d8b855845--- /dev/null+++ b/packages/sie_mcp/docs/examples/sample.html@@ -0,0 +1,40 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="utf-8">+ <title>Superlinked SIE — Quarterly Service Memo</title>+</head>+<body>+ <h1>Quarterly Service Memo</h1>+ <p><strong>Date:</strong> 2026-06-15 <strong>Prepared for:</strong> Finance / Operations</p>++ <h2>1. Summary</h2>+ <p>This memo summarizes document-offload usage on the managed Superlinked+ inference cluster for the quarter. Converting documents to markdown before+ ingestion reduces the tokens billed for document-heavy agent work.</p>++ <h2>2. Usage by document type</h2>+ <table border="1" cellpadding="4" cellspacing="0">+ <thead>+ <tr><th>Document type</th><th>Files</th><th>Pages</th><th>Token reduction</th></tr>+ </thead>+ <tbody>+ <tr><td>PDF (born-digital)</td><td>412</td><td>3,980</td><td>82.6%</td></tr>+ <tr><td>DOCX</td><td>168</td><td>1,204</td><td>79.1%</td></tr>+ <tr><td>PPTX</td><td>54</td><td>620</td><td>88.3%</td></tr>+ <tr><td>Scanned PDF</td><td>37</td><td>451</td><td>74.0%</td></tr>+ </tbody>+ </table>++ <h2>3. Notes</h2>+ <ul>+ <li>Born-digital documents convert cleanly through the standard converter.</li>+ <li>Scanned pages route to a vision-language OCR model for higher-quality text.</li>+ <li>Question-answering uses transient retrieval inside the serving layer.</li>+ </ul>++ <h2>4. Recommendation</h2>+ <p>Continue routing document-heavy work through the offload path. The blended+ token reduction across the corpus this quarter was approximately 82.9%.</p>+</body>+</html>diff --git a/packages/sie_mcp/plugin/SKILL.md b/packages/sie_mcp/plugin/SKILL.mdnew file mode 100644index 000000000..849457e5b--- /dev/null+++ b/packages/sie_mcp/plugin/SKILL.md@@ -0,0 +1,123 @@+---+name: superlinked-docs+description: >-+ Offload document, image, and structured-output work to the Superlinked+ inference cluster: convert PDF/DOCX/PPTX/XLSX/HTML/scans to clean markdown,+ describe an image (caption + tags), or produce schema/grammar-constrained JSON+ off the cluster — instead of ingesting the file directly, which can reduce+ the tokens billed in many cases for document- and image-heavy work. Use+ whenever the user drops or references a document or image file to read,+ summarize, extract from, describe, or answer questions over, or when they need+ reliable structured (schema-valid) output.+---++# Superlinked document offload++When the user gives you a document (PDF, DOCX, PPTX, XLSX, HTML, or a scan), do **not**+open or attach the file into the conversation — that bills every page as text *and* a+page-image. Convert it to markdown on the Superlinked cluster first, then work from the+markdown.++## docs → markdown++1. Read the source file as **raw bytes** and base64-encode it. Do not view or attach it.+2. Call the `docs_to_markdown` MCP tool with:+ - `document_base64`: the base64-encoded bytes+ - `filename`: the original filename (its extension hints the format)+ - `engine`: leave as `auto` (default) — it runs the standard converter and+ automatically falls back to a vision OCR model for scanned/image-only pages, so+ scanned PDFs need no extra flag. Force `vl-ocr` for scanned or complex-layout+ PDFs you want OCR'd page-by-page, or `docling` to pin the standard converter.+ - `ocr`: leave `false`. It only turns on the standard converter's built-in OCR+ under `engine: docling`; under `auto` the vision-OCR fallback handles scans, so+ `ocr` is ignored there.+3. Write the returned `markdown` to a file named after the source, then read and reason+ over **that** file — never the original. Where to write it depends on the surface:+ - **Cowork** (connected folder): `.superlinked/<original-name>.md` (create `.superlinked/` if absent).+ - **claude.ai / Claude desktop app** (code-execution sandbox): `./<original-name>.md` in the+ working directory; offer to export it (Download, save to Google Drive, or add to a+ Project's knowledge to reuse it across chats).+ - **Claude Code** (local filesystem): alongside the source.+4. From here on, read and reason over the saved `.md` — never the original.++The tool response also includes a `metadata` object with two distinct figures: a live+per-call `markdown_tokens_estimate` (a rough ~4 chars/token count of *this* response — an+estimate, not a billed figure) and `token_reduction`, the committed #1311 benchmark+measurement of markdown vs direct document ingestion. Surface these if the user asks how+much was saved; the exact percentages and the benchmark path are in the metadata.++## Structured output (schema-valid JSON / constrained generation)++Two tools constrain the cluster's output at decode time, so the result is a reliable,+machine-parseable artifact instead of free text. Prefer these over asking a model to+"return JSON" — the constraint is enforced by the serving engine's grammar backend.++### extract → structured record++To pull a structured record out of text or markdown (e.g. the output of+`docs_to_markdown`), call the `extract_structured` MCP tool with:++- `content`: the source text/markdown to extract from+- `output_schema`: a JSON Schema describing the record+- `instruction` (optional): extra guidance on what to pull out+- `model` (optional): generation model override (defaults to the cluster's configured structured-output model)+- `max_output_tokens` (optional): raise the output-token ceiling for large records++You get back `{ "data": <object> }`. The model is constrained to `output_schema` at+decode time **and** the result is validated against it before return — if the serving+profile bypasses the constraint, you get a clear error instead of non-conforming JSON.+Values are grounded in `content` — the model is told not to invent them.++### generate → constrained output++To generate output under a constraint, call the `generate_structured` MCP tool with:++- `prompt`: the instruction to answer+- `response_format`: one of+ - `{"type": "json_schema", "json_schema": {"name": ..., "schema": <schema>, "strict": true}}`+ - `{"type": "json_object"}`+ - `{"type": "regex", "regex": "<pattern>"}`+ - `{"type": "grammar", "grammar": "<ebnf>", "syntax": "ebnf"}` (xgrammar-backed models only)+- `model` (optional): generation model override (defaults to the cluster's configured structured-output model)+- `max_output_tokens` (optional): raise the output-token ceiling for large output++You get back `{ "content": "<string>" }` (a JSON string for the json modes). A+`json_schema` result is validated against the schema before return.++### Schema limits++`output_schema` (and a `json_schema` `response_format`) must be in the Outlines-supported+subset: **no `$ref`** (so no recursion), **no conditionals** (`if`/`then`/`else`), nesting+**depth ≤ 16**. The schema must also stay within the gateway safety caps (≤ 16 384 nodes,+≤ 64 KiB serialized; `regex` ≤ 4 KiB). Out-of-subset or over-cap schemas are rejected up+front with a clear error. The default model is Outlines-backed, so **EBNF/`grammar` is not+available** on it — use `json_schema` or `regex` instead; an EBNF request is rejected with a+clear error.++## describe image++When the user gives you an image (PNG/JPEG) to caption, tag, or answer questions over,+do **not** open or attach the image into the conversation — that bills the image tokens.+Describe it on the Superlinked cluster first, then work from the returned text.++1. Read the image file as **raw bytes** and base64-encode it. Do not view or attach it.+2. Call the `describe_image` MCP tool with:+ - `image_base64`: the base64-encoded bytes+ - `labels` (optional): candidate tags to score against; omit to use the service's+ default label set+ - `detailed` (optional): `true` for a longer Florence-2 `<DETAILED_CAPTION>`+ - `top_k` (optional): how many of the top-scoring tags to return+3. You get back `caption` (a Florence-2 caption) and `tags` (a list of+ `{label, score}` ranked by zero-shot similarity to the image). Reason over those+ instead of the raw image.++The caption is produced by Florence-2; the tags are zero-shot — the cluster embeds the+candidate labels and the image (SigLIP/CLIP) and returns the closest labels. No image+pixels reach the calling model.++## Authentication++`docs_to_markdown`, `describe_image`, `extract_structured`, and `generate_structured` are all+served by the Superlinked MCP connector. Configure the connector with your **connector+secret** — credentials are never pasted into the chat. For this POC the connector secret is+provided by your cluster operator; self-serve issuance arrives with the managed service.diff --git a/packages/sie_mcp/plugin/superlinked.md b/packages/sie_mcp/plugin/superlinked.mdnew file mode 100644index 000000000..e44c68bf3--- /dev/null+++ b/packages/sie_mcp/plugin/superlinked.md@@ -0,0 +1,65 @@+# Install Superlinked document offload++`superlinked.md` is a router to each surface's **native** install path. There is no+drop-a-file auto-install — pick your surface below.++## Cowork (lead surface)++Install the **Superlinked plugin**, which provides this skill together with the remote MCP+connector. Configure the connector with your **connector secret** in the connector settings+(not in the chat).++Replace `<host>` below with your Superlinked deployment host (the address the MCP edge is+served at — e.g. the value of `SIE_MCP_HOST` for your cluster):++- MCP endpoint: `https://<host>/mcp`+- Auth header: `Authorization: Bearer <connector-secret>`+- Health check: `GET https://<host>/healthz`++## claude.ai (#1312)++claude.ai is a **two-piece** install: a custom **connector** (the remote MCP) plus a+**skill ZIP** (the agent skill). Unlike Cowork, claude.ai connectors are OAuth-only — you+cannot paste a connector secret into a header — so the connector secret is entered during+an OAuth sign-in instead. Requires a plan that allows custom connectors and skills+(Pro / Max / Team / Enterprise) with code execution enabled.++Replace `<host>` with your Superlinked deployment host (the externally reachable origin of+the MCP edge — set `SIE_MCP_PUBLIC_URL` to pin it for OAuth metadata).++### 1. Connector (remote MCP + OAuth)++1. In claude.ai go to **Customize → Connectors → `+` → Add custom connector**.+2. Enter the remote MCP server URL: `https://<host>/mcp`. Click **Add**.+3. Click **Connect** and complete the OAuth sign-in. On the Superlinked authorize page,+ enter your **connector secret** (provided by your cluster operator). The edge maps the+ secret to your user identity — credentials are never pasted into the chat.++The OAuth metadata, registration, authorize, and token endpoints are served by the same+edge (`/.well-known/oauth-protected-resource`, `/.well-known/oauth-authorization-server`,+`/register`, `/authorize`, `/token`); the connector-secret check at `/mcp` is unchanged.++### 2. Skill ZIP++1. Build the ZIP: `mise run mcp-skill-zip` (writes `dist/superlinked-docs-skill.zip`).+2. In claude.ai go to **Customize → Skills → `+` → Create skill → Upload a skill** and+ upload the ZIP. The archive contains a single `superlinked-docs/SKILL.md` folder, the+ format claude.ai expects.++### File-landing++Generated markdown is written **in the sandbox**; export it by **Download** or **save to+Google Drive**, and optionally add the downloaded file to a **Project**'s knowledge to+reuse it across chats. The skill drives this flow (there is no persistent connected folder+as on Cowork).++### Operator notes++- Pin `SIE_MCP_PUBLIC_URL` to the externally reachable origin so the OAuth metadata URLs+ are stable (otherwise they are derived per-request from forwarded host/proto headers).+- Run the edge as a **single worker** (the default `mise run mcp-serve`): the OAuth+ authorization-code store is in-process, so a code issued on one worker cannot be+ redeemed on another. A shared store lands with per-user key issuance in Req 10 (#1313).+- The OAuth redirect allowlist defaults to claude.ai's callback; override with+ `SIE_MCP_OAUTH_REDIRECT_URIS` (comma-separated). Set `SIE_MCP_OAUTH_ENABLED=0` to+ disable the bridge for Cowork-only deployments.diff --git a/packages/sie_mcp/pyproject.toml b/packages/sie_mcp/pyproject.tomlnew file mode 100644index 000000000..5a9f9528e--- /dev/null+++ b/packages/sie_mcp/pyproject.toml@@ -0,0 +1,35 @@+[project]+name = "sie-mcp"+version = "0.1.0"+description = "SIE MCP edge - hosted MCP server exposing SIE document jobs (Req 12)"+requires-python = ">=3.12,<3.13"+license = { text = "Apache-2.0" }+dependencies = [+ "mcp>=1.9,<2",+ "sie-sdk>=0.1",+ "starlette>=0.40",+ "uvicorn[standard]>=0.32,<1",+ "typer>=0.14,<1",+ # Post-validation of cluster output against the requested schema. Already a+ # transitive dependency via ``mcp``; declared directly since we import it.+ "jsonschema>=4",+ # VL-OCR routing (#1307): rasterize scanned/complex PDF pages for the VL-OCR model.+ "pypdfium2>=5.6.0",+ "pillow>=12.2.0",+]++[project.scripts]+sie-mcp = "sie_mcp.cli:app"++[build-system]+requires = ["hatchling"]+build-backend = "hatchling.build"++[tool.hatch.build.targets.wheel]+packages = ["src/sie_mcp"]++[dependency-groups]+dev = [+ "pytest>=9.0.3",+ "pytest-asyncio>=1.0",+]diff --git a/packages/sie_mcp/src/sie_mcp/__init__.py b/packages/sie_mcp/src/sie_mcp/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/packages/sie_mcp/src/sie_mcp/app.py b/packages/sie_mcp/src/sie_mcp/app.pynew file mode 100644index 000000000..3f2bc8a0a--- /dev/null+++ b/packages/sie_mcp/src/sie_mcp/app.py@@ -0,0 +1,28 @@+"""ASGI app for the SIE MCP edge: MCP streamable-HTTP transport + auth + health."""++from starlette.applications import Starlette+from starlette.requests import Request+from starlette.responses import JSONResponse+from starlette.routing import Route++from sie_mcp.auth import ConnectorSecretAuthMiddleware+from sie_mcp.config import MCPConfig+from sie_mcp.oauth import build_oauth_routes+from sie_mcp.server import build_server+++async def _healthz(_request: Request) -> JSONResponse:+ return JSONResponse({"status": "ok"})+++def build_app() -> Starlette:+ """Construct the ASGI app (uvicorn factory target)."""+ config = MCPConfig.from_env()+ app = build_server(config).streamable_http_app()+ app.router.routes.append(Route("/healthz", _healthz, methods=["GET"]))+ if config.oauth_enabled:+ # The OAuth bridge lets claude.ai connectors authenticate via the connector+ # secret (#1312); the gate below exempts these bootstrap endpoints.+ app.router.routes.extend(build_oauth_routes(config))+ app.add_middleware(ConnectorSecretAuthMiddleware, config=config)+ return appdiff --git a/packages/sie_mcp/src/sie_mcp/auth.py b/packages/sie_mcp/src/sie_mcp/auth.pynew file mode 100644index 000000000..d98623f90--- /dev/null+++ b/packages/sie_mcp/src/sie_mcp/auth.py@@ -0,0 +1,111 @@+"""Connector-secret auth at the MCP edge (the Req 12 shim).++A per-user connector secret (Bearer) is validated here and mapped to a stable+user identity, so per-user metering can attach later (Req 10, #1313). The cluster+credential the service uses downstream is held server-side and never travels+through this edge.++Implemented as pure ASGI (not ``BaseHTTPMiddleware``) so it does not buffer the+streaming MCP responses.+"""++from typing import Any++from starlette.datastructures import Headers+from starlette.responses import JSONResponse+from starlette.types import ASGIApp, Receive, Scope, Send++from sie_mcp.config import MCPConfig++# The OAuth bridge endpoints bootstrap auth for claude.ai connectors, so they sit+# in front of the connector-secret gate (#1312). Metadata + DCR + authorize + token+# must all be reachable unauthenticated.+_EXEMPT_PATHS = frozenset(+ {+ "/healthz",+ "/.well-known/oauth-protected-resource",+ "/.well-known/oauth-protected-resource/mcp",+ "/.well-known/oauth-authorization-server",+ "/register",+ "/authorize",+ "/token",+ }+)+++def base_url(config: MCPConfig, *, scheme: str, headers: Headers) -> str:+ """Resolve the externally reachable origin for OAuth metadata URLs.++ Prefers the pinned ``SIE_MCP_PUBLIC_URL``; otherwise derives it from forwarded+ proxy headers (falling back to the request's own scheme/host).+ """+ if config.public_base_url:+ return config.public_base_url+ proto = headers.get("x-forwarded-proto") or scheme+ host = headers.get("x-forwarded-host") or headers.get("host") or ""+ return f"{proto}://{host}"+++def bearer_token(authorization: str | None) -> str | None:+ if not authorization:+ return None+ value = authorization.strip()+ if not value:+ return None+ if value[:7].lower() == "bearer ":+ return value[7:].strip() or None+ # A bare "Bearer" scheme with no token is not a credential.+ if value.lower() == "bearer":+ return None+ # Otherwise accept a raw token sent without the scheme prefix.+ return value+++def authenticate(config: MCPConfig, token: str | None) -> str | None:+ """Return a user identity for the token, or ``None`` to reject the request."""+ if config.connector_secrets:+ if token and token in config.connector_secrets:+ return config.connector_secrets[token]+ if not token and config.allow_anonymous:+ return "anonymous"+ return None+ # No secrets configured: open only when anonymous access is explicitly allowed.+ return "anonymous" if config.allow_anonymous else None+++class ConnectorSecretAuthMiddleware:+ """Pure-ASGI auth gate that maps a connector secret to a user identity."""++ def __init__(self, app: ASGIApp, config: MCPConfig) -> None:+ self._app = app+ self._config = config++ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:+ if scope["type"] != "http" or scope.get("path") in _EXEMPT_PATHS:+ await self._app(scope, receive, send)+ return++ headers = Headers(scope=scope)+ token = bearer_token(headers.get("authorization"))+ identity = authenticate(self._config, token)+ if identity is None:+ response = JSONResponse(+ {"error": "unauthorized"},+ status_code=401,+ headers=self._challenge_headers(scope, headers),+ )+ await response(scope, receive, send)+ return++ state: dict[str, Any] = dict(scope.get("state") or {})+ state["user_id"] = identity+ scope["state"] = state+ await self._app(scope, receive, send)++ def _challenge_headers(self, scope: Scope, headers: Headers) -> dict[str, str]:+ """Point unauthenticated clients at the OAuth bridge (RFC 9728)."""+ if not self._config.oauth_enabled:+ return {}+ origin = base_url(self._config, scheme=scope.get("scheme", "http"), headers=headers)+ metadata = f"{origin}/.well-known/oauth-protected-resource"+ return {"WWW-Authenticate": f'Bearer resource_metadata="{metadata}"'}diff --git a/packages/sie_mcp/src/sie_mcp/chunking.py b/packages/sie_mcp/src/sie_mcp/chunking.pynew file mode 100644index 000000000..5e0e545a7--- /dev/null+++ b/packages/sie_mcp/src/sie_mcp/chunking.py@@ -0,0 +1,70 @@+"""Transient text chunking for ``answer_questions`` (#1309).++SIE has no chunking pipeline today, so this is a deliberately small,+self-contained primitive: a fixed-size sliding character window with overlap. It+runs entirely in the MCP edge per request — chunks are never persisted and no+index is built (the Req 12 "transient retrieval" boundary).++Character windows (not model-tokenizer windows) keep the job dependency-free and+predictable; sizes are expressed in characters and approximate a token budget at+the ~4-chars-per-token heuristic the edge already uses elsewhere. Precise token+accounting is the cluster's job, not the edge's.+"""++from collections.abc import Sequence+from dataclasses import dataclass+++@dataclass(frozen=True)+class Chunk:+ """A single passage carved from one source document.++ ``id`` is stable within a single call (``d{doc}-c{chunk}``) so the reranker+ can echo it back; ``doc_index`` and ``start`` point back to the source so a+ caller can locate the passage in the original text.+ """++ id: str+ text: str+ doc_index: int+ start: int+++def chunk_text(text: str, *, window: int, overlap: int) -> list[tuple[int, str]]:+ """Slide a fixed character window over ``text``, yielding ``(start, piece)``.++ ``overlap`` characters are shared between neighbouring windows so a passage+ straddling a boundary still lands whole in at least one window. Returns an+ empty list for empty text.+ """+ if window <= 0:+ msg = f"window must be positive, got {window}"+ raise ValueError(msg)+ if not 0 <= overlap < window:+ msg = f"overlap must satisfy 0 <= overlap < window, got overlap={overlap}, window={window}"+ raise ValueError(msg)+ stride = window - overlap+ windows: list[tuple[int, str]] = []+ start = 0+ length = len(text)+ while start < length:+ windows.append((start, text[start : start + window]))+ if start + window >= length:+ break+ start += stride+ return windows+++def chunk_documents(documents: Sequence[str], *, window: int, overlap: int) -> list[Chunk]:+ """Chunk a set of documents into overlapping windows.++ Empty / whitespace-only documents contribute no chunks. Chunk ids are unique+ within the returned list, so a reranker can echo them back unambiguously.+ """+ chunks: list[Chunk] = []+ for doc_index, document in enumerate(documents):+ if not document or not document.strip():+ continue+ for chunk_index, (start, piece) in enumerate(chunk_text(document, window=window, overlap=overlap)):+ chunks.append(Chunk(id=f"d{doc_index}-c{chunk_index}", text=piece, doc_index=doc_index, start=start))+ return chunksdiff --git a/packages/sie_mcp/src/sie_mcp/cli.py b/packages/sie_mcp/src/sie_mcp/cli.pynew file mode 100644index 000000000..972ed0447--- /dev/null+++ b/packages/sie_mcp/src/sie_mcp/cli.py@@ -0,0 +1,90 @@+"""CLI entry point for the SIE MCP edge service."""++import logging+from importlib.metadata import PackageNotFoundError+from importlib.metadata import version as _pkg_version+from pathlib import Path+from typing import Annotated++import typer+import uvicorn++from sie_mcp.skill_zip import build_skill_zip, skill_name++app = typer.Typer(name="sie-mcp", help="SIE MCP edge service (Req 12).", no_args_is_help=True)++_PACKAGE_ROOT = Path(__file__).resolve().parents[2]+_DEFAULT_SKILL_MD = _PACKAGE_ROOT / "plugin" / "SKILL.md"+++def _setup_logging(level: str) -> None:+ logging.basicConfig(+ level=level.upper(),+ format="%(asctime)s %(levelname)s %(name)s %(message)s",+ )+++def serve(+ host: Annotated[str, typer.Option("--host", "-h", help="Host to bind to.")] = "0.0.0.0", # noqa: S104 — intentional bind to all interfaces for the edge service+ port: Annotated[int, typer.Option("--port", "-p", help="Port to listen on.")] = 8088,+ log_level: Annotated[+ str,+ typer.Option("--log-level", "-l", envvar="SIE_LOG_LEVEL", help="Log level."),+ ] = "info",+ reload: Annotated[+ bool,+ typer.Option("--reload", "-r", help="Auto-reload for development."),+ ] = False,+) -> None:+ """Start the MCP edge over remote streamable-HTTP."""+ _setup_logging(log_level)+ uvicorn.run(+ "sie_mcp.app:build_app",+ host=host,+ port=port,+ factory=True,+ reload=reload,+ log_level=log_level.lower(),+ )++[email protected]("skill-zip")+def skill_zip(+ skill: Annotated[+ Path,+ typer.Option(+ "--skill", "-s", help="Path to the SKILL.md to package (default: the surface-agnostic plugin/SKILL.md)."+ ),+ ] = _DEFAULT_SKILL_MD,+ out: Annotated[+ Path | None,+ typer.Option("--out", "-o", help="Output .zip path (default: dist/<name>-skill.zip)."),+ ] = None,+) -> None:+ """Package the surface-agnostic Superlinked Agent Skill as a claude.ai-uploadable ZIP (#1312)."""+ if not skill.is_file():+ raise typer.BadParameter(f"SKILL.md not found at {skill}")+ text = skill.read_text(encoding="utf-8")+ data = build_skill_zip(text)+ target = out or (_PACKAGE_ROOT / "dist" / f"{skill_name(text)}-skill.zip")+ target.parent.mkdir(parents=True, exist_ok=True)+ target.write_bytes(data)+ typer.echo(f"wrote {target} ({len(data)} bytes)")+++def version() -> None:+ """Show version information."""+ try:+ typer.echo(f"sie-mcp {_pkg_version('sie-mcp')}")+ except PackageNotFoundError:+ typer.echo("sie-mcp (version unknown)")+++def main() -> None:+ app()+++if __name__ == "__main__":+ main()diff --git a/packages/sie_mcp/src/sie_mcp/config.py b/packages/sie_mcp/src/sie_mcp/config.pynew file mode 100644index 000000000..12691596c--- /dev/null+++ b/packages/sie_mcp/src/sie_mcp/config.py@@ -0,0 +1,250 @@+"""Environment-driven configuration for the SIE MCP edge service.++The edge holds one server-side cluster credential (`SIE_API_KEY`) and validates+per-user connector secrets at its own boundary — the Req 12 auth shim. Real+per-user key issuance + metering integrates later via Req 10 (#1313).+"""++import os+from dataclasses import dataclass++_DEFAULT_BASE_URL = "http://localhost:8080"+_DEFAULT_MODEL = "docling"+# answer_questions (#1309) model ids: dense encoder and cross-encoder reranker.+# The grounded-answer generator reuses _DEFAULT_GENERATE_MODEL (defined below).+_DEFAULT_ENCODE_MODEL = "BAAI/bge-m3"+_DEFAULT_RERANK_MODEL = "BAAI/bge-reranker-v2-m3"+# Passages fed to the generator, candidates kept before reranking, the character+# window / overlap the documents are chunked into (~4 chars/token), and the+# answer-length ceiling.+_DEFAULT_QA_TOP_K = 5+_DEFAULT_QA_RERANK_CANDIDATES = 20+_DEFAULT_QA_CHUNK_CHARS = 1200+_DEFAULT_QA_CHUNK_OVERLAP_CHARS = 200+_DEFAULT_QA_MAX_TOKENS = 512+# Input bounds for answer_questions. The edge holds every document's text in+# memory and sends all chunks in a single encode request, so unbounded inputs are+# a memory-exhaustion / model-fan-out vector (the same concern the document byte+# cap guards). Cap the total document size, the question count, and the number of+# chunks per call. Override via SIE_MCP_QA_MAX_*.+_DEFAULT_QA_MAX_DOCUMENT_CHARS = 2_000_000+_DEFAULT_QA_MAX_QUESTIONS = 50+_DEFAULT_QA_MAX_CHUNKS = 2000+_DEFAULT_CAPTION_MODEL = "microsoft/Florence-2-base-ft"+# CLIP is the zero-shot default: it is contrastively trained for cosine ranking,+# so client-side cosine/argmax separates labels cleanly. SigLIP's sigmoid-trained+# embeddings rank poorly under naive cosine (validated live on Modal) — override+# via SIE_MCP_EMBED_MODEL if you supply your own scoring.+_DEFAULT_EMBED_MODEL = "openai/clip-vit-base-patch32"+_DEFAULT_IMAGE_TOP_K = 5+# General-purpose zero-shot label set; callers may override per request.+_DEFAULT_IMAGE_LABELS: tuple[str, ...] = (+ "a photo of a person",+ "an animal",+ "food",+ "a landscape or nature scene",+ "a building or architecture",+ "a vehicle",+ "a product photo",+ "a screenshot",+ "a chart or diagram",+ "a document or text",+ "artwork or illustration",+ "a logo or icon",+)+# claude.ai's documented OAuth callback for remote-MCP custom connectors.+_DEFAULT_OAUTH_REDIRECT_URIS = ("https://claude.ai/api/mcp/auth_callback",)+# Production generation profile for the structured-output tools (Outlines-backed+# → json_schema + regex; EBNF is rejected up front by sie_mcp.structured).+_DEFAULT_GENERATE_MODEL = "Qwen/Qwen3.5-4B"+# Default output-token ceiling for the structured tools. The gateway's chat+# default is 1024, which truncates larger extraction/generation JSON; structured+# output is bounded but can exceed that, so default higher. A ceiling, not a+# target — small outputs still stop at the grammar's natural end.+_DEFAULT_MAX_OUTPUT_TOKENS = 4096++# Decoded-payload ceiling for a single document. The edge holds the whole document+# in memory (decode + rasterize), so an unbounded payload is a memory-exhaustion+# vector; 50 MiB comfortably covers real PDFs/scans. Override via SIE_MCP_MAX_DOCUMENT_BYTES.+DEFAULT_MAX_DOCUMENT_BYTES = 50 * 1024 * 1024++# Decoded-payload ceiling for a single image. Same memory-exhaustion concern as+# documents: describe_image base64-decodes the image into memory before sending it+# to the cluster. 20 MiB comfortably covers real JPEG/PNG photos and high-res scans+# rendered to images. Override via SIE_MCP_MAX_IMAGE_BYTES.+DEFAULT_MAX_IMAGE_BYTES = 20 * 1024 * 1024++# Provisional VL-OCR default for the scanned/complex-page quality upgrade (#1307).+# The committed OCR-engine choice is owned by Req 1's ADR (#955); pin MinerU2.5-Pro+# here as the demo default and re-source from #955 once that decision lands.+DEFAULT_VLOCR_MODEL = "opendatalab/MinerU2.5-Pro-2604-1.2B"+++def _parse_connector_secrets(raw: str) -> dict[str, str]:+ """Parse ``SIE_MCP_CONNECTOR_SECRETS`` into a ``{secret: user_id}`` map.++ Format: comma-separated entries, each ``secret`` or ``secret:user_id``. A bare+ secret maps to itself as a stable opaque identity, so per-user metering can+ attach later without changing the wire contract.+ """+ mapping: dict[str, str] = {}+ for chunk in raw.split(","):+ entry = chunk.strip()+ if not entry:+ continue+ secret, _, user_id = entry.partition(":")+ secret = secret.strip()+ if not secret:+ continue+ mapping[secret] = user_id.strip() or secret+ return mapping+++def _parse_redirect_uris(raw: str) -> tuple[str, ...]:+ """Parse ``SIE_MCP_OAUTH_REDIRECT_URIS`` into the OAuth redirect allowlist.++ Comma-separated absolute URIs. An empty value keeps the default (claude.ai's+ callback) so the common case needs no configuration.+ """+ uris = tuple(entry.strip() for entry in raw.split(",") if entry.strip())+ return uris or _DEFAULT_OAUTH_REDIRECT_URIS+++def _parse_csv(raw: str) -> list[str]:+ """Parse a comma-separated env value into a list of trimmed, non-empty items."""+ return [item.strip() for item in raw.split(",") if item.strip()]+++def _env_int(name: str, *, default: int, min_value: int = 1) -> int:+ # ``min_value`` is the lowest accepted value; below it (and for missing/blank/+ # non-integer values) we fall back to ``default``. Size/token limits keep+ # min_value=1 (a 0 cap is nonsensical); top_k passes min_value=0 so+ # SIE_MCP_IMAGE_TOP_K=0 is honored as a caption-only request.+ raw = os.getenv(name)+ if raw is None or not raw.strip():+ return default+ try:+ value = int(raw)+ except ValueError:+ return default+ return value if value >= min_value else default+++def _env_flag(name: str, *, default: bool) -> bool:+ raw = os.getenv(name)+ if raw is None:+ return default+ return raw.strip().lower() in {"1", "true", "yes", "on"}+++def _env_float(name: str, *, default: float) -> float:+ raw = os.getenv(name)+ if raw is None or not raw.strip():+ return default+ try:+ return float(raw)+ except ValueError:+ return default+++def _parse_labels(raw: str, *, default: tuple[str, ...]) -> list[str]:+ """Parse a comma-separated label set, falling back to ``default`` when unset."""+ if not raw.strip():+ return list(default)+ labels = [chunk.strip() for chunk in raw.split(",")]+ return [label for label in labels if label]+++@dataclass(frozen=True)+class MCPConfig:+ """Resolved edge configuration."""++ sie_base_url: str+ sie_api_key: str | None+ connector_secrets: dict[str, str]+ allow_anonymous: bool+ allowed_hosts: list[str]+ max_document_bytes: int+ max_image_bytes: int+ docling_model: str+ generate_model: str+ max_output_tokens: int+ vlocr_model: str+ encode_model: str+ rerank_model: str+ caption_model: str+ embed_model: str+ image_labels: list[str]+ image_top_k: int+ gpu: str | None+ timeout_s: float+ qa_top_k: int+ qa_rerank_candidates: int+ qa_chunk_chars: int+ qa_chunk_overlap_chars: int+ qa_max_tokens: int+ qa_max_document_chars: int+ qa_max_questions: int+ qa_max_chunks: int+ # claude.ai connectors are OAuth-only (no pasteable Bearer); the edge bridges+ # the OAuth handshake onto the connector-secret shim (#1312). `public_base_url`+ # pins the externally reachable origin used to build OAuth metadata URLs; when+ # unset it is derived per-request from forwarded host/proto headers.+ oauth_enabled: bool+ public_base_url: str | None+ oauth_redirect_uris: tuple[str, ...]++ @classmethod+ def from_env(cls) -> "MCPConfig":+ secrets = _parse_connector_secrets(os.getenv("SIE_MCP_CONNECTOR_SECRETS", ""))+ # Clamp the retrieval knobs so a misconfigured deployment can't produce+ # silently-wrong slicing (negative limits) or an opaque per-request+ # ValueError (overlap >= window); overlap is pinned below the window.+ chunk_chars = max(1, _env_int("SIE_MCP_QA_CHUNK_CHARS", default=_DEFAULT_QA_CHUNK_CHARS))+ chunk_overlap = min(+ max(0, _env_int("SIE_MCP_QA_CHUNK_OVERLAP_CHARS", default=_DEFAULT_QA_CHUNK_OVERLAP_CHARS)), chunk_chars - 1+ )+ return cls(+ sie_base_url=os.getenv("SIE_BASE_URL", _DEFAULT_BASE_URL),+ sie_api_key=os.getenv("SIE_API_KEY") or None,+ connector_secrets=secrets,+ # Fail closed: anonymous access is opt-in only. A missing/misnamed secret+ # env var must not silently expose the server-side cluster credential.+ allow_anonymous=_env_flag("SIE_MCP_ALLOW_ANONYMOUS", default=False),+ # Host header allow-list for DNS-rebinding protection; empty disables it+ # (remote edge behind TLS ingress + connector-secret auth). See server.py.+ allowed_hosts=_parse_csv(os.getenv("SIE_MCP_ALLOWED_HOSTS", "")),+ max_document_bytes=_env_int("SIE_MCP_MAX_DOCUMENT_BYTES", default=DEFAULT_MAX_DOCUMENT_BYTES),+ max_image_bytes=_env_int("SIE_MCP_MAX_IMAGE_BYTES", default=DEFAULT_MAX_IMAGE_BYTES),+ docling_model=os.getenv("SIE_MCP_DOCLING_MODEL", _DEFAULT_MODEL),+ generate_model=os.getenv("SIE_MCP_GENERATE_MODEL", _DEFAULT_GENERATE_MODEL),+ max_output_tokens=_env_int("SIE_MCP_MAX_OUTPUT_TOKENS", default=_DEFAULT_MAX_OUTPUT_TOKENS),+ # Treat an empty/whitespace override as unset so OCR routing keeps a real model id.+ vlocr_model=(os.getenv("SIE_MCP_VLOCR_MODEL") or "").strip() or DEFAULT_VLOCR_MODEL,+ encode_model=os.getenv("SIE_MCP_ENCODE_MODEL", _DEFAULT_ENCODE_MODEL),+ rerank_model=os.getenv("SIE_MCP_RERANK_MODEL", _DEFAULT_RERANK_MODEL),+ # Treat an empty/whitespace override as unset so a real model id always stands.+ caption_model=(os.getenv("SIE_MCP_CAPTION_MODEL") or "").strip() or _DEFAULT_CAPTION_MODEL,+ embed_model=(os.getenv("SIE_MCP_EMBED_MODEL") or "").strip() or _DEFAULT_EMBED_MODEL,+ image_labels=_parse_labels(os.getenv("SIE_MCP_IMAGE_LABELS", ""), default=_DEFAULT_IMAGE_LABELS),+ # min_value=0 so a caption-only request (SIE_MCP_IMAGE_TOP_K=0) is honored.+ image_top_k=_env_int("SIE_MCP_IMAGE_TOP_K", default=_DEFAULT_IMAGE_TOP_K, min_value=0),+ gpu=os.getenv("SIE_MCP_GPU") or None,+ # Document conversion can be slow on a cold model load; default generous.+ timeout_s=_env_float("SIE_MCP_TIMEOUT_S", default=300.0),+ qa_top_k=max(1, _env_int("SIE_MCP_QA_TOP_K", default=_DEFAULT_QA_TOP_K)),+ qa_rerank_candidates=max(+ 1, _env_int("SIE_MCP_QA_RERANK_CANDIDATES", default=_DEFAULT_QA_RERANK_CANDIDATES)+ ),+ qa_chunk_chars=chunk_chars,+ qa_chunk_overlap_chars=chunk_overlap,+ qa_max_tokens=max(1, _env_int("SIE_MCP_QA_MAX_TOKENS", default=_DEFAULT_QA_MAX_TOKENS)),+ qa_max_document_chars=max(+ 1, _env_int("SIE_MCP_QA_MAX_DOCUMENT_CHARS", default=_DEFAULT_QA_MAX_DOCUMENT_CHARS)+ ),+ qa_max_questions=max(1, _env_int("SIE_MCP_QA_MAX_QUESTIONS", default=_DEFAULT_QA_MAX_QUESTIONS)),+ qa_max_chunks=max(1, _env_int("SIE_MCP_QA_MAX_CHUNKS", default=_DEFAULT_QA_MAX_CHUNKS)),+ oauth_enabled=_env_flag("SIE_MCP_OAUTH_ENABLED", default=True),+ public_base_url=(os.getenv("SIE_MCP_PUBLIC_URL") or "").rstrip("/") or None,+ oauth_redirect_uris=_parse_redirect_uris(os.getenv("SIE_MCP_OAUTH_REDIRECT_URIS", "")),+ )diff --git a/packages/sie_mcp/src/sie_mcp/describe.py b/packages/sie_mcp/src/sie_mcp/describe.pynew file mode 100644index 000000000..df0e86d15--- /dev/null+++ b/packages/sie_mcp/src/sie_mcp/describe.py@@ -0,0 +1,179 @@+"""``describe_image`` — the Req 12 image-understanding job (#1310).++Stateless orchestration over two existing SIE primitives, run entirely+client-side in the MCP edge so the gateway and workers stay stateless per+request:++- **Caption** — the image's bytes go to the Florence-2 adapter via the+ ``extract`` path with a ``<CAPTION>`` / ``<DETAILED_CAPTION>`` task; the+ caption comes back as the extracted entity text.+- **Tags (zero-shot classify)** — done here in the edge: candidate labels and+ the image are embedded with ``encode`` (SigLIP/CLIP) and the top-k labels by+ cosine similarity to the image embedding are returned. No server-side+ endpoint — it is orchestration over the existing encode primitive.+"""++import asyncio+import base64+import binascii+import math+from typing import Any, Protocol, TypedDict++from sie_mcp.config import DEFAULT_MAX_IMAGE_BYTES++# Florence-2 caption task tokens; the detailed variant yields a longer caption.+_CAPTION_TASK = "<CAPTION>"+_DETAILED_CAPTION_TASK = "<DETAILED_CAPTION>"+++class DescribeImageError(Exception):+ """Raised when the cluster could not caption or classify the image."""+++class DescribeClient(Protocol):+ """The slice of ``SIEAsyncClient`` this job needs (keeps the job unit-testable)."""++ async def extract(self, model: str, items: Any, **kwargs: Any) -> Any:+ """Run an extract request against the SIE cluster."""++ async def encode(self, model: str, items: Any, **kwargs: Any) -> Any:+ """Run an encode request against the SIE cluster."""+++class Tag(TypedDict):+ label: str+ score: float+++class DescribeImageResult(TypedDict):+ caption: str+ tags: list[Tag]+++def _decode_base64(image_base64: str, *, max_bytes: int) -> bytes:+ # Reject oversize payloads from the base64 length before allocating the decoded+ # buffer (decoded size ≈ 3/4 of the encoded length), then enforce the exact bound.+ if (len(image_base64) // 4) * 3 > max_bytes:+ msg = f"image exceeds the {max_bytes}-byte limit"+ raise DescribeImageError(msg)+ try:+ data = base64.b64decode(image_base64, validate=True)+ except (binascii.Error, ValueError) as exc:+ msg = f"image_base64 is not valid base64: {exc}"+ raise DescribeImageError(msg) from exc+ if len(data) > max_bytes:+ msg = f"image exceeds the {max_bytes}-byte limit"+ raise DescribeImageError(msg)+ return data+++def _caption_text(result: Any) -> str:+ """Pull the caption string out of a Florence-2 ExtractResult.++ Captioning returns a single entity whose ``text`` is the caption; take the+ first entity that carries text. Returns ``""`` when none is present.+ """+ entities = result.get("entities") if isinstance(result, dict) else None+ if isinstance(entities, list):+ for entity in entities:+ if isinstance(entity, dict) and entity.get("text"):+ return str(entity["text"])+ return ""+++def _dense_vector(result: Any) -> list[float]:+ """Extract the dense embedding from an EncodeResult as ``list[float]``."""+ dense = result.get("dense") if isinstance(result, dict) else getattr(result, "dense", None)+ if dense is None:+ msg = "encode result missing dense embedding"+ raise DescribeImageError(msg)+ # The real SDK returns a numpy array (``.tolist()``); the list branch is for+ # test fakes that pass a plain list. Keep both — do not "simplify" either away.+ return dense.tolist() if hasattr(dense, "tolist") else [float(x) for x in dense]+++def _cosine(a: list[float], b: list[float]) -> float:+ """Cosine similarity; SigLIP/CLIP embeddings are not normalized by default.++ Callers must pass equal-length vectors (``_top_k_tags`` validates this); strict+ zip turns any dimension mismatch into an error rather than a silent truncation.+ """+ dot = sum(x * y for x, y in zip(a, b, strict=True))+ norm_a = math.sqrt(sum(x * x for x in a))+ norm_b = math.sqrt(sum(y * y for y in b))+ if norm_a == 0.0 or norm_b == 0.0:+ return 0.0+ return dot / (norm_a * norm_b)+++def _top_k_tags(+ image_vec: list[float],+ label_vecs: list[list[float]],+ labels: list[str],+ top_k: int,+) -> list[Tag]:+ """Rank labels by cosine similarity to the image, keep the top-k (argmax).++ Validates the embedding shapes up front and raises ``DescribeImageError`` on any+ mismatch, rather than silently dropping labels via a lenient zip.+ """+ if not image_vec:+ msg = "image embedding is empty"+ raise DescribeImageError(msg)+ if len(labels) != len(label_vecs):+ msg = f"got {len(label_vecs)} label embeddings for {len(labels)} labels"+ raise DescribeImageError(msg)+ scored: list[Tag] = []+ for label, label_vec in zip(labels, label_vecs, strict=True):+ if len(label_vec) != len(image_vec):+ msg = f"label embedding dim {len(label_vec)} != image embedding dim {len(image_vec)}"+ raise DescribeImageError(msg)+ scored.append(Tag(label=label, score=_cosine(image_vec, label_vec)))+ scored.sort(key=lambda tag: tag["score"], reverse=True)+ return scored[: max(top_k, 0)]+++async def describe_image(+ client: DescribeClient,+ *,+ image_base64: str,+ labels: list[str],+ caption_model: str,+ embed_model: str,+ detailed: bool = False,+ top_k: int = 5,+ gpu: str | None = None,+ max_image_bytes: int = DEFAULT_MAX_IMAGE_BYTES,+) -> DescribeImageResult:+ """Caption an image (Florence-2) and tag it via zero-shot classify (SigLIP/CLIP).++ The image's bytes go to the Florence-2 ``extract`` path for the caption; the+ same bytes plus the candidate ``labels`` are embedded with ``encode`` and the+ top-k labels by cosine similarity to the image become the tags. The tag step+ is skipped entirely (no encode call) when there are no labels or ``top_k <= 0``+ — a caption-only call costs no embedding work — and ``tags`` is empty. The+ decoded image is rejected before any cluster call once it exceeds+ ``max_image_bytes`` (memory-exhaustion guard, mirrors the document path).+ """+ data = _decode_base64(image_base64, max_bytes=max_image_bytes)+ image_item = {"images": [data]}++ task = _DETAILED_CAPTION_TASK if detailed else _CAPTION_TASK+ caption_result = await client.extract(caption_model, image_item, options={"task": task}, gpu=gpu)+ caption = _caption_text(caption_result)++ tags: list[Tag] = []+ if labels and top_k > 0:+ # ``top_k <= 0`` keeps no tags, so skip the embeds entirely — no point paying+ # for the label/image encodes on a caption-only call.+ # The label-batch and image embeds are independent — run them concurrently+ # so the tag path costs one round-trip of wall-clock, not two.+ label_results, image_result = await asyncio.gather(+ client.encode(embed_model, [{"text": label} for label in labels], gpu=gpu),+ client.encode(embed_model, image_item, gpu=gpu),+ )+ label_vecs = [_dense_vector(result) for result in label_results]+ image_vec = _dense_vector(image_result)+ tags = _top_k_tags(image_vec, label_vecs, labels, top_k)++ return DescribeImageResult(caption=caption, tags=tags)diff --git a/packages/sie_mcp/src/sie_mcp/documents.py b/packages/sie_mcp/src/sie_mcp/documents.pynew file mode 100644index 000000000..d2ea35521--- /dev/null+++ b/packages/sie_mcp/src/sie_mcp/documents.py@@ -0,0 +1,33 @@+"""Map a filename to the document format hint Docling expects.++Mirrors the suffix→format table the SDK uses for document inputs; the hint+becomes Docling's source name and an extension fallback when byte-sniffing is+ambiguous. Unknown/absent extensions return ``None`` and let Docling sniff.+"""++_SUFFIX_TO_FORMAT: dict[str, str] = {+ ".pdf": "pdf",+ ".docx": "docx",+ ".doc": "doc",+ ".pptx": "pptx",+ ".xlsx": "xlsx",+ ".csv": "csv",+ ".html": "html",+ ".htm": "html",+ ".xhtml": "html",+ ".md": "md",+ ".markdown": "md",+ ".txt": "txt",+ ".rtf": "rtf",+ ".odt": "odt",+}+++def format_from_filename(filename: str | None) -> str | None:+ if not filename:+ return None+ lowered = filename.lower()+ dot = lowered.rfind(".")+ if dot == -1:+ return None+ return _SUFFIX_TO_FORMAT.get(lowered[dot:])diff --git a/packages/sie_mcp/src/sie_mcp/jobs.py b/packages/sie_mcp/src/sie_mcp/jobs.pynew file mode 100644index 000000000..47dbf7e48--- /dev/null+++ b/packages/sie_mcp/src/sie_mcp/jobs.py@@ -0,0 +1,79 @@+"""``docs_to_markdown`` — the Req 12 docs→markdown job (#1306, thickened in #1307).++Stateless orchestration over the SIE ``extract`` primitive: a document's bytes go+to the cluster and come back as markdown. Docling is the front door for all+formats; scanned / complex-layout pages route to a VL-OCR model for better+quality (see :mod:`sie_mcp.ocr_routing`). Runs entirely client-side in the MCP+edge; the gateway and workers stay stateless per request.+"""++import base64+import binascii+from typing import Any, TypedDict++from sie_mcp import ocr_routing+from sie_mcp.config import DEFAULT_MAX_DOCUMENT_BYTES, DEFAULT_VLOCR_MODEL+from sie_mcp.documents import format_from_filename+from sie_mcp.ocr_routing import DocsToMarkdownError, EngineName, ExtractClient+from sie_mcp.savings import build_metadata+++class DocsToMarkdownResult(TypedDict):+ markdown: str+ metadata: dict[str, Any]+++def _decode_base64(document_base64: str, *, max_bytes: int) -> bytes:+ # Reject oversize payloads from the base64 length before allocating the decoded+ # buffer (decoded size ≈ 3/4 of the encoded length), then enforce the exact bound.+ if (len(document_base64) // 4) * 3 > max_bytes:+ msg = f"document exceeds the {max_bytes}-byte limit"+ raise DocsToMarkdownError(msg)+ try:+ data = base64.b64decode(document_base64, validate=True)+ except (binascii.Error, ValueError) as exc:+ msg = f"document_base64 is not valid base64: {exc}"+ raise DocsToMarkdownError(msg) from exc+ if len(data) > max_bytes:+ msg = f"document exceeds the {max_bytes}-byte limit"+ raise DocsToMarkdownError(msg)+ return data+++async def docs_to_markdown(+ client: ExtractClient,+ *,+ document_base64: str,+ filename: str | None = None,+ ocr: bool = False,+ engine: EngineName = "auto",+ model: str = "docling",+ vlocr_model: str = DEFAULT_VLOCR_MODEL,+ gpu: str | None = None,+ max_document_bytes: int = DEFAULT_MAX_DOCUMENT_BYTES,+) -> DocsToMarkdownResult:+ """Convert a document to markdown on the SIE cluster, routing the engine per ``engine``."""+ data = _decode_base64(document_base64, max_bytes=max_document_bytes)+ fmt = format_from_filename(filename)++ result = await ocr_routing.route_to_markdown(+ client,+ data=data,+ fmt=fmt,+ ocr=ocr,+ engine=engine,+ docling_model=model,+ vlocr_model=vlocr_model,+ gpu=gpu,+ )++ return DocsToMarkdownResult(+ markdown=result.markdown,+ metadata=build_metadata(+ markdown=result.markdown,+ document=result.document,+ source_bytes=len(data),+ pages=result.pages,+ engine=result.engine,+ ),+ )diff --git a/packages/sie_mcp/src/sie_mcp/oauth.py b/packages/sie_mcp/src/sie_mcp/oauth.pynew file mode 100644index 000000000..5bd590143--- /dev/null+++ b/packages/sie_mcp/src/sie_mcp/oauth.py@@ -0,0 +1,347 @@+"""OAuth 2.0 bridge for the claude.ai connector surface (Req 12 #1312).++claude.ai custom connectors are OAuth-only — a user cannot paste a Bearer/connector+secret into the connector UI the way the Cowork plugin bakes one into its header.+So this module fronts the MCP edge with the minimal OAuth 2.0 + PKCE handshake the+platform requires (metadata discovery, Dynamic Client Registration, an authorize+page, and a token endpoint) and maps it onto the **existing** connector-secret shim:+the user types their connector secret on the authorize page, and the token endpoint+returns that secret as the access token. claude.ai then sends it as+``Authorization: Bearer <secret>`` and ``auth.authenticate`` validates it unchanged.+The MCP tools and the auth shim are untouched; #1313 (Req 10) later swaps the static+secret for real issued keys.++Security notes:+- Connector secrets, authorization codes, and access tokens are NEVER logged.+- PKCE is required; redirect URIs are validated against a configured allowlist.+- Authorization codes are bound to the requesting ``client_id`` (when one is+ presented), so a leaked code cannot be redeemed by a different public client.+ Audience (``resource``) binding lands with real issued keys in #1313 (Req 10).+- Authorization codes are single-use and short-lived, held in-process (the edge runs+ as a single uvicorn worker for the POC; a shared store is the Req 10 follow-up).+"""++import base64+import functools+import hashlib+import html+import secrets+import time+from dataclasses import dataclass+from typing import Any+from urllib.parse import parse_qs, quote, urlencode++from starlette.requests import Request+from starlette.responses import HTMLResponse, JSONResponse, RedirectResponse, Response+from starlette.routing import Route++from sie_mcp.auth import authenticate, base_url+from sie_mcp.config import MCPConfig++_AUTH_CODE_TTL_S = 120.0+# Only S256 is accepted: `plain` would carry the verifier in cleartext (defeating+# PKCE), and the advertised authorization-server metadata is S256-only.+_SUPPORTED_PKCE_METHODS = frozenset({"S256"})+++def verify_pkce(code_verifier: str, code_challenge: str, method: str) -> bool:+ """Validate a PKCE ``code_verifier`` against the stored S256 challenge (RFC 7636)."""+ if not code_verifier or not code_challenge or method != "S256":+ return False+ try:+ digest = hashlib.sha256(code_verifier.encode("ascii")).digest()+ except UnicodeEncodeError:+ return False+ expected = base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")+ return secrets.compare_digest(expected, code_challenge)+++class OAuthError(Exception):+ """An OAuth error to surface as the spec's ``{error, error_description}`` body."""++ def __init__(self, error: str, description: str, *, status: int = 400) -> None:+ super().__init__(description)+ self.error = error+ self.description = description+ self.status = status+++@dataclass(frozen=True)+class _AuthCode:+ secret: str+ code_challenge: str+ code_challenge_method: str+ redirect_uri: str+ client_id: str+ expires_at: float+++class AuthCodeStore:+ """In-process, single-use, TTL-bounded authorization-code store."""++ def __init__(self, ttl_s: float = _AUTH_CODE_TTL_S) -> None:+ self._ttl = ttl_s+ self._codes: dict[str, _AuthCode] = {}++ def issue(+ self,+ *,+ secret: str,+ code_challenge: str,+ code_challenge_method: str,+ redirect_uri: str,+ client_id: str = "",+ now: float | None = None,+ ) -> str:+ now = time.time() if now is None else now+ self._purge(now)+ code = secrets.token_urlsafe(32)+ self._codes[code] = _AuthCode(+ secret=secret,+ code_challenge=code_challenge,+ code_challenge_method=code_challenge_method or "S256",+ redirect_uri=redirect_uri,+ client_id=client_id,+ expires_at=now + self._ttl,+ )+ return code++ def consume(self, code: str, *, now: float | None = None) -> _AuthCode | None:+ now = time.time() if now is None else now+ record = self._codes.pop(code, None)+ if record is None or record.expires_at < now:+ return None+ return record++ def _purge(self, now: float) -> None:+ expired = [code for code, record in self._codes.items() if record.expires_at < now]+ for code in expired:+ del self._codes[code]+++def protected_resource_metadata(origin: str) -> dict[str, Any]:+ """RFC 9728 metadata pointing the MCP resource at this authorization server."""+ return {+ "resource": f"{origin}/mcp",+ "authorization_servers": [origin],+ "bearer_methods_supported": ["header"],+ }+++def authorization_server_metadata(origin: str) -> dict[str, Any]:+ """RFC 8414 metadata describing the bridge's OAuth endpoints."""+ return {+ "issuer": origin,+ "authorization_endpoint": f"{origin}/authorize",+ "token_endpoint": f"{origin}/token",+ "registration_endpoint": f"{origin}/register",+ "response_types_supported": ["code"],+ "grant_types_supported": ["authorization_code"],+ "code_challenge_methods_supported": ["S256"],+ "token_endpoint_auth_methods_supported": ["none"],+ "scopes_supported": ["mcp"],+ }+++def exchange_authorization_code(+ store: AuthCodeStore,+ *,+ code: str,+ code_verifier: str,+ redirect_uri: str,+ client_id: str = "",+ now: float | None = None,+) -> str:+ """Redeem an authorization code for the access token (the connector secret)."""+ if not code or not code_verifier:+ raise OAuthError("invalid_request", "code and code_verifier are required")+ record = store.consume(code, now=now)+ if record is None:+ raise OAuthError("invalid_grant", "authorization code is invalid or expired")+ # Bind the code to the public client that requested it: a code issued to one+ # client_id cannot be redeemed by another (RFC 6749 §4.1.3 for public clients).+ if record.client_id and client_id != record.client_id:+ raise OAuthError("invalid_grant", "authorization code was issued to a different client")+ if redirect_uri and redirect_uri != record.redirect_uri:+ raise OAuthError("invalid_grant", "redirect_uri does not match the authorization request")+ if not verify_pkce(code_verifier, record.code_challenge, record.code_challenge_method):+ raise OAuthError("invalid_grant", "PKCE verification failed")+ return record.secret+++def _redirect_allowed(config: MCPConfig, redirect_uri: str) -> bool:+ return redirect_uri in config.oauth_redirect_uris+++def _validate_authorize_params(config: MCPConfig, params: dict[str, str]) -> HTMLResponse | None:+ """Validate the OAuth authorize request; return a 400 page on failure, else ``None``.++ Enforced identically on the GET (form render) and POST (code issuance) paths so a+ direct POST cannot skip the invariants the GET handler checks.+ """+ if not _redirect_allowed(config, params.get("redirect_uri", "")):+ return HTMLResponse("<h1>Invalid redirect_uri</h1>", status_code=400)+ if params.get("response_type") != "code":+ return HTMLResponse("<h1>Unsupported response_type (expected 'code')</h1>", status_code=400)+ if not params.get("code_challenge"):+ return HTMLResponse("<h1>Missing PKCE code_challenge</h1>", status_code=400)+ if params.get("code_challenge_method", "S256") not in _SUPPORTED_PKCE_METHODS:+ return HTMLResponse("<h1>Unsupported code_challenge_method (expected S256)</h1>", status_code=400)+ return None+++def _form_fields(params: dict[str, str]) -> str:+ keep = ("response_type", "client_id", "redirect_uri", "state", "code_challenge", "code_challenge_method", "scope")+ return "".join(f'<input type="hidden" name="{name}" value="{html.escape(params.get(name, ""))}">' for name in keep)+++def _render_authorize_form(params: dict[str, str], *, error: str | None = None, status: int = 200) -> HTMLResponse:+ error_html = f'<p class="error">{html.escape(error)}</p>' if error else ""+ body = f"""<!doctype html>+<html lang="en"><head><meta charset="utf-8"><title>Connect Superlinked</title>+<style>+ body {{ font-family: system-ui, sans-serif; max-width: 28rem; margin: 4rem auto; padding: 0 1rem; }}+ label {{ display: block; margin: 1rem 0 0.25rem; font-weight: 600; }}+ input[type=password] {{ width: 100%; padding: 0.5rem; box-sizing: border-box; }}+ button {{ margin-top: 1.25rem; padding: 0.5rem 1rem; }}+ .error {{ color: #b00020; }}+ .hint {{ color: #555; font-size: 0.9rem; }}+</style></head><body>+<h1>Connect to Superlinked</h1>+<p class="hint">Enter the connector secret your cluster operator issued. It is sent+only to the Superlinked gateway and never stored in your chat.</p>+{error_html}+<form method="post" action="/authorize">+ {_form_fields(params)}+ <label for="connector_secret">Connector secret</label>+ <input id="connector_secret" name="connector_secret" type="password" autocomplete="off" required>+ <button type="submit">Authorize</button>+</form>+</body></html>"""+ return HTMLResponse(body, status_code=status)+++def _parse_form(body: bytes) -> dict[str, str]:+ try:+ decoded = body.decode("utf-8")+ except UnicodeDecodeError:+ return {}+ return {key: values[0] for key, values in parse_qs(decoded).items() if values}+++async def _protected_resource(request: Request, config: MCPConfig) -> JSONResponse:+ origin = base_url(config, scheme=request.url.scheme, headers=request.headers)+ return JSONResponse(protected_resource_metadata(origin))+++async def _authorization_server(request: Request, config: MCPConfig) -> JSONResponse:+ origin = base_url(config, scheme=request.url.scheme, headers=request.headers)+ return JSONResponse(authorization_server_metadata(origin))+++async def _register(request: Request) -> JSONResponse:+ """Dynamic Client Registration (RFC 7591). Public PKCE clients, not persisted."""+ try:+ body = await request.json()+ except (ValueError, UnicodeDecodeError):+ body = {}+ redirect_uris = body.get("redirect_uris") if isinstance(body, dict) else None+ return JSONResponse(+ {+ "client_id": f"sl-{secrets.token_urlsafe(16)}",+ "client_id_issued_at": int(time.time()),+ "token_endpoint_auth_method": "none",+ "grant_types": ["authorization_code"],+ "response_types": ["code"],+ "redirect_uris": redirect_uris or [],+ },+ status_code=201,+ )+++async def _authorize_get(request: Request, config: MCPConfig) -> Response:+ params = dict(request.query_params)+ invalid = _validate_authorize_params(config, params)+ if invalid is not None:+ return invalid+ return _render_authorize_form(params)+++async def _authorize(request: Request, config: MCPConfig, store: AuthCodeStore) -> Response:+ if request.method == "POST":+ return await _authorize_post(request, config, store)+ return await _authorize_get(request, config)+++async def _authorize_post(request: Request, config: MCPConfig, store: AuthCodeStore) -> Response:+ form = _parse_form(await request.body())+ invalid = _validate_authorize_params(config, form)+ if invalid is not None:+ return invalid++ secret = form.get("connector_secret") or None+ if secret is None or authenticate(config, secret) is None:+ return _render_authorize_form(form, error="Invalid connector secret.", status=401)++ redirect_uri = form.get("redirect_uri", "")+ code = store.issue(+ secret=secret,+ code_challenge=form.get("code_challenge", ""),+ code_challenge_method=form.get("code_challenge_method", "S256"),+ redirect_uri=redirect_uri,+ client_id=form.get("client_id", ""),+ )+ query = {"code": code}+ if form.get("state"):+ query["state"] = form["state"]+ separator = "&" if "?" in redirect_uri else "?"+ return RedirectResponse(f"{redirect_uri}{separator}{urlencode(query, quote_via=quote)}", status_code=302)+++async def _token(request: Request, store: AuthCodeStore) -> JSONResponse:+ form = _parse_form(await request.body())+ if form.get("grant_type") != "authorization_code":+ return JSONResponse(+ {"error": "unsupported_grant_type", "error_description": "only authorization_code is supported"},+ status_code=400,+ headers={"Cache-Control": "no-store"},+ )+ try:+ access_token = exchange_authorization_code(+ store,+ code=form.get("code", ""),+ code_verifier=form.get("code_verifier", ""),+ redirect_uri=form.get("redirect_uri", ""),+ client_id=form.get("client_id", ""),+ )+ except OAuthError as exc:+ return JSONResponse(+ {"error": exc.error, "error_description": exc.description},+ status_code=exc.status,+ headers={"Cache-Control": "no-store"},+ )+ return JSONResponse(+ {"access_token": access_token, "token_type": "Bearer", "scope": "mcp"},+ headers={"Cache-Control": "no-store"},+ )+++def build_oauth_routes(config: MCPConfig) -> list[Route]:+ """Build the OAuth bridge routes, sharing one in-process authorization-code store."""+ store = AuthCodeStore()+ protected_resource = functools.partial(_protected_resource, config=config)+ return [+ Route("/.well-known/oauth-protected-resource", protected_resource, methods=["GET"]),+ # RFC 9728 also derives the metadata URL with the resource path appended; serve+ # it so a strict client that ignores the advertised URL still resolves the MCP+ # resource at /mcp.+ Route("/.well-known/oauth-protected-resource/mcp", protected_resource, methods=["GET"]),+ Route(+ "/.well-known/oauth-authorization-server",+ functools.partial(_authorization_server, config=config),+ methods=["GET"],+ ),+ Route("/register", _register, methods=["POST"]),+ Route("/authorize", functools.partial(_authorize, config=config, store=store), methods=["GET", "POST"]),+ Route("/token", functools.partial(_token, store=store), methods=["POST"]),+ ]diff --git a/packages/sie_mcp/src/sie_mcp/ocr_routing.py b/packages/sie_mcp/src/sie_mcp/ocr_routing.pynew file mode 100644index 000000000..17f104a0b--- /dev/null+++ b/packages/sie_mcp/src/sie_mcp/ocr_routing.py@@ -0,0 +1,344 @@+"""VL-OCR quality routing for ``docs_to_markdown`` (#1307).++Born-digital documents convert cleanly through Docling, but scanned / image-only+pages carry no text layer for Docling to read — its built-in OCR is the baseline+this path improves on. We rasterize such pages and route them to a vision-language+OCR model (MinerU2.5-Pro, the provisional default pinned in :mod:`sie_mcp.config`;+the committed engine choice is owned by Req 1's OCR-engine ADR, #955), then stitch+the per-page markdown back together in page order.++Two return shapes have to be reconciled here: Docling fills+``ExtractResult["data"]["markdown"]``, whereas MinerU returns generated text in+``ExtractResult["entities"]`` (each ``{text, label: "mineru_…", score}``) — see+``sie_server.adapters.mineru_vl``. This module owns both the rendering mechanism+and the engine-selection policy; orchestration stays client-side in the MCP edge+so the gateway and workers remain stateless per request.+"""++import io+import logging+import math+from dataclasses import dataclass+from typing import Any, Literal, Protocol++import pypdfium2 as pdfium+from PIL import Image+from sie_sdk import SIEError++logger = logging.getLogger(__name__)++EngineName = Literal["auto", "docling", "vl-ocr"]+ENGINES: tuple[EngineName, ...] = ("auto", "docling", "vl-ocr")++# PDF user space is 72 DPI; scale 2.0 → ~144 DPI, a quality/size balance that keeps+# rasterized pages legible for VL-OCR without ballooning the request payload.+_RENDER_SCALE = 2.0+# Page boundary in the stitched markdown — a blank line reads as a paragraph break,+# preserving document structure without injecting synthetic page markers.+_PAGE_SEPARATOR = "\n\n"+# Below this many non-whitespace chars, a renderable document is treated as+# imaged/scanned and (in ``auto``) re-run through VL-OCR. Born-digital pages clear+# this comfortably; a text-layer-less scan lands at ~0.+_NEAR_EMPTY_MARKDOWN_CHARS = 16+# Cap pages sent to VL-OCR. Each page is rasterized to a bitmap and JPEG-encoded+# into the request body, so an unbounded count would exhaust edge memory and the+# gateway request-size limit. Above this we fail loudly (no silent truncation) —+# windowed processing of very large scans is future work.+_MAX_VLOCR_PAGES = 100+# Cap rendered pixels per page so a single pathologically large page (page+# dimensions are attacker-controlled) can't exhaust edge memory. We downscale+# rather than fail. ~25 MP is generous — an A4 scan at 600 DPI is ~35 MP, and+# our ~144 DPI render lands far below this for normal pages.+_MAX_PAGE_PIXELS = 25_000_000+# Cap total rendered pixels across a document so the per-page cap doesn't+# multiply into a huge envelope: ``_MAX_VLOCR_PAGES`` × ``_MAX_PAGE_PIXELS`` is+# 2.5 Gpx (~7.5 GB of RGB) before encode/transport overhead, since every page is+# held in memory at once for the single batched ``extract`` call. ~500 Mpx caps+# the held RGB at ~1.5 GB while clearing a 100-page born-digital scan (~2 Mpx/page+# at our render scale) with wide headroom. We fail loudly (no silent truncation);+# windowed processing of very large scans is future work.+_MAX_TOTAL_PIXELS = 500_000_000++_PDF_MAGIC = b"%PDF-"+# Image magic bytes covering the formats Pillow can open for VL-OCR. TIFF in+# particular is a common scanned-document container, so it must route too.+_PNG_MAGIC = b"\x89PNG\r\n\x1a\n"+_JPEG_MAGIC = b"\xff\xd8\xff"+_TIFF_MAGIC = (b"II*\x00", b"MM\x00*")+_GIF_MAGIC = (b"GIF87a", b"GIF89a")+_BMP_MAGIC = b"BM"+++class DocsToMarkdownError(Exception):+ """Raised when the cluster could not convert the document."""+++class ExtractClient(Protocol):+ """The slice of ``SIEAsyncClient`` this module needs (keeps routing unit-testable)."""++ async def extract(self, model: str, items: Any, **kwargs: Any) -> Any:+ """Run an extract request against the SIE cluster."""+++@dataclass(frozen=True)+class RouteResult:+ """Outcome of routing a document to markdown.++ ``document`` carries Docling's per-item document dict (page metadata) when the+ Docling path won; ``pages`` carries the rendered page count on the VL-OCR path.+ """++ markdown: str+ engine: Literal["docling", "vl-ocr"]+ document: Any = None+ pages: int | None = None+++def entities_to_markdown(result: Any) -> str:+ """Map a MinerU ``ExtractResult``'s ``entities`` to one page's markdown.++ The default text-recognition task yields a single ``mineru_text`` entity per+ page; concatenating every entity's text in order also preserves table/equation+ entities should a layout task be used. Returns ``""`` for a page with no text.+ """+ entities = result.get("entities") if isinstance(result, dict) else None+ if not isinstance(entities, list):+ return ""+ parts = [+ entity["text"]+ for entity in entities+ if isinstance(entity, dict) and isinstance(entity.get("text"), str) and entity["text"].strip()+ ]+ return _PAGE_SEPARATOR.join(parts)+++def _is_pdf(data: bytes) -> bool:+ return data[:5] == _PDF_MAGIC+++def _is_image(data: bytes) -> bool:+ return (+ data[:8] == _PNG_MAGIC+ or data[:3] == _JPEG_MAGIC+ or data[:4] in _TIFF_MAGIC+ or data[:6] in _GIF_MAGIC+ or data[:2] == _BMP_MAGIC+ or (data[:4] == b"RIFF" and data[8:12] == b"WEBP")+ )+++def is_renderable(data: bytes) -> bool:+ """True when the bytes can be rasterized to page images for VL-OCR (PDF or image)."""+ return _is_pdf(data) or _is_image(data)+++def _clamp_scale(width_pt: float, height_pt: float, scale: float) -> float:+ """Reduce ``scale`` so a page renders within ``_MAX_PAGE_PIXELS``; leave it as-is otherwise."""+ pixels = (width_pt * scale) * (height_pt * scale)+ if pixels <= _MAX_PAGE_PIXELS or pixels <= 0:+ return scale+ return scale * math.sqrt(_MAX_PAGE_PIXELS / pixels)+++def _downscale_to_budget(image: Image.Image) -> Image.Image:+ """Return ``image`` shrunk to ``_MAX_PAGE_PIXELS`` if it exceeds the budget, else unchanged."""+ pixels = image.width * image.height+ if pixels <= _MAX_PAGE_PIXELS:+ return image+ factor = math.sqrt(_MAX_PAGE_PIXELS / pixels)+ size = (max(1, int(image.width * factor)), max(1, int(image.height * factor)))+ return image.resize(size)+++def _render_pdf(data: bytes, *, scale: float) -> list[Image.Image]:+ try:+ pdf = pdfium.PdfDocument(data)+ except pdfium.PdfiumError as exc:+ msg = f"could not open PDF for VL-OCR rendering: {exc}"+ raise DocsToMarkdownError(msg) from exc+ try:+ n_pages = len(pdf)+ if n_pages > _MAX_VLOCR_PAGES:+ msg = (+ f"PDF has {n_pages} pages; VL-OCR is capped at {_MAX_VLOCR_PAGES} per request. "+ "Split the document or use engine='docling'."+ )+ raise DocsToMarkdownError(msg)+ images: list[Image.Image] = []+ total_pixels = 0+ for page in pdf:+ # Close every page even if rendering raises mid-loop (no handle leak),+ # and surface render failures as DocsToMarkdownError so ``auto`` can degrade.+ try:+ width_pt, height_pt = page.get_size()+ bitmap = page.render(scale=_clamp_scale(width_pt, height_pt, scale))+ image = bitmap.to_pil().convert("RGB")+ finally:+ page.close()+ # Bound total held memory: stop before the accumulated bitmaps blow the+ # budget (every page lives in ``images`` until the single batched extract).+ total_pixels += image.width * image.height+ if total_pixels > _MAX_TOTAL_PIXELS:+ msg = (+ f"rendered pixels exceed the {_MAX_TOTAL_PIXELS:,}px VL-OCR budget "+ f"by page {len(images) + 1}. Split the document or use engine='docling'."+ )+ raise DocsToMarkdownError(msg)+ images.append(image)+ return images+ except pdfium.PdfiumError as exc:+ msg = f"could not render PDF page for VL-OCR: {exc}"+ raise DocsToMarkdownError(msg) from exc+ finally:+ pdf.close()+++def render_to_images(data: bytes, *, scale: float = _RENDER_SCALE) -> list[Image.Image]:+ """Rasterize a document to one RGB image per page (PDF) or a single image (PNG/JPEG)."""+ if _is_pdf(data):+ return _render_pdf(data, scale=scale)+ if _is_image(data):+ try:+ return [_downscale_to_budget(Image.open(io.BytesIO(data)).convert("RGB"))]+ except (OSError, ValueError) as exc:+ # PIL's UnidentifiedImageError/truncated-file errors subclass OSError;+ # wrap so a magic-byte false positive degrades cleanly in ``auto``.+ msg = f"could not open image for VL-OCR rendering: {exc}"+ raise DocsToMarkdownError(msg) from exc+ msg = "VL-OCR can only rasterize PDF or image inputs; use engine='docling' for this format."+ raise DocsToMarkdownError(msg)+++async def _docling_markdown(+ client: ExtractClient,+ *,+ data: bytes,+ fmt: str | None,+ ocr: bool,+ model: str,+ gpu: str | None,+) -> tuple[str, Any]:+ """Run the Docling front door; return ``(markdown, document_metadata)``."""+ document: dict[str, Any] = {"data": data}+ if fmt:+ document["format"] = fmt+ options = {"ocr": True} if ocr else None+ result = await client.extract(model, {"document": document}, options=options, gpu=gpu)++ payload = _docling_payload(result)+ markdown = payload.get("markdown") or ""+ error = payload.get("error")+ if error and not markdown:+ raise DocsToMarkdownError(str(error))+ return markdown, payload.get("document")+++def _docling_payload(result: Any) -> dict[str, Any]:+ """Pull the Docling per-item dict (``{text, markdown, document}``) out of an ExtractResult."""+ data = result.get("data") if isinstance(result, dict) else None+ if isinstance(data, list):+ data = data[0] if data else None+ return data if isinstance(data, dict) else {}+++async def _vl_ocr_markdown(+ client: ExtractClient,+ *,+ data: bytes,+ model: str,+ gpu: str | None,+ scale: float,+ render: Any,+) -> tuple[str, int]:+ """Rasterize, OCR each page on the cluster, and stitch markdown in page order."""+ images = render(data, scale=scale)+ if not images:+ return "", 0+ items = [{"images": [image]} for image in images]+ results = await client.extract(model, items, gpu=gpu)+ if not isinstance(results, list):+ results = [results]+ page_markdowns = [entities_to_markdown(result) for result in results]+ return _PAGE_SEPARATOR.join(page_markdowns), len(images)+++async def route_to_markdown(+ client: ExtractClient,+ *,+ data: bytes,+ fmt: str | None,+ ocr: bool,+ engine: str,+ docling_model: str,+ vlocr_model: str,+ gpu: str | None,+ render: Any = render_to_images,+ scale: float = _RENDER_SCALE,+) -> RouteResult:+ """Convert a document to markdown, choosing the engine per ``engine``.++ - ``docling``: Docling only (the current front door, all formats). The caller's+ ``ocr`` flag turns Docling's built-in OCR on here.+ - ``vl-ocr``: rasterize and run the VL-OCR model per page; stitch in order.+ - ``auto``: Docling first, falling back to VL-OCR when Docling yields empty /+ near-empty markdown for a rasterizable input (scanned PDFs, image-only docs).++ In ``auto`` the engine owns the OCR decision, so the caller's ``ocr`` flag is+ ignored: Docling's built-in OCR is the baseline VL-OCR supersedes, and running it+ would hand back garbled, run-together text that is both worse than VL-OCR *and*+ non-empty — masking the scan from the near-empty fallback trigger. Docling stays+ the text-layer front door (OCR off); scans land near-empty and fall back cleanly.++ Auto fallback is best-effort: a VL-OCR failure or an emptier VL-OCR result never+ discards a usable Docling result. Per-page hybrid routing (Docling for digital+ pages, VL-OCR only for scanned pages within one mixed doc) is a future thickening;+ today a mixed doc is best served by forcing ``engine='vl-ocr'``.+ """+ if engine not in ENGINES:+ msg = f"unknown engine {engine!r}; expected one of {', '.join(ENGINES)}"+ raise DocsToMarkdownError(msg)++ async def _vl_ocr() -> tuple[str, int]:+ return await _vl_ocr_markdown(client, data=data, model=vlocr_model, gpu=gpu, scale=scale, render=render)++ if engine == "vl-ocr":+ markdown, pages = await _vl_ocr()+ return RouteResult(markdown=markdown, engine="vl-ocr", pages=pages)++ # Honor ``ocr`` only when Docling is pinned; in ``auto`` VL-OCR is the OCR path.+ docling_ocr = ocr and engine == "docling"+ if ocr and not docling_ocr:+ # Surface the override so a caller who set ocr=True doesn't silently wonder+ # why Docling's built-in OCR never ran (VL-OCR fallback owns scans in auto).+ logger.debug("ocr=True ignored under engine=%r; VL-OCR fallback owns OCR in auto", engine)+ try:+ markdown, document = await _docling_markdown(+ client, data=data, fmt=fmt, ocr=docling_ocr, model=docling_model, gpu=gpu+ )+ except DocsToMarkdownError:+ # Docling refused (e.g. no text layer). For a rasterizable input, try VL-OCR+ # before giving up; otherwise the error stands.+ if engine == "auto" and is_renderable(data):+ vl_markdown, pages = await _vl_ocr()+ if vl_markdown.strip():+ return RouteResult(markdown=vl_markdown, engine="vl-ocr", pages=pages)+ raise++ if engine == "auto" and _looks_text_poor(markdown) and is_renderable(data):+ try:+ vl_markdown, pages = await _vl_ocr()+ except (DocsToMarkdownError, SIEError):+ # VL-OCR is best-effort here: a render error *or* an SDK/server failure+ # from the cluster must not discard the usable Docling markdown we hold.+ logger.warning("VL-OCR fallback failed; keeping Docling result", exc_info=True)+ vl_markdown, pages = "", 0+ # Only prefer VL-OCR when it actually recovered more text than Docling.+ if len(vl_markdown.strip()) > len(markdown.strip()):+ return RouteResult(markdown=vl_markdown, engine="vl-ocr", pages=pages)++ return RouteResult(markdown=markdown, engine="docling", document=document)+++def _looks_text_poor(markdown: str) -> bool:+ """Heuristic: Docling produced too little text to be a born-digital extraction."""+ return len(markdown.strip()) < _NEAR_EMPTY_MARKDOWN_CHARSdiff --git a/packages/sie_mcp/src/sie_mcp/qa.py b/packages/sie_mcp/src/sie_mcp/qa.pynew file mode 100644index 000000000..238fcd0a4--- /dev/null+++ b/packages/sie_mcp/src/sie_mcp/qa.py@@ -0,0 +1,363 @@+"""``answer_questions`` — the Req 12 transient-QA job (#1309).++Grounded question answering over a document set too large to drop whole into a+single context window. Composed from shipped SIE primitives and run client-side+in the MCP edge: TRANSIENT retrieval, so nothing is persisted between calls — no+standing index, no cross-call cache, no user-facing search (the M5 boundary).++Per request the chunks are encoded once; then, for each question, the job:++1. ``encode`` the question and rank chunks by dense cosine similarity to+ shortlist the most promising candidates — the cheap first pass that keeps a+ document larger than one context window tractable without reranking every+ chunk;+2. ``score`` (rerank) the shortlist with a cross-encoder to select the final+ passages;+3. generate an answer grounded ONLY in those passages, via a grounded+ chat-completion (system + passages + question).++Each answer is returned with the passages it used, so the grounding is visible.+"""++import math+from collections.abc import Sequence+from typing import Any, Protocol, TypedDict++from sie_mcp.chunking import Chunk, chunk_documents++_SYSTEM = (+ "You answer the question using ONLY the supplied passages. Ground every "+ "statement in them and do not rely on outside knowledge. If the passages do "+ "not contain the answer, say that they do not rather than guessing."+)+++class AnswerQuestionsError(Exception):+ """Raised when the QA pipeline cannot produce a grounded answer."""+++def _validate_params(+ *,+ top_k: int,+ rerank_candidates: int,+ chunk_chars: int,+ chunk_overlap_chars: int,+ max_tokens: int,+ max_document_chars: int,+ max_questions: int,+ max_chunks: int,+) -> None:+ """Reject invalid retrieval knobs up front, in the job's own error type.++ ``MCPConfig.from_env`` already clamps these for the server path; this guards+ direct callers of :func:`answer_questions` so a bad knob surfaces as+ ``AnswerQuestionsError`` rather than a raw ``ValueError`` from+ ``chunk_documents`` deeper in the pipeline. All checks run before any chunking+ or model call.+ """+ must_be_positive = {+ "top_k": top_k,+ "rerank_candidates": rerank_candidates,+ "chunk_chars": chunk_chars,+ "max_tokens": max_tokens,+ "max_document_chars": max_document_chars,+ "max_questions": max_questions,+ "max_chunks": max_chunks,+ }+ for name, value in must_be_positive.items():+ if value < 1:+ msg = f"{name} must be >= 1, got {value}"+ raise AnswerQuestionsError(msg)+ if not 0 <= chunk_overlap_chars < chunk_chars:+ msg = f"chunk_overlap_chars must satisfy 0 <= overlap < chunk_chars ({chunk_chars}), got {chunk_overlap_chars}"+ raise AnswerQuestionsError(msg)+++class QAClient(Protocol):+ """The slice of ``SIEAsyncClient`` this job composes (keeps it unit-testable)."""++ async def encode(self, model: str, items: Any, **kwargs: Any) -> Any:+ """Encode items against an embedding model on the SIE cluster."""++ async def score(self, model: str, query: Any, items: list[Any], **kwargs: Any) -> Any:+ """Rerank items against a query with a reranker model on the SIE cluster."""++ async def chat_completions(self, model: str, messages: list[Any], **kwargs: Any) -> Any:+ """Run an OpenAI-compatible chat completion on the SIE cluster."""+++class Passage(TypedDict):+ """A retrieved passage, where it came from, and the score that selected it.++ ``doc_index`` and ``start`` point back to the caller's input — ``doc_index``+ indexes the ``documents`` list, ``start`` is the character offset of the+ passage within that document — so the grounding can be located in the source.+ """++ id: str+ doc_index: int+ start: int+ text: str+ score: float+++class Answer(TypedDict):+ """One question, its grounded answer, and the passages it was grounded in."""++ question: str+ answer: str+ passages: list[Passage]+++class AnswerQuestionsResult(TypedDict):+ answers: list[Answer]+++def _dense_floats(result: Any) -> list[float]:+ dense = result.get("dense") if isinstance(result, dict) else None+ if dense is None:+ msg = "encode result has no dense embedding"+ raise AnswerQuestionsError(msg)+ return [float(x) for x in dense]+++def _cosine(a: Sequence[float], b: Sequence[float]) -> float:+ dot = sum(x * y for x, y in zip(a, b, strict=False))+ norm_a = math.sqrt(sum(x * x for x in a))+ norm_b = math.sqrt(sum(y * y for y in b))+ if norm_a == 0.0 or norm_b == 0.0:+ return 0.0+ return dot / (norm_a * norm_b)+++def _shortlist(question_vec: Sequence[float], chunk_vecs: Sequence[Sequence[float]], *, limit: int) -> list[int]:+ """Rank chunk indices by cosine similarity to the question, highest first."""+ ranked = sorted(+ range(len(chunk_vecs)),+ key=lambda i: _cosine(question_vec, chunk_vecs[i]),+ reverse=True,+ )+ return ranked[:limit]+++def _select_passages(score_result: Any, shortlist: Sequence[Chunk], *, top_k: int) -> list[Passage]:+ """Pick the top-``top_k`` reranked passages; ``[]`` if no score maps to a chunk.++ Raises only when the reranker returned *no* scores at all (a genuine+ failure); an id mismatch returns ``[]`` so the caller can fall back to the+ dense shortlist rather than failing the whole question.+ """+ scores = score_result.get("scores") if isinstance(score_result, dict) else None+ if not scores:+ msg = "reranker returned no scores"+ raise AnswerQuestionsError(msg)+ # The reranker contract returns scores sorted by relevance descending; sort+ # defensively so selection is correct even if a backend returns them unsorted.+ ranked = sorted(+ (entry for entry in scores if isinstance(entry, dict)),+ key=lambda entry: float(entry.get("score", 0.0)),+ reverse=True,+ )+ by_id = {chunk.id: chunk for chunk in shortlist}+ passages: list[Passage] = []+ for entry in ranked:+ if len(passages) >= top_k:+ break+ chunk = by_id.get(entry.get("item_id"))+ if chunk is None:+ continue+ passages.append(+ Passage(+ id=chunk.id,+ doc_index=chunk.doc_index,+ start=chunk.start,+ text=chunk.text,+ score=float(entry.get("score", 0.0)),+ )+ )+ return passages+++def _format_passages(passages: Sequence[Passage]) -> str:+ blocks = [f"[{i}] (document {passage['doc_index']})\n{passage['text']}" for i, passage in enumerate(passages, 1)]+ return "\n\n".join(blocks)+++def _message_content(resp: Any) -> str:+ choices = resp.get("choices") if isinstance(resp, dict) else None+ if not choices:+ msg = "cluster returned no choices for the answer"+ raise AnswerQuestionsError(msg)+ first = choices[0]+ message = first.get("message") if isinstance(first, dict) else None+ content = message.get("content") if isinstance(message, dict) else None+ if not isinstance(content, str):+ msg = "cluster returned no answer content"+ raise AnswerQuestionsError(msg)+ return content+++def _dense_passages(+ chunks: Sequence[Chunk],+ chunk_vecs: Sequence[Sequence[float]],+ indices: Sequence[int],+ question_vec: Sequence[float],+) -> list[Passage]:+ return [+ Passage(+ id=chunks[i].id,+ doc_index=chunks[i].doc_index,+ start=chunks[i].start,+ text=chunks[i].text,+ score=_cosine(question_vec, chunk_vecs[i]),+ )+ for i in indices+ ]+++async def _answer_one(+ client: QAClient,+ *,+ question: str,+ chunks: Sequence[Chunk],+ chunk_vecs: Sequence[Sequence[float]],+ encode_model: str,+ rerank_model: str,+ generate_model: str,+ top_k: int,+ rerank_candidates: int,+ max_tokens: int,+ gpu: str | None,+) -> Answer:+ # 1. Dense shortlist: cheap bi-encoder pass over every chunk.+ q_encoded = await client.encode(encode_model, {"text": question}, output_types=["dense"], is_query=True, gpu=gpu)+ question_vec = _dense_floats(q_encoded)+ shortlist_idx = _shortlist(question_vec, chunk_vecs, limit=rerank_candidates)+ shortlist = [chunks[i] for i in shortlist_idx]++ # 2. Rerank the shortlist with the cross-encoder to select final passages.+ score_result = await client.score(+ rerank_model,+ {"text": question},+ [{"id": chunk.id, "text": chunk.text} for chunk in shortlist],+ gpu=gpu,+ )+ passages = _select_passages(score_result, shortlist, top_k=top_k)+ if not passages:+ # The reranker returned scores but none mapped to our chunks; fall back to+ # the dense shortlist (already ordered by similarity) so the question still+ # gets a grounded answer instead of failing outright.+ passages = _dense_passages(chunks, chunk_vecs, shortlist_idx[:top_k], question_vec)++ # 3. Generate an answer grounded only in the selected passages.+ user = (+ f"<passages>\n{_format_passages(passages)}\n</passages>\n\n"+ f"Question: {question}\n\n"+ "Answer using only the passages above."+ )+ response = await client.chat_completions(+ generate_model,+ [{"role": "system", "content": _SYSTEM}, {"role": "user", "content": user}],+ # Deterministic, grounded answer — no creative sampling.+ temperature=0.0,+ max_completion_tokens=max_tokens,+ gpu=gpu,+ )+ return Answer(question=question, answer=_message_content(response), passages=passages)+++async def answer_questions(+ client: QAClient,+ *,+ documents: Sequence[str],+ questions: Sequence[str],+ encode_model: str,+ rerank_model: str,+ generate_model: str,+ top_k: int,+ rerank_candidates: int,+ chunk_chars: int,+ chunk_overlap_chars: int,+ max_tokens: int,+ max_document_chars: int,+ max_questions: int,+ max_chunks: int,+ gpu: str | None = None,+) -> AnswerQuestionsResult:+ """Answer each question grounded in passages retrieved from ``documents``.++ Chunks the documents, encodes the chunks once, then for every question runs+ dense-shortlist → rerank → grounded generation. Nothing is persisted between+ calls and no standing index is built. Returns each answer with the passages+ it was grounded in.++ The inputs are bounded before any chunking or encoding: an oversize corpus,+ too many questions, or too many chunks is rejected up front so a single+ request can't exhaust edge memory or fan out into an unbounded model call.+ """+ _validate_params(+ top_k=top_k,+ rerank_candidates=rerank_candidates,+ chunk_chars=chunk_chars,+ chunk_overlap_chars=chunk_overlap_chars,+ max_tokens=max_tokens,+ max_document_chars=max_document_chars,+ max_questions=max_questions,+ max_chunks=max_chunks,+ )+ if not any(d and d.strip() for d in documents):+ msg = "no non-empty documents supplied"+ raise AnswerQuestionsError(msg)+ # Bound the total text held in memory before chunking it.+ total_chars = sum(len(d) for d in documents)+ if total_chars > max_document_chars:+ msg = f"documents exceed the {max_document_chars}-character limit ({total_chars} supplied)"+ raise AnswerQuestionsError(msg)+ qs = [q for q in questions if q and q.strip()]+ if not qs:+ msg = "no non-empty questions supplied"+ raise AnswerQuestionsError(msg)+ # Each question fans out into its own encode → rerank → generate pass.+ if len(qs) > max_questions:+ msg = f"number of questions ({len(qs)}) exceeds the limit of {max_questions}"+ raise AnswerQuestionsError(msg)++ # Chunk over the original ``documents`` (empties skipped, indices preserved)+ # so every passage's ``doc_index`` points back to the caller's input.+ chunks = chunk_documents(documents, window=chunk_chars, overlap=chunk_overlap_chars)+ if not chunks:+ msg = "documents produced no chunks"+ raise AnswerQuestionsError(msg)+ # Every chunk goes into one encode request; bound that fan-out.+ if len(chunks) > max_chunks:+ msg = f"documents produced {len(chunks)} chunks, which exceeds the limit of {max_chunks}"+ raise AnswerQuestionsError(msg)++ # Encode every chunk once for this call; the vectors live only for its+ # duration — no index is built or stored (transient retrieval).+ encoded = await client.encode(+ encode_model,+ [{"id": chunk.id, "text": chunk.text} for chunk in chunks],+ output_types=["dense"],+ is_query=False,+ gpu=gpu,+ )+ chunk_vecs = [_dense_floats(result) for result in encoded]++ answers = [+ await _answer_one(+ client,+ question=question,+ chunks=chunks,+ chunk_vecs=chunk_vecs,+ encode_model=encode_model,+ rerank_model=rerank_model,+ generate_model=generate_model,+ top_k=top_k,+ rerank_candidates=rerank_candidates,+ max_tokens=max_tokens,+ gpu=gpu,+ )+ for question in qs+ ]+ return AnswerQuestionsResult(answers=answers)diff --git a/packages/sie_mcp/src/sie_mcp/savings.py b/packages/sie_mcp/src/sie_mcp/savings.pynew file mode 100644index 000000000..d8b04841d--- /dev/null+++ b/packages/sie_mcp/src/sie_mcp/savings.py@@ -0,0 +1,93 @@+"""Token-savings metadata for ``docs_to_markdown``.++Two distinct figures travel in the metadata; do not conflate them:++- ``markdown_tokens_estimate`` — a LIVE, per-call estimate of *this* response's+ markdown, via a ~4 chars/token heuristic. Order-of-magnitude only.+- ``token_reduction`` — the COMMITTED #1311 measurement of markdown vs direct+ document ingestion, copied verbatim from the benchmark run (AGENTS.md: never+ ship perf claims without baseline data). The authoritative method is+ ``count_tokens`` on the document block (text + one image per page) vs the SIE+ markdown; full detail in ``benchmarks/token_reduction/results/latest.json``.+"""++import copy+import math+from typing import Any++_CHARS_PER_TOKEN = 4 # rough Claude/GPT-family heuristic++# Committed token-reduction measurement — issue #1311, run 20260610T144234Z.+# Source of truth: benchmarks/token_reduction/results/latest.json. Every number+# below is copied verbatim from that committed run; re-run the benchmark to+# change them, never hand-edit (AGENTS.md: no fabricated/rounded perf claims).+# The dict is read-only; build_metadata deep-copies it so callers can't mutate it.+_BENCHMARK_PATH = "benchmarks/token_reduction/results/latest.json"+_OPUS = "claude-opus-4-8"+_SONNET = "claude-sonnet-4-6"+_TOKEN_REDUCTION: dict[str, Any] = {+ "source": _BENCHMARK_PATH,+ "issue": 1311,+ "run": "20260610T144234Z",+ "method": (+ "count_tokens on the document block (text + one image per page, as "+ "Claude bills a document upload) vs the SIE markdown"+ ),+ # Token-weighted across the corpus. Opus is the conservative (lower-reduction)+ # profile; we report it as the headline so we never overstate.+ "blended_reduction_pct": {_OPUS: 82.9, _SONNET: 86.5},+ # Min/max reduction across every per-file-type row of BOTH profiles: the+ # corpus floor is Opus/HTML (63.3), the ceiling is Sonnet/PPTX (94.8).+ "per_file_type_reduction_pct": {"min": 63.3, "max": 94.8},+}++# Built from _TOKEN_REDUCTION so the prose can never drift from the data above.+_blended = _TOKEN_REDUCTION["blended_reduction_pct"]+_per_type = _TOKEN_REDUCTION["per_file_type_reduction_pct"]+_NOTE = (+ "markdown_tokens_estimate is a live ~4 chars/token estimate of this response, "+ "not a measured count. token_reduction is the committed #1311 measurement of "+ "markdown vs direct document ingestion: blended "+ f"{_blended[_OPUS]}% (Opus 4.8, the conservative profile) and "+ f"{_blended[_SONNET]}% (Sonnet 4.6); per-file-type reductions span "+ f"{_per_type['min']}%-{_per_type['max']}% across both profiles "+ f"(floor Opus/HTML, ceiling Sonnet/PPTX). See {_BENCHMARK_PATH}."+)+++def _estimate_tokens(text: str) -> int:+ return math.ceil(len(text) / _CHARS_PER_TOKEN) if text else 0+++def _page_count(document: Any) -> int | None:+ if not isinstance(document, dict):+ return None+ pages = document.get("pages")+ if isinstance(pages, dict | list):+ return len(pages)+ return None+++def build_metadata(+ *,+ markdown: str,+ document: Any = None,+ source_bytes: int,+ pages: int | None = None,+ engine: str | None = None,+) -> dict[str, Any]:+ meta: dict[str, Any] = {+ "markdown_chars": len(markdown),+ "markdown_tokens_estimate": _estimate_tokens(markdown),+ "markdown_tokens_estimated": True, # the token count above is a live estimate, not measured+ "source_bytes": source_bytes,+ "token_reduction": copy.deepcopy(_TOKEN_REDUCTION),+ "note": _NOTE,+ }+ if engine:+ meta["engine"] = engine+ # An explicit page count (VL-OCR render count) wins over Docling's document metadata.+ page_count = pages if pages is not None else _page_count(document)+ if page_count is not None:+ meta["source_pages"] = page_count+ return metadiff --git a/packages/sie_mcp/src/sie_mcp/server.py b/packages/sie_mcp/src/sie_mcp/server.pynew file mode 100644index 000000000..77c7850c9--- /dev/null+++ b/packages/sie_mcp/src/sie_mcp/server.py@@ -0,0 +1,279 @@+"""FastMCP server exposing the Req 12 document tools.++Tracer bullet (#1306): a single ``docs_to_markdown`` tool. The cluster client is+created once per process in the lifespan and reused across requests.+"""++import logging+from collections.abc import AsyncIterator+from contextlib import asynccontextmanager+from typing import Any++from mcp.server.fastmcp import Context, FastMCP+from mcp.server.transport_security import TransportSecuritySettings+from sie_sdk import SIEAsyncClient++from sie_mcp import describe, jobs, qa, structured+from sie_mcp.config import MCPConfig++logger = logging.getLogger(__name__)+++@asynccontextmanager+async def _lifespan(_server: FastMCP) -> AsyncIterator[dict[str, Any]]:+ config = MCPConfig.from_env()+ client = SIEAsyncClient(+ config.sie_base_url,+ api_key=config.sie_api_key,+ timeout_s=config.timeout_s,+ )+ logger.info("sie-mcp connected to cluster at %s", config.sie_base_url)+ try:+ yield {"client": client, "config": config}+ finally:+ await client.close()+++def _transport_security(config: MCPConfig) -> TransportSecuritySettings:+ """Build FastMCP's DNS-rebinding (Host/Origin) protection settings.++ FastMCP auto-enables a *localhost-only* allow-list whenever its host is the+ default ``127.0.0.1``, which would reject the documented remote ``https://<host>/mcp``+ endpoint with ``421 Invalid Host``. This edge is a remote service fronted by TLS+ ingress and guarded by its own connector-secret auth, so:++ - With ``SIE_MCP_ALLOWED_HOSTS`` set, keep protection on, scoped to those hosts.+ - Without it, disable Host validation here (auth is the access control).+ """+ if config.allowed_hosts:+ origins = [origin for host in config.allowed_hosts for origin in (f"https://{host}", f"http://{host}")]+ return TransportSecuritySettings(+ enable_dns_rebinding_protection=True,+ allowed_hosts=config.allowed_hosts,+ allowed_origins=origins,+ )+ return TransportSecuritySettings(enable_dns_rebinding_protection=False)+++def build_server(config: MCPConfig) -> FastMCP:+ server = FastMCP(+ "sie-mcp",+ stateless_http=True,+ lifespan=_lifespan,+ transport_security=_transport_security(config),+ )++ @server.tool()+ async def docs_to_markdown(+ ctx: Context,+ document_base64: str,+ filename: str | None = None,+ ocr: bool = False,+ engine: jobs.EngineName = "auto",+ ) -> dict[str, Any]:+ """Convert a document (PDF/DOCX/PPTX/XLSX/HTML/scan) to clean markdown on the SIE cluster.++ Send the document's raw bytes base64-encoded; you get markdown back. Read the+ source as bytes — do NOT view or attach the document in the conversation — then+ operate on the returned markdown so the page-image tokens are never billed.++ Args:+ document_base64: The document's raw bytes, base64-encoded.+ filename: Optional original filename; its extension hints the format.+ ocr: Turn on Docling's built-in OCR. Only applies under engine="docling";+ under "auto" the VL-OCR fallback handles scans, so this is ignored+ (Docling's built-in OCR is the baseline VL-OCR supersedes).+ engine: Conversion engine. "auto" (default) runs Docling and falls back to+ VL-OCR for scanned/image-only pages; "docling" forces the Docling front+ door; "vl-ocr" rasterizes the document and runs the VL-OCR model per page+ (best for scanned or complex-layout PDFs).+ """+ lifespan_ctx = ctx.request_context.lifespan_context+ client = lifespan_ctx["client"]+ config: MCPConfig = lifespan_ctx["config"]+ result = await jobs.docs_to_markdown(+ client,+ document_base64=document_base64,+ filename=filename,+ ocr=ocr,+ engine=engine,+ model=config.docling_model,+ vlocr_model=config.vlocr_model,+ gpu=config.gpu,+ max_document_bytes=config.max_document_bytes,+ )+ return {"markdown": result["markdown"], "metadata": result["metadata"]}++ @server.tool()+ async def answer_questions(+ ctx: Context,+ documents: list[str],+ questions: list[str],+ ) -> dict[str, Any]:+ """Answer questions grounded in a document set, on the SIE cluster.++ For a document set too large to drop whole into the conversation: pass the+ documents' text and your questions, and get back an answer per question+ plus the passages it was grounded in. Read large sources as text (e.g. the+ markdown from ``docs_to_markdown``) and answer through this tool rather+ than pasting the whole corpus — only the retrieved passages are billed.++ Retrieval is transient: the documents are chunked, encoded, reranked, and+ answered over per call. Nothing is persisted between calls and no standing+ index is built, so pass the relevant documents in each request.++ Args:+ documents: The source documents' text (plain text or markdown).+ questions: The questions to answer over the documents.+ """+ lifespan_ctx = ctx.request_context.lifespan_context+ client = lifespan_ctx["client"]+ config: MCPConfig = lifespan_ctx["config"]+ result = await qa.answer_questions(+ client,+ documents=documents,+ questions=questions,+ encode_model=config.encode_model,+ rerank_model=config.rerank_model,+ generate_model=config.generate_model,+ top_k=config.qa_top_k,+ rerank_candidates=config.qa_rerank_candidates,+ chunk_chars=config.qa_chunk_chars,+ chunk_overlap_chars=config.qa_chunk_overlap_chars,+ max_tokens=config.qa_max_tokens,+ max_document_chars=config.qa_max_document_chars,+ max_questions=config.qa_max_questions,+ max_chunks=config.qa_max_chunks,+ gpu=config.gpu,+ )+ return {"answers": result["answers"]}++ @server.tool()+ async def describe_image(+ ctx: Context,+ image_base64: str,+ labels: list[str] | None = None,+ detailed: bool = False,+ top_k: int | None = None,+ ) -> dict[str, Any]:+ """Describe an image on the SIE cluster: a caption plus top-k zero-shot tags.++ Send the image's raw bytes base64-encoded; you get back a caption (Florence-2)+ and a list of ``{label, score}`` tags. Read the image as bytes — do NOT view or+ attach it in the conversation — so the image tokens are never billed to the+ calling model. Tagging is zero-shot: the image and the candidate labels are+ embedded (SigLIP/CLIP) and the top-k labels by similarity are returned.++ Args:+ image_base64: The image's raw bytes (JPEG/PNG), base64-encoded.+ labels: Optional candidate labels for zero-shot tagging; defaults to the+ service's configured label set.+ detailed: Use Florence-2 <DETAILED_CAPTION> for a longer caption.+ top_k: How many top tags to return (defaults to the service config).+ """+ lifespan_ctx = ctx.request_context.lifespan_context+ client = lifespan_ctx["client"]+ config: MCPConfig = lifespan_ctx["config"]+ result = await describe.describe_image(+ client,+ image_base64=image_base64,+ labels=labels if labels is not None else config.image_labels,+ caption_model=config.caption_model,+ embed_model=config.embed_model,+ detailed=detailed,+ top_k=top_k if top_k is not None else config.image_top_k,+ gpu=config.gpu,+ max_image_bytes=config.max_image_bytes,+ )+ return {"caption": result["caption"], "tags": result["tags"]}++ @server.tool()+ async def extract_structured(+ ctx: Context,+ content: str,+ output_schema: dict[str, Any],+ instruction: str | None = None,+ model: str | None = None,+ max_output_tokens: int | None = None,+ ) -> dict[str, Any]:+ """Extract schema-valid JSON grounded in document content, on the SIE cluster.++ The model is constrained to ``output_schema`` at decode time and the+ returned ``data`` is validated against the schema before it is handed+ back — a non-conforming response (e.g. if the serving profile bypasses+ grammar enforcement) raises a clear error rather than returning+ "mostly-JSON". Extraction is grounded in ``content``: values are drawn+ from it, not invented. Use this to turn already-extracted text/markdown+ (e.g. the output of ``docs_to_markdown``) into a structured record.++ ``output_schema`` must be in the Outlines-supported subset: no ``$ref``+ (so no recursion), no conditionals (``if``/``then``/``else``), nesting+ depth ≤ 16. Out-of-subset schemas are rejected with a clear error.++ Args:+ content: The source text to extract from (plain text or markdown).+ output_schema: A JSON Schema describing the record to extract.+ instruction: Optional extra guidance on what to pull out.+ model: Optional generation model override (defaults to the cluster's+ configured structured-output model).+ max_output_tokens: Optional output-token ceiling (defaults to the+ edge's ``SIE_MCP_MAX_OUTPUT_TOKENS``); raise it for large records.+ """+ lifespan_ctx = ctx.request_context.lifespan_context+ client = lifespan_ctx["client"]+ config: MCPConfig = lifespan_ctx["config"]+ data = await structured.extract_structured(+ client,+ content=content,+ output_schema=output_schema,+ instruction=instruction,+ model=model or config.generate_model,+ gpu=config.gpu,+ max_completion_tokens=max_output_tokens or config.max_output_tokens,+ )+ return {"data": data}++ @server.tool()+ async def generate_structured(+ ctx: Context,+ prompt: str,+ response_format: dict[str, Any],+ model: str | None = None,+ max_output_tokens: int | None = None,+ ) -> dict[str, Any]:+ """Generate output constrained by a schema / regex / grammar, on the SIE cluster.++ ``response_format`` is the OpenAI-compatible constraint, one of:++ - ``{"type": "json_schema", "json_schema": {"name": ..., "schema": <schema>, "strict": true}}``+ - ``{"type": "json_object"}``+ - ``{"type": "regex", "regex": "<pattern>"}``+ - ``{"type": "grammar", "grammar": "<ebnf>", "syntax": "ebnf"}`` — xgrammar-backed+ models only; rejected up front for the Outlines-backed default model.++ A ``json_schema`` is validated against the Outlines subset before the+ call and the returned JSON is validated against it afterwards. Returns+ the constrained ``content`` string (a JSON string for the json modes).++ Args:+ prompt: The instruction the model should answer under the constraint.+ response_format: The output constraint (see above).+ model: Optional generation model override (defaults to the cluster's+ configured structured-output model).+ max_output_tokens: Optional output-token ceiling (defaults to the+ edge's ``SIE_MCP_MAX_OUTPUT_TOKENS``); raise it for large output.+ """+ lifespan_ctx = ctx.request_context.lifespan_context+ client = lifespan_ctx["client"]+ config: MCPConfig = lifespan_ctx["config"]+ content = await structured.generate_structured(+ client,+ prompt=prompt,+ response_format=response_format,+ model=model or config.generate_model,+ gpu=config.gpu,+ max_completion_tokens=max_output_tokens or config.max_output_tokens,+ )+ return {"content": content}++ return serverdiff --git a/packages/sie_mcp/src/sie_mcp/skill_zip.py b/packages/sie_mcp/src/sie_mcp/skill_zip.pynew file mode 100644index 000000000..c25f26208--- /dev/null+++ b/packages/sie_mcp/src/sie_mcp/skill_zip.py@@ -0,0 +1,108 @@+"""Package the claude.ai Agent Skill as an uploadable ZIP (Req 12 #1312).++claude.ai's two-piece install takes the remote MCP connector plus a **skill ZIP**.+The platform requires the archive to contain a single top-level folder named after+the skill, with ``SKILL.md`` inside it (``superlinked-docs/SKILL.md``) — never at the+archive root — and enforces ``name``/``description`` frontmatter constraints. This+module reads the surface-agnostic ``plugin/SKILL.md`` (one skill across Cowork /+claude.ai / the desktop app), validates it against those rules, and emits a+deterministic ZIP so the ``mcp-skill-zip`` task produces a byte-stable artifact.+"""++import io+import re+import zipfile++# claude.ai skill-name rules: lowercase letters/digits/hyphens, <=64 chars, and the+# words "anthropic"/"claude" are reserved.+_NAME_RE = re.compile(r"^[a-z0-9-]{1,64}$")+_RESERVED_NAME_WORDS = ("anthropic", "claude")+_MAX_DESCRIPTION_LEN = 1024+_BLOCK_SCALAR_INDICATORS = frozenset({">", ">-", ">+", "|", "|-", "|+", ""})+# Fixed timestamp keeps the archive reproducible across builds.+_ZIP_DATE_TIME = (2020, 1, 1, 0, 0, 0)+_KEY_RE = re.compile(r"^([A-Za-z0-9_-]+):(.*)$")+++class SkillPackagingError(Exception):+ """Raised when ``SKILL.md`` violates the claude.ai skill-ZIP contract."""+++def parse_frontmatter(skill_md: str) -> dict[str, str]:+ """Extract the leading YAML frontmatter block as a flat ``{key: value}`` map.++ Only the leaf cases the skill contract needs are handled: inline scalars and+ folded/literal block scalars (e.g. ``description: >-``).+ """+ lines = skill_md.splitlines()+ if not lines or lines[0].strip() != "---":+ raise SkillPackagingError("SKILL.md must start with a '---' frontmatter block")+ end = next((i for i in range(1, len(lines)) if lines[i].strip() == "---"), None)+ if end is None:+ raise SkillPackagingError("SKILL.md frontmatter block is not terminated with '---'")++ fields: dict[str, str] = {}+ body = lines[1:end]+ i = 0+ while i < len(body):+ match = _KEY_RE.match(body[i])+ if not match:+ i += 1+ continue+ key, rest = match.group(1), match.group(2).strip()+ if rest in _BLOCK_SCALAR_INDICATORS:+ collected: list[str] = []+ i += 1+ while i < len(body) and (body[i].startswith((" ", "\t")) or not body[i].strip()):+ collected.append(body[i].strip())+ i += 1+ fields[key] = " ".join(part for part in collected if part)+ else:+ fields[key] = _scalar_value(rest)+ i += 1+ return fields+++def _scalar_value(raw: str) -> str:+ """Resolve an inline YAML scalar: unwrap quotes, else strip a trailing ``#`` comment."""+ value = raw.strip()+ if value[:1] in ("'", '"'):+ return value.strip("\"'")+ comment = value.find(" #")+ if comment != -1:+ value = value[:comment].rstrip()+ return value+++def skill_name(skill_md: str) -> str:+ """Validate ``SKILL.md`` against the claude.ai contract and return its skill name."""+ fields = parse_frontmatter(skill_md)+ name = fields.get("name", "")+ if not _NAME_RE.match(name):+ raise SkillPackagingError(f"skill name {name!r} must match ^[a-z0-9-]{{1,64}}$")+ if any(word in name for word in _RESERVED_NAME_WORDS):+ raise SkillPackagingError(f"skill name {name!r} must not contain a reserved word")+ description = fields.get("description", "")+ if not description:+ raise SkillPackagingError("skill description is required and must be non-empty")+ if len(description) > _MAX_DESCRIPTION_LEN:+ raise SkillPackagingError(f"skill description exceeds {_MAX_DESCRIPTION_LEN} characters")+ return name+++def build_skill_zip(skill_md: str, *, extra: dict[str, str] | None = None) -> bytes:+ """Build the skill ZIP bytes, nesting every file under ``<name>/``."""+ name = skill_name(skill_md)+ buffer = io.BytesIO()+ with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive:+ _write(archive, f"{name}/SKILL.md", skill_md)+ for rel_path, content in sorted((extra or {}).items()):+ _write(archive, f"{name}/{rel_path}", content)+ return buffer.getvalue()+++def _write(archive: zipfile.ZipFile, arcname: str, content: str) -> None:+ info = zipfile.ZipInfo(arcname, date_time=_ZIP_DATE_TIME)+ info.compress_type = zipfile.ZIP_DEFLATED+ info.external_attr = 0o644 << 16+ archive.writestr(info, content)diff --git a/packages/sie_mcp/src/sie_mcp/structured.py b/packages/sie_mcp/src/sie_mcp/structured.pynew file mode 100644index 000000000..072617a96--- /dev/null+++ b/packages/sie_mcp/src/sie_mcp/structured.py@@ -0,0 +1,353 @@+"""``extract_structured`` + ``generate_structured`` — the Req 12 structured jobs (#1308).++Both produce schema/grammar-constrained output off the cluster via the+OpenAI-compatible chat-completions surface (``response_format``), *not* the+SIE-native ``generate()`` / ``extract()`` primitives — ``extract.output_schema``+is a declared-but-stub param on every adapter, so grounded JSON comes from a+generative model constrained to the schema and fed the document content.++The cluster (gateway + Outlines backend) is the final authority on grammar+validity; this module pre-validates the JSON-Schema subset (keywords, depth,+node count, and serialized size — mirroring the gateway safety caps) and+rejects EBNF-on-Outlines up front so callers get a clear, fast error instead+of a ``grammar_capability`` / ``unsupported_field`` round-trip.++It also *post-validates* the cluster's response against the requested schema.+Decode-time grammar enforcement is the primary guarantee, but a serving-layer+profile can bypass the grammar FSM (e.g. NEXTN speculative decoding on the+Qwen3.5 default profile — see ``tools/validate_mcp_structured_gpu.py`` and+#1302/#1231); when that happens the output is rejected with a clear error+rather than returned as if it conformed.+"""++import json+from typing import Any, Protocol++# JSON-Schema keywords Outlines does not support (or compiles at prohibitive+# cost). Mirrors the gateway reject-list in+# ``packages/sie_gateway/src/handlers/grammar.rs`` so a schema accepted here is+# also accepted there. ``$ref`` covers recursion: a recursive JSON Schema can+# only refer back to itself through ``$ref``, so rejecting all ``$ref`` rejects+# recursion too. ``if`` / ``then`` / ``else`` cover conditionals.+_UNSUPPORTED_KEYWORDS = (+ "$ref",+ "$dynamicRef",+ "if",+ "then",+ "else",+ "unevaluatedProperties",+ "dependentSchemas",+)++# Keys whose values are nested sub-schemas; descending into them increments the+# depth counter. Mirrors ``is_schema_nesting_key`` in the gateway.+_SCHEMA_NESTING_KEYS = frozenset(+ {+ "properties",+ "patternProperties",+ "additionalProperties",+ "unevaluatedProperties",+ "items",+ "prefixItems",+ "contains",+ "propertyNames",+ "oneOf",+ "anyOf",+ "allOf",+ "not",+ "definitions",+ "$defs",+ "dependentSchemas",+ "if",+ "then",+ "else",+ }+)++# Mirrors ``MAX_SCHEMA_DEPTH`` in the gateway. A schema at exactly this depth is+# accepted; deeper is rejected.+_MAX_SCHEMA_DEPTH = 16++# The remaining gateway safety caps (``packages/sie_gateway/src/handlers/grammar.rs``),+# mirrored so a schema/grammar accepted at this edge is also accepted there —+# the edge preflight stays a faithful fast-fail, not a looser gate that lets a+# request through only for the gateway to reject it after a round-trip.+# * ``_MAX_SCHEMA_NODES`` bounds a *wide* schema (depth alone does not stop a+# shallow object with hundreds of thousands of trivial properties).+# * ``_MAX_GRAMMAR_BYTES`` bounds the serialized schema size.+# * ``_MAX_REGEX_LEN`` / ``_MAX_EBNF_LEN`` bound the regex / EBNF source.+_MAX_SCHEMA_NODES = 16 * 1024+_MAX_GRAMMAR_BYTES = 64 * 1024+_MAX_REGEX_LEN = 4 * 1024+_MAX_EBNF_LEN = 8 * 1024++# Models whose generation profile is Outlines-backed and therefore advertise+# only ``json_schema`` + ``regex`` (EBNF/grammar is an upstream SGLang/Outlines+# limitation). An EBNF request to one of these is rejected up front. The+# production Qwen3.5 profile (``grammar_backend: outlines``) seeds the set.+_OUTLINES_BACKED_MODELS = frozenset({"Qwen/Qwen3.5-4B"})++_EXTRACT_SYSTEM = (+ "You extract structured data from the supplied document content. Use only "+ "information present in the content — do not invent or infer values it does "+ "not support. Where the schema permits and a value is absent, use null."+)+_DEFAULT_EXTRACT_INSTRUCTION = "Extract the structured data described by the schema from the document below."+++class StructuredOutputError(Exception):+ """Raised when an input schema/grammar is out of the supported subset.++ Carries a caller-facing message naming the offending key path so the+ schema can be fixed without a cluster round-trip.+ """+++class ChatClient(Protocol):+ """The slice of ``SIEAsyncClient`` these jobs need (keeps them unit-testable)."""++ async def chat_completions(self, model: str, messages: Any, **kwargs: Any) -> Any:+ """Run an OpenAI-compatible chat completion against the SIE cluster."""+++def _is_outlines_backed(model: str) -> bool:+ return model in _OUTLINES_BACKED_MODELS+++def _walk_schema(node: Any, *, path: str, depth: int, counter: list[int]) -> None:+ # Mirror the gateway's per-node accounting: every visited value (objects,+ # array elements, scalars) counts toward ``_MAX_SCHEMA_NODES`` so a wide+ # schema is bounded even when it stays shallow.+ counter[0] += 1+ if counter[0] > _MAX_SCHEMA_NODES:+ msg = f"output_schema node count exceeds limit ({_MAX_SCHEMA_NODES}) at {path}"+ raise StructuredOutputError(msg)+ if depth > _MAX_SCHEMA_DEPTH:+ msg = f"output_schema nesting depth exceeds limit ({_MAX_SCHEMA_DEPTH}) at {path}"+ raise StructuredOutputError(msg)+ if isinstance(node, dict):+ # Reject before descending so the message names the shallowest occurrence.+ for kw in _UNSUPPORTED_KEYWORDS:+ if kw in node:+ detail = (+ "'$ref' is not supported (the schema subset rejects all $ref, "+ "including internal '#/...', so recursion is not expressible)"+ if kw == "$ref"+ else f"JSON Schema keyword '{kw}' is not supported by the Outlines subset"+ )+ raise StructuredOutputError(f"{detail} at {path}.{kw}")+ for key, child in node.items():+ child_depth = depth + 1 if key in _SCHEMA_NESTING_KEYS else depth+ _walk_schema(child, path=f"{path}.{key}", depth=child_depth, counter=counter)+ elif isinstance(node, list):+ for i, child in enumerate(node):+ _walk_schema(child, path=f"{path}[{i}]", depth=depth, counter=counter)+++def validate_output_schema(schema: Any) -> None:+ """Enforce the Outlines-supported JSON-Schema subset and the gateway caps.++ Rejects ``$ref`` (and thus recursion), conditionals (``if``/``then``/+ ``else``), other unsupported keywords, nesting deeper than+ :data:`_MAX_SCHEMA_DEPTH`, more than :data:`_MAX_SCHEMA_NODES` nodes, and a+ serialized schema larger than :data:`_MAX_GRAMMAR_BYTES` — mirroring the+ gateway so an edge-accepted schema is gateway-accepted too. Raises+ :class:`StructuredOutputError` on the first violation; returns ``None`` when+ the schema is in-subset.+ """+ if not isinstance(schema, dict):+ msg = "output_schema must be a JSON object"+ raise StructuredOutputError(msg)+ # Serialized-size cap first (mirrors the gateway, which checks payload size+ # before walking) so a pathologically large schema is rejected cheaply.+ serialized_len = len(json.dumps(schema).encode("utf-8"))+ if serialized_len > _MAX_GRAMMAR_BYTES:+ msg = f"output_schema serialized size {serialized_len} bytes exceeds limit ({_MAX_GRAMMAR_BYTES} bytes)"+ raise StructuredOutputError(msg)+ _walk_schema(schema, path="output_schema", depth=0, counter=[0])+++def _validate_against_schema(data: Any, schema: dict[str, Any]) -> None:+ """Post-validate cluster output against the requested schema (defense in depth).++ Decode-time grammar enforcement is the primary guarantee, but a serving+ profile can bypass the grammar FSM (NEXTN speculative decoding on the+ Qwen3.5 default profile leaks keys / truncates — see+ ``tools/validate_mcp_structured_gpu.py`` and #1302/#1231). When the returned+ object does not conform, raise rather than hand back non-conforming JSON as+ if it were schema-valid.++ ``jsonschema`` is a guaranteed transitive dependency of the MCP edge+ (``mcp`` → ``jsonschema``); it is imported lazily so ``structured.py`` stays+ importable standalone by the GPU validation harness (which adds the source+ to ``sys.path`` without installing the package). If it is somehow absent the+ check is skipped — this layer is additive safety, not the only guard.+ """+ try:+ import jsonschema # noqa: PLC0415 (lazy: keeps structured.py standalone-importable)+ except ImportError:+ return+ try:+ jsonschema.validate(instance=data, schema=schema)+ except jsonschema.ValidationError as exc:+ msg = (+ "cluster output does not conform to the requested schema — the serving "+ "profile may have bypassed grammar enforcement (e.g. speculative decoding "+ f"on the default Qwen3.5 profile): {exc.message}"+ )+ raise StructuredOutputError(msg) from exc+ except jsonschema.SchemaError:+ # The schema passed our subset walk but jsonschema's metaschema is+ # stricter; don't fail the request on validator strictness — the cluster+ # is the authority on what it can compile.+ return+++def _message_content(resp: Any) -> str:+ choices = resp.get("choices") if isinstance(resp, dict) else None+ if not choices:+ msg = "cluster returned no choices"+ raise StructuredOutputError(msg)+ # Defensive against a malformed response shape (e.g. ``choices: [null]`` or a+ # null ``message``): surface a clear typed error, not a raw AttributeError.+ first = choices[0]+ message = first.get("message") if isinstance(first, dict) else None+ content = message.get("content") if isinstance(message, dict) else None+ if not isinstance(content, str):+ msg = "cluster returned no message content"+ raise StructuredOutputError(msg)+ return content+++async def extract_structured(+ client: ChatClient,+ *,+ content: str,+ output_schema: dict[str, Any],+ instruction: str | None = None,+ model: str,+ gpu: str | None = None,+ max_completion_tokens: int | None = None,+) -> Any:+ """Extract schema-valid JSON grounded in ``content`` via constrained generation.++ Validates ``output_schema`` against the Outlines subset, grounds the+ extraction in ``content`` with a system + user message, and constrains the+ model to the schema with ``response_format`` (``strict``). The parsed result+ is post-validated against ``output_schema`` (defense in depth) before it is+ returned. ``gpu`` pins the machine profile for deterministic routing;+ ``max_completion_tokens`` caps the output so a large schema does not truncate.+ """+ validate_output_schema(output_schema)++ title = output_schema.get("title")+ schema_name = title if isinstance(title, str) and title else "extraction"+ user = f"{instruction or _DEFAULT_EXTRACT_INSTRUCTION}\n\n<document>\n{content}\n</document>"+ messages = [+ {"role": "system", "content": _EXTRACT_SYSTEM},+ {"role": "user", "content": user},+ ]+ resp = await client.chat_completions(+ model,+ messages,+ response_format={+ "type": "json_schema",+ "json_schema": {"name": schema_name, "schema": output_schema, "strict": True},+ },+ # Deterministic, grounded extraction — no creative sampling.+ temperature=0.0,+ gpu=gpu,+ max_completion_tokens=max_completion_tokens,+ )+ raw = _message_content(resp)+ try:+ data = json.loads(raw)+ except json.JSONDecodeError as exc:+ msg = f"cluster returned non-JSON content for a json_schema request: {exc}"+ raise StructuredOutputError(msg) from exc+ _validate_against_schema(data, output_schema)+ return data+++def _validate_response_format(response_format: Any, *, model: str) -> dict[str, Any] | None:+ """Pre-validate ``response_format``; return the json_schema to post-validate, if any."""+ if not isinstance(response_format, dict):+ msg = "response_format must be a JSON object"+ raise StructuredOutputError(msg)+ rf_type = response_format.get("type")+ if rf_type == "json_schema":+ # ``json_schema`` is caller-supplied (untrusted): guard against a+ # non-dict value so a malformed request raises a clear typed error.+ json_schema = response_format.get("json_schema")+ schema = json_schema.get("schema") if isinstance(json_schema, dict) else None+ if schema is None:+ msg = "response_format.json_schema.schema is required for a json_schema request"+ raise StructuredOutputError(msg)+ validate_output_schema(schema)+ return schema+ if rf_type == "regex":+ # Mirror the gateway ``MAX_REGEX_LEN`` cap (UTF-8 byte length, matching+ # Rust ``str::len``) so an oversized pattern fails fast at the edge.+ regex = response_format.get("regex")+ if isinstance(regex, str) and len(regex.encode("utf-8")) > _MAX_REGEX_LEN:+ byte_len = len(regex.encode("utf-8"))+ msg = f"response_format.regex length {byte_len} bytes exceeds limit ({_MAX_REGEX_LEN})"+ raise StructuredOutputError(msg)+ elif rf_type == "grammar":+ if _is_outlines_backed(model):+ msg = (+ f"Model '{model}' is Outlines-backed and does not support EBNF/grammar "+ "constrained output — only 'json_schema' and 'regex'. Use response_format "+ "{'type': 'json_schema', ...} or {'type': 'regex', ...}, or target an "+ "xgrammar-backed model for EBNF."+ )+ raise StructuredOutputError(msg)+ # Non-Outlines (xgrammar-backed) model: EBNF passes through, but mirror+ # the gateway ``MAX_EBNF_LEN`` source cap (UTF-8 byte length).+ ebnf = response_format.get("grammar")+ if isinstance(ebnf, str) and len(ebnf.encode("utf-8")) > _MAX_EBNF_LEN:+ byte_len = len(ebnf.encode("utf-8"))+ msg = f"response_format.grammar (EBNF) length {byte_len} bytes exceeds limit ({_MAX_EBNF_LEN})"+ raise StructuredOutputError(msg)+ return None+++async def generate_structured(+ client: ChatClient,+ *,+ prompt: str,+ response_format: dict[str, Any],+ model: str,+ gpu: str | None = None,+ max_completion_tokens: int | None = None,+) -> str:+ """Generate output constrained by ``response_format`` (schema / regex / grammar).++ Pre-validates the request: a ``json_schema`` is checked against the Outlines+ subset, and an EBNF ``grammar`` request is rejected up front for+ Outlines-backed models. Passes ``response_format`` through unchanged and+ returns the constrained content string (a JSON string for the json modes).+ A ``json_schema`` response is post-validated against the schema (defense in+ depth) before it is returned. ``gpu`` pins the machine profile;+ ``max_completion_tokens`` caps the output so large JSON does not truncate.+ """+ schema = _validate_response_format(response_format, model=model)+ messages = [{"role": "user", "content": prompt}]+ resp = await client.chat_completions(+ model,+ messages,+ response_format=response_format,+ gpu=gpu,+ max_completion_tokens=max_completion_tokens,+ )+ content = _message_content(resp)+ if schema is not None:+ # json_schema mode: confirm the returned string is JSON that conforms,+ # so a grammar-FSM bypass surfaces as a clear error, not silent bad data.+ try:+ parsed = json.loads(content)+ except json.JSONDecodeError as exc:+ msg = f"cluster returned non-JSON content for a json_schema request: {exc}"+ raise StructuredOutputError(msg) from exc+ _validate_against_schema(parsed, schema)+ return contentdiff --git a/packages/sie_mcp/tests/conftest.py b/packages/sie_mcp/tests/conftest.pynew file mode 100644index 000000000..fd39d8dd3--- /dev/null+++ b/packages/sie_mcp/tests/conftest.py@@ -0,0 +1,38 @@+import io+from collections.abc import Callable++import pypdfium2 as pdfium+import pytest+from PIL import Image+++def make_pdf() -> Callable[[int], bytes]:+ """Factory for an in-memory blank PDF with ``n_pages`` pages."""++ def _make(n_pages: int) -> bytes:+ pdf = pdfium.PdfDocument.new()+ for _ in range(n_pages):+ pdf.new_page(200, 300)+ buf = io.BytesIO()+ pdf.save(buf)+ pdf.close()+ return buf.getvalue()++ return _make+++def png_bytes() -> bytes:+ """A minimal valid PNG image as bytes."""+ buf = io.BytesIO()+ Image.new("RGB", (32, 32), "white").save(buf, format="PNG")+ return buf.getvalue()+++def tiff_bytes() -> bytes:+ """A minimal valid TIFF image as bytes (a common scanned-document container)."""+ buf = io.BytesIO()+ Image.new("RGB", (32, 32), "white").save(buf, format="TIFF")+ return buf.getvalue()diff --git a/packages/sie_mcp/tests/test_auth.py b/packages/sie_mcp/tests/test_auth.pynew file mode 100644index 000000000..b53bbbda3--- /dev/null+++ b/packages/sie_mcp/tests/test_auth.py@@ -0,0 +1,161 @@+from typing import Any++import pytest+from sie_mcp.auth import ConnectorSecretAuthMiddleware, authenticate, base_url, bearer_token+from sie_mcp.config import DEFAULT_MAX_DOCUMENT_BYTES, DEFAULT_MAX_IMAGE_BYTES, MCPConfig+from starlette.datastructures import Headers+++def _cfg(**overrides: Any) -> MCPConfig:+ base: dict[str, Any] = {+ "sie_base_url": "http://localhost:8080",+ "sie_api_key": None,+ "connector_secrets": {},+ "allow_anonymous": False,+ "allowed_hosts": [],+ "max_document_bytes": DEFAULT_MAX_DOCUMENT_BYTES,+ "max_image_bytes": DEFAULT_MAX_IMAGE_BYTES,+ "docling_model": "docling",+ "generate_model": "Qwen/Qwen3.5-4B",+ "max_output_tokens": 4096,+ "vlocr_model": "opendatalab/MinerU2.5-Pro-2604-1.2B",+ "encode_model": "BAAI/bge-m3",+ "rerank_model": "BAAI/bge-reranker-v2-m3",+ "caption_model": "microsoft/Florence-2-base-ft",+ "embed_model": "openai/clip-vit-base-patch32",+ "image_labels": [],+ "image_top_k": 5,+ "gpu": None,+ "timeout_s": 300.0,+ "qa_top_k": 5,+ "qa_rerank_candidates": 20,+ "qa_chunk_chars": 1200,+ "qa_chunk_overlap_chars": 200,+ "qa_max_tokens": 512,+ "qa_max_document_chars": 2_000_000,+ "qa_max_questions": 50,+ "qa_max_chunks": 2000,+ "oauth_enabled": True,+ "public_base_url": None,+ "oauth_redirect_uris": ("https://claude.ai/api/mcp/auth_callback",),+ }+ base.update(overrides)+ return MCPConfig(**base)+++async def _run_middleware(cfg: MCPConfig, *, path: str, headers: list[tuple[bytes, bytes]]):+ """Drive the ASGI auth gate over a stub app, returning (reached_app, start_message)."""+ reached: dict[str, Any] = {"app": False, "user_id": None}++ async def _app(scope: Any, _receive: Any, send: Any) -> None:+ reached["app"] = True+ reached["user_id"] = (scope.get("state") or {}).get("user_id")+ await send({"type": "http.response.start", "status": 200, "headers": []})+ await send({"type": "http.response.body", "body": b""})++ sent: list[dict[str, Any]] = []++ async def _send(message: dict[str, Any]) -> None:+ sent.append(message)++ async def _receive() -> dict[str, Any]:+ return {"type": "http.request", "body": b"", "more_body": False}++ scope = {"type": "http", "scheme": "https", "path": path, "headers": headers}+ await ConnectorSecretAuthMiddleware(_app, cfg)(scope, _receive, _send)+ start = next(m for m in sent if m["type"] == "http.response.start")+ return reached, start+++def test_bearer_token_parsing() -> None:+ assert bearer_token("Bearer abc") == "abc"+ assert bearer_token("bearer abc") == "abc"+ assert bearer_token("abc") == "abc"+ assert bearer_token(None) is None+ assert bearer_token("") is None+ assert bearer_token("Bearer ") is None+++def test_valid_secret_maps_to_user() -> None:+ cfg = _cfg(connector_secrets={"s3cret": "user-1"})+ assert authenticate(cfg, "s3cret") == "user-1"+++def test_unknown_token_rejected() -> None:+ cfg = _cfg(connector_secrets={"s3cret": "user-1"})+ assert authenticate(cfg, "nope") is None+++def test_missing_token_rejected_when_closed() -> None:+ cfg = _cfg(connector_secrets={"s3cret": "user-1"})+ assert authenticate(cfg, None) is None+++def test_anonymous_allowed_when_enabled() -> None:+ cfg = _cfg(connector_secrets={}, allow_anonymous=True)+ assert authenticate(cfg, None) == "anonymous"+++def test_closed_by_default_without_secrets() -> None:+ cfg = _cfg(connector_secrets={}, allow_anonymous=False)+ assert authenticate(cfg, None) is None+++def test_invalid_token_rejected_even_when_anonymous_allowed() -> None:+ cfg = _cfg(connector_secrets={"s3cret": "user-1"}, allow_anonymous=True)+ assert authenticate(cfg, "wrong") is None+++def test_base_url_prefers_pinned_public_url() -> None:+ cfg = _cfg(public_base_url="https://mcp.example.com")+ headers = Headers({"host": "internal:8088", "x-forwarded-proto": "http"})+ assert base_url(cfg, scheme="http", headers=headers) == "https://mcp.example.com"+++def test_base_url_derives_from_forwarded_headers() -> None:+ cfg = _cfg(public_base_url=None)+ headers = Headers({"host": "internal:8088", "x-forwarded-proto": "https", "x-forwarded-host": "mcp.example.com"})+ assert base_url(cfg, scheme="http", headers=headers) == "https://mcp.example.com"+++async def test_unauthorized_returns_www_authenticate_challenge() -> None:+ cfg = _cfg(connector_secrets={"s3cret": "user-1"})+ reached, start = await _run_middleware(cfg, path="/mcp", headers=[(b"host", b"mcp.example.com")])+ assert reached["app"] is False+ assert start["status"] == 401+ challenge = Headers(raw=start["headers"])["www-authenticate"]+ assert 'resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource"' in challenge+++async def test_unauthorized_omits_challenge_when_oauth_disabled() -> None:+ cfg = _cfg(connector_secrets={"s3cret": "user-1"}, oauth_enabled=False)+ _reached, start = await _run_middleware(cfg, path="/mcp", headers=[(b"host", b"mcp.example.com")])+ assert start["status"] == 401+ assert "www-authenticate" not in Headers(raw=start["headers"])+++ "path",+ [+ "/healthz",+ "/.well-known/oauth-protected-resource",+ "/.well-known/oauth-authorization-server",+ "/register",+ "/authorize",+ "/token",+ ],+)+async def test_oauth_bootstrap_paths_are_exempt(path: str) -> None:+ cfg = _cfg(connector_secrets={"s3cret": "user-1"})+ reached, start = await _run_middleware(cfg, path=path, headers=[(b"host", b"mcp.example.com")])+ assert reached["app"] is True+ assert start["status"] == 200+++async def test_valid_secret_reaches_app_with_identity() -> None:+ cfg = _cfg(connector_secrets={"s3cret": "user-1"})+ reached, start = await _run_middleware(+ cfg, path="/mcp", headers=[(b"host", b"mcp.example.com"), (b"authorization", b"Bearer s3cret")]+ )+ assert start["status"] == 200+ assert reached["user_id"] == "user-1"diff --git a/packages/sie_mcp/tests/test_chunking.py b/packages/sie_mcp/tests/test_chunking.pynew file mode 100644index 000000000..67a7b5c8c--- /dev/null+++ b/packages/sie_mcp/tests/test_chunking.py@@ -0,0 +1,56 @@+import pytest+from sie_mcp.chunking import chunk_documents, chunk_text+++def test_windows_cover_text_with_overlap() -> None:+ windows = chunk_text("abcdefghij", window=4, overlap=1)++ # stride = window - overlap = 3: starts at 0, 3, 6; the 6-window already+ # reaches the end so no further window is emitted.+ assert [start for start, _ in windows] == [0, 3, 6]+ assert [piece for _, piece in windows] == ["abcd", "defg", "ghij"]+ # Overlap means neighbours share a character ("d", "g").+ assert windows[0][1][-1] == windows[1][1][0]+++def test_single_window_when_text_shorter_than_window() -> None:+ assert chunk_text("short", window=100, overlap=10) == [(0, "short")]+++def test_empty_text_yields_no_windows() -> None:+ assert chunk_text("", window=10, overlap=2) == []+++def test_rejects_overlap_not_smaller_than_window() -> None:+ with pytest.raises(ValueError, match="overlap"):+ chunk_text("abc", window=4, overlap=4)+++def test_rejects_non_positive_window() -> None:+ with pytest.raises(ValueError, match="window"):+ chunk_text("abc", window=0, overlap=0)+++def test_chunk_documents_assigns_unique_ids_and_doc_index() -> None:+ chunks = chunk_documents(["abcdef", "uvwxyz"], window=3, overlap=0)++ assert [c.id for c in chunks] == ["d0-c0", "d0-c1", "d1-c0", "d1-c1"]+ assert [c.doc_index for c in chunks] == [0, 0, 1, 1]+ assert [c.text for c in chunks] == ["abc", "def", "uvw", "xyz"]+ assert [c.start for c in chunks] == [0, 3, 0, 3]+++def test_chunk_documents_skips_empty_documents_but_keeps_doc_index() -> None:+ chunks = chunk_documents(["", " ", "abc"], window=10, overlap=0)++ # Empty/whitespace docs contribute nothing; the real doc keeps its index (2).+ assert [c.doc_index for c in chunks] == [2]+ assert chunks[0].text == "abc"+++def test_large_document_chunks_into_many() -> None:+ # A document far larger than one window must split into multiple chunks.+ chunks = chunk_documents(["x" * 10_000], window=1000, overlap=100)++ assert len(chunks) > 1+ assert all(len(c.text) <= 1000 for c in chunks)diff --git a/packages/sie_mcp/tests/test_config.py b/packages/sie_mcp/tests/test_config.pynew file mode 100644index 000000000..ead3bf20f--- /dev/null+++ b/packages/sie_mcp/tests/test_config.py@@ -0,0 +1,81 @@+import pytest+from sie_mcp.config import (+ _DEFAULT_IMAGE_TOP_K,+ DEFAULT_MAX_DOCUMENT_BYTES,+ DEFAULT_MAX_IMAGE_BYTES,+ DEFAULT_VLOCR_MODEL,+ MCPConfig,+)+++def test_vlocr_model_defaults_when_unset(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.delenv("SIE_MCP_VLOCR_MODEL", raising=False)+ assert MCPConfig.from_env().vlocr_model == DEFAULT_VLOCR_MODEL++[email protected]("blank", ["", " ", "\t\n"])+def test_blank_vlocr_model_falls_back_to_default(monkeypatch: pytest.MonkeyPatch, blank: str) -> None:+ monkeypatch.setenv("SIE_MCP_VLOCR_MODEL", blank)+ assert MCPConfig.from_env().vlocr_model == DEFAULT_VLOCR_MODEL+++def test_explicit_vlocr_model_is_honored(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("SIE_MCP_VLOCR_MODEL", "some/other-model")+ assert MCPConfig.from_env().vlocr_model == "some/other-model"+++def test_anonymous_closed_by_default_without_secrets(monkeypatch: pytest.MonkeyPatch) -> None:+ # A missing/misnamed secret env var must fail closed, not open anonymous access.+ monkeypatch.delenv("SIE_MCP_CONNECTOR_SECRETS", raising=False)+ monkeypatch.delenv("SIE_MCP_ALLOW_ANONYMOUS", raising=False)+ assert MCPConfig.from_env().allow_anonymous is False+++def test_anonymous_is_explicit_opt_in(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.delenv("SIE_MCP_CONNECTOR_SECRETS", raising=False)+ monkeypatch.setenv("SIE_MCP_ALLOW_ANONYMOUS", "1")+ assert MCPConfig.from_env().allow_anonymous is True+++def test_allowed_hosts_parsed_as_trimmed_list(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("SIE_MCP_ALLOWED_HOSTS", " mcp.example.com , mcp.example.com:* ,")+ assert MCPConfig.from_env().allowed_hosts == ["mcp.example.com", "mcp.example.com:*"]+++def test_allowed_hosts_default_empty(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.delenv("SIE_MCP_ALLOWED_HOSTS", raising=False)+ assert MCPConfig.from_env().allowed_hosts == []++[email protected]("bad", ["", " ", "not-a-number", "0", "-5"])+def test_max_document_bytes_falls_back_on_bad_value(monkeypatch: pytest.MonkeyPatch, bad: str) -> None:+ monkeypatch.setenv("SIE_MCP_MAX_DOCUMENT_BYTES", bad)+ assert MCPConfig.from_env().max_document_bytes == DEFAULT_MAX_DOCUMENT_BYTES+++def test_max_document_bytes_honors_explicit_value(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("SIE_MCP_MAX_DOCUMENT_BYTES", "1024")+ assert MCPConfig.from_env().max_document_bytes == 1024++[email protected]("bad", ["", " ", "not-a-number", "0", "-5"])+def test_max_image_bytes_falls_back_on_bad_value(monkeypatch: pytest.MonkeyPatch, bad: str) -> None:+ monkeypatch.setenv("SIE_MCP_MAX_IMAGE_BYTES", bad)+ assert MCPConfig.from_env().max_image_bytes == DEFAULT_MAX_IMAGE_BYTES+++def test_max_image_bytes_honors_explicit_value(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("SIE_MCP_MAX_IMAGE_BYTES", "1024")+ assert MCPConfig.from_env().max_image_bytes == 1024+++def test_image_top_k_zero_is_honored(monkeypatch: pytest.MonkeyPatch) -> None:+ # 0 is a valid caption-only request, not a bad value — it must pass through.+ monkeypatch.setenv("SIE_MCP_IMAGE_TOP_K", "0")+ assert MCPConfig.from_env().image_top_k == 0++[email protected]("bad", ["", " ", "not-a-number", "-3"])+def test_image_top_k_falls_back_on_bad_value(monkeypatch: pytest.MonkeyPatch, bad: str) -> None:+ monkeypatch.setenv("SIE_MCP_IMAGE_TOP_K", bad)+ assert MCPConfig.from_env().image_top_k == _DEFAULT_IMAGE_TOP_Kdiff --git a/packages/sie_mcp/tests/test_describe.py b/packages/sie_mcp/tests/test_describe.pynew file mode 100644index 000000000..c20c568f4--- /dev/null+++ b/packages/sie_mcp/tests/test_describe.py@@ -0,0 +1,227 @@+from typing import Any++import numpy as np+import pytest+from sie_mcp import describe+from sie_mcp.describe import DescribeImageError++_CAPTION_MODEL = "microsoft/Florence-2-base-ft"+_EMBED_MODEL = "openai/clip-vit-base-patch32"+++class _FakeClient:+ """Records extract()/encode() calls and returns canned result-shaped dicts.++ ``encode`` mirrors the SDK contract: a list of items yields a list of+ EncodeResults (the label embeddings), a single item yields one (the image).+ """++ def __init__(+ self,+ *,+ caption_entities: Any,+ label_vectors: dict[str, Any] | None = None,+ image_vector: Any = None,+ ) -> None:+ # Explicit None checks (not ``or``) so numpy-array vectors don't trip the+ # ambiguous-truth-value error.+ self._caption_entities = caption_entities+ self._label_vectors = label_vectors if label_vectors is not None else {}+ self._image_vector = image_vector if image_vector is not None else []+ self.extract_calls: list[dict[str, Any]] = []+ self.encode_calls: list[dict[str, Any]] = []++ async def extract(self, model: str, items: Any, **kwargs: Any) -> Any:+ self.extract_calls.append({"model": model, "items": items, **kwargs})+ return {"entities": self._caption_entities}++ async def encode(self, model: str, items: Any, **kwargs: Any) -> Any:+ self.encode_calls.append({"model": model, "items": items, **kwargs})+ if isinstance(items, list):+ return [{"dense": self._label_vectors[item["text"]]} for item in items]+ return {"dense": self._image_vector}+++def _client(**kwargs: Any) -> _FakeClient:+ return _FakeClient(caption_entities=[{"text": "a cat", "label": "caption", "score": 1.0}], **kwargs)+++async def _describe(client: _FakeClient, **kwargs: Any) -> Any:+ params: dict[str, Any] = {+ "image_base64": "",+ "labels": [],+ "caption_model": _CAPTION_MODEL,+ "embed_model": _EMBED_MODEL,+ }+ params.update(kwargs)+ return await describe.describe_image(client, **params)+++async def test_returns_caption_and_tags() -> None:+ client = _client(+ label_vectors={"cat": [1.0, 0.0], "dog": [0.0, 1.0], "bird": [0.7, 0.7]},+ image_vector=[1.0, 0.0],+ )++ result = await _describe(client, labels=["cat", "dog", "bird"], top_k=3)++ assert result["caption"] == "a cat"+ assert [tag["label"] for tag in result["tags"]] == ["cat", "bird", "dog"]+ assert result["tags"][0]["score"] == pytest.approx(1.0)+ # Scores are sorted descending.+ scores = [tag["score"] for tag in result["tags"]]+ assert scores == sorted(scores, reverse=True)+++async def test_zero_shot_argmax_picks_closest_unnormalized() -> None:+ # Cosine normalizes, so an unnormalized image vector still ranks by direction.+ client = _client(+ label_vectors={"cat": [2.0, 0.0], "dog": [0.0, 3.0]},+ image_vector=[5.0, 0.0],+ )++ result = await _describe(client, labels=["cat", "dog"], top_k=1)++ assert [tag["label"] for tag in result["tags"]] == ["cat"]+ assert result["tags"][0]["score"] == pytest.approx(1.0)+++async def test_top_k_limits_tags() -> None:+ client = _client(+ label_vectors={"a": [1.0, 0.0], "b": [0.9, 0.1], "c": [0.0, 1.0]},+ image_vector=[1.0, 0.0],+ )++ result = await _describe(client, labels=["a", "b", "c"], top_k=2)++ assert len(result["tags"]) == 2+ assert [tag["label"] for tag in result["tags"]] == ["a", "b"]+++async def test_top_k_zero_returns_no_tags_and_skips_encode() -> None:+ client = _client(label_vectors={"a": [1.0, 0.0], "b": [0.0, 1.0]}, image_vector=[1.0, 0.0])++ result = await _describe(client, labels=["a", "b"], top_k=0)++ assert result["tags"] == []+ # top_k<=0 keeps no tags, so no embedding round-trip should be made at all.+ assert client.encode_calls == []+++async def test_top_k_negative_returns_no_tags_and_skips_encode() -> None:+ client = _client(label_vectors={"a": [1.0, 0.0], "b": [0.0, 1.0]}, image_vector=[1.0, 0.0])++ result = await _describe(client, labels=["a", "b"], top_k=-1)++ assert result["tags"] == []+ assert client.encode_calls == []+++async def test_top_k_larger_than_labels_returns_all() -> None:+ client = _client(+ label_vectors={"a": [1.0, 0.0], "b": [0.0, 1.0], "c": [0.7, 0.7]},+ image_vector=[1.0, 0.0],+ )++ result = await _describe(client, labels=["a", "b", "c"], top_k=99)++ assert [tag["label"] for tag in result["tags"]] == ["a", "c", "b"]+++async def test_handles_numpy_dense_vectors() -> None:+ # The real SDK returns numpy arrays for ``dense``; exercise that ``.tolist()`` path.+ client = _client(+ label_vectors={"cat": np.array([1.0, 0.0]), "dog": np.array([0.0, 1.0])},+ image_vector=np.array([2.0, 0.0]),+ )++ result = await _describe(client, labels=["cat", "dog"], top_k=2)++ assert [tag["label"] for tag in result["tags"]] == ["cat", "dog"]+ assert result["tags"][0]["score"] == pytest.approx(1.0)+++async def test_default_task_is_plain_caption() -> None:+ client = _client(label_vectors={"cat": [1.0]}, image_vector=[1.0])++ await _describe(client, labels=["cat"])++ assert client.extract_calls[0]["options"] == {"task": "<CAPTION>"}+ assert client.extract_calls[0]["model"] == _CAPTION_MODEL+++async def test_detailed_uses_detailed_caption_task() -> None:+ client = _client(label_vectors={"cat": [1.0]}, image_vector=[1.0])++ await _describe(client, labels=["cat"], detailed=True)++ assert client.extract_calls[0]["options"] == {"task": "<DETAILED_CAPTION>"}+++async def test_empty_labels_skips_encode() -> None:+ client = _client()++ result = await _describe(client, labels=[])++ assert result["caption"] == "a cat"+ assert result["tags"] == []+ assert client.encode_calls == []+++async def test_encode_uses_embed_model_and_image_item() -> None:+ client = _client(label_vectors={"cat": [1.0]}, image_vector=[1.0])++ await _describe(client, labels=["cat"])++ # Two encode calls (run concurrently, so order is not asserted): the label+ # batch (list of text items) and the image (single item).+ assert len(client.encode_calls) == 2+ assert all(call["model"] == _EMBED_MODEL for call in client.encode_calls)+ items = [call["items"] for call in client.encode_calls]+ assert [{"text": "cat"}] in items+ assert any(isinstance(it, dict) and "images" in it for it in items)+++async def test_caption_missing_returns_empty_string() -> None:+ client = _FakeClient(caption_entities=[])++ result = await _describe(client, labels=[])++ assert result["caption"] == ""+++async def test_rejects_invalid_base64() -> None:+ client = _client()++ with pytest.raises(DescribeImageError):+ await _describe(client, image_base64="!!not base64!!")+++async def test_rejects_oversize_image_before_any_cluster_call() -> None:+ client = _client(label_vectors={"cat": [1.0]}, image_vector=[1.0])+ # 400 base64 chars decode to ~300 bytes, well over the 4-byte cap; the+ # pre-decode length check must reject it before any extract/encode round-trip.+ oversize = "A" * 400++ with pytest.raises(DescribeImageError):+ await _describe(client, image_base64=oversize, labels=["cat"], max_image_bytes=4)++ assert client.extract_calls == []+ assert client.encode_calls == []+++async def test_raises_on_missing_dense_embedding() -> None:+ client = _client(label_vectors={"cat": [1.0]}, image_vector=[1.0])+ client._image_vector = None # type: ignore[assignment] # simulate a malformed encode result++ with pytest.raises(DescribeImageError):+ await _describe(client, labels=["cat"])+++async def test_raises_on_embedding_dim_mismatch() -> None:+ # A label vector whose dimension differs from the image vector must raise rather+ # than silently drop the label via a lenient zip.+ client = _client(label_vectors={"cat": [1.0, 0.0]}, image_vector=[1.0])++ with pytest.raises(DescribeImageError):+ await _describe(client, labels=["cat"], top_k=1)diff --git a/packages/sie_mcp/tests/test_jobs.py b/packages/sie_mcp/tests/test_jobs.pynew file mode 100644index 000000000..03562b2da--- /dev/null+++ b/packages/sie_mcp/tests/test_jobs.py@@ -0,0 +1,144 @@+import base64+from collections.abc import Callable+from typing import Any++import pytest+from sie_mcp import jobs+from sie_mcp.jobs import DocsToMarkdownError+++class _FakeClient:+ """Records extract() calls and returns a canned ExtractResult-shaped dict."""++ def __init__(self, payload: Any) -> None:+ self._payload = payload+ self.calls: list[dict[str, Any]] = []++ async def extract(self, model: str, items: Any, **kwargs: Any) -> Any:+ self.calls.append({"model": model, "items": items, **kwargs})+ return {"data": self._payload}+++class _VLOCRFakeClient:+ """Docling (dict item) returns ``{"data": ...}``; VL-OCR (list of items) returns+ a ``list[ExtractResult]`` with the same ``mineru_text`` entity per page.+ """++ def __init__(self, *, docling: Any = None, vl_text: str = "") -> None:+ self._docling = docling+ self._vl_text = vl_text+ self.calls: list[dict[str, Any]] = []++ async def extract(self, model: str, items: Any, **kwargs: Any) -> Any:+ self.calls.append({"model": model, "items": items, **kwargs})+ if isinstance(items, list):+ return [{"entities": [{"text": self._vl_text, "label": "mineru_text", "score": 1.0}]} for _ in items]+ return {"data": self._docling}+++async def test_returns_markdown_and_metadata() -> None:+ client = _FakeClient({"markdown": "# Title\n\nbody", "document": {"pages": {"1": {}}}})++ result = await jobs.docs_to_markdown(client, document_base64="", filename="report.pdf")++ assert result["markdown"] == "# Title\n\nbody"+ assert result["metadata"]["source_pages"] == 1+ assert result["metadata"]["markdown_tokens_estimated"] is True+ assert result["metadata"]["markdown_chars"] == len("# Title\n\nbody")+ # Committed #1311 figures are wired in and trace back to the benchmark run.+ reduction = result["metadata"]["token_reduction"]+ assert reduction["run"] == "20260610T144234Z"+ assert reduction["blended_reduction_pct"] == {"claude-opus-4-8": 82.9, "claude-sonnet-4-6": 86.5}+ assert reduction["per_file_type_reduction_pct"] == {"min": 63.3, "max": 94.8}+ assert reduction["source"].endswith("latest.json")+++async def test_token_reduction_is_isolated_from_committed_figures() -> None:+ """Mutating one response's metadata must not corrupt the committed benchmark."""+ client = _FakeClient({"markdown": "x"})++ first = await jobs.docs_to_markdown(client, document_base64="", filename="a.pdf")+ first["metadata"]["token_reduction"]["blended_reduction_pct"]["claude-opus-4-8"] = 0.0++ second = await jobs.docs_to_markdown(client, document_base64="", filename="b.pdf")++ assert second["metadata"]["token_reduction"]["blended_reduction_pct"]["claude-opus-4-8"] == 82.9+++async def test_derives_format_hint_from_filename() -> None:+ client = _FakeClient({"markdown": "x"})++ await jobs.docs_to_markdown(client, document_base64="", filename="report.pdf")++ assert client.calls[0]["items"]["document"]["format"] == "pdf"+ assert client.calls[0]["options"] is None # no OCR by default+++async def test_passes_ocr_option_when_requested() -> None:+ # ocr only enables Docling's built-in OCR under engine="docling"; under "auto"+ # the VL-OCR fallback owns scans (see test_ocr_routing).+ client = _FakeClient({"markdown": "x"})++ await jobs.docs_to_markdown(client, document_base64="", filename="scan.pdf", ocr=True, engine="docling")++ assert client.calls[0]["options"] == {"ocr": True}+++async def test_handles_data_returned_as_list() -> None:+ client = _FakeClient([{"markdown": "from list"}])++ result = await jobs.docs_to_markdown(client, document_base64="", filename="a.docx")++ assert result["markdown"] == "from list"+++async def test_raises_on_error_payload() -> None:+ client = _FakeClient({"error": "unsupported format"})++ with pytest.raises(DocsToMarkdownError):+ await jobs.docs_to_markdown(client, document_base64="", filename="a.bin")+++async def test_rejects_invalid_base64() -> None:+ client = _FakeClient({"markdown": "x"})++ with pytest.raises(DocsToMarkdownError):+ await jobs.docs_to_markdown(client, document_base64="!!not base64!!", filename="a.pdf")+++async def test_rejects_oversize_document() -> None:+ client = _FakeClient({"markdown": "x"})+ oversize = base64.b64encode(b"a" * 1024).decode()++ with pytest.raises(DocsToMarkdownError, match="exceeds"):+ await jobs.docs_to_markdown(client, document_base64=oversize, filename="a.pdf", max_document_bytes=512)+ # Rejected at the edge — no cluster call made.+ assert client.calls == []+++async def test_metadata_reports_docling_engine() -> None:+ client = _FakeClient({"markdown": "# Title\n\nbody", "document": {"pages": {"1": {}}}})++ result = await jobs.docs_to_markdown(client, document_base64="", filename="report.pdf")++ assert result["metadata"]["engine"] == "docling"+++async def test_engine_vl_ocr_renders_pdf_and_stitches_pages(make_pdf: Callable[[int], bytes]) -> None:+ pdf_b64 = base64.b64encode(make_pdf(2)).decode()+ client = _VLOCRFakeClient(vl_text="scanned page text")++ result = await jobs.docs_to_markdown(+ client,+ document_base64=pdf_b64,+ filename="scan.pdf",+ engine="vl-ocr",+ vlocr_model="opendatalab/MinerU2.5-Pro-2604-1.2B",+ )++ assert result["markdown"] == "scanned page text\n\nscanned page text"+ assert result["metadata"]["engine"] == "vl-ocr"+ assert result["metadata"]["source_pages"] == 2+ # One batched VL-OCR call, two image items (one per page), routed to the VL-OCR model.+ assert client.calls[0]["model"] == "opendatalab/MinerU2.5-Pro-2604-1.2B"+ assert len(client.calls[0]["items"]) == 2diff --git a/packages/sie_mcp/tests/test_oauth.py b/packages/sie_mcp/tests/test_oauth.pynew file mode 100644index 000000000..32deee3ac--- /dev/null+++ b/packages/sie_mcp/tests/test_oauth.py@@ -0,0 +1,382 @@+import base64+import hashlib+from typing import Any+from urllib.parse import parse_qs, urlparse++import pytest+from sie_mcp.config import DEFAULT_MAX_DOCUMENT_BYTES, DEFAULT_MAX_IMAGE_BYTES, MCPConfig+from sie_mcp.oauth import (+ AuthCodeStore,+ OAuthError,+ authorization_server_metadata,+ build_oauth_routes,+ exchange_authorization_code,+ protected_resource_metadata,+ verify_pkce,+)+from starlette.applications import Starlette+from starlette.testclient import TestClient++_REDIRECT = "https://claude.ai/api/mcp/auth_callback"+++def _cfg(**overrides: Any) -> MCPConfig:+ base: dict[str, Any] = {+ "sie_base_url": "http://localhost:8080",+ "sie_api_key": None,+ "connector_secrets": {"s3cret": "user-1"},+ "allow_anonymous": False,+ "allowed_hosts": [],+ "max_document_bytes": DEFAULT_MAX_DOCUMENT_BYTES,+ "max_image_bytes": DEFAULT_MAX_IMAGE_BYTES,+ "docling_model": "docling",+ "generate_model": "Qwen/Qwen3.5-4B",+ "max_output_tokens": 4096,+ "vlocr_model": "opendatalab/MinerU2.5-Pro-2604-1.2B",+ "encode_model": "BAAI/bge-m3",+ "rerank_model": "BAAI/bge-reranker-v2-m3",+ "caption_model": "microsoft/Florence-2-base-ft",+ "embed_model": "openai/clip-vit-base-patch32",+ "image_labels": [],+ "image_top_k": 5,+ "gpu": None,+ "timeout_s": 300.0,+ "qa_top_k": 5,+ "qa_rerank_candidates": 20,+ "qa_chunk_chars": 1200,+ "qa_chunk_overlap_chars": 200,+ "qa_max_tokens": 512,+ "qa_max_document_chars": 2_000_000,+ "qa_max_questions": 50,+ "qa_max_chunks": 2000,+ "oauth_enabled": True,+ "public_base_url": None,+ "oauth_redirect_uris": ("https://claude.ai/api/mcp/auth_callback",),+ }+ base.update(overrides)+ return MCPConfig(**base)+++def _s256(verifier: str) -> str:+ digest = hashlib.sha256(verifier.encode("ascii")).digest()+ return base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")+++def test_verify_pkce_s256_roundtrip() -> None:+ verifier = "verifier-abc123"+ assert verify_pkce(verifier, _s256(verifier), "S256") is True+ assert verify_pkce("wrong", _s256(verifier), "S256") is False+++def test_verify_pkce_rejects_non_s256_methods() -> None:+ # `plain` is intentionally unsupported — only S256 is accepted.+ assert verify_pkce("same", "same", "plain") is False+ assert verify_pkce("same", "same", "weird") is False+ assert verify_pkce("", "", "S256") is False+++def test_verify_pkce_rejects_non_ascii_verifier() -> None:+ assert verify_pkce("vérifier", "x", "S256") is False+++def test_auth_code_store_is_single_use() -> None:+ store = AuthCodeStore()+ code = store.issue(+ secret="s3cret", # noqa: S106+ code_challenge=_s256("v"),+ code_challenge_method="S256",+ redirect_uri="https://claude.ai/api/mcp/auth_callback",+ now=1000.0,+ )+ assert store.consume(code, now=1001.0) is not None+ assert store.consume(code, now=1001.0) is None # already consumed+++def test_auth_code_store_expires() -> None:+ store = AuthCodeStore(ttl_s=60.0)+ code = store.issue(+ secret="s3cret", # noqa: S106+ code_challenge=_s256("v"),+ code_challenge_method="S256",+ redirect_uri="https://claude.ai/api/mcp/auth_callback",+ now=1000.0,+ )+ assert store.consume(code, now=1100.0) is None # past ttl+++def test_exchange_returns_connector_secret_as_access_token() -> None:+ store = AuthCodeStore()+ redirect = "https://claude.ai/api/mcp/auth_callback"+ code = store.issue(+ secret="s3cret", # noqa: S106+ code_challenge=_s256("verifier-1"),+ code_challenge_method="S256",+ redirect_uri=redirect,+ now=1000.0,+ )+ token = exchange_authorization_code(store, code=code, code_verifier="verifier-1", redirect_uri=redirect, now=1001.0)+ assert token == "s3cret" # noqa: S105+++def test_exchange_rejects_bad_verifier() -> None:+ store = AuthCodeStore()+ redirect = "https://claude.ai/api/mcp/auth_callback"+ code = store.issue(+ secret="s3cret", # noqa: S106+ code_challenge=_s256("verifier-1"),+ code_challenge_method="S256",+ redirect_uri=redirect,+ now=1000.0,+ )+ with pytest.raises(OAuthError) as exc:+ exchange_authorization_code(store, code=code, code_verifier="nope", redirect_uri=redirect, now=1001.0)+ assert exc.value.error == "invalid_grant"+++def test_exchange_rejects_redirect_mismatch() -> None:+ store = AuthCodeStore()+ code = store.issue(+ secret="s3cret", # noqa: S106+ code_challenge=_s256("v"),+ code_challenge_method="S256",+ redirect_uri="https://claude.ai/api/mcp/auth_callback",+ now=1000.0,+ )+ with pytest.raises(OAuthError):+ exchange_authorization_code(+ store, code=code, code_verifier="v", redirect_uri="https://evil.example/cb", now=1001.0+ )+++def test_exchange_binds_code_to_client_id() -> None:+ store = AuthCodeStore()+ redirect = "https://claude.ai/api/mcp/auth_callback"+ code = store.issue(+ secret="s3cret", # noqa: S106+ code_challenge=_s256("v"),+ code_challenge_method="S256",+ redirect_uri=redirect,+ client_id="sl-owner",+ now=1000.0,+ )+ # A different public client cannot redeem a code issued to "sl-owner".+ with pytest.raises(OAuthError) as exc:+ exchange_authorization_code(+ store, code=code, code_verifier="v", redirect_uri=redirect, client_id="sl-thief", now=1001.0+ )+ assert exc.value.error == "invalid_grant"+++def test_exchange_accepts_matching_client_id() -> None:+ store = AuthCodeStore()+ redirect = "https://claude.ai/api/mcp/auth_callback"+ code = store.issue(+ secret="s3cret", # noqa: S106+ code_challenge=_s256("v"),+ code_challenge_method="S256",+ redirect_uri=redirect,+ client_id="sl-owner",+ now=1000.0,+ )+ token = exchange_authorization_code(+ store, code=code, code_verifier="v", redirect_uri=redirect, client_id="sl-owner", now=1001.0+ )+ assert token == "s3cret" # noqa: S105+++def test_exchange_rejects_unknown_code() -> None:+ store = AuthCodeStore()+ with pytest.raises(OAuthError) as exc:+ exchange_authorization_code(store, code="missing", code_verifier="v", redirect_uri="", now=1.0)+ assert exc.value.error == "invalid_grant"+++def test_exchange_requires_code_and_verifier() -> None:+ store = AuthCodeStore()+ with pytest.raises(OAuthError) as exc:+ exchange_authorization_code(store, code="", code_verifier="", redirect_uri="", now=1.0)+ assert exc.value.error == "invalid_request"+++def test_metadata_documents_use_origin() -> None:+ origin = "https://mcp.example.com"+ resource = protected_resource_metadata(origin)+ assert resource["resource"] == "https://mcp.example.com/mcp"+ assert resource["authorization_servers"] == [origin]++ server = authorization_server_metadata(origin)+ assert server["issuer"] == origin+ assert server["authorization_endpoint"] == "https://mcp.example.com/authorize"+ assert server["token_endpoint"] == "https://mcp.example.com/token" # noqa: S105+ assert server["registration_endpoint"] == "https://mcp.example.com/register"+ assert server["code_challenge_methods_supported"] == ["S256"]+++def _client(cfg: MCPConfig) -> TestClient:+ app = Starlette(routes=build_oauth_routes(cfg))+ return TestClient(app, base_url="https://mcp.example.com")+++def _authorize_params(verifier: str) -> dict[str, str]:+ return {+ "response_type": "code",+ "client_id": "sl-test",+ "redirect_uri": _REDIRECT,+ "state": "st-1",+ "code_challenge": _s256(verifier),+ "code_challenge_method": "S256",+ "scope": "mcp",+ }+++def _obtain_code(client: TestClient, verifier: str) -> str:+ params = _authorize_params(verifier)+ redirect = client.post("/authorize", data={**params, "connector_secret": "s3cret"}, follow_redirects=False)+ assert redirect.status_code == 302+ return parse_qs(urlparse(redirect.headers["location"]).query)["code"][0]+++def test_metadata_endpoints_use_request_origin() -> None:+ client = _client(_cfg())+ resource = client.get("/.well-known/oauth-protected-resource").json()+ assert resource["resource"] == "https://mcp.example.com/mcp"+ server = client.get("/.well-known/oauth-authorization-server").json()+ assert server["issuer"] == "https://mcp.example.com"+++def test_dynamic_client_registration_returns_client_id() -> None:+ client = _client(_cfg())+ resp = client.post("/register", json={"redirect_uris": [_REDIRECT]})+ assert resp.status_code == 201+ body = resp.json()+ assert body["client_id"].startswith("sl-")+ assert body["token_endpoint_auth_method"] == "none" # noqa: S105+++def test_authorize_token_roundtrip_returns_connector_secret() -> None:+ client = _client(_cfg())+ verifier = "verifier-roundtrip"+ params = _authorize_params(verifier)++ form_page = client.get("/authorize", params=params)+ assert form_page.status_code == 200+ assert 'name="connector_secret"' in form_page.text++ redirect = client.post("/authorize", data={**params, "connector_secret": "s3cret"}, follow_redirects=False)+ assert redirect.status_code == 302+ location = urlparse(redirect.headers["location"])+ assert f"{location.scheme}://{location.netloc}{location.path}" == _REDIRECT+ query = parse_qs(location.query)+ assert query["state"] == ["st-1"]+ code = query["code"][0]++ token = client.post(+ "/token",+ data={+ "grant_type": "authorization_code",+ "code": code,+ "code_verifier": verifier,+ "redirect_uri": _REDIRECT,+ "client_id": "sl-test",+ },+ )+ assert token.status_code == 200+ assert token.headers["cache-control"] == "no-store"+ body = token.json()+ assert body == {"access_token": "s3cret", "token_type": "Bearer", "scope": "mcp"}+++def test_authorize_rejects_invalid_connector_secret() -> None:+ client = _client(_cfg())+ params = _authorize_params("verifier-bad")+ resp = client.post("/authorize", data={**params, "connector_secret": "wrong"}, follow_redirects=False)+ assert resp.status_code == 401+ assert "Invalid connector secret" in resp.text+++def test_authorize_rejects_unlisted_redirect_uri() -> None:+ client = _client(_cfg())+ params = {**_authorize_params("v"), "redirect_uri": "https://evil.example/cb"}+ resp = client.get("/authorize", params=params)+ assert resp.status_code == 400+++def test_authorize_rejects_plain_pkce_method() -> None:+ client = _client(_cfg())+ params = {**_authorize_params("v"), "code_challenge_method": "plain"}+ assert client.get("/authorize", params=params).status_code == 400+++def test_authorize_post_requires_code_challenge() -> None:+ # A direct POST cannot skip the PKCE invariant the GET handler enforces.+ client = _client(_cfg())+ params = _authorize_params("v")+ params.pop("code_challenge")+ resp = client.post("/authorize", data={**params, "connector_secret": "s3cret"}, follow_redirects=False)+ assert resp.status_code == 400+++def test_token_rejects_bad_pkce_over_http() -> None:+ client = _client(_cfg())+ code = _obtain_code(client, "verifier-good")+ resp = client.post(+ "/token",+ data={+ "grant_type": "authorization_code",+ "code": code,+ "code_verifier": "verifier-wrong",+ "redirect_uri": _REDIRECT,+ "client_id": "sl-test",+ },+ )+ assert resp.status_code == 400+ assert resp.json()["error"] == "invalid_grant"+++def test_authorization_code_is_single_use_over_http() -> None:+ client = _client(_cfg())+ verifier = "verifier-reuse"+ body = {+ "grant_type": "authorization_code",+ "code": _obtain_code(client, verifier),+ "code_verifier": verifier,+ "redirect_uri": _REDIRECT,+ "client_id": "sl-test",+ }+ assert client.post("/token", data=body).status_code == 200+ replay = client.post("/token", data=body)+ assert replay.status_code == 400+ assert replay.json()["error"] == "invalid_grant"+++def test_token_rejects_client_id_mismatch_over_http() -> None:+ # A code issued to the authorize-time client_id cannot be redeemed by another.+ client = _client(_cfg())+ verifier = "verifier-bind"+ resp = client.post(+ "/token",+ data={+ "grant_type": "authorization_code",+ "code": _obtain_code(client, verifier),+ "code_verifier": verifier,+ "redirect_uri": _REDIRECT,+ "client_id": "sl-evil",+ },+ )+ assert resp.status_code == 400+ assert resp.json()["error"] == "invalid_grant"+++def test_protected_resource_metadata_path_suffixed() -> None:+ # RFC 9728 path-suffixed variant resolves the same metadata.+ client = _client(_cfg())+ resp = client.get("/.well-known/oauth-protected-resource/mcp")+ assert resp.status_code == 200+ assert resp.json()["resource"] == "https://mcp.example.com/mcp"+++def test_token_rejects_unsupported_grant_type() -> None:+ client = _client(_cfg())+ resp = client.post("/token", data={"grant_type": "client_credentials"})+ assert resp.status_code == 400+ assert resp.json()["error"] == "unsupported_grant_type"diff --git a/packages/sie_mcp/tests/test_ocr_routing.py b/packages/sie_mcp/tests/test_ocr_routing.pynew file mode 100644index 000000000..50accf8b2--- /dev/null+++ b/packages/sie_mcp/tests/test_ocr_routing.py@@ -0,0 +1,329 @@+import io+from collections.abc import Callable+from typing import Any++import pytest+from PIL import Image+from sie_mcp import ocr_routing+from sie_mcp.ocr_routing import DocsToMarkdownError+from sie_sdk import SIEError+++class _RoutingFakeClient:+ """Distinguishes Docling (dict item) from VL-OCR (list of items) calls.++ Docling calls return ``{"data": <docling_payload>}``; VL-OCR batch calls return+ a ``list[ExtractResult]`` with one ``entities`` list per page item (in order).+ Set ``vl_error`` to make the VL-OCR batch call raise (simulating a cluster fault).+ """++ def __init__(+ self,+ *,+ docling: Any = None,+ vl_pages: list[list[dict[str, Any]]] | None = None,+ vl_error: Exception | None = None,+ ) -> None:+ self._docling = docling+ self._vl_pages = vl_pages or []+ self._vl_error = vl_error+ self.calls: list[dict[str, Any]] = []++ async def extract(self, model: str, items: Any, **kwargs: Any) -> Any:+ self.calls.append({"model": model, "items": items, **kwargs})+ if isinstance(items, list):+ if self._vl_error is not None:+ raise self._vl_error+ return [{"entities": self._vl_pages[i]} for i in range(len(items))]+ return {"data": self._docling}+++def _page(text: str) -> list[dict[str, Any]]:+ return [{"text": text, "label": "mineru_text", "score": 1.0}]+++def _fake_render(n_pages: int) -> Callable[..., list[str]]:+ """An injectable renderer that returns ``n_pages`` opaque page sentinels."""++ def _render(_data: bytes, *, scale: float = 2.0) -> list[str]:+ return [f"page-image-{i}" for i in range(n_pages)]++ return _render+++# --- entities_to_markdown ---------------------------------------------------+++def test_entities_to_markdown_single_entity() -> None:+ result = {"entities": _page("# Heading\n\nbody")}+ assert ocr_routing.entities_to_markdown(result) == "# Heading\n\nbody"+++def test_entities_to_markdown_concatenates_multiple_entities() -> None:+ result = {+ "entities": [+ {"text": "table md", "label": "mineru_table", "score": 1.0},+ {"text": "para md", "label": "mineru_text", "score": 1.0},+ ]+ }+ assert ocr_routing.entities_to_markdown(result) == "table md\n\npara md"+++def test_entities_to_markdown_skips_blank_and_handles_missing() -> None:+ assert ocr_routing.entities_to_markdown({"entities": [{"text": " ", "label": "x"}]}) == ""+ assert ocr_routing.entities_to_markdown({"entities": []}) == ""+ assert ocr_routing.entities_to_markdown({}) == ""+ assert ocr_routing.entities_to_markdown("not a dict") == ""+++# --- renderability detection + rendering ------------------------------------+++def test_is_renderable_by_magic_bytes(png_bytes: bytes, tiff_bytes: bytes) -> None:+ assert ocr_routing.is_renderable(b"%PDF-1.7\n...") is True+ assert ocr_routing.is_renderable(png_bytes) is True+ assert ocr_routing.is_renderable(b"\xff\xd8\xff\xe0jpeg") is True+ assert ocr_routing.is_renderable(tiff_bytes) is True # scanned-doc TIFF+ assert ocr_routing.is_renderable(b"GIF89a....") is True+ assert ocr_routing.is_renderable(b"RIFF\x00\x00\x00\x00WEBPVP8 ") is True+ assert ocr_routing.is_renderable(b"PK\x03\x04 docx/zip") is False+ assert ocr_routing.is_renderable(b"") is False+++def test_render_tiff_yields_single_image(tiff_bytes: bytes) -> None:+ images = ocr_routing.render_to_images(tiff_bytes)+ assert len(images) == 1+ assert images[0].mode == "RGB"+++def test_render_caps_page_count(make_pdf: Callable[[int], bytes], monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(ocr_routing, "_MAX_VLOCR_PAGES", 2)+ with pytest.raises(DocsToMarkdownError, match="capped at 2"):+ ocr_routing.render_to_images(make_pdf(3))+++def test_render_wraps_image_open_failure() -> None:+ # Passes the BMP magic-byte gate but is not a decodable image.+ with pytest.raises(DocsToMarkdownError):+ ocr_routing.render_to_images(b"BMnot-a-real-bitmap")+++def test_render_pdf_yields_one_rgb_image_per_page(make_pdf: Callable[[int], bytes]) -> None:+ images = ocr_routing.render_to_images(make_pdf(3))+ assert len(images) == 3+ assert all(isinstance(img, Image.Image) and img.mode == "RGB" for img in images)+++def test_render_image_yields_single_image(png_bytes: bytes) -> None:+ images = ocr_routing.render_to_images(png_bytes)+ assert len(images) == 1+ assert images[0].mode == "RGB"+++def test_render_rejects_non_renderable_format() -> None:+ with pytest.raises(DocsToMarkdownError):+ ocr_routing.render_to_images(b"PK\x03\x04 not a pdf")+++def test_render_raises_on_corrupt_pdf() -> None:+ with pytest.raises(DocsToMarkdownError):+ ocr_routing.render_to_images(b"%PDF-garbage-not-a-real-pdf")+++# --- route_to_markdown: explicit engines ------------------------------------+++async def _route(client: _RoutingFakeClient, **kwargs: Any) -> ocr_routing.RouteResult:+ defaults: dict[str, Any] = {+ "data": b"%PDF-fake",+ "fmt": "pdf",+ "ocr": False,+ "engine": "auto",+ "docling_model": "docling",+ "vlocr_model": "mineru",+ "gpu": None,+ }+ defaults.update(kwargs)+ return await ocr_routing.route_to_markdown(client, **defaults)+++async def test_engine_vl_ocr_stitches_pages_in_order() -> None:+ client = _RoutingFakeClient(vl_pages=[_page("PAGE ONE"), _page("PAGE TWO"), _page("PAGE THREE")])++ result = await _route(client, engine="vl-ocr", render=_fake_render(3))++ assert result.engine == "vl-ocr"+ assert result.pages == 3+ assert result.markdown == "PAGE ONE\n\nPAGE TWO\n\nPAGE THREE"+ # Single batched VL-OCR call, one image item per page, routed to the VL-OCR model.+ assert len(client.calls) == 1+ assert client.calls[0]["model"] == "mineru"+ assert len(client.calls[0]["items"]) == 3+++async def test_engine_docling_never_falls_back_even_when_empty() -> None:+ client = _RoutingFakeClient(docling={"markdown": ""}, vl_pages=[_page("recovered")])++ result = await _route(client, engine="docling", render=_fake_render(1))++ assert result.engine == "docling"+ assert result.markdown == ""+ assert len(client.calls) == 1 # no VL-OCR call+++async def test_invalid_engine_raises() -> None:+ client = _RoutingFakeClient(docling={"markdown": "x"})+ with pytest.raises(DocsToMarkdownError):+ await _route(client, engine="nope")+++# --- route_to_markdown: auto routing ----------------------------------------+++async def test_auto_keeps_docling_for_born_digital() -> None:+ client = _RoutingFakeClient(+ docling={"markdown": "# Real digital page\n\nlots of extracted text", "document": {"pages": {"1": {}}}},+ vl_pages=[_page("should not be used")],+ )++ result = await _route(client, engine="auto", render=_fake_render(1))++ assert result.engine == "docling"+ assert result.markdown.startswith("# Real digital page")+ assert len(client.calls) == 1 # Docling only; no fallback+++async def test_auto_falls_back_to_vl_ocr_for_scanned_pdf() -> None:+ client = _RoutingFakeClient(docling={"markdown": " "}, vl_pages=[_page("OCR p1"), _page("OCR p2")])++ result = await _route(client, engine="auto", render=_fake_render(2))++ assert result.engine == "vl-ocr"+ assert result.markdown == "OCR p1\n\nOCR p2"+ assert result.pages == 2+ assert len(client.calls) == 2 # Docling first, then VL-OCR+++async def test_auto_falls_back_when_docling_errors() -> None:+ client = _RoutingFakeClient(docling={"error": "no text layer"}, vl_pages=[_page("OCR recovered")])++ result = await _route(client, engine="auto", render=_fake_render(1))++ assert result.engine == "vl-ocr"+ assert result.markdown == "OCR recovered"+++async def test_auto_no_fallback_for_non_renderable_format() -> None:+ # A near-empty docx (zip magic) is not rasterizable — Docling result stands.+ client = _RoutingFakeClient(docling={"markdown": ""}, vl_pages=[_page("unused")])++ result = await _route(client, data=b"PK\x03\x04docx", fmt="docx", engine="auto", render=_fake_render(1))++ assert result.engine == "docling"+ assert result.markdown == ""+ assert len(client.calls) == 1+++async def test_auto_keeps_docling_when_vl_ocr_recovers_nothing() -> None:+ # Docling near-empty, but VL-OCR also yields nothing → don't discard Docling.+ client = _RoutingFakeClient(docling={"markdown": "tiny"}, vl_pages=[[]])++ result = await _route(client, engine="auto", render=_fake_render(1))++ assert result.engine == "docling"+ assert result.markdown == "tiny"+++async def test_auto_keeps_docling_when_vl_ocr_raises_sdk_error() -> None:+ # Docling is text-poor (would normally fall back), but the cluster VL-OCR call+ # fails with an SDK/server error. The usable Docling markdown must still survive.+ client = _RoutingFakeClient(docling={"markdown": "tiny"}, vl_error=SIEError("cluster unavailable"))++ result = await _route(client, engine="auto", render=_fake_render(1))++ assert result.engine == "docling"+ assert result.markdown == "tiny"+ assert len(client.calls) == 2 # Docling, then the attempted VL-OCR fallback+++async def test_auto_propagates_docling_error_when_not_renderable() -> None:+ client = _RoutingFakeClient(docling={"error": "unsupported format"})++ with pytest.raises(DocsToMarkdownError):+ await _route(client, data=b"PK\x03\x04docx", fmt="docx", engine="auto")+++# --- route_to_markdown: ocr flag is engine-scoped ---------------------------+++async def test_auto_ignores_ocr_flag_so_scanned_pdf_falls_back() -> None:+ # engine=auto + ocr=True must NOT run Docling's built-in OCR: doing so returns+ # garbled, non-empty text that masks the scan from the near-empty fallback. With+ # OCR forced off the scan lands empty and falls back to VL-OCR cleanly.+ client = _RoutingFakeClient(docling={"markdown": ""}, vl_pages=[_page("clean OCR")])++ result = await _route(client, engine="auto", ocr=True, render=_fake_render(1))++ assert result.engine == "vl-ocr"+ assert result.markdown == "clean OCR"+ # The Docling front-door pass ran with built-in OCR disabled (no options).+ assert client.calls[0]["options"] is None+++async def test_docling_engine_honors_ocr_flag() -> None:+ # When Docling is pinned, the caller's ocr flag enables its built-in OCR.+ client = _RoutingFakeClient(docling={"markdown": "scanned text via docling ocr"})++ result = await _route(client, engine="docling", ocr=True, render=_fake_render(1))++ assert result.engine == "docling"+ assert client.calls[0]["options"] == {"ocr": True}+++# --- rendered-pixel budget --------------------------------------------------+++def test_clamp_scale_reduces_oversized_page() -> None:+ # A 5000x5000 pt page at scale 2.0 → 1e8 px, far above the budget; clamp it down.+ clamped = ocr_routing._clamp_scale(5000, 5000, 2.0)+ assert clamped < 2.0+ assert (5000 * clamped) * (5000 * clamped) <= ocr_routing._MAX_PAGE_PIXELS + 1+++def test_clamp_scale_keeps_small_page_unchanged() -> None:+ assert ocr_routing._clamp_scale(200, 300, 2.0) == 2.0+++def test_downscale_to_budget_shrinks_large_image(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(ocr_routing, "_MAX_PAGE_PIXELS", 1024)+ out = ocr_routing._downscale_to_budget(Image.new("RGB", (256, 256)))+ assert out.width * out.height <= 1024+++def test_downscale_to_budget_leaves_small_image(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(ocr_routing, "_MAX_PAGE_PIXELS", 1024)+ out = ocr_routing._downscale_to_budget(Image.new("RGB", (16, 16)))+ assert out.size == (16, 16)+++def test_render_downscales_oversized_image(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(ocr_routing, "_MAX_PAGE_PIXELS", 1024)+ buf = io.BytesIO()+ Image.new("RGB", (256, 256), "white").save(buf, format="PNG") # 65536 px ≫ 1024+ images = ocr_routing.render_to_images(buf.getvalue())+ assert len(images) == 1+ assert images[0].width * images[0].height <= 1024+++def test_render_caps_total_pixels(make_pdf: Callable[[int], bytes], monkeypatch: pytest.MonkeyPatch) -> None:+ # Each 200x300pt page renders to 400x600 = 240k px; two pages exceed a 300k cap,+ # so the total-budget guard fails loudly on the second page (no silent truncation).+ monkeypatch.setattr(ocr_routing, "_MAX_TOTAL_PIXELS", 300_000)+ with pytest.raises(DocsToMarkdownError, match="VL-OCR budget"):+ ocr_routing.render_to_images(make_pdf(2))+++def test_render_allows_total_pixels_within_budget(make_pdf: Callable[[int], bytes]) -> None:+ # A 3-page doc (~720k px) stays well under the default budget and renders fully.+ images = ocr_routing.render_to_images(make_pdf(3))+ assert len(images) == 3diff --git a/packages/sie_mcp/tests/test_qa.py b/packages/sie_mcp/tests/test_qa.pynew file mode 100644index 000000000..d09fc3149--- /dev/null+++ b/packages/sie_mcp/tests/test_qa.py@@ -0,0 +1,325 @@+from typing import Any++import pytest+from sie_mcp import qa+from sie_mcp.qa import AnswerQuestionsError++# A tiny keyword vocabulary lets the fake produce deterministic embeddings:+# encode() returns per-keyword counts, so cosine / dot-product retrieval is+# meaningful without a real cluster.+_VOCAB = ("alpha", "bravo", "charlie", "delta", "echo")++_PARAMS: dict[str, Any] = {+ "encode_model": "enc",+ "rerank_model": "rr",+ "generate_model": "gen",+ "top_k": 1,+ "rerank_candidates": 20,+ "chunk_chars": 1000,+ "chunk_overlap_chars": 100,+ "max_tokens": 64,+ "max_document_chars": 1_000_000,+ "max_questions": 50,+ "max_chunks": 1000,+}+++def _embed(text: str) -> list[float]:+ lowered = text.lower()+ return [float(lowered.count(word)) for word in _VOCAB]+++class _FakeQAClient:+ """Keyword-embedding fake: encode → counts, score → dot product, chat → canned."""++ def __init__(self, answer: str = "grounded answer") -> None:+ self.answer = answer+ self.encode_calls: list[dict[str, Any]] = []+ self.score_calls: list[dict[str, Any]] = []+ self.chat_calls: list[dict[str, Any]] = []++ async def encode(self, model: str, items: Any, **kwargs: Any) -> Any:+ self.encode_calls.append({"model": model, "items": items, **kwargs})+ single = isinstance(items, dict)+ item_list = [items] if single else items+ results = [{"id": item.get("id"), "dense": _embed(item["text"])} for item in item_list]+ return results[0] if single else results++ async def score(self, model: str, query: Any, items: list[Any], **kwargs: Any) -> Any:+ self.score_calls.append({"model": model, "query": query, "items": items, **kwargs})+ q = _embed(query["text"])+ scored = sorted(+ ((item["id"], sum(a * b for a, b in zip(_embed(item["text"]), q, strict=False))) for item in items),+ key=lambda pair: pair[1],+ reverse=True,+ )+ return {+ "model": model,+ "scores": [{"item_id": cid, "score": s, "rank": r} for r, (cid, s) in enumerate(scored)],+ }++ async def chat_completions(self, model: str, messages: list[Any], **kwargs: Any) -> Any:+ self.chat_calls.append({"model": model, "messages": messages, **kwargs})+ return {"choices": [{"message": {"role": "assistant", "content": self.answer}}]}+++# Three single-chunk documents (each shorter than the window), one keyword apiece.+_DOCS = [+ "Alpha report: the alpha subsystem is green.",+ "Bravo report: the bravo subsystem is amber.",+ "Charlie report: the charlie subsystem is red.",+]+++async def test_returns_grounded_answer_and_passages() -> None:+ client = _FakeQAClient(answer="The bravo subsystem is amber.")++ result = await qa.answer_questions(client, documents=_DOCS, questions=["What is the status of bravo?"], **_PARAMS)++ answers = result["answers"]+ assert len(answers) == 1+ answer = answers[0]+ assert answer["question"] == "What is the status of bravo?"+ assert answer["answer"] == "The bravo subsystem is amber."+ # The selected passage is the bravo document — retrieval grounded the answer.+ assert [p["text"] for p in answer["passages"]] == [_DOCS[1]]+ passage = answer["passages"][0]+ assert passage["doc_index"] == 1+ # start points back into the source document (single-chunk doc → offset 0).+ assert passage["start"] == 0+ assert _DOCS[passage["doc_index"]][passage["start"] :].startswith(passage["text"])+++async def test_passages_are_substrings_of_the_documents() -> None:+ client = _FakeQAClient()++ result = await qa.answer_questions(client, documents=_DOCS, questions=["alpha?"], **_PARAMS)++ for passage in result["answers"][0]["passages"]:+ assert passage["text"] in _DOCS[passage["doc_index"]]+++async def test_passes_configured_models_and_query_flags() -> None:+ client = _FakeQAClient()++ await qa.answer_questions(client, documents=_DOCS, questions=["charlie?"], **_PARAMS)++ # Chunks are encoded once as documents; the question is encoded as a query.+ chunk_encode = client.encode_calls[0]+ assert chunk_encode["model"] == "enc"+ assert chunk_encode["is_query"] is False+ assert isinstance(chunk_encode["items"], list)+ question_encode = client.encode_calls[1]+ assert question_encode["model"] == "enc"+ assert question_encode["is_query"] is True+ # Rerank and generation route to their configured models.+ assert client.score_calls[0]["model"] == "rr"+ assert client.chat_calls[0]["model"] == "gen"+ assert client.chat_calls[0]["temperature"] == 0.0+ assert client.chat_calls[0]["max_completion_tokens"] == _PARAMS["max_tokens"]+++async def test_generator_is_fed_only_the_selected_passages() -> None:+ client = _FakeQAClient()++ await qa.answer_questions(client, documents=_DOCS, questions=["bravo?"], **_PARAMS)++ messages = client.chat_calls[0]["messages"]+ assert messages[0]["role"] == "system"+ user_content = messages[1]["content"]+ # The grounding passage is in the prompt; the unrelated documents are not.+ assert _DOCS[1] in user_content+ assert _DOCS[0] not in user_content+++async def test_shortlist_limits_candidates_sent_to_reranker() -> None:+ docs = [+ "Alpha note: alpha alpha.",+ "Bravo note: bravo bravo.",+ "Charlie note: charlie charlie.",+ "Delta note: delta delta.",+ "Echo note: echo echo.",+ ]+ client = _FakeQAClient()++ await qa.answer_questions(+ client,+ documents=docs,+ questions=["bravo and charlie"],+ **{**_PARAMS, "rerank_candidates": 2, "top_k": 2},+ )++ reranked = client.score_calls[0]["items"]+ # Only the two dense-closest chunks (bravo, charlie) reach the reranker.+ assert len(reranked) == 2+ assert {item["id"] for item in reranked} == {"d1-c0", "d2-c0"}+++async def test_works_on_document_larger_than_one_window() -> None:+ big_doc = "Bravo status update. " * 400 # ~8000 chars, far larger than the window.+ client = _FakeQAClient()++ result = await qa.answer_questions(+ client,+ documents=[big_doc],+ questions=["bravo?"],+ **{**_PARAMS, "chunk_chars": 200, "chunk_overlap_chars": 20, "top_k": 3},+ )++ # The oversized document chunked into many pieces, encoded in one batch.+ assert len(client.encode_calls[0]["items"]) > 1+ passages = result["answers"][0]["passages"]+ assert passages+ assert all(p["doc_index"] == 0 and p["text"] in big_doc for p in passages)+++async def test_no_state_persisted_between_calls() -> None:+ client = _FakeQAClient()++ await qa.answer_questions(client, documents=_DOCS, questions=["alpha?"], **_PARAMS)+ chunk_encodes_after_first = sum(1 for c in client.encode_calls if c["is_query"] is False)++ await qa.answer_questions(client, documents=_DOCS, questions=["bravo?"], **_PARAMS)+ chunk_encodes_after_second = sum(1 for c in client.encode_calls if c["is_query"] is False)++ # Each call re-encodes its chunks from scratch — no standing index or cache.+ assert chunk_encodes_after_first == 1+ assert chunk_encodes_after_second == 2+++async def test_rejects_empty_documents() -> None:+ client = _FakeQAClient()++ with pytest.raises(AnswerQuestionsError):+ await qa.answer_questions(client, documents=["", " "], questions=["alpha?"], **_PARAMS)+++async def test_rejects_empty_questions() -> None:+ client = _FakeQAClient()++ with pytest.raises(AnswerQuestionsError):+ await qa.answer_questions(client, documents=_DOCS, questions=[" "], **_PARAMS)+++async def test_rejects_documents_over_char_limit() -> None:+ # The corpus is bounded before any chunking/encoding, so the client is never called.+ client = _FakeQAClient()++ with pytest.raises(AnswerQuestionsError, match="character limit"):+ await qa.answer_questions(+ client, documents=_DOCS, questions=["alpha?"], **{**_PARAMS, "max_document_chars": 10}+ )++ assert client.encode_calls == []+++async def test_rejects_too_many_questions() -> None:+ client = _FakeQAClient()++ with pytest.raises(AnswerQuestionsError, match="number of questions"):+ await qa.answer_questions(+ client, documents=_DOCS, questions=["alpha?", "bravo?"], **{**_PARAMS, "max_questions": 1}+ )++ assert client.encode_calls == []+++async def test_rejects_too_many_chunks() -> None:+ # _DOCS yields three chunks (one per doc); a max of one rejects before encoding.+ client = _FakeQAClient()++ with pytest.raises(AnswerQuestionsError, match="exceeds the limit"):+ await qa.answer_questions(client, documents=_DOCS, questions=["alpha?"], **{**_PARAMS, "max_chunks": 1})++ assert client.encode_calls == []+++ "bad",+ [+ {"top_k": 0},+ {"rerank_candidates": 0},+ {"chunk_chars": 0},+ {"max_tokens": 0},+ {"max_document_chars": 0},+ {"max_questions": 0},+ {"max_chunks": 0},+ {"chunk_overlap_chars": 1000}, # overlap == chunk_chars (not < it)+ ],+)+async def test_rejects_invalid_knobs(bad: dict[str, Any]) -> None:+ # Invalid retrieval knobs raise the job's own error before any chunking/encoding,+ # rather than a raw ValueError from chunk_documents deeper in the pipeline.+ client = _FakeQAClient()++ with pytest.raises(AnswerQuestionsError):+ await qa.answer_questions(client, documents=_DOCS, questions=["alpha?"], **{**_PARAMS, **bad})++ assert client.encode_calls == []+++async def test_raises_when_reranker_returns_no_scores() -> None:+ class _NoScores(_FakeQAClient):+ async def score(self, model: str, query: Any, items: list[Any], **kwargs: Any) -> Any:+ return {"model": model, "scores": []}++ with pytest.raises(AnswerQuestionsError, match="no scores"):+ await qa.answer_questions(_NoScores(), documents=_DOCS, questions=["alpha?"], **_PARAMS)+++async def test_doc_index_points_to_original_documents_when_some_are_empty() -> None:+ # A leading empty document must not shift the surviving document's doc_index:+ # the bravo doc stays at its caller-supplied index 2.+ docs = ["", " ", "Bravo report: the bravo subsystem is amber."]+ client = _FakeQAClient()++ result = await qa.answer_questions(client, documents=docs, questions=["bravo?"], **_PARAMS)++ passage = result["answers"][0]["passages"][0]+ assert passage["doc_index"] == 2+ assert passage["text"] == docs[2]+++async def test_falls_back_to_dense_when_rerank_ids_unmatched() -> None:+ # Reranker returns scores whose item_ids don't map to any chunk; the job must+ # still answer, grounded in the dense-shortlisted top passages.+ class _ForeignIds(_FakeQAClient):+ async def score(self, model: str, query: Any, items: list[Any], **kwargs: Any) -> Any:+ self.score_calls.append({"model": model, "query": query, "items": items})+ return {"model": model, "scores": [{"item_id": "nonexistent", "score": 9.0, "rank": 0}]}++ client = _ForeignIds()+ result = await qa.answer_questions(client, documents=_DOCS, questions=["bravo?"], **_PARAMS)++ passages = result["answers"][0]["passages"]+ assert passages # did not fail the question+ assert passages[0]["text"] == _DOCS[1] # dense retrieval still surfaced bravo+++async def test_dense_floats_accepts_numpy_array_from_real_encode() -> None:+ # The real cluster returns dense as a numpy array, not a list; pin that.+ np = pytest.importorskip("numpy")++ floats = qa._dense_floats({"dense": np.asarray([1.0, 2.0, 3.0], dtype=np.float32)})++ assert floats == [1.0, 2.0, 3.0]+++async def test_raises_when_encode_has_no_dense_embedding() -> None:+ class _NoDense(_FakeQAClient):+ async def encode(self, model: str, items: Any, **kwargs: Any) -> Any:+ single = isinstance(items, dict)+ result = {"id": "x"} # no "dense" key+ return result if single else [result]++ with pytest.raises(AnswerQuestionsError, match="no dense embedding"):+ await qa.answer_questions(_NoDense(), documents=_DOCS, questions=["alpha?"], **_PARAMS)+++async def test_raises_when_generation_returns_no_content() -> None:+ class _NoContent(_FakeQAClient):+ async def chat_completions(self, model: str, messages: list[Any], **kwargs: Any) -> Any:+ return {"choices": []}++ with pytest.raises(AnswerQuestionsError, match="no choices"):+ await qa.answer_questions(_NoContent(), documents=_DOCS, questions=["alpha?"], **_PARAMS)diff --git a/packages/sie_mcp/tests/test_server.py b/packages/sie_mcp/tests/test_server.pynew file mode 100644index 000000000..2795a5d50--- /dev/null+++ b/packages/sie_mcp/tests/test_server.py@@ -0,0 +1,72 @@+from urllib.parse import urlparse++import pytest++# sie_mcp.server pulls in FastMCP (`mcp`), which is intentionally outside the public+# dependency closure — skip these in environments (integration/docker) without it.+pytest.importorskip("mcp")++from sie_mcp.config import (+ DEFAULT_MAX_DOCUMENT_BYTES,+ DEFAULT_MAX_IMAGE_BYTES,+ DEFAULT_VLOCR_MODEL,+ MCPConfig,+)+from sie_mcp.server import _transport_security+++def _cfg(**overrides: object) -> MCPConfig:+ base: dict[str, object] = {+ "sie_base_url": "http://localhost:8080",+ "sie_api_key": None,+ "connector_secrets": {},+ "allow_anonymous": False,+ "allowed_hosts": [],+ "max_document_bytes": DEFAULT_MAX_DOCUMENT_BYTES,+ "max_image_bytes": DEFAULT_MAX_IMAGE_BYTES,+ "docling_model": "docling",+ "generate_model": "Qwen/Qwen3.5-4B",+ "max_output_tokens": 4096,+ "vlocr_model": DEFAULT_VLOCR_MODEL,+ "encode_model": "BAAI/bge-m3",+ "rerank_model": "BAAI/bge-reranker-v2-m3",+ "caption_model": "microsoft/Florence-2-base-ft",+ "embed_model": "openai/clip-vit-base-patch32",+ "image_labels": [],+ "image_top_k": 5,+ "gpu": None,+ "timeout_s": 300.0,+ "qa_top_k": 5,+ "qa_rerank_candidates": 20,+ "qa_chunk_chars": 1200,+ "qa_chunk_overlap_chars": 200,+ "qa_max_tokens": 512,+ "qa_max_document_chars": 2_000_000,+ "qa_max_questions": 50,+ "qa_max_chunks": 2000,+ "oauth_enabled": True,+ "public_base_url": None,+ "oauth_redirect_uris": ("https://claude.ai/api/mcp/auth_callback",),+ }+ base.update(overrides)+ return MCPConfig(**base) # type: ignore[arg-type]+++def test_transport_security_disabled_without_allowed_hosts() -> None:+ # No allow-list: FastMCP's localhost-only default would 421 the remote /mcp endpoint,+ # so Host validation is off (the connector-secret auth is the access control).+ settings = _transport_security(_cfg(allowed_hosts=[]))+ assert settings.enable_dns_rebinding_protection is False+++def test_transport_security_scopes_to_allowed_hosts() -> None:+ settings = _transport_security(_cfg(allowed_hosts=["mcp.example.com"]))+ assert settings.enable_dns_rebinding_protection is True+ assert settings.allowed_hosts == ["mcp.example.com"]+ # Compare parsed (scheme, host) pairs rather than substring-matching the origin+ # strings, so the assertion is exact (and not flagged as URL substring checks).+ parsed_origins = {+ (parsed.scheme, parsed.hostname) for parsed in (urlparse(origin) for origin in settings.allowed_origins)+ }+ assert ("https", "mcp.example.com") in parsed_origins+ assert ("http", "mcp.example.com") in parsed_originsdiff --git a/packages/sie_mcp/tests/test_skill_zip.py b/packages/sie_mcp/tests/test_skill_zip.pynew file mode 100644index 000000000..06f30cb67--- /dev/null+++ b/packages/sie_mcp/tests/test_skill_zip.py@@ -0,0 +1,97 @@+import io+import zipfile+from pathlib import Path++import pytest+from sie_mcp.skill_zip import (+ SkillPackagingError,+ build_skill_zip,+ parse_frontmatter,+ skill_name,+)++_SKILL_MD = Path(__file__).resolve().parents[1] / "plugin" / "SKILL.md"++_VALID = """---+name: superlinked-docs+description: >-+ Offload document work to the Superlinked inference cluster: convert documents+ to clean markdown instead of ingesting the file directly.+---++# Body+"""+++def test_parses_folded_description() -> None:+ fields = parse_frontmatter(_VALID)+ assert fields["name"] == "superlinked-docs"+ assert fields["description"].startswith("Offload document work")+ assert "\n" not in fields["description"]+++def test_zip_nests_skill_md_under_name_folder() -> None:+ data = build_skill_zip(_VALID)+ with zipfile.ZipFile(io.BytesIO(data)) as archive:+ names = archive.namelist()+ assert names == ["superlinked-docs/SKILL.md"]+ # SKILL.md must NOT sit at the archive root — claude.ai rejects that layout.+ assert "SKILL.md" not in names+++def test_zip_is_reproducible() -> None:+ assert build_skill_zip(_VALID) == build_skill_zip(_VALID)+++def test_extra_files_are_nested_too() -> None:+ data = build_skill_zip(_VALID, extra={"reference.md": "x"})+ with zipfile.ZipFile(io.BytesIO(data)) as archive:+ assert set(archive.namelist()) == {"superlinked-docs/SKILL.md", "superlinked-docs/reference.md"}+++def test_rejects_uppercase_name() -> None:+ bad = _VALID.replace("name: superlinked-docs", "name: Superlinked-Docs")+ with pytest.raises(SkillPackagingError):+ skill_name(bad)+++def test_rejects_reserved_word_in_name() -> None:+ bad = _VALID.replace("name: superlinked-docs", "name: claude-docs")+ with pytest.raises(SkillPackagingError):+ skill_name(bad)+++def test_rejects_missing_description() -> None:+ bad = "---\nname: superlinked-docs\n---\n\n# Body\n"+ with pytest.raises(SkillPackagingError):+ skill_name(bad)+++def test_rejects_overlong_description() -> None:+ bad = _VALID.replace("to clean markdown instead of ingesting the file directly.", "x" * 1100)+ with pytest.raises(SkillPackagingError):+ skill_name(bad)+++def test_requires_frontmatter() -> None:+ with pytest.raises(SkillPackagingError):+ parse_frontmatter("# no frontmatter here\n")+++def test_strips_trailing_comment_on_inline_name() -> None:+ text = _VALID.replace("name: superlinked-docs", "name: superlinked-docs # prod build")+ assert skill_name(text) == "superlinked-docs"+++def test_preserves_quoted_inline_values() -> None:+ fields = parse_frontmatter('---\nname: "superlinked-docs"\ndescription: "hello there"\n---\n')+ assert fields["name"] == "superlinked-docs"+ assert fields["description"] == "hello there"+++def test_shipped_claude_ai_skill_is_valid_and_packs() -> None:+ text = _SKILL_MD.read_text(encoding="utf-8")+ assert skill_name(text) == "superlinked-docs"+ data = build_skill_zip(text)+ with zipfile.ZipFile(io.BytesIO(data)) as archive:+ assert archive.namelist() == ["superlinked-docs/SKILL.md"]diff --git a/packages/sie_mcp/tests/test_structured.py b/packages/sie_mcp/tests/test_structured.pynew file mode 100644index 000000000..59f1f5ab0--- /dev/null+++ b/packages/sie_mcp/tests/test_structured.py@@ -0,0 +1,380 @@+import json+from typing import Any++import pytest+from sie_mcp import structured+from sie_mcp.structured import StructuredOutputError, validate_output_schema++_MODEL = "Qwen/Qwen3.5-4B"+++class _FakeChatClient:+ """Records chat_completions() calls and returns a canned ChatCompletion dict."""++ def __init__(self, content: str) -> None:+ self._content = content+ self.calls: list[dict[str, Any]] = []++ async def chat_completions(self, model: str, messages: Any, **kwargs: Any) -> Any:+ self.calls.append({"model": model, "messages": messages, **kwargs})+ return {"choices": [{"message": {"role": "assistant", "content": self._content}}]}+++# ── schema-subset validation ────────────────────────────────────────────+++def test_accepts_realistic_extraction_schema() -> None:+ schema = {+ "type": "object",+ "properties": {+ "items": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {"name": {"type": "string"}, "qty": {"type": "integer"}},+ "required": ["name", "qty"],+ },+ },+ "total": {"type": "number"},+ },+ "required": ["items"],+ "additionalProperties": False,+ }+ validate_output_schema(schema) # no raise+++def test_rejects_non_object_schema() -> None:+ with pytest.raises(StructuredOutputError):+ validate_output_schema("nope")+++def test_rejects_dollar_ref() -> None:+ schema = {"type": "object", "properties": {"a": {"$ref": "#/$defs/Foo"}}}+ with pytest.raises(StructuredOutputError, match=r"\$ref"):+ validate_output_schema(schema)+++ "keyword",+ ["$dynamicRef", "if", "then", "else", "unevaluatedProperties", "dependentSchemas"],+)+def test_rejects_each_unsupported_keyword(keyword: str) -> None:+ schema = {"type": "object", keyword: {"x": True}}+ with pytest.raises(StructuredOutputError, match=keyword.replace("$", r"\$")):+ validate_output_schema(schema)+++def test_rejects_too_deep_schema() -> None:+ leaf: Any = {"type": "string"}+ for _ in range(structured._MAX_SCHEMA_DEPTH + 5):+ leaf = {"type": "object", "properties": {"x": leaf}}+ with pytest.raises(StructuredOutputError, match="depth"):+ validate_output_schema(leaf)+++def test_accepts_schema_at_depth_limit() -> None:+ leaf: Any = {"type": "string"}+ # Each "properties" wrap adds one to depth; stay at the limit.+ for _ in range(structured._MAX_SCHEMA_DEPTH):+ leaf = {"type": "object", "properties": {"x": leaf}}+ validate_output_schema(leaf) # no raise+++# ── gateway safety caps (mirror handlers/grammar.rs) ─────────────────────+++def test_rejects_wide_object_schema_over_caps() -> None:+ # Mirrors the review repro: a 20k-property object exceeds the gateway caps+ # (serialized size and/or node count) and must be rejected at the edge.+ schema = {"type": "object", "properties": {f"f{i}": {"type": "string"} for i in range(20_000)}}+ with pytest.raises(StructuredOutputError, match="exceeds limit"):+ validate_output_schema(schema)+++def test_rejects_oversized_serialized_schema() -> None:+ schema = {"type": "object", "properties": {"x": {"type": "string", "description": "a" * (64 * 1024)}}}+ with pytest.raises(StructuredOutputError, match="serialized size"):+ validate_output_schema(schema)+++def test_rejects_too_many_nodes(monkeypatch: pytest.MonkeyPatch) -> None:+ # Node count is shadowed by the byte cap under default JSON serialization, so+ # exercise it directly with a lowered cap to prove the walker counts nodes.+ monkeypatch.setattr(structured, "_MAX_SCHEMA_NODES", 5)+ schema = {"type": "object", "properties": {f"p{i}": {"type": "string"} for i in range(10)}}+ with pytest.raises(StructuredOutputError, match="node count"):+ validate_output_schema(schema)+++# ── extract_structured ──────────────────────────────────────────────────+++async def test_extract_returns_parsed_json_and_call_shape() -> None:+ client = _FakeChatClient(json.dumps({"city": "Lisbon", "country": "Portugal"}))+ schema = {+ "type": "object",+ "properties": {"city": {"type": "string"}, "country": {"type": "string"}},+ "required": ["city", "country"],+ "title": "location",+ }++ data = await structured.extract_structured(+ client, content="I flew to Lisbon, Portugal.", output_schema=schema, model=_MODEL+ )++ assert data == {"city": "Lisbon", "country": "Portugal"}+ call = client.calls[0]+ assert call["model"] == _MODEL+ assert call["temperature"] == 0.0+ rf = call["response_format"]+ assert rf["type"] == "json_schema"+ assert rf["json_schema"]["name"] == "location"+ assert rf["json_schema"]["schema"] is schema+ assert rf["json_schema"]["strict"] is True+ # Content is grounded in the supplied document.+ assert "Lisbon" in call["messages"][-1]["content"]+++async def test_extract_uses_default_schema_name_without_title() -> None:+ client = _FakeChatClient("{}")+ await structured.extract_structured(client, content="x", output_schema={"type": "object"}, model=_MODEL)+ assert client.calls[0]["response_format"]["json_schema"]["name"] == "extraction"+++async def test_extract_includes_instruction() -> None:+ client = _FakeChatClient("{}")+ await structured.extract_structured(+ client,+ content="x",+ output_schema={"type": "object"},+ instruction="Pull out the invoice number.",+ model=_MODEL,+ )+ assert "invoice number" in client.calls[0]["messages"][-1]["content"]+++async def test_extract_validates_schema_before_calling_cluster() -> None:+ client = _FakeChatClient("{}")+ with pytest.raises(StructuredOutputError):+ await structured.extract_structured(+ client,+ content="x",+ output_schema={"type": "object", "properties": {"a": {"$ref": "#/x"}}},+ model=_MODEL,+ )+ assert client.calls == [] # never reached the cluster+++async def test_extract_raises_on_non_json_content() -> None:+ client = _FakeChatClient("not json at all")+ with pytest.raises(StructuredOutputError, match="non-JSON"):+ await structured.extract_structured(client, content="x", output_schema={"type": "object"}, model=_MODEL)+++async def test_extract_raises_on_missing_content() -> None:+ class _Empty:+ async def chat_completions(self, model: str, messages: Any, **kwargs: Any) -> Any:+ return {"choices": []}++ with pytest.raises(StructuredOutputError):+ await structured.extract_structured(_Empty(), content="x", output_schema={"type": "object"}, model=_MODEL)+++ "resp",+ [+ {"choices": [None]}, # malformed: non-dict choice+ {"choices": [{"message": None}]}, # malformed: null message+ {"choices": [{"message": {"content": None}}]}, # malformed: null content+ {"choices": ["oops"]}, # malformed: string choice+ ],+)+async def test_extract_raises_typed_error_on_malformed_response(resp: Any) -> None:+ class _Malformed:+ async def chat_completions(self, model: str, messages: Any, **kwargs: Any) -> Any:+ return resp++ # Must raise the typed error, never a raw AttributeError/TypeError.+ with pytest.raises(StructuredOutputError):+ await structured.extract_structured(_Malformed(), content="x", output_schema={"type": "object"}, model=_MODEL)+++# ── generate_structured ─────────────────────────────────────────────────+++async def test_generate_passes_response_format_through() -> None:+ client = _FakeChatClient("yes")+ rf = {"type": "regex", "regex": "(yes|no)"}++ content = await structured.generate_structured(client, prompt="Is the sky blue?", response_format=rf, model=_MODEL)++ assert content == "yes"+ call = client.calls[0]+ assert call["response_format"] is rf+ assert call["messages"] == [{"role": "user", "content": "Is the sky blue?"}]+++async def test_generate_validates_json_schema_subset() -> None:+ client = _FakeChatClient("{}")+ rf = {+ "type": "json_schema",+ "json_schema": {"name": "x", "schema": {"type": "object", "if": {}}},+ }+ with pytest.raises(StructuredOutputError, match="if"):+ await structured.generate_structured(client, prompt="p", response_format=rf, model=_MODEL)+ assert client.calls == []+++async def test_generate_rejects_ebnf_on_outlines_model() -> None:+ client = _FakeChatClient("x")+ rf = {"type": "grammar", "grammar": 'root ::= "yes" | "no"', "syntax": "ebnf"}+ with pytest.raises(StructuredOutputError, match="EBNF"):+ await structured.generate_structured(client, prompt="p", response_format=rf, model=_MODEL)+ assert client.calls == []+++async def test_generate_allows_grammar_on_non_outlines_model() -> None:+ client = _FakeChatClient("yes")+ rf = {"type": "grammar", "grammar": 'root ::= "yes"', "syntax": "ebnf"}+ # An xgrammar-backed model is not in the Outlines set → passes through.+ content = await structured.generate_structured(client, prompt="p", response_format=rf, model="some/xgrammar-model")+ assert content == "yes"+ assert client.calls[0]["response_format"] is rf+++async def test_generate_rejects_json_schema_missing_schema() -> None:+ client = _FakeChatClient("{}")+ rf = {"type": "json_schema", "json_schema": {"name": "x"}}+ with pytest.raises(StructuredOutputError, match="schema is required"):+ await structured.generate_structured(client, prompt="p", response_format=rf, model=_MODEL)+++async def test_generate_rejects_non_dict_json_schema() -> None:+ # Caller-supplied json_schema that is a string (not an object) must raise a+ # typed error, not a raw AttributeError.+ client = _FakeChatClient("{}")+ rf = {"type": "json_schema", "json_schema": "oops"}+ with pytest.raises(StructuredOutputError, match="schema is required"):+ await structured.generate_structured(client, prompt="p", response_format=rf, model=_MODEL)+ assert client.calls == []+++async def test_generate_rejects_non_object_response_format() -> None:+ client = _FakeChatClient("{}")+ with pytest.raises(StructuredOutputError):+ await structured.generate_structured(+ client,+ prompt="p",+ response_format="json",+ model=_MODEL, # type: ignore[arg-type]+ )+++async def test_generate_rejects_oversized_regex() -> None:+ client = _FakeChatClient("x")+ rf = {"type": "regex", "regex": "a" * (structured._MAX_REGEX_LEN + 1)}+ with pytest.raises(StructuredOutputError, match="regex length"):+ await structured.generate_structured(client, prompt="p", response_format=rf, model=_MODEL)+ assert client.calls == [] # never reached the cluster+++async def test_generate_rejects_oversized_ebnf_on_non_outlines_model() -> None:+ client = _FakeChatClient("x")+ rf = {"type": "grammar", "grammar": "a" * (structured._MAX_EBNF_LEN + 1), "syntax": "ebnf"}+ with pytest.raises(StructuredOutputError, match="EBNF"):+ await structured.generate_structured(client, prompt="p", response_format=rf, model="some/xgrammar-model")+ assert client.calls == []+++# ── gpu + token-budget thread-through ────────────────────────────────────+++async def test_extract_threads_gpu_and_max_tokens() -> None:+ client = _FakeChatClient("{}")+ await structured.extract_structured(+ client,+ content="x",+ output_schema={"type": "object"},+ model=_MODEL,+ gpu="a100-40gb",+ max_completion_tokens=2048,+ )+ call = client.calls[0]+ assert call["gpu"] == "a100-40gb"+ assert call["max_completion_tokens"] == 2048+++async def test_generate_threads_gpu_and_max_tokens() -> None:+ client = _FakeChatClient("yes")+ await structured.generate_structured(+ client,+ prompt="p",+ response_format={"type": "regex", "regex": "(yes|no)"},+ model=_MODEL,+ gpu="a100-40gb",+ max_completion_tokens=128,+ )+ call = client.calls[0]+ assert call["gpu"] == "a100-40gb"+ assert call["max_completion_tokens"] == 128+++# ── post-validation of cluster output (defense in depth) ─────────────────+++async def test_extract_rejects_nonconforming_output() -> None:+ # additionalProperties:False + a leaked extra key (the speculative-decoding+ # failure mode) must be caught post-hoc, not returned as schema-valid.+ client = _FakeChatClient(json.dumps({"city": "Lisbon", "leak": "x"}))+ schema = {+ "type": "object",+ "properties": {"city": {"type": "string"}},+ "required": ["city"],+ "additionalProperties": False,+ }+ with pytest.raises(StructuredOutputError, match="does not conform"):+ await structured.extract_structured(client, content="x", output_schema=schema, model=_MODEL)+++async def test_extract_rejects_output_missing_required_field() -> None:+ client = _FakeChatClient(json.dumps({"city": "Lisbon"}))+ schema = {+ "type": "object",+ "properties": {"city": {"type": "string"}, "country": {"type": "string"}},+ "required": ["city", "country"],+ }+ with pytest.raises(StructuredOutputError, match="does not conform"):+ await structured.extract_structured(client, content="x", output_schema=schema, model=_MODEL)+++async def test_extract_accepts_conforming_output() -> None:+ client = _FakeChatClient(json.dumps({"city": "Lisbon", "country": "Portugal"}))+ schema = {+ "type": "object",+ "properties": {"city": {"type": "string"}, "country": {"type": "string"}},+ "required": ["city", "country"],+ "additionalProperties": False,+ }+ data = await structured.extract_structured(client, content="x", output_schema=schema, model=_MODEL)+ assert data == {"city": "Lisbon", "country": "Portugal"}+++async def test_generate_rejects_nonconforming_json_schema_output() -> None:+ client = _FakeChatClient(json.dumps({"answer": "Paris", "leak": 1}))+ schema = {+ "type": "object",+ "properties": {"answer": {"type": "string"}},+ "required": ["answer"],+ "additionalProperties": False,+ }+ rf = {"type": "json_schema", "json_schema": {"name": "qa", "schema": schema, "strict": True}}+ with pytest.raises(StructuredOutputError, match="does not conform"):+ await structured.generate_structured(client, prompt="p", response_format=rf, model=_MODEL)+++async def test_generate_rejects_truncated_json_schema_output() -> None:+ client = _FakeChatClient('{"answer": "Par') # truncated mid-JSON+ schema = {"type": "object", "properties": {"answer": {"type": "string"}}, "required": ["answer"]}+ rf = {"type": "json_schema", "json_schema": {"name": "qa", "schema": schema, "strict": True}}+ with pytest.raises(StructuredOutputError, match="non-JSON"):+ await structured.generate_structured(client, prompt="p", response_format=rf, model=_MODEL)diff --git a/packages/sie_sdk/pyproject.toml b/packages/sie_sdk/pyproject.tomlindex 3c6419869..7893b2efe 100644--- a/packages/sie_sdk/pyproject.toml+++ b/packages/sie_sdk/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-sdk"-version = "0.6.9"+version = "0.6.10"description = "Search Inference Engine - Python SDK"requires-python = ">=3.12"license = { text = "Apache-2.0" }diff --git a/packages/sie_server/README.md b/packages/sie_server/README.mdindex c7edc2773..37b2ac3c9 100644--- a/packages/sie_server/README.md+++ b/packages/sie_server/README.md@@ -17,6 +17,22 @@ GPU inference server for embeddings, reranking, and entity extraction.pip install sie-server```+`sie-server` ships several model bundles, and a single environment can only hold one+`transformers` version — install the one your bundle needs:++- **Default bundle** (embeddings, reranking, extraction) — verified on `transformers` 4.x:++ ```bash+ pip install sie-server "transformers<5"+ ```++- **OCR-VLM bundle** (LightOnOCR, GLM-OCR) — requires `transformers` 5.x, and is served with `-b transformers5`:++ ```bash+ pip install sie-server "transformers>=5,<6"+ sie-server serve -b transformers5+ ```+## Quick Start```bashdiff --git a/packages/sie_server/models/gliner-community__gliner_large-v2.5.yaml b/packages/sie_server/models/gliner-community__gliner_large-v2.5.yamlindex 37ee53f71..2a5750fb4 100644--- a/packages/sie_server/models/gliner-community__gliner_large-v2.5.yaml+++ b/packages/sie_server/models/gliner-community__gliner_large-v2.5.yaml@@ -16,4 +16,6 @@ profiles:adapter_path: sie_server.adapters.gliner:GLiNERAdapteradapter_options:loadtime: {}- runtime: {}+ runtime:+ # Empirically tuned for SIE CoNLL2003 F1 target 0.6518; GLiNER library default is 0.5.+ threshold: 0.75diff --git a/packages/sie_server/models/gliner-community__gliner_medium-v2.5.yaml b/packages/sie_server/models/gliner-community__gliner_medium-v2.5.yamlindex fdd7d386d..1b75de6c5 100644--- a/packages/sie_server/models/gliner-community__gliner_medium-v2.5.yaml+++ b/packages/sie_server/models/gliner-community__gliner_medium-v2.5.yaml@@ -16,4 +16,6 @@ profiles:adapter_path: sie_server.adapters.gliner:GLiNERAdapteradapter_options:loadtime: {}- runtime: {}+ runtime:+ # Empirically tuned for SIE CoNLL2003 F1 target 0.6598; GLiNER library default is 0.5.+ threshold: 0.55diff --git a/packages/sie_server/models/gliner-community__gliner_small-v2.5.yaml b/packages/sie_server/models/gliner-community__gliner_small-v2.5.yamlindex 055631211..14818ae05 100644--- a/packages/sie_server/models/gliner-community__gliner_small-v2.5.yaml+++ b/packages/sie_server/models/gliner-community__gliner_small-v2.5.yaml@@ -16,4 +16,6 @@ profiles:adapter_path: sie_server.adapters.gliner:GLiNERAdapteradapter_options:loadtime: {}- runtime: {}+ runtime:+ # Empirically tuned for SIE CoNLL2003 F1 target 0.666; GLiNER library default is 0.5.+ threshold: 0.6diff --git a/packages/sie_server/models/microsoft__Florence-2-base-ft.yaml b/packages/sie_server/models/microsoft__Florence-2-base-ft.yamlindex 7c82c0396..4ab8977a5 100644--- a/packages/sie_server/models/microsoft__Florence-2-base-ft.yaml+++ b/packages/sie_server/models/microsoft__Florence-2-base-ft.yaml@@ -18,6 +18,8 @@ profiles:loadtime:trust_remote_code: trueruntime:- task: <OCR_WITH_REGION>+ # Re-tasked to object detection (#1347): Florence-2's flagship capability,+ # measured on COCO. The shared adapter's <OD> branch emits pixel COCO boxes.+ task: <OD>max_new_tokens: 1024num_beams: 1diff --git a/packages/sie_server/models/microsoft__Florence-2-large.yaml b/packages/sie_server/models/microsoft__Florence-2-large.yamlindex c4ddb252e..0a987b2aa 100644--- a/packages/sie_server/models/microsoft__Florence-2-large.yaml+++ b/packages/sie_server/models/microsoft__Florence-2-large.yaml@@ -18,6 +18,8 @@ profiles:loadtime:trust_remote_code: trueruntime:- task: <OCR_WITH_REGION>+ # Re-tasked to object detection (#1347): Florence-2's flagship capability,+ # measured on COCO. The shared adapter's <OD> branch emits pixel COCO boxes.+ task: <OD>max_new_tokens: 1024num_beams: 1diff --git a/packages/sie_server/models/naver-clova-ix__donut-base-finetuned-rvlcdip.yaml b/packages/sie_server/models/naver-clova-ix__donut-base-finetuned-rvlcdip.yamldeleted file mode 100644index 9d77125e2..000000000--- a/packages/sie_server/models/naver-clova-ix__donut-base-finetuned-rvlcdip.yaml+++ /dev/null@@ -1,22 +0,0 @@-sie_id: naver-clova-ix/donut-base-finetuned-rvlcdip-hf_id: naver-clova-ix/donut-base-finetuned-rvlcdip-inputs:- text: false- image: true- audio: false- video: false-tasks:- encode: null- score: null- extract: {}-profiles:- default:- max_batch_tokens: 16384- compute_precision: float16- adapter_path: sie_server.adapters.donut:DonutAdapter- adapter_options:- loadtime: {}- runtime:- task: <s_rvlcdip>- max_new_tokens: 512- num_beams: 1diff --git a/packages/sie_server/openapi.json b/packages/sie_server/openapi.jsonindex fefea8131..0dd256374 100644--- a/packages/sie_server/openapi.json+++ b/packages/sie_server/openapi.json@@ -3,7 +3,7 @@"info": {"title": "SIE Server","description": "Search Inference Engine - GPU inference server for search workloads",- "version": "0.6.9"+ "version": "0.6.10"},"paths": {"/": {diff --git a/packages/sie_server/pyproject.toml b/packages/sie_server/pyproject.tomlindex 94809d981..4e95f7541 100644--- a/packages/sie_server/pyproject.toml+++ b/packages/sie_server/pyproject.toml@@ -1,6 +1,6 @@[project]name = "sie-server"-version = "0.6.9"+version = "0.6.10"description = "Search Inference Engine - GPU inference server for search workloads"requires-python = ">=3.12,<3.13"license = { text = "Apache-2.0" }@@ -16,7 +16,7 @@ dependencies = [# ML / Inference# torch 2.9.x required - flash-attn prebuilt wheels are version-specific"torch>=2.9,<2.10",- "transformers>=4.57,<5",+ "transformers>=4.57,<6","tokenizers>=0.20,<1","sentence-transformers>=5.0,<6","safetensors>=0.4,<1",diff --git a/packages/sie_server/src/sie_server/adapters/florence2/__init__.py b/packages/sie_server/src/sie_server/adapters/florence2/__init__.pyindex 8e4c47d44..0e06b01d8 100644--- a/packages/sie_server/src/sie_server/adapters/florence2/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/florence2/__init__.py@@ -510,18 +510,20 @@ class Florence2Adapter(BaseAdapter):)elif task in (TASK_OD, TASK_DENSE_REGION_CAPTION, TASK_REGION_PROPOSAL):- # Object detection returns bboxes and labels+ # Object detection returns pixel-space [x1, y1, x2, y2] boxes (the+ # processor rescales the model's quantized coords back to image_size).+ # Emit COCO [x, y, w, h] in pixels so the detection harness scores them+ # directly — mirrors the owlv2 adapter's _results_to_objects.bboxes = task_output.get("bboxes", [])labels = task_output.get("labels", [])for bbox, label in zip(bboxes, labels, strict=False):- # Normalize bbox- norm_bbox = self._normalize_bbox(bbox, image_size)+ x1, y1, x2, y2 = bboxobjects.append(DetectedObject(label=label or "object",score=1.0,- bbox=[int(b) for b in norm_bbox], # Convert to int list+ bbox=[int(x1), int(y1), int(x2 - x1), int(y2 - y1)],))@@ -591,25 +593,3 @@ class Florence2Adapter(BaseAdapter):x2 / width,y2 / height,]-- def _normalize_bbox(- self,- bbox: list[float],- image_size: tuple[int, int],- ) -> list[float]:- """Normalize bbox to [0, 1] range.-- Args:- bbox: [x1, y1, x2, y2] in pixel coordinates.- image_size: (width, height) of original image.-- Returns:- Normalized bbox [x1, y1, x2, y2] in range [0, 1].- """- width, height = image_size- return [- bbox[0] / width,- bbox[1] / height,- bbox[2] / width,- bbox[3] / height,- ]diff --git a/packages/sie_server/src/sie_server/adapters/qwen3_vl_embedding/__init__.py b/packages/sie_server/src/sie_server/adapters/qwen3_vl_embedding/__init__.pyindex 52bbe1ec3..f33e2c45d 100644--- a/packages/sie_server/src/sie_server/adapters/qwen3_vl_embedding/__init__.py+++ b/packages/sie_server/src/sie_server/adapters/qwen3_vl_embedding/__init__.py@@ -2,6 +2,7 @@ from __future__ import annotationsimport ioimport logging+import unicodedatafrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, ClassVar@@ -32,6 +33,27 @@ _DEFAULT_INSTRUCTION = "Represent the user's input."_SUPPORTED_POOLING = ("last", "mean")+def _normalize_instruction(instruction: str) -> str:+ """Match the official Qwen3-VL-Embedding ``format_model_input`` instruction shaping.++ The reference recipe strips the instruction and appends a period unless it+ already ends in a Unicode punctuation character::++ instruction = instruction.strip()+ if not unicodedata.category(instruction[-1]).startswith("P"):+ instruction += "."++ SIE previously passed the resolved instruction verbatim, so MTEB query+ instructions without trailing punctuation (e.g. FiQA's "...best answer the+ question") differed from the official prompt by a missing period token on+ every query.+ """+ inst = instruction.strip()+ if inst and not unicodedata.category(inst[-1]).startswith("P"):+ inst += "."+ return inst++def _build_conversation(*,text: str | None = None,@@ -226,7 +248,9 @@ class Qwen3VLEmbeddingAdapter(BaseAdapter):assert self._model is not Noneassert self._processor is not None- inst = instruction or self._default_instruction+ # Blank/whitespace-only/None all coalesce to the default; a meaningful+ # instruction is normalized. Avoids forwarding an empty system turn.+ inst = _normalize_instruction(instruction or "") or _normalize_instruction(self._default_instruction)embeddings_list: list[np.ndarray] = []for item in items:@@ -323,13 +347,17 @@ class Qwen3VLEmbeddingAdapter(BaseAdapter):inputs = {k: v.to(self._device) for k, v in inputs.items()}with torch.inference_mode():- outputs = self._model(- **inputs,- output_hidden_states=True,- return_dict=True,- )-- last_hidden = outputs.hidden_states[-1] # (1, seq_len, hidden_dim)+ # Pool the POST-final-RMSNorm tensor, matching the official+ # Qwen3VLForEmbedding recipe (method_output_name='last_hidden_state').+ # Calling the CausalLM wrapper with output_hidden_states=True returns+ # per-decoder-layer hidden states that are PRE-norm (the post-norm tie+ # only fires on the base model's `last_hidden_state`, which the CausalLM+ # output object does not expose). `self._model.model` is the base+ # Qwen3VLModel whose forward applies the final RMSNorm and returns the+ # post-norm `last_hidden_state`.+ outputs = self._model.model(**inputs, return_dict=True)++ last_hidden = outputs.last_hidden_state # (1, seq_len, hidden_dim), post-RMSNormmask = inputs.get("attention_mask")if self._pooling == "mean":diff --git a/packages/sie_server/src/sie_server/core/worker/handlers/extract.py b/packages/sie_server/src/sie_server/core/worker/handlers/extract.pyindex d13375213..2dfe9dca3 100644--- a/packages/sie_server/src/sie_server/core/worker/handlers/extract.py+++ b/packages/sie_server/src/sie_server/core/worker/handlers/extract.py@@ -38,7 +38,8 @@ class ExtractHandler(OperationHandler[ExtractOutput]):Returns:Hashable tuple for grouping."""- labels_key = tuple(sorted(metadata.labels)) if metadata.labels else None+ # Label order is part of the model input for label-conditioned extractors.+ labels_key = tuple(metadata.labels) if metadata.labels else Noneoptions_key = make_hashable(metadata.options) if metadata.options else Nonereturn (labels_key,diff --git a/packages/sie_server/src/sie_server/ipc_server.py b/packages/sie_server/src/sie_server/ipc_server.pyindex 772e30e82..b960a39d1 100644--- a/packages/sie_server/src/sie_server/ipc_server.py+++ b/packages/sie_server/src/sie_server/ipc_server.py@@ -198,6 +198,7 @@ class IpcServer:self._drain_deadline_s: float | None = Noneself._streaming_processor: Any | None = Noneself._streaming_processor_lock = asyncio.Lock()+ self._generation_prewarm_lock = asyncio.Lock()self._generation_prewarmed = False# -- Public surface ----------------------------------------------------@@ -582,7 +583,7 @@ class IpcServer:) -> SignalGenerateCancelResponse:if not req.request_id:return SignalGenerateCancelResponse(matched=False)- processor = await self._get_streaming_processor()+ processor = await self._get_streaming_processor(prewarm=False)return SignalGenerateCancelResponse(matched=bool(processor.signal_cancel(req.request_id)))async def _handle_process_generate(@@ -592,34 +593,41 @@ class IpcServer:request_id: str,writer: asyncio.StreamWriter,) -> None:- processor = await self._get_streaming_processor()sink = _IpcGenerateSink(self, writer, request_id)msg = _IpcGenerateMessage(sink, req.work_item_msgpack)token = _GENERATE_SINK.set(sink)try:+ # Keep the JetStream lease alive while the first generation+ # request lazily constructs the streaming processor and prewarms+ # grammars. The processor's own heartbeat starts later, once+ # request processing reaches the decode path.+ await msg.in_progress()+ processor = await self._get_streaming_processor()await processor.process(msg, req.model_id)await sink.send(GenerateEvent(kind="done"))finally:_GENERATE_SINK.reset(token)- async def _get_streaming_processor(self) -> Any:+ async def _get_streaming_processor(self, *, prewarm: bool = True) -> Any:if self._streaming_processor is not None:- return self._streaming_processor+ processor = self._streaming_processor+ if prewarm:+ await self._prewarm_generation_grammars(processor)+ return processorasync with self._streaming_processor_lock:- if self._streaming_processor is not None:- return self._streaming_processor-- from sie_server.processors.streaming import StreamingProcessor # noqa: PLC0415-- processor = StreamingProcessor(- nc=_IpcGenerateNatsShim(), # type: ignore[arg-type]- registry=self._executor.registry,- worker_id=self._worker_id,- admission_resolver=self._resolve_generation_admission,- )- self._streaming_processor = processor+ if self._streaming_processor is None:+ from sie_server.processors.streaming import StreamingProcessor # noqa: PLC0415++ self._streaming_processor = StreamingProcessor(+ nc=_IpcGenerateNatsShim(), # type: ignore[arg-type]+ registry=self._executor.registry,+ worker_id=self._worker_id,+ admission_resolver=self._resolve_generation_admission,+ )+ processor = self._streaming_processor+ if prewarm:await self._prewarm_generation_grammars(processor)- return processor+ return processordef _resolve_generation_admission(self, model_id: str) -> tuple[int | None, bool | None]:try:@@ -643,21 +651,22 @@ class IpcServer:return budget, resolve_admission_enabled(profile_admission=profile_admission)async def _prewarm_generation_grammars(self, processor: Any) -> None:- if self._generation_prewarmed:- return- self._generation_prewarmed = True- try:- configs = self._executor.registry.get_configs_snapshot()- except Exception: # noqa: BLE001- logger.debug("Could not snapshot configs for generation grammar prewarm", exc_info=True)- return- for model_id, config in configs.items():+ async with self._generation_prewarm_lock:+ if self._generation_prewarmed:+ return+ self._generation_prewarmed = Truetry:- if config.tasks.generate is None:- continue- await processor.prewarm_grammars_for_model(model_id)+ configs = self._executor.registry.get_configs_snapshot()except Exception: # noqa: BLE001- logger.warning("Generation grammar prewarm failed for %s", model_id, exc_info=True)+ logger.debug("Could not snapshot configs for generation grammar prewarm", exc_info=True)+ return+ for model_id, config in configs.items():+ try:+ if config.tasks.generate is None:+ continue+ await processor.prewarm_grammars_for_model(model_id)+ except Exception: # noqa: BLE001+ logger.warning("Generation grammar prewarm failed for %s", model_id, exc_info=True)# -- Error helper ------------------------------------------------------diff --git a/packages/sie_server/tests/adapters/test_florence2.py b/packages/sie_server/tests/adapters/test_florence2.pyindex a40ea9c2b..091dd52b5 100644--- a/packages/sie_server/tests/adapters/test_florence2.py+++ b/packages/sie_server/tests/adapters/test_florence2.py@@ -91,19 +91,6 @@ class TestFlorence2Adapter:assert abs(bbox[2] - 0.5) < 1e-6assert abs(bbox[3] - 0.5) < 1e-6- def test_normalize_bbox(self, adapter: Florence2Adapter) -> None:- """Bbox is correctly normalized."""- bbox = [50.0, 25.0, 150.0, 75.0]- image_size = (200, 100)-- norm_bbox = adapter._normalize_bbox(bbox, image_size)-- assert len(norm_bbox) == 4- assert abs(norm_bbox[0] - 0.25) < 1e-6- assert abs(norm_bbox[1] - 0.25) < 1e-6- assert abs(norm_bbox[2] - 0.75) < 1e-6- assert abs(norm_bbox[3] - 0.75) < 1e-6-def test_build_prompt_basic_task(self, adapter: Florence2Adapter) -> None:"""Build prompt returns task token for basic tasks."""prompt = adapter._build_prompt("<OCR>", labels=None, instruction=None)@@ -167,7 +154,9 @@ class TestFlorence2Adapter:assert len(objects) == 1assert objects[0]["label"] == "car"assert objects[0]["score"] == 1.0- assert objects[0]["bbox"] is not None+ # Pixel-space COCO [x, y, w, h] (NOT normalized) so the detection harness+ # scores boxes directly: [x1, y1, x2, y2] -> [x1, y1, x2 - x1, y2 - y1].+ assert objects[0]["bbox"] == [10, 20, 70, 70]def test_extract_threads_docvqa_task_into_postprocessing(self,diff --git a/packages/sie_server/tests/adapters/test_qwen3_vl_embedding.py b/packages/sie_server/tests/adapters/test_qwen3_vl_embedding.pynew file mode 100644index 000000000..1bce457c2--- /dev/null+++ b/packages/sie_server/tests/adapters/test_qwen3_vl_embedding.py@@ -0,0 +1,178 @@+from __future__ import annotations++from types import SimpleNamespace+from typing import Any++import pytest+import torch+from sie_server.adapters.qwen3_vl_embedding import (+ _DEFAULT_INSTRUCTION,+ Qwen3VLEmbeddingAdapter,+ _normalize_instruction,+)+++class TestNormalizeInstruction:+ """Match the official ``format_model_input`` instruction shaping.++ The reference recipe strips the instruction and appends ``.`` unless the+ final character is already Unicode punctuation. SIE previously passed the+ instruction verbatim, so MTEB query instructions without trailing+ punctuation differed from the official prompt by a missing period token.+ """++ def test_appends_period_when_missing(self) -> None:+ assert (+ _normalize_instruction("Given a financial question, retrieve user replies that best answer the question")+ == "Given a financial question, retrieve user replies that best answer the question."+ )++ def test_keeps_existing_trailing_period(self) -> None:+ assert _normalize_instruction("Represent the user's input.") == "Represent the user's input."++ def test_keeps_other_trailing_punctuation(self) -> None:+ # '?', '!', ':' are all Unicode category 'P*' -> no extra period.+ assert _normalize_instruction("What is the capital?") == "What is the capital?"+ assert _normalize_instruction("Find the answer!") == "Find the answer!"+ assert _normalize_instruction("Retrieve documents:") == "Retrieve documents:"++ def test_strips_surrounding_whitespace(self) -> None:+ assert _normalize_instruction(" retrieve relevant passages ") == "retrieve relevant passages."++ def test_strips_then_keeps_trailing_punctuation(self) -> None:+ assert _normalize_instruction(" Answer the query. ") == "Answer the query."++ def test_empty_stays_empty(self) -> None:+ assert _normalize_instruction("") == ""+ assert _normalize_instruction(" ") == ""++ def test_default_instruction_is_noop(self) -> None:+ # The default already ends in punctuation -> documents are unaffected.+ assert _normalize_instruction(_DEFAULT_INSTRUCTION) == _DEFAULT_INSTRUCTION+++class _FakeBaseModel:+ """Stand-in for ``Qwen3VLModel`` exposing a post-RMSNorm ``last_hidden_state``."""++ def __init__(self, last_hidden: torch.Tensor) -> None:+ self._last_hidden = last_hidden+ self.calls: list[dict[str, Any]] = []++ def __call__(self, **kwargs: Any) -> SimpleNamespace:+ self.calls.append(kwargs)+ return SimpleNamespace(last_hidden_state=self._last_hidden)+++class _FakeCausalLM:+ """Stand-in for ``Qwen3VLForConditionalGeneration``.++ Exposes ``.model`` (the base ``Qwen3VLModel``) and asserts that the adapter+ never calls the CausalLM wrapper directly (which would return PRE-norm+ per-layer ``hidden_states`` instead of the post-norm ``last_hidden_state``).+ """++ def __init__(self, last_hidden: torch.Tensor) -> None:+ self.model = _FakeBaseModel(last_hidden)++ def __call__(self, **kwargs: Any) -> SimpleNamespace:+ raise AssertionError(+ "adapter must pool from self._model.model(...).last_hidden_state, not the CausalLM wrapper output"+ )+++class _FakeProcessor:+ def __init__(self, inputs: dict[str, torch.Tensor]) -> None:+ self._inputs = inputs+ self.conversations: list[Any] = []++ def apply_chat_template(self, conversation: Any = None, *_args: Any, **_kwargs: Any) -> str:+ self.conversations.append(conversation)+ return "PROMPT"++ def __call__(self, **_kwargs: Any) -> dict[str, torch.Tensor]:+ return self._inputs+++class TestPostNormPooling:+ """The forward path must pool the post-RMSNorm ``last_hidden_state``."""++ @pytest.fixture+ def adapter(self) -> Qwen3VLEmbeddingAdapter:+ a = Qwen3VLEmbeddingAdapter("Qwen/Qwen3-VL-Embedding-2B")+ a._device = "cpu"+ return a++ def test_pools_last_token_from_last_hidden_state(self, adapter: Qwen3VLEmbeddingAdapter) -> None:+ # seq_len=3, hidden_dim=4; attention mask marks all 3 tokens valid.+ last_hidden = torch.tensor([[[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [3.0, 4.0, 0.0, 0.0]]])+ inputs = {+ "input_ids": torch.tensor([[1, 2, 3]]),+ "attention_mask": torch.tensor([[1, 1, 1]]),+ }+ fake_model = _FakeCausalLM(last_hidden)+ adapter._model = fake_model # ty: ignore[invalid-assignment]+ adapter._processor = _FakeProcessor(inputs) # ty: ignore[invalid-assignment]++ result = adapter._forward_conversation([{"role": "user", "content": [{"type": "text", "text": "hi"}]}])++ # Last-token vector [3, 4, 0, 0] L2-normalized -> [0.6, 0.8, 0, 0].+ assert result.shape == (4,)+ assert pytest.approx(result.tolist(), abs=1e-5) == [0.6, 0.8, 0.0, 0.0]+ # The base model was called (post-norm path), not the CausalLM wrapper.+ assert len(fake_model.model.calls) == 1+ assert "output_hidden_states" not in fake_model.model.calls[0]++ def test_mean_pool_uses_last_hidden_state(self, adapter: Qwen3VLEmbeddingAdapter) -> None:+ adapter._pooling = "mean"+ last_hidden = torch.tensor([[[2.0, 0.0], [4.0, 0.0]]])+ inputs = {+ "input_ids": torch.tensor([[1, 2]]),+ "attention_mask": torch.tensor([[1, 1]]),+ }+ adapter._model = _FakeCausalLM(last_hidden) # ty: ignore[invalid-assignment]+ adapter._processor = _FakeProcessor(inputs) # ty: ignore[invalid-assignment]++ result = adapter._forward_conversation([{"role": "user", "content": [{"type": "text", "text": "hi"}]}])++ # mean([2,0],[4,0]) = [3,0] -> normalized [1,0].+ assert result.shape == (2,)+ assert pytest.approx(result.tolist(), abs=1e-5) == [1.0, 0.0]+++class TestInstructionResolution:+ """``encode()`` resolves the system-turn instruction.++ The official recipe always uses a non-empty system instruction, so both an+ omitted (``None``) and an empty (``""``) instruction coalesce to the model+ default; a non-empty instruction is forwarded after ``_normalize_instruction``+ shaping. This is the inverse of preserving ``""`` as an empty system turn,+ which the model was never trained on.+ """++ def _run(self, instruction: str | None) -> str:+ adapter = Qwen3VLEmbeddingAdapter("Qwen/Qwen3-VL-Embedding-2B")+ adapter._device = "cpu"+ inputs = {"input_ids": torch.tensor([[1]]), "attention_mask": torch.tensor([[1]])}+ proc = _FakeProcessor(inputs)+ adapter._model = _FakeCausalLM(torch.tensor([[[1.0, 0.0]]])) # ty: ignore[invalid-assignment]+ adapter._processor = proc # ty: ignore[invalid-assignment]+ item = SimpleNamespace(text="hi", images=None, video=None)+ adapter.encode([item], ["dense"], instruction=instruction)+ # conversation[0] is the system turn: {"role": "system", "content": [{"type": "text", "text": ...}]}+ return proc.conversations[0][0]["content"][0]["text"]++ def test_none_uses_default(self) -> None:+ assert self._run(None) == _DEFAULT_INSTRUCTION++ def test_empty_string_coalesces_to_default(self) -> None:+ # CodeRabbit suggested preserving "" as a distinct value; for this model+ # "" is not a trained input, so it must resolve to the default instead.+ assert self._run("") == _DEFAULT_INSTRUCTION++ def test_whitespace_only_coalesces_to_default(self) -> None:+ # Whitespace-only is truthy but normalizes to "" -> must fall back to the+ # default rather than forwarding an empty system turn.+ assert self._run(" ") == _DEFAULT_INSTRUCTION++ def test_non_empty_is_normalized_and_forwarded(self) -> None:+ assert self._run("Find relevant passages") == "Find relevant passages."diff --git a/packages/sie_server/tests/core/test_worker_extract.py b/packages/sie_server/tests/core/test_worker_extract.pyindex 9c58a2df5..45902f042 100644--- a/packages/sie_server/tests/core/test_worker_extract.py+++ b/packages/sie_server/tests/core/test_worker_extract.py@@ -82,8 +82,7 @@ class TestModelWorkerExtract:mock_adapter.extract.assert_called_once()call_kwargs = mock_adapter.extract.call_args.kwargs- # Labels are sorted when grouping for batching- assert sorted(call_kwargs["labels"]) == sorted(["person", "organization", "location"])+ assert call_kwargs["labels"] == ["person", "organization", "location"]finally:await worker.stop()@@ -133,8 +132,8 @@ class TestModelWorkerExtract:await worker.stop()@pytest.mark.asyncio- async def test_submit_extract_groups_by_labels(self, mock_adapter: MagicMock) -> None:- """Requests with different labels are grouped separately."""+ async def test_submit_extract_groups_by_ordered_labels(self, mock_adapter: MagicMock) -> None:+ """Requests with different ordered labels are grouped separately."""from sie_server.core.prepared import ExtractPreparedItemconfig = WorkerConfig(@@ -146,7 +145,9 @@ class TestModelWorkerExtract:await worker.start()try:- # Submit requests with different labels+ # Submit requests with the same labels in different orders. Some+ # extractors condition on label order, so the worker must not+ # normalize it while grouping.item1 = ExtractPreparedItem(cost=6, original_index=0)item2 = ExtractPreparedItem(cost=6, original_index=0)@@ -158,18 +159,17 @@ class TestModelWorkerExtract:future2 = await worker.submit_extract([item2],[Item(text="Text 2")],- labels=["location"], # Different labels!+ labels=["organization", "person"],)await asyncio.gather(future1, future2)- # Should have been 2 separate calls (different label sets)+ # Should have been 2 separate calls because label order differs.assert mock_adapter.extract.call_count >= 2- # Verify different labels were passed- label_sets = [tuple(sorted(call.kwargs["labels"])) for call in mock_adapter.extract.call_args_list]- assert ("location",) in label_sets- assert ("organization", "person") in label_sets+ label_orders = [tuple(call.kwargs["labels"]) for call in mock_adapter.extract.call_args_list]+ assert ("person", "organization") in label_orders+ assert ("organization", "person") in label_ordersfinally:await worker.stop()diff --git a/packages/sie_server/tests/test_all_models.py b/packages/sie_server/tests/test_all_models.pyindex 6170af1f8..375144513 100644--- a/packages/sie_server/tests/test_all_models.py+++ b/packages/sie_server/tests/test_all_models.py@@ -998,11 +998,6 @@ def test_naver_clova_ix_donut_base_finetuned_docvqa_extract() -> None:pass[email protected](reason="requires image input and special extract handling")-def test_naver_clova_ix_donut_base_finetuned_rvlcdip_extract() -> None:- pass--# =============================================================================# Extract models (image input - OWLv2 detection)# =============================================================================diff --git a/packages/sie_server/tests/test_ipc_server.py b/packages/sie_server/tests/test_ipc_server.pyindex 8981bc40b..c62f2bd76 100644--- a/packages/sie_server/tests/test_ipc_server.py+++ b/packages/sie_server/tests/test_ipc_server.py@@ -22,8 +22,10 @@ from sie_server.ipc_server import IpcServer, IpcServerErrorfrom sie_server.ipc_types import (IPC_VERSION,ApplyModelConfigRequest,+ ProcessGenerateRequest,ReplaceModelConfigEntry,ReplaceModelConfigsRequest,+ SignalGenerateCancelRequest,)from sie_server.queue_executor import QueueExecutor@@ -86,6 +88,30 @@ class _ClosedWriter:return None+class _CapturingWriter:+ def __init__(self) -> None:+ self.buf = bytearray()++ def write(self, payload: bytes) -> None:+ self.buf.extend(payload)++ async def drain(self) -> None:+ return None+++def _decode_written_frames(writer: _CapturingWriter) -> list[dict]:+ frames: list[dict] = []+ offset = 0+ data = bytes(writer.buf)+ while offset < len(data):+ (length,) = _LEN_STRUCT.unpack(data[offset : offset + _LEN_STRUCT.size])+ offset += _LEN_STRUCT.size+ payload = data[offset : offset + length]+ offset += length+ frames.append(msgpack.unpackb(payload, raw=False))+ return frames++def _make_executor() -> tuple[QueueExecutor, MagicMock]:reg = MagicMock()reg.model_names = ["test/model"]@@ -892,8 +918,73 @@ class TestGenerationSidecarIpc:assert resp["ok"] is Trueassert resp["body"] == {"matched": True}+ srv._get_streaming_processor.assert_awaited_once_with(prewarm=False) # type: ignore[attr-defined]processor.signal_cancel.assert_called_once_with("req-123")+ @pytest.mark.asyncio+ async def test_signal_generate_cancel_does_not_prewarm(self) -> None:+ executor, _reg = _make_executor()+ processor = MagicMock()+ processor.signal_cancel.return_value = False+ sock = _short_sock_path()+ srv = IpcServer(sock, executor, worker_id="w")+ srv._streaming_processor = processor+ srv._prewarm_generation_grammars = AsyncMock() # type: ignore[method-assign]++ resp = await srv._handle_signal_generate_cancel(+ SignalGenerateCancelRequest(request_id="req-123"),+ )++ assert resp.matched is False+ srv._prewarm_generation_grammars.assert_not_awaited() # type: ignore[attr-defined]+ processor.signal_cancel.assert_called_once_with("req-123")++ @pytest.mark.asyncio+ async def test_cancel_created_processor_still_prewarms_on_generate(self) -> None:+ executor, _reg = _make_executor()+ processor = MagicMock()+ sock = _short_sock_path()+ srv = IpcServer(sock, executor, worker_id="w")+ srv._prewarm_generation_grammars = AsyncMock() # type: ignore[method-assign]++ with patch("sie_server.processors.streaming.StreamingProcessor", return_value=processor):+ cancel_processor = await srv._get_streaming_processor(prewarm=False)+ generate_processor = await srv._get_streaming_processor()++ assert cancel_processor is processor+ assert generate_processor is processor+ srv._prewarm_generation_grammars.assert_awaited_once_with(processor) # type: ignore[attr-defined]++ @pytest.mark.asyncio+ async def test_process_generate_sends_progress_before_lazy_processor(self) -> None:+ executor, _reg = _make_executor()+ processor = MagicMock()+ processor.process = AsyncMock()+ sock = _short_sock_path()+ srv = IpcServer(sock, executor, worker_id="w")+ writer = _CapturingWriter()+ work_item_msgpack = msgpack.packb({"request_id": "req-1"}, use_bin_type=True)++ async def get_processor() -> MagicMock:+ frames = _decode_written_frames(writer)+ assert [frame["body"]["kind"] for frame in frames] == ["in_progress"]+ return processor++ get_processor_mock = AsyncMock(side_effect=get_processor)+ srv._get_streaming_processor = get_processor_mock # type: ignore[method-assign]++ await srv._handle_process_generate(+ ProcessGenerateRequest(model_id="test/model", work_item_msgpack=work_item_msgpack),+ request_id="ipc-req-1",+ writer=writer, # type: ignore[arg-type]+ )++ frames = _decode_written_frames(writer)+ assert [frame["body"]["kind"] for frame in frames] == ["in_progress", "done"]+ assert [frame["request_id"] for frame in frames] == ["ipc-req-1", "ipc-req-1"]+ get_processor_mock.assert_awaited_once()+ processor.process.assert_awaited_once()+# -----------------------------------------------------------------------------# Socket cleanupdiff --git a/packages/sie_server_sidecar/Cargo.lock b/packages/sie_server_sidecar/Cargo.lockindex 43f68a410..e043e1bdd 100644--- a/packages/sie_server_sidecar/Cargo.lock+++ b/packages/sie_server_sidecar/Cargo.lock@@ -2208,7 +2208,7 @@ checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"[[package]]name = "sie-server-sidecar"-version = "0.6.9"+version = "0.6.10"dependencies = ["anyhow","async-nats",diff --git a/packages/sie_server_sidecar/Cargo.toml b/packages/sie_server_sidecar/Cargo.tomlindex dd502e50b..b991312df 100644--- a/packages/sie_server_sidecar/Cargo.toml+++ b/packages/sie_server_sidecar/Cargo.toml@@ -1,6 +1,6 @@[package]name = "sie-server-sidecar"-version = "0.6.9"+version = "0.6.10"edition = "2021"description = "SIE worker sidecar: NATS JetStream consumer, scheduler, IPC client, and GPU-independent prep for sie-server pods."diff --git a/packages/sie_server_sidecar/src/dispatcher.rs b/packages/sie_server_sidecar/src/dispatcher.rsindex 8ca29ea50..1b21da05f 100644--- a/packages/sie_server_sidecar/src/dispatcher.rs+++ b/packages/sie_server_sidecar/src/dispatcher.rs@@ -47,6 +47,53 @@ use crate::subject::extract_model_id;use crate::tokenize::TokenizerRegistry;use crate::work_types::WorkItem;+#[derive(Debug, Clone)]+struct DeliveryContext {+ subject: String,+ stream: String,+ consumer: String,+ stream_sequence: u64,+ consumer_sequence: u64,+ delivered: i64,+ pending: u64,+ has_metadata: bool,+}++impl DeliveryContext {+ fn from_message(msg: &Message) -> Self {+ match msg.info() {+ Ok(info) => Self {+ subject: msg.subject.to_string(),+ stream: info.stream.to_string(),+ consumer: info.consumer.to_string(),+ stream_sequence: info.stream_sequence,+ consumer_sequence: info.consumer_sequence,+ delivered: info.delivered,+ pending: info.pending,+ has_metadata: true,+ },+ Err(_) => Self {+ subject: msg.subject.to_string(),+ stream: String::new(),+ consumer: String::new(),+ stream_sequence: 0,+ consumer_sequence: 0,+ delivered: 0,+ pending: 0,+ has_metadata: false,+ },+ }+ }+}++#[derive(Debug, Clone)]+struct GenerateDeliveryLogContext {+ work_item_id: String,+ request_id: String,+ model_id: String,+ delivery: DeliveryContext,+}+/// Base NAK delay in milliseconds. Mirrors Python's `_NAK_DELAY_S`/// (default 5 000 ms, overridable via `SIE_NAK_DELAY_S`). Used for:///@@ -514,6 +561,7 @@ impl Dispatcher {async fn handle_generate_item(self: Arc<Self>, mut wi: WorkItem, msg: Message) {let model_id = wi.model_id.clone();+ let delivery = DeliveryContext::from_message(&msg);let model_lbl = self.metrics.model_label(&model_id).into_owned();let _timer = self.metrics@@ -521,12 +569,35 @@ impl Dispatcher {.with_label_values(&[&model_lbl, "generate"]).start_timer();let base_delay_ms = base_nak_delay_ms();+ info!(+ work_item_id = %wi.work_item_id,+ request_id = %wi.request_id,+ model = %model_id,+ subject = %delivery.subject,+ stream = %delivery.stream,+ consumer = %delivery.consumer,+ stream_seq = delivery.stream_sequence,+ consumer_seq = delivery.consumer_sequence,+ delivery_count = delivery.delivered,+ pending = delivery.pending,+ has_metadata = delivery.has_metadata,+ "generate delivery received"+ );let readiness_resp = match self.backend.ensure_model_ready(&model_id).await {Ok(r) => r,Err(e) => {warn!(+ work_item_id = %wi.work_item_id,+ request_id = %wi.request_id,model = %model_id,+ subject = %delivery.subject,+ stream = %delivery.stream,+ consumer = %delivery.consumer,+ stream_seq = delivery.stream_sequence,+ consumer_seq = delivery.consumer_sequence,+ delivery_count = delivery.delivered,+ pending = delivery.pending,error = %ErrChain(&e),"EnsureModelReady failed for generate — NAKing");@@ -534,14 +605,45 @@ impl Dispatcher {return;}};- match readiness_resp.state {+ match &readiness_resp.state {ReadinessState::Ready => {}ReadinessState::LoadingStarted | ReadinessState::RetryLater => {+ info!(+ work_item_id = %wi.work_item_id,+ request_id = %wi.request_id,+ model = %model_id,+ readiness = ?readiness_resp.state,+ delay_ms = base_delay_ms,+ subject = %delivery.subject,+ stream = %delivery.stream,+ consumer = %delivery.consumer,+ stream_seq = delivery.stream_sequence,+ consumer_seq = delivery.consumer_sequence,+ delivery_count = delivery.delivered,+ pending = delivery.pending,+ "generate model not ready — NAKing"+ );nak_one(&msg, base_delay_ms, &self.metrics).await;return;}ReadinessState::LoadingInProgress => {- nak_one(&msg, base_delay_ms.saturating_mul(2), &self.metrics).await;+ let delay_ms = base_delay_ms.saturating_mul(2);+ info!(+ work_item_id = %wi.work_item_id,+ request_id = %wi.request_id,+ model = %model_id,+ readiness = ?readiness_resp.state,+ delay_ms,+ subject = %delivery.subject,+ stream = %delivery.stream,+ consumer = %delivery.consumer,+ stream_seq = delivery.stream_sequence,+ consumer_seq = delivery.consumer_sequence,+ delivery_count = delivery.delivered,+ pending = delivery.pending,+ "generate model still loading — NAKing"+ );+ nak_one(&msg, delay_ms, &self.metrics).await;return;}}@@ -562,6 +664,15 @@ impl Dispatcher {Err(e) => {warn!(work_item_id = %wi.work_item_id,+ request_id = %wi.request_id,+ model = %model_id,+ subject = %delivery.subject,+ stream = %delivery.stream,+ consumer = %delivery.consumer,+ stream_seq = delivery.stream_sequence,+ consumer_seq = delivery.consumer_sequence,+ delivery_count = delivery.delivered,+ pending = delivery.pending,error = %e,"failed to decode offloaded generate payload — publishing error + ACK");@@ -576,7 +687,15 @@ impl Dispatcher {Ok(_) => match ack(&msg).await {Ok(()) => self.metrics.messages_acked_total.inc(),Err(e) => {- warn!(error = %e, "ack after offload-decode error failed");+ warn!(+ work_item_id = %wi.work_item_id,+ request_id = %wi.request_id,+ model = %model_id,+ stream_seq = delivery.stream_sequence,+ delivery_count = delivery.delivered,+ error = %e,+ "ack after offload-decode error failed"+ );self.metrics.jetstream_ack_failures_total.inc();}},@@ -588,6 +707,15 @@ impl Dispatcher {Err(e) => {warn!(work_item_id = %wi.work_item_id,+ request_id = %wi.request_id,+ model = %model_id,+ subject = %delivery.subject,+ stream = %delivery.stream,+ consumer = %delivery.consumer,+ stream_seq = delivery.stream_sequence,+ consumer_seq = delivery.consumer_sequence,+ delivery_count = delivery.delivered,+ pending = delivery.pending,error = %e,"failed to resolve offloaded generate payload — NAKing");@@ -603,6 +731,14 @@ impl Dispatcher {warn!(work_item_id = %wi.work_item_id,request_id = %wi.request_id,+ model = %model_id,+ subject = %delivery.subject,+ stream = %delivery.stream,+ consumer = %delivery.consumer,+ stream_seq = delivery.stream_sequence,+ consumer_seq = delivery.consumer_sequence,+ delivery_count = delivery.delivered,+ pending = delivery.pending,error = %e,"failed to re-encode generate WorkItem — publishing error + ACK");@@ -613,7 +749,15 @@ impl Dispatcher {Ok(_) => match ack(&msg).await {Ok(()) => self.metrics.messages_acked_total.inc(),Err(e) => {- warn!(error = %e, "ack after generate encode error failed");+ warn!(+ work_item_id = %wi.work_item_id,+ request_id = %wi.request_id,+ model = %model_id,+ stream_seq = delivery.stream_sequence,+ delivery_count = delivery.delivered,+ error = %e,+ "ack after generate encode error failed"+ );self.metrics.jetstream_ack_failures_total.inc();}},@@ -625,10 +769,17 @@ impl Dispatcher {let settled = Arc::new(AtomicBool::new(false));let msg = Arc::new(msg);+ let delivery_log = Arc::new(GenerateDeliveryLogContext {+ work_item_id: wi.work_item_id.clone(),+ request_id: wi.request_id.clone(),+ model_id: model_id.clone(),+ delivery,+ });let publisher = Arc::clone(&self.publisher);let metrics = Arc::clone(&self.metrics);let settled_for_events = Arc::clone(&settled);let msg_for_events = Arc::clone(&msg);+ let delivery_log_for_events = Arc::clone(&delivery_log);let result = self.ipc.process_generate(@@ -641,8 +792,9 @@ impl Dispatcher {let metrics = Arc::clone(&metrics);let settled = Arc::clone(&settled_for_events);let msg = Arc::clone(&msg_for_events);+ let delivery_log = Arc::clone(&delivery_log_for_events);async move {- handle_generate_event(event, publisher, metrics, settled, msg)+ handle_generate_event(event, publisher, metrics, settled, msg, delivery_log).await.map_err(|e| IpcError::Server(e.to_string()))}@@ -656,6 +808,14 @@ impl Dispatcher {warn!(work_item_id = %wi.work_item_id,request_id = %wi.request_id,+ model = %model_id,+ subject = %delivery_log.delivery.subject,+ stream = %delivery_log.delivery.stream,+ consumer = %delivery_log.delivery.consumer,+ stream_seq = delivery_log.delivery.stream_sequence,+ consumer_seq = delivery_log.delivery.consumer_sequence,+ delivery_count = delivery_log.delivery.delivered,+ pending = delivery_log.delivery.pending,"ProcessGenerate ended without ACK/NAK event — NAKing");nak_one(&msg, base_delay_ms, &self.metrics).await;@@ -666,6 +826,13 @@ impl Dispatcher {work_item_id = %wi.work_item_id,request_id = %wi.request_id,model = %model_id,+ subject = %delivery_log.delivery.subject,+ stream = %delivery_log.delivery.stream,+ consumer = %delivery_log.delivery.consumer,+ stream_seq = delivery_log.delivery.stream_sequence,+ consumer_seq = delivery_log.delivery.consumer_sequence,+ delivery_count = delivery_log.delivery.delivered,+ pending = delivery_log.delivery.pending,error = %e,"ProcessGenerate failed — NAKing if unsettled");@@ -2070,6 +2237,7 @@ async fn handle_generate_event(metrics: Arc<MetricsRegistry>,settled: Arc<AtomicBool>,msg: Arc<Message>,+ delivery_log: Arc<GenerateDeliveryLogContext>,) -> Result<(), DispatchError> {match event.kind.as_str() {"publish" => {@@ -2080,9 +2248,37 @@ async fn handle_generate_event("ack" => {if !settled.swap(true, Ordering::SeqCst) {match ack(&msg).await {- Ok(()) => metrics.messages_acked_total.inc(),+ Ok(()) => {+ info!(+ work_item_id = %delivery_log.work_item_id,+ request_id = %delivery_log.request_id,+ model = %delivery_log.model_id,+ subject = %delivery_log.delivery.subject,+ stream = %delivery_log.delivery.stream,+ consumer = %delivery_log.delivery.consumer,+ stream_seq = delivery_log.delivery.stream_sequence,+ consumer_seq = delivery_log.delivery.consumer_sequence,+ delivery_count = delivery_log.delivery.delivered,+ pending = delivery_log.delivery.pending,+ "generate delivery ACKed"+ );+ metrics.messages_acked_total.inc();+ }Err(e) => {- warn!(error = %e, "generate ACK failed");+ warn!(+ work_item_id = %delivery_log.work_item_id,+ request_id = %delivery_log.request_id,+ model = %delivery_log.model_id,+ subject = %delivery_log.delivery.subject,+ stream = %delivery_log.delivery.stream,+ consumer = %delivery_log.delivery.consumer,+ stream_seq = delivery_log.delivery.stream_sequence,+ consumer_seq = delivery_log.delivery.consumer_sequence,+ delivery_count = delivery_log.delivery.delivered,+ pending = delivery_log.delivery.pending,+ error = %e,+ "generate ACK failed"+ );metrics.jetstream_ack_failures_total.inc();}}@@ -2091,15 +2287,56 @@ async fn handle_generate_event("nak" => {if !settled.swap(true, Ordering::SeqCst) {let delay_ms = event.delay_ms.unwrap_or_else(base_nak_delay_ms);+ warn!(+ work_item_id = %delivery_log.work_item_id,+ request_id = %delivery_log.request_id,+ model = %delivery_log.model_id,+ delay_ms,+ subject = %delivery_log.delivery.subject,+ stream = %delivery_log.delivery.stream,+ consumer = %delivery_log.delivery.consumer,+ stream_seq = delivery_log.delivery.stream_sequence,+ consumer_seq = delivery_log.delivery.consumer_sequence,+ delivery_count = delivery_log.delivery.delivered,+ pending = delivery_log.delivery.pending,+ "generate delivery NAKed by Python"+ );nak_one(&msg, delay_ms, &metrics).await;}}"in_progress" => {if !settled.load(Ordering::SeqCst) {match msg.ack_with(async_nats::jetstream::AckKind::Progress).await {- Ok(()) => {}+ Ok(()) => {+ debug!(+ work_item_id = %delivery_log.work_item_id,+ request_id = %delivery_log.request_id,+ model = %delivery_log.model_id,+ subject = %delivery_log.delivery.subject,+ stream = %delivery_log.delivery.stream,+ consumer = %delivery_log.delivery.consumer,+ stream_seq = delivery_log.delivery.stream_sequence,+ consumer_seq = delivery_log.delivery.consumer_sequence,+ delivery_count = delivery_log.delivery.delivered,+ pending = delivery_log.delivery.pending,+ "generate delivery progress ACKed"+ );+ }Err(e) => {- debug!(error = %e, "generate in-progress ACK failed");+ debug!(+ work_item_id = %delivery_log.work_item_id,+ request_id = %delivery_log.request_id,+ model = %delivery_log.model_id,+ subject = %delivery_log.delivery.subject,+ stream = %delivery_log.delivery.stream,+ consumer = %delivery_log.delivery.consumer,+ stream_seq = delivery_log.delivery.stream_sequence,+ consumer_seq = delivery_log.delivery.consumer_sequence,+ delivery_count = delivery_log.delivery.delivered,+ pending = delivery_log.delivery.pending,+ error = %e,+ "generate in-progress ACK failed"+ );metrics.jetstream_ack_failures_total.inc();}}diff --git a/packages/sie_server_sidecar/src/nats_consumer.rs b/packages/sie_server_sidecar/src/nats_consumer.rsindex b7160b43f..628f25c32 100644--- a/packages/sie_server_sidecar/src/nats_consumer.rs+++ b/packages/sie_server_sidecar/src/nats_consumer.rs@@ -29,7 +29,7 @@ const ACK_WAIT_SECS: u64 = 30;const GENERATION_ACK_WAIT_SECS: u64 = 300;const DEFAULT_MAX_DELIVER: i64 = 20;const DEFAULT_MAX_ACK_PENDING: i64 = 1000;-const DEFAULT_STREAM_MAX_AGE_SECS: u64 = ACK_WAIT_SECS * (DEFAULT_MAX_DELIVER as u64);+const DEFAULT_STREAM_MAX_AGE_SECS: u64 = 1_800;const STREAM_MAX_MSGS: i64 = 100_000;/// Env-overridable `max_deliver`. Mirrors Python's `SIE_MAX_DELIVER`@@ -44,8 +44,8 @@ fn max_deliver() -> i64 {}/// Env-overridable stream `max_age`. Mirrors Python's-/// `SIE_STREAM_MAX_AGE_S` (default 600). Should be >=-/// `max_deliver * ack_wait` so messages don't expire mid-retry.+/// `SIE_STREAM_MAX_AGE_S` (default 1800). Should be >+/// `max_deliver * ack_wait` so messages remain inspectable after DLQ.fn stream_max_age_secs() -> u64 {std::env::var("SIE_STREAM_MAX_AGE_S").ok()@@ -164,6 +164,41 @@ async fn reconcile_stream_subjects(Ok(())}+async fn reconcile_stream_max_age(+ js: &JsContext,+ stream: &mut JsStream,+ stream_name: &str,+ desired_max_age: Duration,+) -> Result<(), NatsSetupError> {+ let observed_max_age = stream.cached_info().config.max_age;+ if observed_max_age == desired_max_age {+ return Ok(());+ }++ let mut updated = stream.cached_info().config.clone();+ updated.max_age = desired_max_age;+ js.update_stream(updated)+ .await+ .map_err(|e| NatsSetupError::EnsureStream {+ name: stream_name.to_string(),+ source: e.into(),+ })?;+ *stream = js+ .get_stream(stream_name)+ .await+ .map_err(|e| NatsSetupError::EnsureStream {+ name: stream_name.to_string(),+ source: e.into(),+ })?;+ info!(+ stream = %stream_name,+ observed_max_age_s = observed_max_age.as_secs(),+ desired_max_age_s = desired_max_age.as_secs(),+ "reconciled NATS stream max_age"+ );+ Ok(())+}+/// Predicate used by [`cleanup_overlapping_consumers`]. Returns true/// iff any of the consumer's configured filter(s) overlaps the/// worker's intended `desired_subject` per NATS wildcard semantics.@@ -373,13 +408,14 @@ pub async fn ensure_worker_stream_and_consumer(let stream_name = config.worker_stream_name();let subject = config.worker_subject_filter();let consumer_name = config.worker_consumer_name();+ let desired_max_age = Duration::from_secs(generation_stream_max_age_secs());let stream_cfg = StreamConfig {name: stream_name.clone(),subjects: vec![subject.clone()],retention: RetentionPolicy::WorkQueue,storage: StorageType::Memory,- max_age: Duration::from_secs(generation_stream_max_age_secs()),+ max_age: desired_max_age,max_messages: STREAM_MAX_MSGS,num_replicas: 1,discard: DiscardPolicy::New,@@ -397,6 +433,7 @@ pub async fn ensure_worker_stream_and_consumer(source: e.into(),})?;reconcile_stream_subjects(js, &mut stream, &stream_name, &subject).await?;+ reconcile_stream_max_age(js, &mut stream, &stream_name, desired_max_age).await?;cleanup_overlapping_consumers(&stream, &consumer_name, &subject).await;@@ -486,26 +523,7 @@ async fn ensure_stream_and_consumer_inner(source: e.into(),})?;reconcile_stream_subjects(js, &mut stream, &stream_name, &stream_subject).await?;-- // `get_or_create_stream` is a no-op against an EXISTING stream with a- // different config (the first writer's config wins). We reconcile- // subject filters above to the canonical lane-aware shape. This is a- // cutover, not a mixed-version bridge: old subjects are intentionally- // removed from the stream config. Other config drift (such as max_age)- // is still warned below: if the gateway and the worker disagree on- // `max_age`, retries may be purged before `max_deliver` is reached —- // silent data loss.- let observed_max_age = stream.cached_info().config.max_age;- if observed_max_age != desired_max_age {- warn!(- stream = %stream_name,- observed_max_age_s = observed_max_age.as_secs(),- desired_max_age_s = desired_max_age.as_secs(),- "stream max_age drift: existing stream config disagrees with this worker's intent; \- whoever created the stream first wins. This can cause retries to expire before \- max_deliver is reached. Align SIE_STREAM_MAX_AGE_S across gateway + workers."- );- }+ reconcile_stream_max_age(js, &mut stream, &stream_name, desired_max_age).await?;// Self-heal stale durables whose filters overlap this concrete// `(pool, machine_profile, bundle)` lane. Without this, NATS rejects@@ -639,12 +657,12 @@ mod tests {// ack_wait = 30s// max_deliver = 20 (env SIE_MAX_DELIVER)// max_ack_pending = 1000 (env SIE_MAX_ACK_PENDING)- // stream max_age = 600s (env SIE_STREAM_MAX_AGE_S)+ // stream max_age = 1800s (env SIE_STREAM_MAX_AGE_S)// stream max_msgs = 100_000assert_eq!(ACK_WAIT_SECS, 30);assert_eq!(DEFAULT_MAX_DELIVER, 20);assert_eq!(DEFAULT_MAX_ACK_PENDING, 1000);- assert_eq!(DEFAULT_STREAM_MAX_AGE_SECS, 600);+ assert_eq!(DEFAULT_STREAM_MAX_AGE_SECS, 1_800);assert_eq!(STREAM_MAX_MSGS, 100_000);}diff --git a/packages/sie_ts_sdk/package.json b/packages/sie_ts_sdk/package.jsonindex 3e5969d27..01fd4bc73 100644--- a/packages/sie_ts_sdk/package.json+++ b/packages/sie_ts_sdk/package.json@@ -1,6 +1,6 @@{"name": "@superlinked/sie-sdk",- "version": "0.6.9",+ "version": "0.6.10","description": "Official TypeScript SDK for SIE (Search Inference Engine)","type": "module","main": "./dist/index.cjs",diff --git a/packages/sie_ts_sdk/src/version.ts b/packages/sie_ts_sdk/src/version.tsindex a56c39d6c..43e4c99a4 100644--- a/packages/sie_ts_sdk/src/version.ts+++ b/packages/sie_ts_sdk/src/version.ts@@ -1 +1 @@-export const SDK_VERSION = "0.6.9"; // x-release-please-version+export const SDK_VERSION = "0.6.10"; // x-release-please-versiondiff --git a/uv.lock b/uv.lockindex e747ee75a..aa20e1202 100644--- a/uv.lock+++ b/uv.lock@@ -60,7 +60,7 @@ wheels = [[[package]]name = "aiohttp"-version = "3.14.0"+version = "3.14.1"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "aiohappyeyeballs" },@@ -72,26 +72,26 @@ dependencies = [{ name = "typing-extensions" },{ name = "yarl" },]-sdist = { url = "https://files.pythonhosted.org/packages/ee/ab/93ce242f899b68c51b0578c027aafa791ab3614cb9345fa5d37b5f5c8e3e/aiohttp-3.14.0.tar.gz", hash = "sha256:2882de819734c715fd1b9c11c97e09fa020d14438203d1d354d8ed1702791c9b", size = 7940674 }-wheels = [- { url = "https://files.pythonhosted.org/packages/89/97/2b6889bfb6b6847520d50d95eb8c4307a45e28aaca39faf4a9454b3d1b2f/aiohttp-3.14.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:b29518c9c2ec7e373e68259206a137c7f4f5439c58baaec4b5ab3ab799850a4e", size = 750194 },- { url = "https://files.pythonhosted.org/packages/21/e2/62634b7fff918ed98c3c6b2f0e70d520f7f28846cb412d451b04354c6459/aiohttp-3.14.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:dbec68ce61b64cb73cab4d33df9433427b1713c8bcccb181dce695c1b6f8e87c", size = 506966 },- { url = "https://files.pythonhosted.org/packages/dd/fb/5ce075150828c797a5106f1c2fb26034e709d4289b9d2bf8b07f1e59fac6/aiohttp-3.14.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:3cdf534aa455593e589302990c5097aa5c92c06c4262a20da22934f9186a5fff", size = 507527 },- { url = "https://files.pythonhosted.org/packages/01/d5/405a0ae4e6b081754a3609c1c97c63a950e000a2def16046f1e736933a0e/aiohttp-3.14.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:cb6c657104393b5fbff01a5f59b2023db74058a8077d94475d6c25d03882a108", size = 1762420 },- { url = "https://files.pythonhosted.org/packages/ae/1d/e05a7c896b15a6bc6fb8fc5319eb437861c2c49c34559ef928add6590315/aiohttp-3.14.0-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:46fbbec4e4fab7428d4396a3823f9320e4560aa3113b89eeebce712c27c9ed5a", size = 1733672 },- { url = "https://files.pythonhosted.org/packages/cc/22/a72f7c459e195fa41bf4f7abd1f925b91fe91f8097e51c654229ba144a33/aiohttp-3.14.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:2c2c7e05dd5335b298085abf45ddf98673934c3ee1c083d0b9ea13d4186ad500", size = 1805064 },- { url = "https://files.pythonhosted.org/packages/80/50/e85bdaba0be59ca4838005ebfef4048fcdd5f35a02b07057a9a123394440/aiohttp-3.14.0-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:3c7139100fbaae76515b73051d8f0aa3a3ff02e415eec8a8eee8e2223d9ba955", size = 1902125 },- { url = "https://files.pythonhosted.org/packages/19/d8/51de5c6b971c27bb1ef620293b8d1ca611ec78736b34b3f6ccf68e4c8785/aiohttp-3.14.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:78d6f9286a629ce52728430afe18f8ed2b6c39a1fddb3802d7244b9983910ad2", size = 1783112 },- { url = "https://files.pythonhosted.org/packages/73/ae/b4402bfde77e43dfb1b6ccff83c7b7ab63ed06b50c4754f0c5423fb374fe/aiohttp-3.14.0-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:cc3c3e12cdaeb92d7dcf13db00e9f6b1956b910e47256e696df1cfa946d02159", size = 1586356 },- { url = "https://files.pythonhosted.org/packages/bc/05/750a3265ca4dc54a460bd0cb1121a8f2ce9171fce4a135fb47ea7fd594d2/aiohttp-3.14.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:4d6a998191f5ebe3b8c28463ff72bc030250008b3193c402464efadd08b5ca02", size = 1723119 },- { url = "https://files.pythonhosted.org/packages/37/01/8c0812c50b3b1b1c37b323bf170d6be8847a8f234060485b7d1e71953f60/aiohttp-3.14.0-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:0fc2b75ae8d169d853be2862d960be8550da6c5c65711d5476407eb3fdb006bd", size = 1757216 },- { url = "https://files.pythonhosted.org/packages/47/2a/50fb98028a26887cbe48dcc1df92a90825615bc73b5584301304090cded8/aiohttp-3.14.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:16eee56bcc72d04600bc56c1759982c2385ec0b41d3fd3521f836bf64a0957ef", size = 1770500 },- { url = "https://files.pythonhosted.org/packages/bd/32/0ffd598a2fa2b9a423daf242e700cfdabda35d6e602394ad9ae58972c1c7/aiohttp-3.14.0-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:5a2e7ca615c3ddc15b82687e05a624e5f5cba3f1d6c20cb81172d70ea498451e", size = 1576224 },- { url = "https://files.pythonhosted.org/packages/0b/f9/b9fc381dd9b66afb33f2634c40e229d106467be0afcabe79648631ab6712/aiohttp-3.14.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:f0b7b8bbbec3ce9467ee0ebe334622fd90624f593edd3136c567811453fc4fae", size = 1794252 },- { url = "https://files.pythonhosted.org/packages/a8/fb/05d9214c975f23225a8cd5c439325e338c7c377b315480ef3871db51f54e/aiohttp-3.14.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:5ba10966d4f03dd96a14365be4b8e37c327c76f11c3ca867116966cdd9f98066", size = 1760193 },- { url = "https://files.pythonhosted.org/packages/d9/4b/02992fc4fb9e1b6673ee3f888a8e587a6447afda1f6f4aca776c148c2876/aiohttp-3.14.0-cp312-cp312-win32.whl", hash = "sha256:101df7779c80c0636014a6b2c6642acd3efb5b355d48347c9d7dfb720aee9430", size = 448650 },- { url = "https://files.pythonhosted.org/packages/39/e9/246532214c3abda518477cbaaf16d420295ad8effa5233844cbb38f299ab/aiohttp-3.14.0-cp312-cp312-win_amd64.whl", hash = "sha256:b0a5747586d4467efd1f932710b269131c9717a872dce082cd92a00c1c13123a", size = 476145 },- { url = "https://files.pythonhosted.org/packages/2b/c3/63f8c20090048915711598b0adf475b149216d736157961de06480a45b15/aiohttp-3.14.0-cp312-cp312-win_arm64.whl", hash = "sha256:5f1c5be60add78fabb4aacd13c5a348ae79d2fcbfc7fa78da8f1eb192273b370", size = 444250 },+sdist = { url = "https://files.pythonhosted.org/packages/82/78/8ea7308cac6934de8c74a14f3d5f65d1c89287426688be79538d0e5c013d/aiohttp-3.14.1.tar.gz", hash = "sha256:307f2cff90a764d329e77040603fa032db89c5c24fdad50c4c15334cba744035", size = 7955794 }+wheels = [+ { url = "https://files.pythonhosted.org/packages/1d/21/151624b51cd92553d95424daf4bf19f19ce9be9002d19253e7e7ce67197b/aiohttp-3.14.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:d35143e27778b4bb0fb189562d7f275bff79c62ab8e98459717c0ea617ff2480", size = 757402 },+ { url = "https://files.pythonhosted.org/packages/c2/82/280619e0bd7bf2454987e19282616e84762255dd9c8468f62382e8c191f1/aiohttp-3.14.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:bcfb80a2cc36fba2534e5e5b5264dc7ae6fcd9bf15256da3e53d2f499e6fa29d", size = 512310 },+ { url = "https://files.pythonhosted.org/packages/55/b2/2aac325583aaa1353045f96dffa586d8a34e8322e14a7ba49cffeb103ab4/aiohttp-3.14.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:27fd7c91e51729b4f7e1577865fa6d34c9adccbc39aabe9000285b48af9f0ec2", size = 512448 },+ { url = "https://files.pythonhosted.org/packages/8a/72/a60607cb849faa8af8a356c9329ea2eb6f395d49e82cc82ccba1fd8deb8f/aiohttp-3.14.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:64c567bf9eaf664280116a8688f63016e6b32db2505908e2bdaca1b6438142f2", size = 1766854 },+ { url = "https://files.pythonhosted.org/packages/b5/d3/d9fe1c9ec7557ab4d0d82bebaa728c6418f0b93295ec2f4ab015f7710cc7/aiohttp-3.14.1-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:f5e6ff2bdbb8f4cd3fbe41f99e25bbcd58e3bf9f13d3dd31a11e7917251cc77a", size = 1740884 },+ { url = "https://files.pythonhosted.org/packages/c1/dc/f2cecfaf9337ba3e63f181500814ff502aa3d00d9c7ec93a9d23d10a27b2/aiohttp-3.14.1-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:2f73e01dc37122325caf079982621262f96d74823c179038a82fddfc50359264", size = 1810034 },+ { url = "https://files.pythonhosted.org/packages/66/d7/2ff65c5e65c0d7476daf7e15c032e0805e36811185b9623e3238ad6c763e/aiohttp-3.14.1-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:bb2c0c80d431c0d03f2c7dbf125150fedd4f0de17366a7ca33f7ccb822391842", size = 1904054 },+ { url = "https://files.pythonhosted.org/packages/20/9c/d445818389df371f56d141d881153ba23183c4735a03f7356ffb43f7757d/aiohttp-3.14.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3e6fc1a85fa7194a1a7d19f44e8609180f4a8eb5fa4c7ed8b4355f080fad235c", size = 1790278 },+ { url = "https://files.pythonhosted.org/packages/4d/aa/bf04cb4d865fc6101c2229a294ad744973b72e513fdc5a6b791e6983d72a/aiohttp-3.14.1-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:686b6c0d3911ec387b444ddf5dc62fb7f7c0a7d5186a7861626496a5ab4aff95", size = 1591795 },+ { url = "https://files.pythonhosted.org/packages/dc/b4/4dac0038960427ba832f6609dfb4ea5437d7fd80c72001b9e48f834f428b/aiohttp-3.14.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:c6fa4dc7ad6f8109c70bb1499e589f76b0b792baf39f9b017eb92c8a81d0a199", size = 1728397 },+ { url = "https://files.pythonhosted.org/packages/2b/f9/7cd4e8ad7aa3b75f17d56bb5498dd604a93d4e6eece822ba0568c413fff0/aiohttp-3.14.1-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:87a5eea1b2a5e21e1ebdbb33ad4165359189327e63fc4e4894693e7f821ac817", size = 1766504 },+ { url = "https://files.pythonhosted.org/packages/f9/df/fc01d9fcad0f73fed3f3d361f1f94f975947b50dff82919f6dc2bf4316cc/aiohttp-3.14.1-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:1c1421eb01d4fd608d88cc8290211d177a58532b55ad94076fb349c5bf467f0a", size = 1777806 },+ { url = "https://files.pythonhosted.org/packages/41/09/47e2d090bddcc8fb4ccb4c314aadc32d7c5d9bb55f50f6ad1c92fc15d501/aiohttp-3.14.1-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:34b257ec41345c1e8f2df68fa908a7952f5de932723871eb633ecbbff396c9a4", size = 1580707 },+ { url = "https://files.pythonhosted.org/packages/3d/36/f1a4ce904ae0b6930cfe9afc96d0896f7ec1a620c400405d63783bb95a9c/aiohttp-3.14.1-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:de538791a80e5d862addbc183f70f0158ac9b9bb872bb147f1fd2a683691e087", size = 1798121 },+ { url = "https://files.pythonhosted.org/packages/70/0a/e0075ce9ca0279ee1d4f0c0b85f54fea02ebc83c3007651a72bece658fec/aiohttp-3.14.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:6f71173be42d3241d428f760122febb748de0623f44308a6f120d0dd9ec572e3", size = 1767580 },+ { url = "https://files.pythonhosted.org/packages/3e/61/a0c0a8f327a9c52095cdd8e312391b00d3ed64ab6c72bb5c33d8ec251cf7/aiohttp-3.14.1-cp312-cp312-win32.whl", hash = "sha256:ec8dc383ee57ea3e883477dcca3f11b65d58199f1080acaf4cd6ad9a99698be4", size = 452771 },+ { url = "https://files.pythonhosted.org/packages/df/d9/ea367c75f16ac9c6cdc8febb25e8318fa21a2b1bc8d6514d4b2d890bface/aiohttp-3.14.1-cp312-cp312-win_amd64.whl", hash = "sha256:2aa92c87868cd13674989f9ee83e5f9f7ea4237589b728048e1f0c8f6caa3271", size = 479873 },+ { url = "https://files.pythonhosted.org/packages/03/64/8d96784a7851156db8a4c6c3f6f91042fdf39fb15a4cc38c8b3c14833c45/aiohttp-3.14.1-cp312-cp312-win_arm64.whl", hash = "sha256:2c840c90759922cb5e6dda94596e079a30fb5a5ba548e7e0dc00574703940847", size = 448073 },][[package]]@@ -5719,7 +5719,7 @@ dev = [[[package]]name = "sie-admin"-version = "0.6.9"+version = "0.6.10"source = { editable = "packages/sie_admin" }dependencies = [{ name = "httpx" },@@ -5752,7 +5752,7 @@ requires-dist = [[[package]]name = "sie-bench"-version = "0.6.9"+version = "0.6.10"source = { editable = "packages/sie_bench" }dependencies = [{ name = "aiohttp" },@@ -5837,7 +5837,7 @@ requires-dist = [[[package]]name = "sie-chroma"-version = "0.6.9"+version = "0.6.10"source = { editable = "integrations/sie_chroma" }dependencies = [{ name = "chromadb" },@@ -5909,7 +5909,7 @@ dev = [[[package]]name = "sie-crewai"-version = "0.6.9"+version = "0.6.10"source = { editable = "integrations/sie_crewai" }dependencies = [{ name = "crewai" },@@ -5934,7 +5934,7 @@ requires-dist = [[[package]]name = "sie-dspy"-version = "0.6.9"+version = "0.6.10"source = { editable = "integrations/sie_dspy" }dependencies = [{ name = "dspy" },@@ -5959,7 +5959,7 @@ requires-dist = [[[package]]name = "sie-haystack"-version = "0.6.9"+version = "0.6.10"source = { editable = "integrations/sie_haystack" }dependencies = [{ name = "haystack-ai" },@@ -5986,7 +5986,7 @@ requires-dist = [[[package]]name = "sie-lancedb"-version = "0.6.9"+version = "0.6.10"source = { editable = "integrations/sie_lancedb" }dependencies = [{ name = "lancedb" },@@ -6013,7 +6013,7 @@ requires-dist = [[[package]]name = "sie-langchain"-version = "0.6.9"+version = "0.6.10"source = { editable = "integrations/sie_langchain" }dependencies = [{ name = "langchain-core" },@@ -6040,7 +6040,7 @@ requires-dist = [[[package]]name = "sie-llamaindex"-version = "0.6.9"+version = "0.6.10"source = { editable = "integrations/sie_llamaindex" }dependencies = [{ name = "llama-index-core" },@@ -6106,7 +6106,7 @@ dev = [[[package]]name = "sie-qdrant"-version = "0.6.9"+version = "0.6.10"source = { editable = "integrations/sie_qdrant" }dependencies = [{ name = "qdrant-client" },@@ -6129,7 +6129,7 @@ requires-dist = [[[package]]name = "sie-sdk"-version = "0.6.9"+version = "0.6.10"source = { editable = "packages/sie_sdk" }dependencies = [{ name = "aiohttp" },@@ -6182,7 +6182,7 @@ requires-dist = [[[package]]name = "sie-server"-version = "0.6.9"+version = "0.6.10"source = { editable = "packages/sie_server" }dependencies = [{ name = "blake3" },@@ -6284,7 +6284,7 @@ requires-dist = [{ name = "torch", marker = "sys_platform == 'linux'", specifier = ">=2.9,<2.10", index = "https://download.pytorch.org/whl/cu129" },{ name = "torchvision", marker = "sys_platform != 'linux'", specifier = ">=0.18,<1" },{ name = "torchvision", marker = "sys_platform == 'linux'", specifier = ">=0.18,<1", index = "https://download.pytorch.org/whl/cu129" },- { name = "transformers", specifier = ">=4.57,<5" },+ { name = "transformers", specifier = ">=4.57,<6" },{ name = "typer", specifier = ">=0.14,<1" },{ name = "uvicorn", extras = ["standard"], specifier = ">=0.32,<1" },{ name = "uvloop", specifier = ">=0.22" },@@ -6312,7 +6312,7 @@ requires-dist = [[[package]]name = "sie-weaviate"-version = "0.6.9"+version = "0.6.10"source = { editable = "integrations/sie_weaviate" }dependencies = [{ name = "sie-sdk" },