Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
feat(gateway): run the standalone gateway as a multi-replica service on Redis (#6513)
t0saki026f1a23b887
diff --git a/.github/workflows/gateway-chart.yml b/.github/workflows/gateway-chart.ymlnew file mode 100644index 000000000..693fcebe1--- /dev/null+++ b/.github/workflows/gateway-chart.yml@@ -0,0 +1,25 @@+name: OpenViking Gateway Chart+on:+ pull_request:+ paths:+ - "deploy/helm/openviking-gateway/**"+ - "Dockerfile"+ - "openviking_gateway/**"+ - "openviking_cli/utils/config/encryption_config.py"+ - "openviking_cli/utils/config/agfs_config.py"+ - "scripts/gateway_chart_check.py"+ - ".github/workflows/gateway-chart.yml"+ workflow_dispatch:+jobs:+ chart:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-python@v5+ with:+ python-version: "3.10"+ - uses: azure/[email protected]+ with:+ version: v3.17.3+ - run: pip install "pydantic>=2" "packaging>=24" "json-repair>=0.25" "loguru>=0.7" "aiohttp>=3.13.3" "orjson>=3.11.7" PyYAML+ - run: PYTHONPATH=. python scripts/gateway_chart_check.pydiff --git a/.github/workflows/gateway-e2e.yml b/.github/workflows/gateway-e2e.ymlnew file mode 100644index 000000000..2a8f80a68--- /dev/null+++ b/.github/workflows/gateway-e2e.yml@@ -0,0 +1,72 @@+name: OpenViking Gateway kind acceptance+on:+ schedule:+ - cron: "17 2 * * *"+ workflow_dispatch:+ inputs:+ ref:+ description: "Git ref to test (empty uses the selected workflow ref)"+ required: false+ overlay:+ description: "Build the selected ref over the release image"+ type: boolean+ default: true+ base_ref:+ description: "Release tag of the overlay base image (empty uses build_overlay.py's default)"+ required: false+permissions:+ contents: read+jobs:+ kind:+ runs-on: ubuntu-latest+ timeout-minutes: 65+ env:+ OV_TEST_KIND_KUBECONFIG: ${{ runner.temp }}/kubeconfig+ OV_TEST_GATEWAY_IMAGE: ghcr.io/volcengine/openviking:main+ steps:+ - uses: actions/checkout@v4+ with:+ ref: ${{ inputs.ref || github.ref }}+ fetch-depth: 0+ - uses: actions/setup-python@v5+ with:+ python-version: "3.13"+ - uses: azure/[email protected]+ with:+ version: v3.17.3+ - uses: actions/setup-node@v4+ with:+ node-version: "22"+ - name: Install test clients and kind+ run: |+ pip install pytest httpx openai==3.37.0 anthropic==2.2.0+ npm install --global @openai/[email protected]+ curl -fsSL https://kind.sigs.k8s.io/dl/v0.27.0/kind-linux-amd64 -o /usr/local/bin/kind+ chmod +x /usr/local/bin/kind+ mkdir -p artifacts+ - name: Create dedicated three-node cluster+ run: kind create cluster --name ovgw-e2e --config tests/gateway/e2e/kind.yaml --kubeconfig "$OV_TEST_KIND_KUBECONFIG" --wait 120s+ - name: Build source overlay for a manual run+ if: github.event_name == 'workflow_dispatch' && inputs.overlay+ env:+ BASE_REF: ${{ inputs.base_ref }}+ run: |+ python tests/gateway/e2e/build_overlay.py ${BASE_REF:+--base-ref "$BASE_REF"} --tag ovgw-e2e:local+ echo 'OV_TEST_GATEWAY_IMAGE=ovgw-e2e:local' >> "$GITHUB_ENV"+ - name: Load test images+ run: |+ docker image inspect "$OV_TEST_GATEWAY_IMAGE" >/dev/null 2>&1 || docker pull "$OV_TEST_GATEWAY_IMAGE"+ docker pull redis:7.2-alpine+ python tests/gateway/e2e/load_images.py --cluster ovgw-e2e "$OV_TEST_GATEWAY_IMAGE" redis:7.2-alpine+ - name: Run standalone and Cluster matrices+ run: pytest tests/gateway/e2e --confcutdir=tests/gateway/e2e -o addopts='' -v --basetemp=artifacts/pytest --junitxml=artifacts/results.xml+ - name: Collect cluster evidence+ if: always()+ run: |+ kind export logs artifacts/kind --name ovgw-e2e || true+ kubectl --kubeconfig "$OV_TEST_KIND_KUBECONFIG" get pods -A -o wide > artifacts/pods.txt || true+ - uses: actions/upload-artifact@v4+ if: always()+ with:+ name: gateway-kind-evidence+ path: artifactsdiff --git a/.github/workflows/gateway.yml b/.github/workflows/gateway.ymlindex 4d6505f48..8f4a3004b 100644--- a/.github/workflows/gateway.yml+++ b/.github/workflows/gateway.yml@@ -1,11 +1,23 @@name: OpenViking Gatewayon:pull_request:- paths: ["openviking_gateway/**", "tests/gateway/**", "scripts/gateway_*", "tests/fixtures/gateway_upstream_urls.json", "openviking_cli/utils/config/openviking_gateway_config.py", "openviking_cli/utils/config/encryption_config.py", "openviking_cli/setup_wizard.py", "openviking/crypto/**", ".github/workflows/gateway.yml"]+ paths: ["openviking_gateway/**", "tests/gateway/**", "scripts/gateway_*", "tests/fixtures/gateway_upstream_urls.json", "openviking_cli/utils/config/openviking_gateway_config.py", "openviking_cli/utils/config/encryption_config.py", "openviking_cli/utils/config/agfs_config.py", "openviking/server/account_stores/redis_client.py", "pyproject.toml", "MANIFEST.in", "openviking_cli/setup_wizard.py", "openviking/crypto/**", ".github/workflows/gateway.yml"]workflow_dispatch:jobs:test:runs-on: ubuntu-latest+ services:+ redis:+ image: redis:7.2+ ports: ["6379:6379"]+ options: >-+ --health-cmd "redis-cli ping"+ --health-interval 2s --health-timeout 2s --health-retries 20+ env:+ OV_TEST_REDIS: redis://127.0.0.1:6379+ OV_TEST_REDIS_CLUSTER: redis://127.0.0.1:7000,redis://127.0.0.1:7001,redis://127.0.0.1:7002+ OV_TEST_REDIS_USERNAME: gateway+ OV_TEST_REDIS_PASSWORD: gateway-test-passwordsteps:- uses: actions/checkout@v4- uses: actions/setup-python@v5@@ -13,5 +25,41 @@ jobs:python-version: "3.10"# The gateway talks to OpenViking over HTTP and reuses only its pure-Python crypto# module, so its tests run from the source tree without building the native wheel.- - run: pip install "aiohttp>=3.13.3" "async-timeout>=5.0.1" "orjson>=3.11.7" "packaging>=24.0" "fastapi>=0.128.0" "uvicorn>=0.39.0" "pydantic>=2.0.0" "httpx>=0.25.0" "cryptography>=48.0.1" "json-repair>=0.25.0" "loguru>=0.7.3" "mcp>=1.27,<2" pytest pytest-asyncio+ - run: pip install "aiohttp>=3.13.3" "async-timeout>=5.0.1" "orjson>=3.11.7" "packaging>=24.0" "fastapi>=0.128.0" "uvicorn>=0.39.0" "pydantic>=2.0.0" "httpx>=0.25.0" "cryptography>=48.0.1" "json-repair>=0.25.0" "loguru>=0.7.3" "mcp>=1.27,<2" "redis==6.4.0" pytest pytest-asyncio+ - name: Start Redis Cluster and configure the gateway ACL+ shell: bash+ run: |+ set -euo pipefail+ for port in 7000 7001 7002; do+ docker run -d --network host --name gateway-redis-$port redis:7.2 \+ redis-server --port "$port" --cluster-enabled yes \+ --cluster-config-file nodes.conf --cluster-node-timeout 5000 \+ --cluster-announce-ip 127.0.0.1 --appendonly no+ done+ for port in 7000 7001 7002; do+ for attempt in {1..30}; do+ if docker exec gateway-redis-$port redis-cli -p "$port" ping; then break; fi+ sleep 1+ done+ done+ docker exec gateway-redis-7000 redis-cli --cluster create \+ 127.0.0.1:7000 127.0.0.1:7001 127.0.0.1:7002 --cluster-yes+ for port in 7000 7001 7002; do+ for attempt in {1..30}; do+ state=$(docker exec gateway-redis-$port redis-cli -p "$port" cluster info)+ if [[ "$state" == *cluster_state:ok* ]]; then break; fi+ sleep 1+ done+ [[ "$state" == *cluster_state:ok* ]]+ done+ for port in 6379 7000 7001 7002; do+ docker run --rm --network host redis:7.2 redis-cli -p "$port" ACL SETUSER \+ gateway reset on '>gateway-test-password' '~ovgw:*' \+ +@read +@write +@scripting +@connection +@transaction \+ +ping +time +scan +unlink '+cluster|slots' '+cluster|shards'+ done- run: PYTHONPATH=. pytest tests/gateway --confcutdir=tests/gateway -o addopts=''+ # Only the storage ports touch redis-py directly; check them on the oldest supported client.+ - run: |+ pip install "redis==5.3.1"+ PYTHONPATH=. pytest tests/gateway/test_storage_ports.py --confcutdir=tests/gateway -o addopts=''diff --git a/Dockerfile b/Dockerfileindex fca8de8ed..9694bfd3f 100644--- a/Dockerfile+++ b/Dockerfile@@ -123,6 +123,8 @@ PYCODE# Fail the image build if VikingBot and the separately released SDK drift apart.RUN /app/.venv/bin/python -I -c "import inspect, typing; from importlib.metadata import version; from openviking_sdk.client import AsyncHTTPClient; from openviking_sdk.options import BatchWriteOptions; checks = {'get_skill.include_integrity': 'include_integrity' in inspect.signature(AsyncHTTPClient.get_skill).parameters, 'ls.offset': 'offset' in inspect.signature(AsyncHTTPClient.ls).parameters, 'grep.level_limit': 'level_limit' in inspect.signature(AsyncHTTPClient.grep).parameters, 'BatchWriteOptions.skip_conflicts': 'skip_conflicts' in typing.get_type_hints(BatchWriteOptions)}; missing = [name for name, ok in checks.items() if not ok]; raise SystemExit(f\"incompatible openviking-sdk {version('openviking-sdk')}: missing {', '.join(missing)}\" if missing else 0)"RUN /app/.venv/bin/python -I -c "from importlib.util import find_spec; from pathlib import Path; spec = find_spec('openviking.web_studio'); locations = list(spec.submodule_search_locations or ()) if spec else []; root = Path('/app/.venv').resolve(); p = (Path(locations[0]).resolve() / 'dist/index.html').resolve() if len(locations) == 1 else None; valid = p is not None and p.is_file() and p.is_relative_to(root); raise SystemExit(0 if valid else f'missing or misplaced Studio bundle: spec_found={spec is not None}, locations={locations!r}, resource={p}')"+# Redis and the gateway Lua scripts must survive wheel packaging.+RUN /app/.venv/bin/python -I -c "import redis; from importlib.resources import files; assert any(p.name.endswith('.lua') for p in files('openviking_gateway').joinpath('lua').iterdir()), 'gateway Lua scripts missing from installed package'"COPY deploy/docker/openviking-entrypoint.sh /usr/local/bin/openviking-entrypointCOPY deploy/docker/pending_health_server.py /usr/local/bin/openviking-pending-healthRUN mkdir -p /app/.openviking \diff --git a/MANIFEST.in b/MANIFEST.inindex 69d225fbc..1279412b8 100644--- a/MANIFEST.in+++ b/MANIFEST.in@@ -24,3 +24,5 @@ global-exclude __pycache__global-exclude .git*global-exclude .DS_Storeprune src/build++recursive-include openviking_gateway *.luadiff --git a/deploy/helm/README.md b/deploy/helm/README.mdindex e25a7928f..9c9901cf1 100644--- a/deploy/helm/README.md+++ b/deploy/helm/README.md@@ -226,6 +226,54 @@ setting only after switching to a remote vectordb backend such as VikingDB.For deployment, Studio management, backups and troubleshooting, see[OpenViking Gateway deployment and operations](https://docs.openviking.ai/en/guides/22-gateway-operations).+## Standalone OpenViking Gateway++Use `deploy/helm/openviking-gateway` when the gateway needs independent replicas,+rollouts and a Service. The `openviking` chart's `gateway.enabled` runs inside the+OpenViking Server and follows its single-replica lifecycle; it is still the+simplest choice when you operate both together.++The standalone chart targets unreleased gateway features: until `appVersion`+names a published release, `image.tag` is required and must name a compatible build.+To release the chart, set `appVersion` to the release without the `v` and bump `version`,+then run `PYTHONPATH=. python scripts/gateway_chart_check.py` and the gateway kind suite+(`tests/gateway/e2e`) against that release image.++```bash+helm upgrade --install gateway ./deploy/helm/openviking-gateway \+ --set-string image.tag='<gateway-image-tag>' \+ --set-string config.openviking_url=https://ov.example.com+```++By default this creates a single SQLite replica, PVC, and ClusterIP Service on+port 80, forwarding to 1935. `config` renders a JSON `gateway.conf`; `host`, `port`+and `storage_path` are fixed by the chart. The OpenViking endpoint must use API-key+authentication. A default StorageClass is sufficient, or select one with+`persistence.storageClass` or use `persistence.existingClaim`.++Set both `config.storage.kernel` and `config.storage.management` to `redis`, and+set `config.storage.redis` (endpoints, `password_env: OPENVIKING_GATEWAY_REDIS_PASSWORD`),+before increasing `replicaCount`. Redis deployments use RollingUpdate and do+not create a PVC; multiple replicas get a PDB. SQLite uses Recreate and rejects+multiple replicas. Disabling persistence uses emptyDir and loses SQLite state+when the Pod is replaced. PVCs are retained after uninstall.++Use `existingSecret` entries `management-key`, `redis-password` and `root-key`+for the management credential, Redis password and encryption root key. Local+and KMS encryption require a pre-generated root key, shared read-only by all+replicas. Other credentials use `$VAR` references in `config` and `extraEnv`+with `secretKeyRef`. External Secret changes require a Deployment restart.++The chart provides no Ingress. Its Service and Deployment share a name; use+`fullnameOverride` to pin it. The stable selectors are `app.kubernetes.io/name`+and `app.kubernetes.io/instance`. `service.type`, `service.loadBalancerSourceRanges`,+and optional `networkPolicy.ingressFrom` support external routing. All probes+use `/health`; startup allows 300 seconds, preStop sleeps 15 seconds, and the+default termination grace is 660 seconds.++For Redis settings, encryption key creation, a complete multi-replica values+example, shutdown timing and operations, see the [gateway operations guide](../../docs/en/guides/22-gateway-operations.md#helm).+## Configuration| Parameter | Description | Default |diff --git a/deploy/helm/openviking-gateway/.helmignore b/deploy/helm/openviking-gateway/.helmignorenew file mode 100644index 000000000..c885071b1--- /dev/null+++ b/deploy/helm/openviking-gateway/.helmignore@@ -0,0 +1,3 @@+.git/+.DS_Store+ci/diff --git a/deploy/helm/openviking-gateway/Chart.yaml b/deploy/helm/openviking-gateway/Chart.yamlnew file mode 100644index 000000000..a62db7132--- /dev/null+++ b/deploy/helm/openviking-gateway/Chart.yaml@@ -0,0 +1,8 @@+apiVersion: v2+name: openviking-gateway+description: Standalone OpenViking Gateway with SQLite or shared Redis storage+type: application+version: 0.1.0-dev.0+# Replace only after a release containing the Redis gateway has been published.+appVersion: "0.0.0-unreleased"+kubeVersion: ">=1.24.0-0"diff --git a/deploy/helm/openviking-gateway/ci/redis.yaml b/deploy/helm/openviking-gateway/ci/redis.yamlnew file mode 100644index 000000000..15412d757--- /dev/null+++ b/deploy/helm/openviking-gateway/ci/redis.yaml@@ -0,0 +1,14 @@+image:+ tag: ci+replicaCount: 2+existingSecret: gateway-credentials+config:+ storage:+ kernel: redis+ management: redis+ redis:+ endpoints: ["redis://redis:6379"]+ password_env: OPENVIKING_GATEWAY_REDIS_PASSWORD+ encryption:+ enabled: true+ provider: localdiff --git a/deploy/helm/openviking-gateway/ci/sqlite-invalid.yaml b/deploy/helm/openviking-gateway/ci/sqlite-invalid.yamlnew file mode 100644index 000000000..f14c712db--- /dev/null+++ b/deploy/helm/openviking-gateway/ci/sqlite-invalid.yaml@@ -0,0 +1,3 @@+image:+ tag: ci+replicaCount: 2diff --git a/deploy/helm/openviking-gateway/ci/sqlite.yaml b/deploy/helm/openviking-gateway/ci/sqlite.yamlnew file mode 100644index 000000000..787591acf--- /dev/null+++ b/deploy/helm/openviking-gateway/ci/sqlite.yaml@@ -0,0 +1,2 @@+image:+ tag: cidiff --git a/deploy/helm/openviking-gateway/templates/NOTES.txt b/deploy/helm/openviking-gateway/templates/NOTES.txtnew file mode 100644index 000000000..52c68fa23--- /dev/null+++ b/deploy/helm/openviking-gateway/templates/NOTES.txt@@ -0,0 +1,7 @@+Gateway Service: {{ include "openviking-gateway.fullname" . }}:{{ .Values.service.port }}+Model API: /gateway/v1; health: /health++{{- if and (include "openviking-gateway.sqlite" .) (not .Values.persistence.enabled) }}+WARNING: SQLite is on emptyDir. Pod replacement loses upstreams, issued keys,+profiles, conversation state, and pending captures. Enable persistence to retain them.+{{- end }}diff --git a/deploy/helm/openviking-gateway/templates/_helpers.tpl b/deploy/helm/openviking-gateway/templates/_helpers.tplnew file mode 100644index 000000000..5631edc2f--- /dev/null+++ b/deploy/helm/openviking-gateway/templates/_helpers.tpl@@ -0,0 +1,44 @@+{{- define "openviking-gateway.name" -}}+{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" -}}+{{- end -}}++{{- define "openviking-gateway.fullname" -}}+{{- if .Values.fullnameOverride -}}+{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" -}}+{{- else -}}+{{- $name := include "openviking-gateway.name" . -}}+{{- if contains $name .Release.Name -}}+{{- .Release.Name | trunc 63 | trimSuffix "-" -}}+{{- else -}}+{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" -}}+{{- end -}}+{{- end -}}+{{- end -}}++{{- define "openviking-gateway.selectorLabels" -}}+app.kubernetes.io/name: {{ include "openviking-gateway.name" . }}+app.kubernetes.io/instance: {{ .Release.Name }}+{{- end -}}++{{- define "openviking-gateway.labels" -}}+helm.sh/chart: {{ printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }}+{{ include "openviking-gateway.selectorLabels" . }}+app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}+app.kubernetes.io/managed-by: {{ .Release.Service }}+{{- end -}}++{{- define "openviking-gateway.image" -}}+{{- $tag := default (printf "v%s" .Chart.AppVersion) .Values.image.tag -}}+{{- if eq .Chart.AppVersion "0.0.0-unreleased" -}}+{{- $tag = required "image.tag is required: no release containing this gateway chart's configuration has been published yet" .Values.image.tag -}}+{{- end -}}+{{- printf "%s:%s" .Values.image.repository $tag -}}+{{- end -}}++{{- define "openviking-gateway.sqlite" -}}+{{- if or (eq .Values.config.storage.kernel "sqlite") (eq .Values.config.storage.management "sqlite") -}}true{{- end -}}+{{- end -}}++{{- define "openviking-gateway.rootKey" -}}+{{- if and .Values.config.encryption.enabled (has .Values.config.encryption.provider (list "local" "volcengine_kms")) -}}true{{- end -}}+{{- end -}}diff --git a/deploy/helm/openviking-gateway/templates/configmap.yaml b/deploy/helm/openviking-gateway/templates/configmap.yamlnew file mode 100644index 000000000..ffafad464--- /dev/null+++ b/deploy/helm/openviking-gateway/templates/configmap.yaml@@ -0,0 +1,19 @@+{{- $config := deepCopy .Values.config -}}+{{- $_ := set $config "host" "0.0.0.0" -}}+{{- $_ := set $config "port" 1935 -}}+{{- $_ := set $config "storage_path" "/app/.openviking/gateway" -}}+{{- if include "openviking-gateway.rootKey" . -}}+{{- $provider := $config.encryption.provider -}}+{{- $settings := index $config.encryption $provider | default dict -}}+{{- $_ := set $settings "key_file" "/etc/openviking-gateway/keys/root-key" -}}+{{- $_ := set $config.encryption $provider $settings -}}+{{- end -}}+apiVersion: v1+kind: ConfigMap+metadata:+ name: {{ include "openviking-gateway.fullname" . }}-config+ labels:+ {{- include "openviking-gateway.labels" . | nindent 4 }}+data:+ gateway.conf: |+ {{- $config | toPrettyJson | nindent 4 }}diff --git a/deploy/helm/openviking-gateway/templates/deployment.yaml b/deploy/helm/openviking-gateway/templates/deployment.yamlnew file mode 100644index 000000000..aff5286d8--- /dev/null+++ b/deploy/helm/openviking-gateway/templates/deployment.yaml@@ -0,0 +1,129 @@+{{- $sqlite := include "openviking-gateway.sqlite" . -}}+{{- if and $sqlite (gt (int .Values.replicaCount) 1) -}}+{{- fail "SQLite storage requires replicaCount: 1; set both config.storage.kernel and config.storage.management to redis for multiple replicas" -}}+{{- end -}}+apiVersion: apps/v1+kind: Deployment+metadata:+ name: {{ include "openviking-gateway.fullname" . }}+ labels:+ {{- include "openviking-gateway.labels" . | nindent 4 }}+spec:+ replicas: {{ .Values.replicaCount }}+ strategy:+ {{- if $sqlite }}+ type: Recreate+ {{- else }}+ type: RollingUpdate+ rollingUpdate:+ maxUnavailable: 0+ maxSurge: 1+ {{- end }}+ selector:+ matchLabels:+ {{- include "openviking-gateway.selectorLabels" . | nindent 6 }}+ template:+ metadata:+ labels:+ {{- mergeOverwrite (deepCopy .Values.podLabels) (include "openviking-gateway.selectorLabels" . | fromYaml) | toYaml | nindent 8 }}+ annotations:+ {{- $checksum := include (print $.Template.BasePath "/configmap.yaml") . | sha256sum }}+ {{- mergeOverwrite (deepCopy .Values.podAnnotations) (dict "checksum/config" $checksum) | toYaml | nindent 8 }}+ spec:+ enableServiceLinks: false+ automountServiceAccountToken: false+ terminationGracePeriodSeconds: {{ .Values.terminationGracePeriodSeconds }}+ {{- with .Values.imagePullSecrets }}+ imagePullSecrets:+ {{- toYaml . | nindent 8 }}+ {{- end }}+ containers:+ - name: gateway+ image: {{ include "openviking-gateway.image" . | quote }}+ imagePullPolicy: {{ .Values.image.pullPolicy }}+ args: ["openviking-gateway"]+ ports:+ - name: http+ containerPort: 1935+ env:+ - name: OPENVIKING_GATEWAY_CONFIG_FILE+ value: /etc/openviking-gateway/gateway.conf+ {{- if .Values.existingSecret }}+ - name: OPENVIKING_GATEWAY_MANAGEMENT_KEY+ valueFrom:+ secretKeyRef:+ name: {{ .Values.existingSecret }}+ key: management-key+ optional: true+ - name: OPENVIKING_GATEWAY_REDIS_PASSWORD+ valueFrom:+ secretKeyRef:+ name: {{ .Values.existingSecret }}+ key: redis-password+ optional: true+ {{- end }}+ {{- with .Values.extraEnv }}+ {{- toYaml . | nindent 12 }}+ {{- end }}+ lifecycle:+ preStop:+ exec:+ command: ["sleep", "15"]+ startupProbe:+ {{- toYaml .Values.startupProbe | nindent 12 }}+ livenessProbe:+ {{- toYaml .Values.livenessProbe | nindent 12 }}+ readinessProbe:+ {{- toYaml .Values.readinessProbe | nindent 12 }}+ resources:+ {{- toYaml .Values.resources | nindent 12 }}+ volumeMounts:+ - name: config+ mountPath: /etc/openviking-gateway/gateway.conf+ subPath: gateway.conf+ readOnly: true+ - name: data+ mountPath: /app/.openviking+ {{- if include "openviking-gateway.rootKey" . }}+ - name: root-key+ mountPath: /etc/openviking-gateway/keys+ readOnly: true+ {{- end }}+ {{- with .Values.extraVolumeMounts }}+ {{- toYaml . | nindent 12 }}+ {{- end }}+ volumes:+ - name: config+ configMap:+ name: {{ include "openviking-gateway.fullname" . }}-config+ - name: data+ {{- if and $sqlite .Values.persistence.enabled }}+ persistentVolumeClaim:+ claimName: {{ default (printf "%s-data" (include "openviking-gateway.fullname" .)) .Values.persistence.existingClaim }}+ {{- else }}+ emptyDir: {}+ {{- end }}+ {{- if include "openviking-gateway.rootKey" . }}+ - name: root-key+ secret:+ defaultMode: 0600+ secretName: {{ required "existingSecret must contain root-key for local/KMS encryption" .Values.existingSecret }}+ items:+ - key: root-key+ path: root-key+ {{- end }}+ {{- with .Values.extraVolumes }}+ {{- toYaml . | nindent 8 }}+ {{- end }}+ {{- with .Values.nodeSelector }}+ nodeSelector:+ {{- toYaml . | nindent 8 }}+ {{- end }}+ {{- with .Values.affinity }}+ affinity:+ {{- toYaml . | nindent 8 }}+ {{- end }}+ {{- with .Values.tolerations }}+ tolerations:+ {{- toYaml . | nindent 8 }}+ {{- end }}diff --git a/deploy/helm/openviking-gateway/templates/networkpolicy.yaml b/deploy/helm/openviking-gateway/templates/networkpolicy.yamlnew file mode 100644index 000000000..237736fbe--- /dev/null+++ b/deploy/helm/openviking-gateway/templates/networkpolicy.yaml@@ -0,0 +1,23 @@+{{- if .Values.networkPolicy.enabled }}+apiVersion: networking.k8s.io/v1+kind: NetworkPolicy+metadata:+ name: {{ include "openviking-gateway.fullname" . }}+ labels:+ {{- include "openviking-gateway.labels" . | nindent 4 }}+spec:+ podSelector:+ matchLabels:+ {{- include "openviking-gateway.selectorLabels" . | nindent 6 }}+ policyTypes: [Ingress]+ {{- if .Values.networkPolicy.ingressFrom }}+ ingress:+ - from:+ {{- toYaml .Values.networkPolicy.ingressFrom | nindent 8 }}+ ports:+ - protocol: TCP+ port: 1935+ {{- else }}+ ingress: []+ {{- end }}+{{- end }}diff --git a/deploy/helm/openviking-gateway/templates/pdb.yaml b/deploy/helm/openviking-gateway/templates/pdb.yamlnew file mode 100644index 000000000..c2d0e8a51--- /dev/null+++ b/deploy/helm/openviking-gateway/templates/pdb.yaml@@ -0,0 +1,13 @@+{{- if gt (int .Values.replicaCount) 1 }}+apiVersion: policy/v1+kind: PodDisruptionBudget+metadata:+ name: {{ include "openviking-gateway.fullname" . }}+ labels:+ {{- include "openviking-gateway.labels" . | nindent 4 }}+spec:+ maxUnavailable: 1+ selector:+ matchLabels:+ {{- include "openviking-gateway.selectorLabels" . | nindent 6 }}+{{- end }}diff --git a/deploy/helm/openviking-gateway/templates/pvc.yaml b/deploy/helm/openviking-gateway/templates/pvc.yamlnew file mode 100644index 000000000..b1e49279d--- /dev/null+++ b/deploy/helm/openviking-gateway/templates/pvc.yaml@@ -0,0 +1,18 @@+{{- if and (include "openviking-gateway.sqlite" .) .Values.persistence.enabled (not .Values.persistence.existingClaim) }}+apiVersion: v1+kind: PersistentVolumeClaim+metadata:+ name: {{ include "openviking-gateway.fullname" . }}-data+ annotations:+ helm.sh/resource-policy: keep+ labels:+ {{- include "openviking-gateway.labels" . | nindent 4 }}+spec:+ accessModes: [{{ .Values.persistence.accessMode | quote }}]+ {{- with .Values.persistence.storageClass }}+ storageClassName: {{ . | quote }}+ {{- end }}+ resources:+ requests:+ storage: {{ .Values.persistence.size }}+{{- end }}diff --git a/deploy/helm/openviking-gateway/templates/service.yaml b/deploy/helm/openviking-gateway/templates/service.yamlnew file mode 100644index 000000000..6cf0c4250--- /dev/null+++ b/deploy/helm/openviking-gateway/templates/service.yaml@@ -0,0 +1,22 @@+apiVersion: v1+kind: Service+metadata:+ name: {{ include "openviking-gateway.fullname" . }}+ labels:+ {{- include "openviking-gateway.labels" . | nindent 4 }}+ {{- with .Values.service.annotations }}+ annotations:+ {{- toYaml . | nindent 4 }}+ {{- end }}+spec:+ type: {{ .Values.service.type }}+ {{- with .Values.service.loadBalancerSourceRanges }}+ loadBalancerSourceRanges:+ {{- toYaml . | nindent 4 }}+ {{- end }}+ ports:+ - name: http+ port: {{ .Values.service.port }}+ targetPort: http+ selector:+ {{- include "openviking-gateway.selectorLabels" . | nindent 4 }}diff --git a/deploy/helm/openviking-gateway/values.yaml b/deploy/helm/openviking-gateway/values.yamlnew file mode 100644index 000000000..c87603c17--- /dev/null+++ b/deploy/helm/openviking-gateway/values.yaml@@ -0,0 +1,82 @@+replicaCount: 1+nameOverride: ""+fullnameOverride: ""+image:+ repository: ghcr.io/volcengine/openviking+ # Required until appVersion names a published release containing these features.+ tag: ""+ pullPolicy: IfNotPresent+imagePullSecrets: []++# Optional management-key and redis-password entries; root-key is required for+# enabled local/KMS encryption. See the operations guide for generating it.+existingSecret: ""+config:+ openviking_url: http://openviking:1933+ # Seven-day retention for sessions and Responses state.+ session_ttl_days: 7+ response_ttl_seconds: 604800+ storage:+ kernel: sqlite+ management: sqlite+ # Redis also needs connection settings, e.g.+ # redis: {endpoints: ["redis://redis:6379"], password_env: OPENVIKING_GATEWAY_REDIS_PASSWORD}+ encryption:+ enabled: false+ provider: local++persistence:+ enabled: true+ existingClaim: ""+ storageClass: ""+ accessMode: ReadWriteOnce+ size: 10Gi++service:+ type: ClusterIP+ port: 80+ annotations: {}+ loadBalancerSourceRanges: []+networkPolicy:+ enabled: false+ # Kubernetes NetworkPolicyPeer entries, e.g. podSelector or ipBlock.+ # Empty denies incoming traffic when the policy is enabled.+ ingressFrom: []++terminationGracePeriodSeconds: 660+resources:+ requests:+ cpu: 500m+ memory: 1Gi+ limits:+ cpu: "2"+ memory: 4Gi+startupProbe:+ httpGet:+ path: /health+ port: http+ periodSeconds: 2+ failureThreshold: 150+ timeoutSeconds: 2+livenessProbe:+ httpGet:+ path: /health+ port: http+ periodSeconds: 30+ timeoutSeconds: 5+readinessProbe:+ httpGet:+ path: /health+ port: http+ periodSeconds: 5+ timeoutSeconds: 5++# Inject other credentials through secretKeyRef and refer to them as $VAR in config.+extraEnv: []+extraVolumes: []+extraVolumeMounts: []+podLabels: {}+podAnnotations: {}+nodeSelector: {}+affinity: {}+tolerations: []diff --git a/docs/en/about/02-changelog.md b/docs/en/about/02-changelog.mdindex eee9c12ff..35f380241 100644--- a/docs/en/about/02-changelog.md+++ b/docs/en/about/02-changelog.md@@ -7,6 +7,26 @@ This changelog is automatically generated from [GitHub Releases](https://github.## Unreleased+- **Gateway deployment and behavior**:+ - New standalone Helm chart, `deploy/helm/openviking-gateway`: one SQLite replica with a+ PVC, or several replicas sharing Redis. Until a release includes these features, set+ `image.tag` explicitly; see the [operations guide](../guides/22-gateway-operations.md#helm).+ - New opt-in settings: `storage` (Redis), `management_api`, `openviking_keys`, `tenancy`,+ `default_upstreams` and `default_profile`, `request_log_sink`, `capture_concurrency` and `keep_alive_seconds`.+ SQLite remains the default storage.+ - New `X-OpenViking-Upstream-URL` request header picks one of the allowed upstreams by its+ Base URL; see [Pick the upstream per request](../gateway/07-upstreams.md#upstream-url-header).+ - Behavior changes with no configuration change: standalone keep-alive rises from 5 to 75+ seconds; a gateway bound to a public address waits and retries at startup while+ OpenViking is unreachable or returns 5xx; idle SSE streams carry a comment heartbeat every+ 15 seconds; a request whose key OpenViking refuses with 402 or 403 is rejected instead of+ forwarded; and an OpenViking 401 while saving, once `/health` also returns 401, pauses+ saving with `gateway_key_revoked`.+- **Volcengine KMS `key_file` (upgrade action)**: `encryption.volcengine_kms.key_file` now takes+ effect for the server and the gateway; earlier releases ignored it and kept the root key at+ `~/.openviking/openviking-volcengine-root-key.enc`. If you set `key_file`, move that file to+ the configured path before upgrading. While the configured file is missing and the default+ one exists, startup fails instead of creating a new root key.- **LangChain import migration (breaking change)**: The server no longer ships`openviking.integrations.langchain` or its forwarding modules. Old imports failimmediately; there is no deprecation period or compatibility stub. Installdiff --git a/docs/en/gateway/01-how-it-works.md b/docs/en/gateway/01-how-it-works.mdindex 886c85e60..23dccd8c0 100644--- a/docs/en/gateway/01-how-it-works.md+++ b/docs/en/gateway/01-how-it-works.md@@ -132,8 +132,8 @@ The table explains why the gateway's main design choices were made and what they| Where memory goes | At the end of the newest user message, not in the system prompt: one changed character in the system prompt invalidates the whole cache, while appending at the end and replaying unchanged keeps the prefix stable. | The gateway must reliably record the exact text of every addition; a lost record costs one cache miss. || When turns are saved | One turn behind: only when the next message brings the previous turn back is it clear the user kept it. | The last turn is saved only after **Save the latest reply after** (10 minutes by default). || Long conversations | The gateway has the same model write the summary: only the gateway knows what the model actually received, and the summary request mostly hits the cache. | The turn that triggers compaction costs one extra, billed model call; text before the cut is no longer sent to the model. |-| Local state | SQLite on one host, with no Postgres or Redis dependency, which suits self-hosting. | The gateway cannot fail over between machines and is a single point on the model call path. |-| Client identity | The gateway issues its own keys instead of using OpenViking keys directly: they can be revoked on their own, and one person's clients can use different context profiles. | The gateway has to store users' OpenViking keys, so turn on encryption; a leaked gateway key exposes that user's memory. |+| Storage | SQLite by default, with no external dependency; Redis can share state between hosts. | Multiple replicas require both storage ports to use shared Redis and the same encryption root key. |+| Client identity | By default the gateway issues its own keys instead of using OpenViking keys directly: they can be revoked on their own, and one person's clients can use different context profiles. With `openviking_keys` on, clients can also use OpenViking API keys directly, which take the account's default profile and upstreams. | The gateway has to store users' OpenViking keys, so turn on encryption; a leaked gateway key exposes that user's memory. An OpenViking key used directly can only be revoked in OpenViking. |## Next steps {#next-steps}diff --git a/docs/en/gateway/03-connect-clients.md b/docs/en/gateway/03-connect-clients.mdindex 8b2064030..9602a347b 100644--- a/docs/en/gateway/03-connect-clients.md+++ b/docs/en/gateway/03-connect-clients.md@@ -4,7 +4,7 @@ description: Point Claude Code, Codex, chat apps, SDKs and other clients at Open# Connect clients to OpenViking Gateway-This page gives the exact settings for each client and a way to check that they work. Every client needs three things: the gateway address, a gateway key, and an enabled upstream bound to that key that speaks the client's protocol and serves the model it requests. No gateway key yet? Start with [Get started](02-quickstart.md).+This page gives the exact settings for each client and a way to check that they work. Every client needs three things: the gateway address, a gateway key (or, when the deployment turns on `openviking_keys`, the user's OpenViking API key; see [Use an OpenViking API key directly](09-gateway-keys.md#openviking-keys)), and an enabled upstream bound to that key that speaks the client's protocol and serves the model it requests. No gateway key yet? Start with [Get started](02-quickstart.md).Two limits apply to every client:@@ -32,12 +32,22 @@ The last column is explained in [How conversations are recognized](#how-conversaBy default the gateway holds the provider API key, and clients send only the gateway key. An [upstream](07-upstreams.md#upstreams) can instead have **Who provides the API key** set to **Each client sends its own key** (see [Credentials](07-upstreams.md#credentials)). Then the client keeps the gateway key in its usual API key setting and also sends its own provider API key in an `X-OpenViking-Upstream-Key` header on every request. In Studio, the **Bring your own provider key** card on the **Connect** tab lists which of your upstreams need it.-Without the header, every request fails with 401 `Upstream API key is missing`. To add it:+Without the header, every request fails with 401 `Upstream API key is missing`. How each client sends it is in [Add a header to a client](#add-a-header).-| Client | How to send `X-OpenViking-Upstream-Key` |+## Override profile settings {#override-profile-settings}++A client can change the settings of its key's context profile for a new conversation with an `X-OpenViking-Context` header. Its value is a JSON object of the fields to change, for example `{"recall":false}` to skip recall, or `{"disabled_tools":[]}` to offer every OpenViking tool, including the ones that change data. The profile must have **Let clients override settings** on, which is the default; what the header may contain and the errors it can get are in [Let clients override settings](08-context-profiles.md#client-overrides). How each client sends it is in [Add a header to a client](#add-a-header).++A conversation keeps the settings it started with, so a changed header takes effect in the next new conversation, for example with a new `X-OpenViking-Session` value. Like every `X-OpenViking-*` header, it is not forwarded to the provider.++## Add a header to a client {#add-a-header}++The two headers above go on every request. To add one:++| Client | How to add a header || --- | --- |-| Claude Code | `export ANTHROPIC_CUSTOM_HEADERS='X-OpenViking-Upstream-Key: <provider-key>'` |-| Codex CLI | `env_http_headers` in the provider block, for example `env_http_headers = { "X-OpenViking-Upstream-Key" = "PROVIDER_API_KEY" }`, with the key exported as `PROVIDER_API_KEY` |+| Claude Code | `export ANTHROPIC_CUSTOM_HEADERS='<Name>: <value>'`. For several headers, put each on its own line, for example `export ANTHROPIC_CUSTOM_HEADERS=$'X-OpenViking-Upstream-Key: <provider-key>\nX-OpenViking-Context: {"recall":false}'` |+| Codex CLI | In the provider block, `http_headers` for a fixed value, for example `http_headers = { "X-OpenViking-Context" = '{"recall":false}' }`, or `env_http_headers` to read the value from an environment variable, for example `env_http_headers = { "X-OpenViking-Upstream-Key" = "PROVIDER_API_KEY" }` with the provider key exported as `PROVIDER_API_KEY` || OpenAI and Anthropic SDKs | `default_headers` on the client, or `extra_headers` on each request || Open WebUI | Add it to the connection's custom headers, next to the session headers |diff --git a/docs/en/gateway/06-manage-in-studio.md b/docs/en/gateway/06-manage-in-studio.mdindex 4a35f796f..0b69bff18 100644--- a/docs/en/gateway/06-manage-in-studio.md+++ b/docs/en/gateway/06-manage-in-studio.md@@ -6,6 +6,8 @@ description: Find your way around the OpenViking Gateway pages in Studio, see whThis page is for anyone who uses the gateway pages in Studio: what each tab is for, who can change what, and when saved changes take effect. Open Studio with your OpenViking API key (a server in [local dev mode](02-quickstart.md#local-server-no-api-key) needs none) and choose **OpenViking Gateway** in the sidebar; a standalone gateway serves its own Studio at `/studio/`. Upstreams and context profiles are shared by everyone in an OpenViking account, while gateway keys and request logs belong to each user.+With [`management_api: false`](13-configuration.md#gateway-fields), gateway administration is unavailable and the standalone gateway no longer serves Studio. In embedded deployments, OpenViking Server still serves its own Studio, but the gateway pages show an error because `/gateway/admin/access` returns 404. Restart the host after changing this setting.+## Studio tabs {#studio-tabs}The gateway pages have six tabs. Each row links the page that explains the tab in detail.diff --git a/docs/en/gateway/07-upstreams.md b/docs/en/gateway/07-upstreams.mdindex 99e1302e3..b4941e883 100644--- a/docs/en/gateway/07-upstreams.md+++ b/docs/en/gateway/07-upstreams.md@@ -29,6 +29,15 @@ When you choose a provider in the editor, its default Base URL is filled in:| Volcano Engine Ark | All three | `https://ark.cn-beijing.volces.com/api/v3` for Chat Completions and Responses; `https://ark.cn-beijing.volces.com/api/compatible` for Anthropic Messages || BytePlus ModelArk | All three | `https://ark.ap-southeast.bytepluses.com/api/v3` for Chat Completions and Responses; `https://ark.ap-southeast.bytepluses.com/api/compatible` for Anthropic Messages |+## Deployment default upstreams {#deployment-default-upstreams}++Operators can set `default_upstreams` in the gateway configuration for clients that [use OpenViking API keys directly](09-gateway-keys.md#openviking-keys); see the [configuration example](13-configuration.md#gateway-fields).++- Defaults apply only when the account has no stored upstreams. Once it stores any upstream, its stored set replaces the defaults as a whole, even if every stored upstream is disabled.+- Deployment defaults are not copied into account storage and do not appear in Studio. Issued gateway keys continue to use their selected, stored upstreams.+- Keep the object keys, such as `ark-chat`, stable: each key is the upstream ID frozen into conversations and used to route later turns.+- For managed credentials, write `"api_key": "$ARK_API_KEY"` and inject `ARK_API_KEY` from a Secret through `extraEnv` in Helm deployments. The gateway expands environment references when loading the file; keep plaintext API keys out of ConfigMaps.+## Add an upstream {#add-an-upstream}1. On the **Upstreams** tab, choose **Add upstream**. The **New upstream** editor opens with four sections: **Endpoint**, **Credentials**, **Models** and **Routing**.@@ -149,6 +158,15 @@ Turning an upstream off moves the conversations that were using it to the next cThe gateway does not fail over: when the chosen upstream returns an error, the client receives it, and an unreachable provider returns 502 "Model upstream is unavailable".+### Pick the upstream per request {#upstream-url-header}++A service in front of the gateway can choose the upstream for each request with the `X-OpenViking-Upstream-URL` header; clients may send it too. Its value must equal the **Base URL** of an upstream bound to the key (for an OpenViking key without stored upstreams, a [deployment default upstream](#deployment-default-upstreams)); only a trailing `/` is ignored. The header narrows routing to those upstreams, and the usual API, model and **Priority** rules choose among them, so a Chat Completions and a Responses upstream can share one Base URL.++- No bound upstream has that Base URL: the request fails with 403 "Upstream URL is not allowed". The gateway never sends a request to an address that is not configured.+- The gateway uses the selected upstream's credentials as usual. For **Each client sends its own key**, the key comes in `X-OpenViking-Upstream-Key`; a Coding Plan upstream is still rejected unless it is allowed.+- A conversation that names a different Base URL moves to that upstream, flagged **Upstream switched** as when its upstream is turned off.+- Without the header, routing is unchanged. Like every `X-OpenViking-*` header, it is not forwarded to the provider.+### Restore reasoning the client drops {#restore-reasoning}When clients send the history back, they often leave out the reasoning of the model's earlier replies. **Restore reasoning the client drops** is on by default for DeepSeek, Volcano Engine Ark and BytePlus ModelArk, and off for other providers.diff --git a/docs/en/gateway/08-context-profiles.md b/docs/en/gateway/08-context-profiles.mdindex d8a49ae3b..764016d99 100644--- a/docs/en/gateway/08-context-profiles.md+++ b/docs/en/gateway/08-context-profiles.md@@ -8,9 +8,11 @@ In Studio: **Profiles** tab. A context profile decides how OpenViking Gateway re## What a context profile is {#context-profiles}-A [context profile](../guides/15-gateway.md#key-terms) is a named set of memory settings. Each [gateway key](09-gateway-keys.md#gateway-keys) uses one profile, chosen when the key is issued, and one profile can serve many keys. For example, a "Coding" profile might recall memories, resources and skills, while a "Chat" profile recalls only memories, with a smaller budget.+A [context profile](../guides/15-gateway.md#key-terms) is a named set of memory settings. Each [gateway key](09-gateway-keys.md#gateway-keys) uses one profile, chosen when the key is issued, and one profile can serve many keys. Clients that use an [OpenViking API key directly](09-gateway-keys.md#openviking-keys) use the account's profile with the ID `default` (the one Quick mode creates), or the deployment's `default_profile` when there is none; they do not count as keys using it. For example, a "Coding" profile might recall memories, resources and skills, while a "Chat" profile recalls only memories, with a smaller budget.-A profile has four sections. The defaults below are also the recommended settings:+In embedded dev mode, startup seeds `default_profile` into the `default` account once; later edits to `ov.conf` do not change that saved profile, so edit it in Studio.++Besides its name and the [Let clients override settings](#client-overrides) switch, a profile has four sections. The defaults below are also the recommended settings:| Section | What it does | Main settings and defaults || --- | --- | --- |@@ -26,13 +28,13 @@ Saved changes reach only conversations that start afterwards; see [When changes### Create, duplicate or delete a profile {#manage-profiles}1. Open the **Profiles** tab. While it is empty, choose **Create with recommended settings** to create a profile named "Default" in one click, or **Customize** to open the editor first. Once a profile exists, use **New profile** instead.-2. In the editor, enter a **Name**; it is shown when someone chooses a profile for a gateway key. Change the sections described on this page as needed.+2. In the editor, enter a **Name**; it is shown when someone chooses a profile for a gateway key. Below it, **Let clients override settings** is on; see [Let clients override settings](#client-overrides). Change the sections described on this page as needed.3. Choose **Create profile**, or **Save** when you edit an existing one. You should see a card for the profile that summarizes each section and counts the keys that use it (**Not used by any key** at first).Other actions:- **Duplicate**, on a card or in the editor's **More actions** (⋯) menu, opens a copy named "Copy of …". It is the quickest way to make a variant.-- **Reset to recommended**, in the same menu, restores the recommended settings; save to apply them.+- **Reset to recommended**, in the same menu, restores the recommended settings of the four sections; the name and **Let clients override settings** stay as they are. Save to apply them.- A profile that keys use cannot be deleted. Revoke those keys first, or, if they are still needed, issue replacements that use another profile.- While Studio is read-only, cards show **View** instead of **Edit**, and creating, duplicating and deleting are unavailable; see [Unlock editing](06-manage-in-studio.md#unlock-editing).@@ -101,6 +103,24 @@ The last two sections of the editor each have their own page:The API name and range of every setting are in the [Configuration reference](13-configuration.md#context-profile-settings).+## Let clients override settings {#client-overrides}++**Let clients override settings**, below the profile's **Name**, is on by default. It lets a client change the profile's settings for a conversation: the client sends the fields to change as a JSON object in an `X-OpenViking-Context` request header, with the API names from the [Configuration reference](13-configuration.md#context-profile-settings). For example:++```text+X-OpenViking-Context: {"recall":false,"max_tokens":800,"context_types":["memory"]}+```++- **What it can change.** Every setting except `name` and `client_overrides`. Fields the header leaves out keep the profile's values. `{"disabled_tools":[]}` offers every OpenViking tool, including the ones that change data and any the server adds later.+- **When it applies.** As with a saved profile change, a conversation keeps the settings it started with: only the header on a conversation's first request shapes it. Later headers are still checked, so an invalid one, or any header once the switch is off, still fails.+- **Errors.** With the switch off, any request that carries the header gets 403 `context_override_not_allowed` instead of being served with the saved settings. With it on, the request gets 400 `context_override_invalid` when the header:+ - is not a JSON object;+ - names an unknown field, `name` or `client_overrides`;+ - holds a value out of range.+- **In the request log.** [Request details](10-overview-and-requests.md#request-details) list the names of the fields the client sent in the header, never their values.++The switch defaults on, so anyone holding a key that uses the profile can change any field, including budgets and write tools. On the `default` profile, that includes every client using an [OpenViking API key directly](09-gateway-keys.md#openviking-keys). Turn it off on profiles that must stay locked. How each client sends the header is in [Override profile settings](03-connect-clients.md#override-profile-settings).+## Next steps {#next-steps}- [Issue a gateway key](09-gateway-keys.md#issue-a-key) that uses the profile.diff --git a/docs/en/gateway/09-gateway-keys.md b/docs/en/gateway/09-gateway-keys.mdindex efde9cffe..faf81dda9 100644--- a/docs/en/gateway/09-gateway-keys.md+++ b/docs/en/gateway/09-gateway-keys.md@@ -16,6 +16,25 @@ In Studio: **OpenViking Gateway** → **Keys**. A gateway key (`ovgw_…`) is whThe **Keys** tab lists your own keys. Account admins and root see every key in the account, with an **OpenViking user** column. The **Key** column shows only the first characters of each key.+A gateway key is one of two credentials a client can use. The other, when the deployment allows it, is the user's own OpenViking API key; see [Use an OpenViking API key directly](#openviking-keys).++## Use an OpenViking API key directly {#openviking-keys}++When the deployment sets [`openviking_keys`](13-configuration.md#gateway-fields) to `true`, a client can put a user's OpenViking API key where a gateway key goes. Any key that does not start with `ovgw_` is then treated as an OpenViking API key. It is off by default, and with it off such a key is rejected without asking OpenViking.++- **Its user is the key's own.** On the first request the gateway confirms the key with OpenViking; an admin or user key is accepted, a root key is not. To act as another user, the client sends that user's key; there is no header to switch identity.+- **It uses the account's defaults.** It uses the account's `default` [context profile](08-context-profiles.md#context-profiles) (built-in defaults when there is none) and every enabled upstream, with every model allowed. The client can still change that profile's settings for a conversation with the `X-OpenViking-Context` header; see [Let clients override settings](08-context-profiles.md#client-overrides).+- **The gateway stores it like an issued key**, so capture and logs work the same way. Turn on [encryption](../guides/22-gateway-operations.md#encryption). The **Keys** tab lists it as **OpenViking API key**, with **Account default** as its profile and upstreams.+- **Only OpenViking can revoke it.** The **Keys** tab has no **Revoke** for it. [Deleting the user's gateway data](#delete-a-users-gateway-data) deletes the stored copy, logs and conversation state, but a client that still sends the key keeps working and starts fresh. To stop it, regenerate the key in OpenViking or turn `openviking_keys` off. After a key is regenerated, the gateway deletes its copy on a later request, as for a [gateway key](#when-the-openviking-key-changes).++With `tenancy: account` (the default), keys for the same OpenViking account and user share conversation state. With `tenancy: key`, each OpenViking key gets a separate partition, even when two libraries return the same account and user identity. Conversations, recall, capture, model bindings and request logs use that partition. Set `management_api: false` and configure `default_upstreams` and `default_profile` before starting this mode; Studio and the management routes are unavailable.++Rotating an OpenViking key in key tenancy starts a new partition and new conversations. For troubleshooting, derive its partition without printing the key: `"k_" + hashlib.sha256(("openviking\0" + key).encode()).hexdigest()`. The OpenViking account identity is kept separately for revocation checks.++The stored OpenViking key and its user record expire after the configured `session_ttl_days`, measured from creation. Requests do not renew them. The next request confirms the key with OpenViking and recreates the records with the same partition and conversation scope. Issued gateway keys have no such TTL. See [Retention](11-security-and-data.md#retention) for pending capture and cleanup behavior.++Use gateway keys when clients need their own context profile, upstreams or allowed models, or must be revocable on their own.+## Issue a key {#issue-a-key}If the **Keys** tab asks you to add an upstream or create a context profile first, do that, or ask whoever deployed the gateway if you cannot. On a new gateway, **Get a key** in the Overview tab's **Quick mode** card does all of this in one click; see [Get started checklist and Quick mode](06-manage-in-studio.md#get-started-checklist).@@ -71,7 +90,7 @@ If OpenViking is only unreachable or returns an error, the gateway keeps the keyRevoking keys does not delete what the gateway keeps for a user. To delete it, an account admin or root opens the **…** menu on one of the user's keys on the **Keys** tab, chooses **Delete this user's gateway data…** and confirms with **Delete gateway data**. This:-- revokes all of the user's gateway keys, so their clients lose access at once;+- revokes all of the user's gateway keys, so their clients lose access at once; a client using the user's [OpenViking API key directly](#openviking-keys) keeps working until the key is regenerated in OpenViking;- deletes the conversation state the gateway keeps for them, including content not yet saved to OpenViking;- deletes their request logs.diff --git a/docs/en/gateway/10-overview-and-requests.md b/docs/en/gateway/10-overview-and-requests.mdindex 417a6eb5f..d10edb14e 100644--- a/docs/en/gateway/10-overview-and-requests.md+++ b/docs/en/gateway/10-overview-and-requests.md@@ -10,7 +10,9 @@ This page explains every card, column, label and saving status on the gateway'sBoth tabs read the gateway's request log: one record per model request that went through the gateway. Users see only their own requests; account admins and root see the whole account's. The Overview figures are computed from the same records, so they cover the same requests.-The log holds metadata only, never prompts, replies or memory text; see [What request logs record](11-security-and-data.md#what-request-logs-record). Records are kept for 30 days by default; see [Retention](11-security-and-data.md#retention).+With `request_log_sink: "stdout"`, new records go only to stdout. The Requests page and Overview's request figures stay empty on a fresh deployment; previously stored records remain visible until they expire. Use the [stdout monitoring workflow](../guides/22-gateway-operations.md#monitoring) for new requests.++The log holds metadata only, never prompts, replies or memory text; see [What request logs record](11-security-and-data.md#what-request-logs-record). Stored records are kept for 30 days by default; stdout retention belongs to the log collector. See [Retention](11-security-and-data.md#retention).## Overview {#overview}@@ -89,6 +91,7 @@ Expand a row to see:- context window use, and whether the history was compacted or the model started a new window- the saving status, with the next retry time- OpenViking tool details, including why tools were not offered+- the profile settings the client sent in `X-OpenViking-Context`, by name only; they take effect only on a conversation's first requestFor a request with an issue, the expanded row also explains what happened and what to do.diff --git a/docs/en/gateway/11-security-and-data.md b/docs/en/gateway/11-security-and-data.mdindex 66bdbd01d..52d349ec2 100644--- a/docs/en/gateway/11-security-and-data.md+++ b/docs/en/gateway/11-security-and-data.md@@ -4,27 +4,27 @@ description: What OpenViking Gateway stores, who can reach it, what providers se# OpenViking Gateway security and data-This page is for operators and security reviewers approving a gateway deployment, and for users who want to know what the gateway keeps about them. Sessions and memories always live in OpenViking under its own rules; the gateway keeps only its settings, the state it needs to continue conversations, and metadata-only request logs, in two SQLite files under `storage_path`. Each section below answers one review question and can be linked on its own.+This page is for operators and security reviewers approving a gateway deployment, and for users who want to know what the gateway keeps about them. Sessions and memories always live in OpenViking under its own rules; the gateway keeps only its settings, the state it needs to continue conversations, and metadata-only request logs, in local SQLite by default or in configured Redis storage. Each section below answers one review question and can be linked on its own.## Isolation by user {#isolation-by-user}-Each [gateway key](../guides/15-gateway.md#key-terms) is bound to one OpenViking user. The gateway searches memory, saves conversations and calls tools with that user's own OpenViking key, so it can never do more than the user can. Each user's conversation state is kept separate from every other user's.+Each [gateway key](../guides/15-gateway.md#key-terms) is bound to one OpenViking user. The gateway searches memory, saves conversations and calls tools with that user's own OpenViking key, so it can never do more than the user can. Each user's conversation state is kept separate from every other user's. With `tenancy: key`, different OpenViking keys also have separate partitions when their account and user identities match; rotating the key starts a new partition.## What the gateway stores {#what-the-gateway-stores}-Everything the gateway keeps is in two SQLite databases in `storage_path` (default `~/.openviking/gateway`):+By default, data is in two SQLite databases in `storage_path` (default `~/.openviking/gateway`). Either storage port can use [Redis](13-configuration.md#storage) instead:| File | What it holds || --- | --- |-| `management.sqlite3` | Upstreams, context profiles, gateway keys, request logs, and which upstream created each Responses response |-| `kernel.sqlite3` | The state of each conversation: the memory text added to messages, OpenViking tool rounds and their results, summaries, conversation text waiting to be saved, and the reasoning of model replies when **Restore reasoning the client drops** is on |+| `management.sqlite3` (or Redis management) | Upstreams, context profiles, gateway keys, request logs when using the default `store` sink, and which upstream created each Responses response |+| `kernel.sqlite3` (or Redis kernel) | The state of each conversation: the memory text added to messages, OpenViking tool rounds and their results, summaries, conversation text waiting to be saved, and the reasoning of model replies when **Restore reasoning the client drops** is on |Some of this is sensitive:- `management.sqlite3` holds upstream API keys, header values and the OpenViking keys bound to gateway keys. Gateway keys themselves are stored only as a hash and a short prefix.- `kernel.sqlite3` holds memory text word for word, because the gateway needs it to [replay](01-how-it-works.md#replay) what it added in earlier turns.-Only the system user that runs the gateway can read the files. With [encryption](../guides/22-gateway-operations.md#encryption) on, every stored value is encrypted as well; with it off, the credentials above are in plain text, protected only by file permissions.+Only the system user that runs the gateway can read SQLite files. Redis access is controlled by its network and ACL configuration. With [encryption](../guides/22-gateway-operations.md#encryption) on, every stored value is encrypted as well; with it off, the credentials above are in plain text, protected by file permissions or Redis access controls. All replicas must mount the same encryption root key from a Secret; a missing entry on a read-only mount prevents startup. Redis keys contain hashes, but indexes can contain original account, object and session identifiers; use TLS as well as value encryption.## What request logs record {#what-request-logs-record}@@ -37,7 +37,7 @@ Request logs hold metadata only, never content:| Token counts, memory counts and timing | Tool arguments or results || Saving status and issues | Any key |-The gateway writes no HTTP access log, and its error messages never repeat submitted values. To read the logs in Studio, see [Requests](10-overview-and-requests.md#requests).+The gateway writes no HTTP access log, and its error messages never repeat submitted values. The default `store` sink makes request logs available in Studio; see [Requests](10-overview-and-requests.md#requests). The `stdout` sink emits the same metadata with account and user identifiers as plain JSON; storage encryption does not apply to stdout. Log collection and access are managed by your deployment; see [Monitoring](../guides/22-gateway-operations.md#monitoring).## What providers see {#what-providers-see}@@ -65,16 +65,38 @@ The full rules, including the management API, are in the [access matrix](../api/## Retention {#retention}-Gateway data expires on its own. A cleanup job runs every hour:+Gateway data expires on its own. SQLite runs an hourly cleanup job; Redis uses key TTLs:| Data | Kept for | Setting || --- | --- | --- || Conversation state | 30 days after last use | `session_ttl_days` |-| Request logs | 30 days | `log_retention_days` |+| Cached OpenViking keys and their user records | Configured TTL from creation, without renewal | `session_ttl_days` |+| Stored request logs | 30 days | `log_retention_days` || Which upstream created each Responses response | 30 days | `response_ttl_seconds` || Sessions and memories in OpenViking | OpenViking's own rules | — |-Minimums and where to set these are in [Gateway fields](13-configuration.md#gateway-fields).+When an OpenViking key record expires, or is evicted by a Redis backend using `volatile-lru`, capture pauses with `gateway_key_revoked` because it cannot read the stored credential. The user's next request recreates the record and resumes capture in the same scope. If the user never returns, the last pending turn is not saved to OpenViking. This state is a cache and can be lost. The existing short process-local cache can delay visibility of expiry, like revocation.++Redis keeps at most 10,000 request-log entries per account. Reads skip entries older than `log_retention_days`; those entries stay stored until newer ones push them past the cap, or until the account logs nothing for `log_retention_days`. Redis needs no hourly cleanup. Redis Responses routing objects expire by TTL and are not scanned during user deletion; revoked keys cannot access them.++Minimums and where to set these are in [Gateway fields](13-configuration.md#gateway-fields). Retention and deletion of stdout logs are controlled by the log collector, independently of gateway cleanup.++## Redis conversation state {#redis-conversation-state}++With `storage.kernel: redis`, conversation state is a cache with a TTL of `session_ttl_days`. Writes renew it; reading a record alone does not.++Eviction has observable effects:++| Lost state | Effect |+| --- | --- |+| Replay, recalled memory or restored reasoning | Earlier decisions cannot be replayed; the next request takes a cache miss. Lost compaction summaries can require another summary or leave the request over the model's context limit. |+| Pending capture document | Unsaved turns can be lost. Rebuilding from client history can save previously delivered messages again; a worker whose document disappeared stops using its old lease. |+| Observation or thinking state | Recall bookkeeping resets, and earlier reasoning may no longer be recognized. |+| Tool receipt while another request waits | The result is reported as timed out or unknown. The gateway does not retry that operation; inspect its state before retrying a write. |++Asynchronous Redis failover can lose recent writes or leases, causing occasional duplicate capture. Persist Redis to preserve pending work and deletions; restoring a snapshot taken before a deletion makes the deleted data visible again. See [Redis memory policy](../guides/22-gateway-operations.md#redis-memory-policy).++With encryption on, values are encrypted. Key names are hashed, but index members contain original session IDs, and record kinds, versions, scheduling times and lease owners stay in plain text. Protect Redis access and backups accordingly.## Deleting data {#deleting-data}@@ -86,7 +108,7 @@ Revoking a gateway key, or the bound OpenViking key becoming invalid, does not d| Root | `DELETE /gateway/admin/account/data?account_id=<account>` | All gateway data of an account || Embedded deployment, automatically | Deleting a user or account in OpenViking | The matching gateway data |-A standalone deployment has no automatic step; its data stays until it is explicitly deleted or [expires](#retention).+A standalone deployment has no automatic step; its data stays until it is explicitly deleted or [expires](#retention). With [`management_api: false`](13-configuration.md#gateway-fields), the deletion API is also unavailable: deleting an OpenViking user does not notify the standalone gateway, so its conversation state remains until `session_ttl_days` expires. Request logs and response mappings follow their own retention settings. Embedded deployments retain the server's automatic deletion hook in account tenancy. In key tenancy, the hook cannot locate the `k_` partitions from the OpenViking account and user IDs; their cached data instead follows the retention settings above.None of this touches memories and sessions already stored in OpenViking. The reverse also holds: after you delete a memory in OpenViking, the copy the gateway saved for an ongoing conversation is still replayed until that conversation expires. To clear it now, delete the user's gateway data.@@ -94,7 +116,8 @@ None of this touches memories and sessions already stored in OpenViking. The revBack up these, together:-- The whole `storage_path` directory: both databases and their `-wal` and `-shm` files.+- For Redis, enable AOF and back up Redis persistence together with the encryption root key. Without persistence, restarting Redis loses management settings and pending conversation data.+- For SQLite, the whole `storage_path` directory: both databases and their `-wal` and `-shm` files.- With encryption on, OpenViking's encryption root key (not the root API key), as the [Encryption guide](../guides/08-encryption.md) describes.For a consistent copy, stop the gateway first, or use SQLite's online backup while it runs:@@ -108,9 +131,9 @@ What losing each piece means:| Lost | What happens | What to do || --- | --- | --- |-| `kernel.sqlite3` | Memory added earlier cannot be replayed. Each ongoing conversation takes one provider cache miss, Claude conversations lose their earlier thinking once ([**Memory record missing**](12-troubleshooting.md#issues-on-degraded-requests)), and turns not yet saved are lost. | None; ongoing conversations recover after one miss |-| `management.sqlite3` | Upstreams, context profiles, keys and request logs are gone. | Set them up again and issue new keys |-| Encryption root key (encryption on) | The encrypted values in both databases cannot be read. | Start again with an empty `storage_path` |+| `kernel.sqlite3` (or Redis kernel) | Memory added earlier cannot be replayed. Each ongoing conversation takes one provider cache miss, Claude conversations lose their earlier thinking once ([**Memory record missing**](12-troubleshooting.md#issues-on-degraded-requests)), and turns not yet saved are lost. | None; ongoing conversations recover after one miss |+| `management.sqlite3` (or Redis management) | Upstreams, context profiles, keys and request logs are gone. | Restore a backup, or set them up again and issue new keys; OpenViking key records rebuild on later requests |+| Encryption root key (encryption on) | The encrypted values in both databases cannot be read. | Start again with an empty `storage_path` (SQLite), or a new `storage.key_prefix` that the ACL key pattern still covers (for example `ovgw:2:`), or delete all keys under the old prefix (Redis) |## Next steps {#next-steps}diff --git a/docs/en/gateway/12-troubleshooting.md b/docs/en/gateway/12-troubleshooting.mdindex f369043af..8b9791309 100644--- a/docs/en/gateway/12-troubleshooting.md+++ b/docs/en/gateway/12-troubleshooting.md@@ -18,7 +18,7 @@ Use this page when a client gets an error, memory or saving is missing, or Studi| A request in the log shows HTTP 400 or above | The provider rejected or failed the call. | [The upstream returned an error](#the-upstream-returned-an-error) || A conversation gets no recall and is not saved | An OpenViking plugin was detected, and the gateway left recall, saving and tools to the plugin. | Expected: it keeps content from being added or saved twice. See [When both are in use](../guides/15-gateway.md#when-both-are-in-use). || Requests go without memory | OpenViking unreachable or too slow, budget used up, nothing relevant, and so on. | [No memory is added](#no-memory-is-added) |-| Saving shows **Retrying**, then **Paused** | OpenViking rejected the save or could not be reached, or the conversation's gateway key was revoked (`gateway_key_revoked`), for example after the user's OpenViking key was regenerated. | Saving resumes on its own once OpenViking is back. After a revocation, issue a new gateway key; the user's next request resumes saving. See [Conversations do not appear in OpenViking](#conversations-do-not-appear-in-openviking). |+| Saving shows **Retrying**, then **Paused** | OpenViking rejected the save or could not be reached, or the conversation's gateway key was revoked (`gateway_key_revoked`), for example after the user's OpenViking key was regenerated. | Saving resumes on its own once OpenViking is back. With `gateway_key_revoked`: for an issued gateway key, issue a new one, then the next request resumes saving; for an OpenViking key whose record expired, was evicted or got a 401, the user's next valid request resumes saving (account tenancy; with `tenancy: key` a new key starts a new conversation). See [Conversations do not appear in OpenViking](#conversations-do-not-appear-in-openviking). || The profile has tools on, but the conversation has none | No request that could use tools has arrived yet, loading the tool list failed on the first one, the client does not send the full history, or the client has its own OpenViking tools. | Check the reason in the request log; see [When tools are not offered](04-openviking-tools.md#when-tools-are-not-offered). **The client already has OpenViking tools** (`tool_name_collision`) is expected when the client has the OpenViking MCP server; for other reasons, fix the cause and start a new conversation. || The **First-call cache hit rate** dropped, or Overview warns about cache misses | Memory could not be replayed, the conversation switched upstreams, or the client or relay changes the request prefix. | [The first-call cache hit rate dropped](#the-first-call-cache-hit-rate-dropped) || The provider rejects a long conversation as too long | The gateway does not know the model's real window and compacts too late. | [Long conversations hit the context limit](#long-conversations-hit-the-context-limit) |@@ -79,11 +79,13 @@ The gateway checks each client request before forwarding it: the gateway key, th| Status and message | Cause and fix || --- | --- || 401 "Invalid gateway key. It may have been revoked, or removed because its OpenViking API key was regenerated…" | The client sent no gateway key, a revoked key or its provider API key, or the gateway deleted the key after the user's OpenViking API key was regenerated. Check which key the client actually sends, and [issue a new one](09-gateway-keys.md#issue-a-key) if needed. |+| 402 `openviking_http_402` "OpenViking service is not ordered for this API key.", 403 `openviking_http_403` "OpenViking request failed." | OpenViking refused the OpenViking key (or the one behind the gateway key) when the gateway checked it, for example because the service is not ordered; the request is not forwarded. Restore the subscription or the key's permission. || 403 "Claude subscription OAuth credentials are not supported" | The client sent a Claude subscription token, for example Claude Code signed in with a subscription and no `ANTHROPIC_AUTH_TOKEN` set; or the upstream stores a subscription token. Use an API key. || 403 "Model is not allowed by this key" | The model is not in the key's [allowed models](09-gateway-keys.md#allowed-models). Issue a key that allows it. || 400 "Request model is missing", 415 "Compressed request bodies are not supported" | Only for keys that allow specific models: the request body must name a model and must not be content-encoded. || 404 "This upstream is an exact endpoint for … only" | **Append protocol endpoint path** is off on the key's upstream ([Send to an exact endpoint](07-upstreams.md#exact-endpoint)), so it accepts only that protocol's endpoint, and the client called another path, such as `/v1/models`. || 404 "No allowed upstream matches this protocol and model" | No enabled upstream bound to the key uses the API the client called and serves the requested model. Check the upstreams' protocol, models and aliases, whether they are enabled, and which upstreams the key is bound to. |+| 403 "Upstream URL is not allowed" | `X-OpenViking-Upstream-URL` does not equal the Base URL of any upstream bound to the key. See [Pick the upstream per request](07-upstreams.md#upstream-url-header). || 401 "Upstream API key is missing" | The upstream expects each client to send its own key in `X-OpenViking-Upstream-Key`, or an upstream where the gateway holds the key has none stored. See [Credentials](07-upstreams.md#credentials). || 403 "Coding Plan upstreams are disabled; configure a model API key" | The upstream is marked as a [Coding Plan key](07-upstreams.md#coding-plan-keys). Use a model API key, or deliberately check **Allow this plan through the gateway**. || 403 "Context policy is unavailable" | The key's context profile no longer exists. Issue a new key with an existing context profile. |@@ -140,7 +142,7 @@ A message whose search failed never gets memory later; the next message searches| --- | --- | --- || The latest turn is missing | Saving runs one turn behind: a turn appears when the next message arrives, and the last turn waits for **Save the latest reply after** (10 minutes by default). | Wait, or send the next message. || The **Saving** column shows **Off** | The context profile does not save conversations. | Turn saving on in the context profile; it reaches only new conversations ([When changes take effect](06-manage-in-studio.md#when-changes-take-effect)). |-| **Retrying** or **Paused** | Saving failed; the expanded row shows the reason. | Fix the cause (for example, make OpenViking reachable again); the gateway retries within 5 minutes. With `gateway_key_revoked`, issue a new gateway key; the next request resumes saving. If the conversation stays paused, use **Resync conversation…** ([Resync a conversation](10-overview-and-requests.md#resync-a-conversation)). |+| **Retrying** or **Paused** | Saving failed; the expanded row shows the reason. | Fix the cause (for example, make OpenViking reachable again); the gateway retries within 5 minutes. With `gateway_key_revoked`: for an issued gateway key, issue a new one, then the next request resumes saving; for an OpenViking key whose record expired, was evicted or got a 401, the next valid request resumes saving (account tenancy; with `tenancy: key` a new key starts a new conversation). If the conversation stays paused, use **Resync conversation…** ([Resync a conversation](10-overview-and-requests.md#resync-a-conversation)). || **OpenViking plugin in use** (`plugin_present`) | The gateway saves nothing for a conversation in which it detected an OpenViking plugin. | Expected; use either the plugin or the gateway for a given client. || Only part of the conversation is in the session | The gateway writes the current history to a new `gateway-…` session when the client edits, regenerates or compacts it (`history_changed`, `history_changed_during_delivery`), when a turn already saved after **Save the latest reply after** continues (`continued_after_idle`), or after **Resync conversation…** (`manual_reset`). Earlier turns stay in the older session. | Look in the older session too; see [Saving status](10-overview-and-requests.md#saving-status). || No `gateway-…` sessions at all | You are looking as a different OpenViking user from the one behind the gateway key. | Sign in as that user. |@@ -153,7 +155,7 @@ The **First-call cache hit rate** on the Overview tab is the share of input toke| What you see | Cause | What to do || --- | --- | --- || **Memory record missing** (`missing_injection_record`) | The gateway's storage was lost or restored from an old backup, or the record expired, so memory added earlier could not be replayed. | Nothing; ongoing conversations recover after one miss. |-| **Upstream switched** (`upstream_changed`) | The conversation's upstream was turned off, is not bound to the key the client now uses, or no longer serves the model, so the conversation moved to another upstream. | Turn the upstream back on or give the client a key that includes it; see [Routing](07-upstreams.md#routing). |+| **Upstream switched** (`upstream_changed`) | The conversation's upstream was turned off, is not bound to the key the client now uses, does not match the request's `X-OpenViking-Upstream-URL`, or no longer serves the model, so the conversation moved to another upstream. | Turn the upstream back on or give the client a key that includes it; see [Routing](07-upstreams.md#routing). || **Cache parameters changed** (`ark_cache_parameters_changed`) | On Ark or ModelArk, the client changed the model, thinking mode, sampling parameters, system prompt or tools within a conversation. | Keep them the same within a conversation. || No issue flagged | The client itself may change earlier messages or its system prompt every turn, for example by inserting the current time, which the gateway cannot fix. Each compaction, and each new context window the model starts, also costs one miss; that is expected. | Check the client's system prompt for content that changes every request. || **… long conversations keep missing the prompt cache**, or a hit rate that stays at 0%, and the provider's or relay's cache records show hits | The upstream isn't passing cache usage back to the gateway, for example a relay that drops the cache fields when it converts protocols. The gateway reads the common fields, such as `cache_read_input_tokens`, `prompt_tokens_details.cached_tokens`, `input_tokens_details.cached_tokens` and `prompt_cache_hit_tokens`. | Make the relay pass cache usage through. |@@ -211,6 +213,10 @@ A degraded request is one the gateway could not fully handle; the Requests and O| Reply not saved (`capture_parse_failure`) | A streamed reply could not be parsed, so it was not saved. The client was not affected. | Nothing to do; it is for information only. || Key not verified (`revocation_check_unavailable`) | OpenViking could not confirm the gateway key, so the request was served without checking whether the key was revoked. | Check that OpenViking is reachable and healthy. |+## Redis unavailable {#redis-unavailable}++If startup fails at Redis PING, check `storage.redis.endpoints`, TLS trust, and the password environment variable. The gateway requires `openviking[expiry]` outside the official image. An HTTP 500 with plain text `Internal Server Error` during authentication can also mean Redis is unavailable; inspect stderr. `/health` stays healthy during a runtime Redis failure and is not a Redis connectivity check. See [Storage providers](13-configuration.md#storage) for the ACL and timeout settings, and [Redis memory policy](../guides/22-gateway-operations.md#redis-memory-policy) for persistence.+## Next steps {#next-steps}- [Gateway overview and request log](10-overview-and-requests.md#requests): read every column, label and saving state in the request log.diff --git a/docs/en/gateway/13-configuration.md b/docs/en/gateway/13-configuration.mdindex ca2630e2c..a32136bc9 100644--- a/docs/en/gateway/13-configuration.md+++ b/docs/en/gateway/13-configuration.md@@ -28,20 +28,86 @@ An embedded and a standalone gateway share most fields; they differ in which fil| `host` | Standalone | `127.0.0.1` | | Listen address || `port` | Standalone | `1935` | 1–65,535 | Listen port || `workers` | Standalone | `1` | 1–64 | Worker processes |+| `keep_alive_seconds` | Standalone | `75` | More than 0 | Seconds to keep an idle HTTP connection open between requests; set it above the load balancer's backend idle timeout || `public_url` | Both | empty | HTTP(S) URL, without `/gateway` | The external address clients use; the gateway appends `/gateway` itself. When empty, an embedded gateway uses the server's public address; with neither, setup guides use the request's origin, and MCP file uploads and downloads do not work unless `mcp_file_links` is `direct`. See [Public address](../guides/22-gateway-operations.md#public-address) || `mcp_file_links` | Both | `proxy` | `proxy`, `direct` | How links from the MCP upload and download tools reach the client. `proxy` rewrites them to `public_url` plus `/gateway/uploads` or `/gateway/downloads` and needs `public_url`. `direct` passes OpenViking's links through unchanged and needs the server's `OPENVIKING_PUBLIC_BASE_URL` (or `server.public_base_url`) to be reachable by the client || `storage_path` | Both | `~/.openviking/gateway` | | Local storage directory |+| `storage` | Both | Both ports `sqlite` | See [Storage providers](#storage) | Per-port providers and one shared Redis connection || `encryption` | Standalone | not set (plain text) | Same fields as the `encryption` section of `ov.conf` | Encrypts stored data; see [Encryption](../guides/22-gateway-operations.md#encryption). Embedded gateways use the server's section |+| `management_api` | Both | `true` | `true`, `false` | Registers the gateway administration routes; disabling it also removes the standalone OpenViking admin proxy and Studio. Model routes and `/health` remain available || `management_key` | Both | empty | At least 32 characters | Optional [gateway management key](../guides/22-gateway-operations.md#gateway-management-key) |+| `openviking_keys` | Both | `false` | `true`, `false` | Lets clients use a user's OpenViking API key in place of a gateway key, with the account's default context profile and every enabled upstream; see [Use an OpenViking API key directly](09-gateway-keys.md#openviking-keys) |+| `tenancy` | Both | `account` | `account`, `key` | Partitions OpenViking-key requests by account or by key; `key` requires `management_api: false` |+| `default_upstreams` | Both | `{}` | Object mapping stable IDs to [upstream settings](#upstream-settings) | Upstreams for OpenViking keys when the account stores none; see [Deployment default upstreams](07-upstreams.md#deployment-default-upstreams) |+| `default_profile` | Both | Built-in profile defaults | [Context profile settings](#context-profile-settings) | Used when the account has no profile with the ID `default`; also the initial profile seeded in embedded dev mode || `min_server_version` | Both | `0.4.16` | Version string | Lowest OpenViking Server version a standalone gateway accepts |-| `session_ttl_days` | Both | `30` | 1 or more | Days of inactivity before a conversation expires |+| `session_ttl_days` | Both | `30` | 1 or more | Days of inactivity before a conversation expires; also the fixed lifetime of cached OpenViking keys and their user records || `response_ttl_seconds` | Both | `2592000` (30 days) | 60 or more | Seconds to remember which upstream created a Responses response |-| `log_retention_days` | Both | `30` | 1 or more | Days to keep request logs |+| `request_log_sink` | Both | `store` | `store`, `stdout` | Write request and background saving logs to storage or one flushed JSON line per record on stdout; see [Monitoring](../guides/22-gateway-operations.md#monitoring) |+| `log_retention_days` | Both | `30` | 1 or more | Days to keep request logs in storage; stdout retention is managed by the log collector || `max_body_bytes` | Both | `33554432` (32 MiB) | 1,024 or more | Size limit for requests and uploads, in bytes || `upstream_timeout_seconds` | Both | `600` | More than 0 | Timeout for provider requests || `health_interval_seconds` | Both | `60` | 1 or more | Seconds between OpenViking status checks |+| `capture_concurrency` | Both | `1` | 1 or more | Concurrent conversation deliveries per process; shutdown stops new claims and gives in-flight deliveries up to 100 seconds to finish || `client_rules` | Both | `{}` (packaged rules only) | See [Client rules](#client-rules) | Text added to or removed from what the gateway recognizes as housekeeping requests and client-inserted messages |+For example, a standalone `gateway.conf` can route OpenViking keys before any account is configured:++```json+{+ "openviking_url": "http://openviking:1933",+ "openviking_keys": true,+ "default_upstreams": {+ "ark-chat": {+ "name": "Ark Chat",+ "protocol": "chat",+ "base_url": "https://ark.cn-beijing.volces.com/api/v3",+ "api_key": "$ARK_API_KEY",+ "models": ["your-model-id"]+ }+ },+ "default_profile": {"max_tokens": 2400}+}+```++## Storage providers {#storage}++The default is local SQLite, with no external service. `storage.kernel` and `storage.management` each select `sqlite` or `redis`; Redis ports share one client and the settings in `storage.redis`. Install `pip install "openviking[expiry]"` for Redis; the official image already includes it. Standalone Redis and Redis Cluster are tested. Sentinel configuration is accepted but is not covered by gateway CI.++```json+{+ "storage": {+ "kernel": "redis",+ "management": "redis",+ "key_prefix": "ovgw:",+ "redis": {+ "mode": "standalone",+ "endpoints": ["rediss://redis.example.com:6379"],+ "username": "gateway",+ "password_env": "OPENVIKING_GATEWAY_REDIS_PASSWORD",+ "pool_size": 32,+ "command_timeout_ms": 5000+ }+ },+ "session_ttl_days": 7+}+```++`OPENVIKING_GATEWAY_STORAGE` accepts the same `storage` object as JSON. Inject the password through the named environment variable, for example from a Kubernetes Secret. `key_prefix` defaults to `ovgw:` and cannot contain `{`, `}`, `*`, `?`, `[`, `]` or `\`; every key starts with that prefix plus `v1:`. Give separate deployments different prefixes.++`storage.redis` reuses OpenViking's `RedisCacheConfig`: `mode`, `endpoints`, `username`, `password_env`, legacy `password`, `db`, `pool_size`, `connect_timeout_ms`, `command_timeout_ms`, `default_ttl_seconds`, `tls_insecure_skip_verify`, and the Sentinel fields `master_name`, `sentinel_username`, `sentinel_password_env`, `sentinel_password`. The gateway overrides the command timeout default from 20 to 5000 ms for large conversation values; `default_ttl_seconds` does not set gateway retention. URLs contain only a scheme, host and port; use the dedicated credentials and `db` fields. For Cluster use `mode: "cluster"`, multiple seed endpoints and `db: 0`. TLS follows the `rediss://` scheme. For a private CA, mount its certificate and set `SSL_CERT_FILE` to its path (with Helm, use `extraVolumes` and `extraVolumeMounts`).++Give the gateway its own Redis instance with `volatile-lru` eviction and AOF; the `redis.conf` settings and what to monitor are in [Redis memory policy](../guides/22-gateway-operations.md#redis-memory-policy).++Create an ACL user with the following command, replacing the password and prefix. Run it on **every Cluster node**, because ACLs are not replicated between nodes:++```bash+redis-cli ACL SETUSER gateway reset on '>replace-with-secret' '~ovgw:*' \+ +@read +@write +@scripting +@connection +@transaction +ping +time +scan +unlink+```++For Cluster also grant `'+cluster|slots' '+cluster|shards'`. `+time` is required by Lua scripts. These permissions and prefix isolation are exercised in CI. Application commands do not retry after connection errors because a failed write may already have reached Redis.+## Environment variables {#environment-variables}Every gateway field can be set as an environment variable named `OPENVIKING_GATEWAY_` plus the field name in upper case, in both forms:@@ -55,7 +121,7 @@ OPENVIKING_GATEWAY_MANAGEMENT_KEY='<management-key>'- Values that start with `tcp://` or `udp://` are ignored, so the variables Kubernetes sets for a Service named `openviking-gateway` (such as `OPENVIKING_GATEWAY_PORT=tcp://…`) do not override the file.- A value in the file can also be a `"$VAR"` reference, resolved from the environment.- The `encryption` block can only be set in the file.-- `client_rules` takes the whole section as JSON: `OPENVIKING_GATEWAY_CLIENT_RULES='{"auxiliary_patterns":{"add":["You are the Acme title writer"]}}'`.+- `client_rules`, `storage`, `default_upstreams` and `default_profile` take whole sections as JSON, for example `OPENVIKING_GATEWAY_CLIENT_RULES='{"auxiliary_patterns":{"add":["You are the Acme title writer"]}}'` or `OPENVIKING_GATEWAY_DEFAULT_PROFILE='{"max_tokens":2400}'`.- Containers usually need no file: set the fields they need as variables.## Validation {#validation}@@ -65,6 +131,7 @@ OPENVIKING_GATEWAY_MANAGEMENT_KEY='<management-key>'| `openviking_url` and `public_url` | HTTP(S), with no credentials, query or fragment || Upstream `base_url` | Its own rules; see [Endpoint](07-upstreams.md#endpoint) || `management_key` | At least 32 characters once `$VAR` references are resolved; an unresolved `$VAR` fails |+| `tenancy` | `key` requires `management_api: false`; it has no effect when `openviking_keys` is off || `client_rules` | Every added pattern must be a valid Python regular expression; added tag names start with an ASCII letter and use only ASCII letters, digits, `_`, `.`, `:` and `-` || Unknown fields | Fail validation || Removed fields | Ignored, with a startup warning: `encryption_key_env`, and in `ov.conf` also the v0.5 fields listed in [Migration](../guides/22-gateway-operations.md#migration) |@@ -103,7 +170,7 @@ In `gateway.conf`, `client_rules` sits at the root, without the `gateway` wrappe## Context profile settings {#context-profile-settings}-In Studio: **Profiles** → a profile. The tables follow the editor's sections, with the Studio label first and then the name in the management API, which calls context profiles `policies`. **Name** (`name`, default `Default`) is the profile's display name; what each section does is explained in [Context profiles](08-context-profiles.md#context-profiles).+In Studio: **Profiles** → a profile. The tables follow the editor's sections, with the Studio label first and then the name in the management API, which calls context profiles `policies`. **Name** (`name`, default `Default`) is the profile's display name; what each section does is explained in [Context profiles](08-context-profiles.md#context-profiles). **Let clients override settings** (`client_overrides`, default `true`) lets clients change every other setting for a new conversation with the `X-OpenViking-Context` header; see [Let clients override settings](08-context-profiles.md#client-overrides).### Recall memory {#profile-recall}@@ -123,7 +190,7 @@ Explained in [Recall memory](08-context-profiles.md#recall-memory).| Query length | `query_max_chars` | `8000` | 3–32,000 | Characters of the message used as the search query. || Limit by category | `quotas` | `{}` (off) | Keys: `events`, `entities`, `preferences`, `experiences`, `resources`, `skills`; when set, at least one above 0 (checked by Studio only) | Most entries per category; only categories above 0 are searched. |-The management API saves `context_types` and `quotas` without checking them. An unknown `quotas` key makes every recall fail, because OpenViking rejects it.+The management API saves `context_types` and the `quotas` keys without checking them. An unknown `quotas` key makes every recall fail, because OpenViking rejects it.### Save conversations {#profile-saving}diff --git a/docs/en/guides/15-gateway.md b/docs/en/guides/15-gateway.mdindex c27ada462..c35abf7b6 100644--- a/docs/en/guides/15-gateway.md+++ b/docs/en/guides/15-gateway.md@@ -47,11 +47,11 @@ Every gateway page uses these terms in exactly this sense. Users in an OpenVikin## Architecture at a glance {#architecture-at-a-glance}-+- **Where it runs**: once enabled, inside OpenViking Server on the server's port. You can also run `openviking-gateway` on its own against an existing OpenViking service, open source or OpenViking Cloud. Either way, every gateway URL is under `/gateway`, such as `/gateway/v1`, so clients use the same paths. See [Choose a deployment form](22-gateway-operations.md#deployment-options).- **How it relates to OpenViking**: the gateway only calls OpenViking's public APIs. Embedding and memory extraction happen in OpenViking.-- **Where the data lives**: sessions and memories live in OpenViking. The gateway host keeps only two SQLite files, encrypted when OpenViking encryption is on, one for upstreams, keys and settings and one for conversation state. See [Security and data](../gateway/11-security-and-data.md).+- **Where the data lives**: sessions and memories live in OpenViking. The gateway defaults to two SQLite files and can use shared Redis for multiple replicas. OpenViking encryption protects stored values in either backend. See [Security and data](../gateway/11-security-and-data.md).- **When something fails**: if OpenViking is down, conversations go on without memory and saving retries on its own. If the gateway is down, every model call that goes through it fails.## What you get and what it costs {#what-you-get-and-what-it-costs}diff --git a/docs/en/guides/22-gateway-operations.md b/docs/en/guides/22-gateway-operations.mdindex 64d84feff..7ddd223e2 100644--- a/docs/en/guides/22-gateway-operations.md+++ b/docs/en/guides/22-gateway-operations.md@@ -25,7 +25,7 @@ This page is for the people who run OpenViking Gateway as a service: deploy it i| OpenViking version | An embedded gateway ships with the server, so there is nothing to check. A standalone gateway needs OpenViking Server 0.4.16 or later. || Installation | The gateway is part of the OpenViking core package. The optional `gateway-fast` extra (`pip install "openviking[gateway-fast]"`) adds a faster event loop and HTTP parser. || Sign-in | Remote deployments need an OpenViking API key; users, account admins and root can all sign in to the gateway pages in Studio. Local dev mode needs no key and always uses the `default/default` identity. |-| Storage | A local disk. The gateway's SQLite databases serve one host only; network filesystems and storage shared between hosts are not supported. |+| Storage | SQLite on a local disk for one host, or shared Redis for multiple replicas. Redis requires `pip install "openviking[expiry]"`; the official image includes it. |## Choose a deployment form {#deployment-options}@@ -86,9 +86,20 @@ docker run -d -p 1933:1933 -v ~/.openviking:/app/.openviking \The bundled Caddy forwards all paths to `openviking:1933`. Clients can keep using the compatibility port 1934, or go straight to the server on 1933. For HTTPS, a single `reverse_proxy openviking:1933` carries Studio, the management API and model traffic; see [Public access](12-public-access.md).+For a standalone container, mount `gateway.conf` and use the gateway command. Set `host: "0.0.0.0"` and an API-key-authenticated `openviking_url` in that file. Choose an image containing the features you configure:++```bash+docker run -d --no-healthcheck -p 1935:1935 \+ -v "$PWD/gateway.conf:/etc/openviking/gateway.conf:ro" \+ -v gateway-data:/app/.openviking \+ ghcr.io/volcengine/openviking:'<gateway-image-tag>' openviking-gateway+```++`--no-healthcheck` disables the image's server probe on port 1933. Probe the standalone gateway at `http://localhost:1935/health` instead.+## Helm {#helm}-With the Helm chart, set `gateway.enabled: true` in the chart values. The gateway runs inside the server container, keeps its data in `<persistence.mountPath>/gateway`, and uses the server port for both the Service and the Ingress. Keep `replicaCount: 1`.+With the embedded `deploy/helm/openviking` chart, set `gateway.enabled: true` in the chart values. The gateway runs inside the server container, keeps its data in `<persistence.mountPath>/gateway`, and uses the server port for both the Service and the Ingress. Keep `replicaCount: 1`.```yamlgateway:@@ -105,6 +116,26 @@ config:The NGINX annotations, the commands to create the Secrets and the notes on upgrading from the sidecar chart are in the [chart README](https://github.com/volcengine/OpenViking/blob/main/deploy/helm/README.md#openviking-gateway).+For an independent deployment, use `deploy/helm/openviking-gateway`. It has its own Service on port 80, forwards to port 1935, and runs `openviking-gateway`. Its `config` value is the standalone `gateway.conf` object; the chart fixes `host`, `port` and `storage_path`.++Until a release containing these features is published, set `image.tag` to a build that includes them; see the [chart README](https://github.com/volcengine/OpenViking/blob/main/deploy/helm/README.md#standalone-openviking-gateway).++```bash+helm upgrade --install gateway ./deploy/helm/openviking-gateway \+ --set-string image.tag='<gateway-image-tag>' \+ --set-string config.openviking_url=https://ov.example.com+```++The default is one SQLite replica with a persistent volume and `Recreate` updates. A default StorageClass, or `persistence.storageClass`/`persistence.existingClaim`, must be available. Setting `persistence.enabled: false` loses SQLite state when a Pod is replaced; Helm NOTES warns about this. PVCs are retained on uninstall. Use both Redis providers before scaling; see [Scaling](#scaling).++The chart sets `session_ttl_days: 7` and `response_ttl_seconds: 604800`, shorter than the gateway's 30-day defaults; override `config.*` to change them. Each Pod requests 500m CPU and 1Gi of memory, with limits of 2 CPUs and 4Gi; set `resources` for your load.++The standalone chart's `existingSecret` accepts `management-key`, `redis-password` and `root-key`. The first two become `OPENVIKING_GATEWAY_MANAGEMENT_KEY` and `OPENVIKING_GATEWAY_REDIS_PASSWORD`; `config.storage.redis.password_env` names the latter. Local and KMS encryption mount `root-key` read-only at `/etc/openviking-gateway/keys/root-key` and set the provider's `key_file` to it. Generate the key before installing, as described under [Encryption](#encryption). For upstream credentials and KMS AK/SK, use `$VAR` in `config` and `extraEnv` with `secretKeyRef`; never put plaintext credentials in a ConfigMap.++`extraVolumes` and `extraVolumeMounts` support private CA files; `extraEnv`, `podLabels`, `podAnnotations`, `nodeSelector`, `affinity`, `tolerations` and `imagePullSecrets` cover deployment-specific settings. ConfigMap changes trigger a rollout through `checksum/config`. After changing an external Secret, restart the Deployment so every replica loads the same credentials.++The chart does not create an Ingress. Route your proxy to its Service and keep `fullnameOverride`, `nameOverride` and the release name stable: the Service and Deployment share a name, and their selectors are `app.kubernetes.io/name` and `app.kubernetes.io/instance`. For direct exposure, set `service.type: LoadBalancer` and `service.loadBalancerSourceRanges`. Optional `networkPolicy.enabled` restricts ingress to `networkPolicy.ingressFrom` on port 1935; an empty list denies ingress. Include the proxy's actual source ranges or Pod selectors and verify kubelet probes with your CNI.+## Standalone deployment {#standalone-deployment}A standalone gateway does not read `ov.conf`. It only needs the OpenViking address, so an existing open-source or OpenViking Cloud service needs no configuration change.@@ -133,12 +164,17 @@ Without an OpenViking address from either source, the gateway exits and asks you### Startup checks {#startup-checks}-Before it starts, a standalone gateway contacts OpenViking once:+When a Redis port is selected, startup PING must succeed. Wrong addresses or credentials, or an unavailable Redis service, fail startup; Kubernetes restarts the container. Use `maxUnavailable: 0` when rolling out. Runtime Redis failures do not change `/health`; failures during authentication return a plain-text HTTP 500 and a traceback in stderr.++Before it starts listening, a standalone gateway checks OpenViking's authentication mode:- If OpenViking uses trusted authentication, the gateway refuses to start.-- When the gateway binds to a non-loopback address, it starts only after confirming that OpenViking uses `api_key` authentication. If OpenViking is unreachable or runs in local dev mode, the gateway exits. Start OpenViking first, or bind to `127.0.0.1`.+- When the gateway binds to a non-loopback address, it starts only after confirming that OpenViking uses `api_key` authentication. Connection failures and HTTP 5xx responses produce a warning and retry after 1, 2, 4, 8, 16, then 30 seconds, with subsequent waits capped at 30 seconds. Dev mode, unknown authentication modes and other errors such as HTTP 404 still cause an immediate exit.+- Loopback binds (`127.0.0.1`, `::1`, `localhost`) probe once and can start while OpenViking is unavailable; they still reject trusted authentication.- When OpenViking runs on another host, connect over TLS or a private network.+The wait happens before the HTTP port opens. In Kubernetes, startup probes continue to fail during this wait: size the `startupProbe` budget (`periodSeconds × failureThreshold`) for the expected OpenViking outage. For example, `periodSeconds: 2` and `failureThreshold: 150` allow about 300 seconds before kubelet restarts the container. The gateway does not impose a separate startup deadline.+### Connecting to the public OpenViking service {#public-openviking-service}A standalone gateway that connects to the public OpenViking service, `https://api.vikingdb.cn-beijing.volces.com/openviking`, without a management key is open to that service's users. The startup log shows the `public_openviking_without_management_key` warning, and Studio shows **This gateway is open to every OpenViking Cloud user**: anyone with an API key for that service can sign in to this gateway and change the upstreams in their account.@@ -206,6 +242,10 @@ Whatever proxy you use, it needs these settings:| Read timeout | At least 600 seconds | The gateway waits up to 600 seconds for a provider by default || Logging of `/gateway/uploads` and `/gateway/downloads` | Leave out the query strings | They carry one-time tokens |+For a standalone gateway, keep `keep_alive_seconds` (default 75) above the load balancer's backend idle timeout.++Once response headers have been sent, idle event streams emit an SSE comment (`: keep-alive`) every 15 seconds, including while OpenViking tools run. SSE clients ignore these comments; they do not change model events or captured replies. Set the proxy's idle timeout above 15 seconds and keep response buffering off. Heartbeats wait for a complete event boundary and are disabled for compressed upstream streams, so retain the longer read timeout above for partial events and the wait before response headers arrive. The heartbeat interval is fixed and does not extend the provider timeout or the tools' total time limit.+Set up authentication and the [public address](#public-address) before you expose the service; see [Public access](12-public-access.md).## Keys and credentials {#keys-and-credentials}@@ -235,7 +275,7 @@ To set one:- **`openviking-gateway init`** (standalone): answer yes to **Require a management key to change upstreams and profiles?**. Init generates an `ovgm_` value, prints it once and saves it to `management_key` in `gateway.conf`.- **Studio** (embedded, root): the confirmation dialog of **Enable gateway** has a checkbox, **Only people with the gateway management key can change upstreams and context profiles**, which is off by default. If you check it, Studio generates an `ovgm_` value, saves it to `gateway.management_key` in `ov.conf` along with `gateway.enabled: true`, and shows it once.- **By hand**: use at least 32 characters, for example from `openssl rand -base64 32`. Put it in `management_key`, or set the `OPENVIKING_GATEWAY_MANAGEMENT_KEY` environment variable, which overrides the file in both forms; see [Configuration reference](../gateway/13-configuration.md#configuration-reference).-- **Compose and Helm**: Compose passes `OPENVIKING_GATEWAY_MANAGEMENT_KEY` into the container; Helm reads it from the `management-key` entry of the Secret named in `gateway.existingSecret`. See [Docker Compose](#docker-compose) and [Helm](#helm).+- **Compose and Helm**: Compose passes `OPENVIKING_GATEWAY_MANAGEMENT_KEY` into the container; Helm reads it from the `management-key` entry of `gateway.existingSecret` (embedded) or `existingSecret` (standalone). See [Docker Compose](#docker-compose) and [Helm](#helm).There is no command-line flag for the management key, because flags show up in process lists and shell history. Setting, changing or removing it takes a restart. It does not revoke issued gateway keys or change existing upstreams and context profiles.@@ -243,7 +283,7 @@ There is no command-line flag for the management key, because flags show up in pIf nobody has the [gateway management key](#gateway-management-key), look where the gateway reads it from, in this order:-1. The `OPENVIKING_GATEWAY_MANAGEMENT_KEY` environment variable, which wins over the files. Compose usually sets it in the `.env` file next to `docker-compose.yml`; Helm reads it from the `management-key` entry of the Secret named in `gateway.existingSecret`.+1. The `OPENVIKING_GATEWAY_MANAGEMENT_KEY` environment variable, which wins over the files. Compose usually sets it in the `.env` file next to `docker-compose.yml`; Helm reads it from the `management-key` entry of `gateway.existingSecret` (embedded) or `existingSecret` (standalone).2. Otherwise, `gateway.management_key` in `ov.conf` (embedded) or `management_key` in `gateway.conf` (standalone). A value written as `$VAR` lives in that environment variable.On an embedded gateway, root can also open `ov.conf` in Studio under **Settings** → **Server configuration** → **File editor**. Keys generated by `openviking-server init` and by Studio's **Enable gateway** are stored there in plain text.@@ -257,7 +297,7 @@ If you can't recover it, replace it:## Encryption {#encryption}-The gateway encrypts stored credentials and conversation state with OpenViking's own encryption (see the [Encryption guide](08-encryption.md)). When encryption is off or not configured, the gateway stores everything in plain text, protected only by file permissions.+The gateway encrypts stored credentials and conversation state with OpenViking's own encryption (see the [Encryption guide](08-encryption.md)). When encryption is off or not configured, the gateway stores values in plain text, protected by storage access controls.- **Embedded**: the gateway follows the server's `encryption` section in `ov.conf`. There is nothing to set for the gateway itself.- **Standalone**: add an `encryption` block to `gateway.conf`. It has exactly the same fields as the `encryption` section of `ov.conf`, for example:@@ -273,6 +313,18 @@ The gateway encrypts stored credentials and conversation state with OpenViking's}```+For a shared deployment, every replica must use the same root key, mounted read-only. Generate a local provider key as **hex text**, not raw bytes:++```bash+umask 077+openssl rand -hex 32 > gateway-root-key+kubectl create secret generic gateway-credentials --from-file=root-key=gateway-root-key+```++Set `existingSecret: gateway-credentials`, `config.encryption.enabled: true` and `config.encryption.provider: local`. Add `management-key` and `redis-password` entries to that Secret when needed.++For `provider: volcengine_kms`, `root-key` is the **KMS ciphertext file**, not hex text. In a protected writable local directory, configure `encryption.volcengine_kms.key_file` to an absolute path, provide KMS credentials through environment references, and start the gateway once. After successful startup, stop it and copy the generated file into the Secret's `root-key` entry. Keep the KMS key ID and credentials consistent across replicas. A missing key file is generated on first use; generation on a read-only Secret mount fails startup. Vault stores its encrypted root key in Vault and does not use this file mount.+Changing the setting later:- **Turning encryption on** is safe: values written before stay readable, and new writes are encrypted.@@ -283,19 +335,85 @@ Data written by the v0.5 gateway, which used its own key, is converted on the fi## Scaling {#scaling}-One storage directory serves one deployment on one host, and an embedded and a standalone gateway must not share a directory. An embedded gateway follows the server's worker setting; a standalone gateway takes `workers`, from 1 to 64. For load balancing, failover or rate limiting across providers, add a service such as LiteLLM as an upstream.+SQLite serves one deployment on one host; do not share its directory across hosts, or between embedded and standalone gateways. A standalone process supports `workers: 1–64`, but in Kubernetes use `workers: 1` and scale Pods. The embedded gateway follows the server's worker and replica limits.++For multiple standalone replicas, set **both** `storage.kernel` and `storage.management` to `redis`, use one shared `storage.redis` connection and `storage.key_prefix`, and use the same read-only encryption root key. The chart rejects multiple replicas if either provider is SQLite. A two-replica starting point, merged with your URL and Secret settings:++```yaml+replicaCount: 2+existingSecret: gateway-credentials+config:+ capture_concurrency: 4+ storage:+ kernel: redis+ management: redis+ key_prefix: "ovgw:"+ redis:+ mode: standalone+ endpoints: ["redis://redis:6379"]+ password_env: OPENVIKING_GATEWAY_REDIS_PASSWORD+ encryption:+ enabled: true+ provider: local+```++For a headless per-key deployment, add `management_api: false`, `openviking_keys: true`, `tenancy: key`, `default_upstreams` and `request_log_sink: stdout`; see [Use an OpenViking API key directly](../gateway/09-gateway-keys.md#openviking-keys) and [Deployment default upstreams](../gateway/07-upstreams.md#deployment-default-upstreams). Without the management API, deleting a user in OpenViking does not reach the gateway; that user's gateway data expires through [retention](../gateway/11-security-and-data.md#retention). A service in front of such a deployment follows the [host integration contract](#host-integration-contract).++Redis `mode: standalone` covers a single endpoint, including a managed proxy; `mode: cluster` uses Redis Cluster endpoints and database 0. Use `rediss://` for TLS and never embed credentials in endpoint URLs. `pool_size` caps the Redis commands in flight per process; further commands wait for a free connection. Keep `pool_size >= capture_concurrency + 8`. Redis is in the authentication path: a total outage returns HTTP 500. Use replication and automatic failover for availability, and configure memory and persistence as described in [Redis memory policy](#redis-memory-policy).++Redis deployments use `RollingUpdate` with `maxUnavailable: 0`, `maxSurge: 1`, and a PDB with `maxUnavailable: 1` when there are multiple replicas. Use `affinity` to spread replicas across nodes. Management changes and issued-key revocations can take up to **2 seconds** to reach another replica because each process caches management records.++All probes call `/health` without credentials; it reports local state without calling OpenViking or Redis. Startup has a 300-second probe budget (`2 × 150`). After startup, an OpenViking outage does not remove Pods from service.++The shutdown budget is `15s preStop + upstream_timeout_seconds + up to 100s capture drain`. The chart's default `terminationGracePeriodSeconds: 660` covers preStop and a stream that runs to the default 600-second upstream timeout; if Kubernetes stops capture delivery before it drains, another replica picks it up after its lease expires. To let captures finish draining before the Pod is killed, raise it to `15 + upstream_timeout_seconds + 100` (715 with the default timeout).++### Host integration contract {#host-integration-contract}++A service in front of a headless gateway, such as one that picks the model endpoint for each request, forwards the client's request with these headers:++| Header | Value |+| --- | --- |+| `X-API-Key` or `Authorization: Bearer` | The client's OpenViking API key, passed through unchanged |+| `X-OpenViking-Upstream-URL` | The chosen endpoint. It must equal the `base_url` of a `default_upstreams` entry; any other value returns 403 and nothing is sent. See [Pick the upstream per request](../gateway/07-upstreams.md#upstream-url-header) |+| `X-OpenViking-Upstream-Key` | The provider API key, for an upstream with `auth_mode: passthrough` |+| Other headers | The client's own headers, such as `X-OpenViking-Session` and `X-OpenViking-Context`, passed through |++The gateway removes every `X-OpenViking-*` header, the client's credentials and hop-by-hop headers before it forwards the request to the provider.++## Redis memory policy {#redis-memory-policy}++Give the gateway its own Redis instance; do not share it with OpenViking's `expiry_redis_host` timer store. Start from this `redis.conf`, with `maxmemory` sized for your workload:++```conf+maxmemory 2gb+maxmemory-policy volatile-lru+appendonly yes+appendfsync everysec+```++`volatile-lru` evicts only data that expires anyway: conversation state, replay, pending capture and OpenViking key records. What each loss costs is listed under [Redis conversation state](../gateway/11-security-and-data.md#redis-conversation-state). Do not use `allkeys-*`: it can also evict data with no TTL, so issued keys, upstreams and profiles disappear, deleted conversation state can come back, and pending capture is no longer scheduled. `noeviction` also works, but once memory is full, writes fail and requests lose memory enhancement.++Monitor the rate of `evicted_keys` and memory usage; with enough capacity, nothing is evicted. The gateway does not check the eviction policy or any other Redis setting. To watch the capture backlog, `ZCARD <key_prefix>v1:k:{cap}:ready` counts scheduled or in-progress captures, including a few stale entries that are removed later. In Redis Cluster all capture data lives on one shard, so size that shard for the backlog an OpenViking outage builds up. Capture leases use the Redis clock, but scheduling times come from the gateway hosts; keep them synchronized with NTP.++Without persistence, a Redis restart deletes all gateway management data: issued gateway keys stop working, and upstreams and profiles must be set up again. AOF keeps this data, pending capture and deletions across restarts. On Redis 7.2, keep command permissions on a disabled `default` user (for example `user default off ~* &* +@all`): AOF replay checks them for transactions, and without them the replayed writes fail with `NOPERM`. `appendfsync everysec` can still lose about one second of writes, and asynchronous failover can lose the latest ones. Allow extra memory for copy-on-write during AOF rewrites and snapshots. Backups may retain data deleted after they were taken.## Monitoring and routine checks {#monitoring}-The gateway exports no metrics such as Prometheus and writes no HTTP access log. Check its state on Studio's [Overview and Requests](../gateway/10-overview-and-requests.md#overview) tabs, or through the management API's `/gateway/admin/overview` and `/gateway/admin/logs`.+The gateway exports no metrics such as Prometheus. By default, request logs are stored and available on Studio's [Overview and Requests](../gateway/10-overview-and-requests.md#overview) tabs, or through the management API's `/gateway/admin/overview` and `/gateway/admin/logs`.++Set `request_log_sink: "stdout"` in the gateway configuration, or `OPENVIKING_GATEWAY_REQUEST_LOG_SINK=stdout`, and restart to send new records only to stdout. Each finished model request and background saving status change produces one JSON line, flushed immediately even when stdout is a pipe. Each record includes `time` (Unix seconds when written), `account`, `user_id` (possibly `null` for older saving state), and the existing request metrics at the top level, such as `kind`, `status`, `input_tokens` and `cached_tokens`. Credentials, prompts and replies are not included. The collector controls retention and access to these records; `log_retention_days` applies only to stored logs.++When `management_api: false` disables Studio and the management endpoints, configure the stdout sink and collect process or container logs for monitoring. The same workflow applies with the stdout sink when management is enabled: the Requests page and Overview's request figures have no new records. Previously stored records remain visible until they expire.++Aggregate reasons and first-call cache results from the request log's top-level fields. Alert on capture pauses (`kind: capture`), capture queue growth, `openviking_http_429`, Redis memory/evictions and HTTP error rates. Identify rejection happens before a proxy request is logged, so count its 401/402/403 responses and Redis-related 500s in proxy access logs; use gateway stderr for their traceback. Proxy concurrent connections can approximate active streams. Confirm your platform collects stdout; a mounted directory alone does not redirect it to files.### Routine checks {#day-to-day-operations}- **Liveness:** `/health`, which is the server's health check in an embedded deployment and the gateway's own in a standalone one.-- **Gateway health:** the **First-call cache hit rate** on the Overview tab ([what it means](../gateway/10-overview-and-requests.md#overview)). If it drops noticeably, see [The first-call cache hit rate dropped](../gateway/12-troubleshooting.md#the-first-call-cache-hit-rate-dropped).-- **A single request:** expand its row on the Requests tab; see [Requests](../gateway/10-overview-and-requests.md#requests).+- **Gateway health:** the **First-call cache hit rate** on the Overview tab ([what it means](../gateway/10-overview-and-requests.md#overview)), or calculate it from stdout metrics: within an account and time window, select `kind: "user"` records and divide the sum of `first_upstream_cached_tokens` by the sum of `first_upstream_input_tokens`. For each missing field, use that record's `cached_tokens` or `input_tokens` instead (missing usage counts as 0). A zero denominator means no reported input usage. These are top-level fields, not a nested `metrics` object. If the rate drops noticeably, see [The first-call cache hit rate dropped](../gateway/12-troubleshooting.md#the-first-call-cache-hit-rate-dropped).+- **A single request:** expand its row on the Requests tab, or find its stdout record by `account`, `user_id` and `request_id`; see [Requests](../gateway/10-overview-and-requests.md#requests). Background saving events use `kind: "capture"` and identify the conversation with its hashed `session`.- **Public address:** `public_url` still matches the address clients use; see [Public address](#public-address).-- **Backups:** the storage directory and, with encryption on, the encryption root key; see [Backups and recovery](../gateway/11-security-and-data.md#backups).+- **Backups:** the SQLite directory or Redis persistence/backup, and, with encryption on, the encryption root key; see [Backups and recovery](../gateway/11-security-and-data.md#backups).## Upgrades {#upgrades}@@ -303,6 +421,10 @@ The gateway exports no metrics such as Prometheus and writes no HTTP access log.- A standalone gateway needs OpenViking Server `min_server_version` (0.4.16) or later. With an older server, no keys can be issued and saving retries fail with `openviking_version_mismatch`; memory search may also fail, shown as `openviking_http_<status>`. When you upgrade the two separately, upgrade OpenViking first, then the gateway. An embedded gateway ships with its server and skips this check.- To move from the sidecar or an older standalone gateway, see [Migration](#migration).+- Switching SQLite to Redis starts a fresh conversation cache. Re-create issued `ovgw_` keys, upstreams and profiles in management storage; no migration command is provided. Deployment defaults can supply upstreams and profiles for OpenViking-key access.+- Redis keys include the layout version (`<storage.key_prefix>v1:`). A rollback with the same layout can read existing state. A future layout-version change starts fresh: conversation state expires as cache data, OpenViking key records rebuild on access, and deployments with issued keys must reconfigure them. Do not assume cross-version data migration.+- For an emergency stop, remove the proxy route or scale the gateway Deployment to zero. Clients can switch their base URL back to their model provider and keep using their model credential; gateway memory is then unavailable. Roll back with `helm rollback` only to a build compatible with the configured fields and Redis layout.+## Migration from earlier releases {#migration}These steps apply when you move from the sidecar or standalone gateway of earlier releases to the embedded gateway. Steps 4 and 7 are detailed in the tables after the list.@@ -315,7 +437,7 @@ These steps apply when you move from the sidecar or standalone gateway of earlie4. **Update client addresses and deployment config.** Every gateway URL now lives under `/gateway`, so clients change both the port and the path, and the old paths are not served any more; see [New addresses](#new-addresses). Remove the old 1935 Service and Ingress routes, the Compose `gateway` service and profile, and the Helm sidecar settings `gateway.workers`, `gateway.port` and `gateway.resources`.5. **Let the first start convert stored data.** The v0.5 gateway encrypted its data with its own key. On the first start, the new gateway (embedded or standalone) decrypts it with that key and rewrites it under the current [encryption](#encryption) settings, or in plain text when encryption is off, so turn on OpenViking encryption before this start if you want the data to stay encrypted.- The old key is read from the `OPENVIKING_GATEWAY_ENCRYPTION_KEY` environment variable, or from `encryption.key` in `storage_path`. `encryption_key_env` is ignored: if you used it to point at another variable, export the key as `OPENVIKING_GATEWAY_ENCRYPTION_KEY` for this start. If old encrypted data exists and neither source has the key, the gateway refuses to start and the error names both places. With Helm, keep the `encryption-key` entry in the `existingSecret` Secret for the upgrade release only. After a successful start the old key is never read again, so you can remove the variable, the Secret entry and `encryption.key`.+ The old key is read from the `OPENVIKING_GATEWAY_ENCRYPTION_KEY` environment variable, or from `encryption.key` in `storage_path`. `encryption_key_env` is ignored: if you used it to point at another variable, export the key as `OPENVIKING_GATEWAY_ENCRYPTION_KEY` for this start. If old encrypted data exists and neither source has the key, the gateway refuses to start and the error names both places. With the embedded Helm chart, keep the `encryption-key` entry in the `gateway.existingSecret` Secret for the upgrade release only. With the standalone chart, inject the migration variable through `extraEnv` for that upgrade. After a successful start the old key is never read again, so you can remove the variable, the Secret entry and `encryption.key`.6. **Remove the shared admin token.** `OPENVIKING_GATEWAY_ADMIN_TOKEN` is **not** used as a management key. To restrict who can change upstreams and context profiles, set `management_key` explicitly; see [Gateway management key](#gateway-management-key).7. **Check upstream addresses.** On the first start, the gateway rewrites stored Base URLs once, so each upstream keeps calling the same address as before the upgrade; see [How stored upstream addresses change](#upstream-address-rewrite). Use **Test** on the Upstreams tab to confirm each one still answers.8. **Note the changes to logs and revocation.** Request logs gain a user column; older records have no user and appear only in account admin and root views. Revoking a key no longer deletes the user's data; explicit deletion and retention still apply.diff --git a/docs/images/gateway/architecture.en.svg b/docs/images/gateway/architecture.en.svgindex e1901071d..072dde8d1 100644--- a/docs/images/gateway/architecture.en.svg+++ b/docs/images/gateway/architecture.en.svg@@ -66,7 +66,7 @@<line x1="1190" y1="362" x2="1190" y2="516" stroke="#7F3BF5" stroke-width="1.5"/><ellipse cx="1065.0" cy="362" rx="125.0" ry="16" fill="#FFFFFF" stroke="#7F3BF5" stroke-width="1.5"/><text x="1065" y="400" font-family="Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Noto Sans SC', 'Noto Sans CJK SC', sans-serif" font-size="16" font-weight="700" fill="#1F2329" text-anchor="middle">Gateway local state</text>-<text x="1065" y="421" font-family="Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Noto Sans SC', 'Noto Sans CJK SC', sans-serif" font-size="14" font-weight="400" fill="#646A73" text-anchor="middle">Two SQLite files</text>+<text x="1065" y="421" font-family="Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Noto Sans SC', 'Noto Sans CJK SC', sans-serif" font-size="14" font-weight="400" fill="#646A73" text-anchor="middle">SQLite by default, or Redis</text><text x="1065" y="446" font-family="Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Noto Sans SC', 'Noto Sans CJK SC', sans-serif" font-size="14" font-weight="400" fill="#1F2329" text-anchor="middle">Management: upstreams, keys,</text><text x="1065" y="465" font-family="Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Noto Sans SC', 'Noto Sans CJK SC', sans-serif" font-size="14" font-weight="400" fill="#1F2329" text-anchor="middle">profiles, request logs</text><text x="1065" y="490" font-family="Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Noto Sans SC', 'Noto Sans CJK SC', sans-serif" font-size="14" font-weight="400" fill="#1F2329" text-anchor="middle">Conversations: added memory,</text>@@ -106,8 +106,8 @@<line x1="1190" y1="830" x2="1190" y2="960" stroke="#7F3BF5" stroke-width="1.5"/><ellipse cx="1065.0" cy="830" rx="125.0" ry="16" fill="#FFFFFF" stroke="#7F3BF5" stroke-width="1.5"/><text x="1065" y="868" font-family="Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Noto Sans SC', 'Noto Sans CJK SC', sans-serif" font-size="16" font-weight="700" fill="#1F2329" text-anchor="middle">Gateway local state</text>-<text x="1065" y="896" font-family="Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Noto Sans SC', 'Noto Sans CJK SC', sans-serif" font-size="14" font-weight="400" fill="#1F2329" text-anchor="middle">Same two SQLite files,</text>-<text x="1065" y="915" font-family="Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Noto Sans SC', 'Noto Sans CJK SC', sans-serif" font-size="14" font-weight="400" fill="#1F2329" text-anchor="middle">on the gateway's host</text>+<text x="1065" y="896" font-family="Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Noto Sans SC', 'Noto Sans CJK SC', sans-serif" font-size="14" font-weight="400" fill="#1F2329" text-anchor="middle">Same storage options:</text>+<text x="1065" y="915" font-family="Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Noto Sans SC', 'Noto Sans CJK SC', sans-serif" font-size="14" font-weight="400" fill="#1F2329" text-anchor="middle">local SQLite or shared Redis</text><text x="1260" y="142" font-family="Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Noto Sans SC', 'Noto Sans CJK SC', sans-serif" font-size="17" font-weight="700" fill="#FF8800" text-anchor="start">Upstream model providers</text><rect x="1260" y="160" width="300" height="620" rx="10" fill="#FFF3E8" stroke="#FF8800" stroke-width="1.5"/><text x="1410" y="420" font-family="Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Noto Sans SC', 'Noto Sans CJK SC', sans-serif" font-size="16" font-weight="400" fill="#1F2329" text-anchor="middle">Anthropic · OpenAI · DeepSeek</text>diff --git a/docs/images/gateway/architecture.zh.svg b/docs/images/gateway/architecture.zh.svgindex 2d67ecd51..5ea6a7e5a 100644--- a/docs/images/gateway/architecture.zh.svg+++ b/docs/images/gateway/architecture.zh.svg@@ -66,7 +66,7 @@<line x1="1190" y1="362" x2="1190" y2="516" stroke="#7F3BF5" stroke-width="1.5"/><ellipse cx="1065.0" cy="362" rx="125.0" ry="16" fill="#FFFFFF" stroke="#7F3BF5" stroke-width="1.5"/><text x="1065" y="400" font-family="Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Noto Sans SC', 'Noto Sans CJK SC', sans-serif" font-size="16" font-weight="700" fill="#1F2329" text-anchor="middle">网关本地状态</text>-<text x="1065" y="421" font-family="Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Noto Sans SC', 'Noto Sans CJK SC', sans-serif" font-size="14" font-weight="400" fill="#646A73" text-anchor="middle">两个 SQLite 文件</text>+<text x="1065" y="421" font-family="Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Noto Sans SC', 'Noto Sans CJK SC', sans-serif" font-size="14" font-weight="400" fill="#646A73" text-anchor="middle">默认 SQLite,也可用 Redis</text><text x="1065" y="446" font-family="Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Noto Sans SC', 'Noto Sans CJK SC', sans-serif" font-size="14" font-weight="400" fill="#1F2329" text-anchor="middle">管理库:上游、密钥、</text><text x="1065" y="465" font-family="Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Noto Sans SC', 'Noto Sans CJK SC', sans-serif" font-size="14" font-weight="400" fill="#1F2329" text-anchor="middle">上下文配置、请求日志</text><text x="1065" y="490" font-family="Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Noto Sans SC', 'Noto Sans CJK SC', sans-serif" font-size="14" font-weight="400" fill="#1F2329" text-anchor="middle">对话状态库:补充的记忆、</text>@@ -106,8 +106,8 @@<line x1="1190" y1="830" x2="1190" y2="960" stroke="#7F3BF5" stroke-width="1.5"/><ellipse cx="1065.0" cy="830" rx="125.0" ry="16" fill="#FFFFFF" stroke="#7F3BF5" stroke-width="1.5"/><text x="1065" y="868" font-family="Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Noto Sans SC', 'Noto Sans CJK SC', sans-serif" font-size="16" font-weight="700" fill="#1F2329" text-anchor="middle">网关本地状态</text>-<text x="1065" y="896" font-family="Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Noto Sans SC', 'Noto Sans CJK SC', sans-serif" font-size="14" font-weight="400" fill="#1F2329" text-anchor="middle">同样两个 SQLite 文件,</text>-<text x="1065" y="915" font-family="Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Noto Sans SC', 'Noto Sans CJK SC', sans-serif" font-size="14" font-weight="400" fill="#1F2329" text-anchor="middle">和网关在同一台主机上</text>+<text x="1065" y="896" font-family="Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Noto Sans SC', 'Noto Sans CJK SC', sans-serif" font-size="14" font-weight="400" fill="#1F2329" text-anchor="middle">相同的存储选项:</text>+<text x="1065" y="915" font-family="Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Noto Sans SC', 'Noto Sans CJK SC', sans-serif" font-size="14" font-weight="400" fill="#1F2329" text-anchor="middle">本地 SQLite 或共享 Redis</text><text x="1260" y="142" font-family="Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Noto Sans SC', 'Noto Sans CJK SC', sans-serif" font-size="17" font-weight="700" fill="#FF8800" text-anchor="start">上游模型服务商</text><rect x="1260" y="160" width="300" height="620" rx="10" fill="#FFF3E8" stroke="#FF8800" stroke-width="1.5"/><text x="1410" y="420" font-family="Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Noto Sans SC', 'Noto Sans CJK SC', sans-serif" font-size="16" font-weight="400" fill="#1F2329" text-anchor="middle">Anthropic · OpenAI · DeepSeek</text>diff --git a/docs/zh/about/02-changelog.md b/docs/zh/about/02-changelog.mdindex 4b3c44461..ac9d5151a 100644--- a/docs/zh/about/02-changelog.md+++ b/docs/zh/about/02-changelog.md@@ -7,6 +7,24 @@ OpenViking 的所有重要变更都将记录在此文件中。## 未发布+- **网关部署与行为**:+ - 新增独立 Helm chart `deploy/helm/openviking-gateway`:带 PVC 的单副本 SQLite,+ 或共享 Redis 的多副本部署。在包含这些功能的版本发布之前,需要显式设置 `image.tag`,+ 见[运维指南](../guides/22-gateway-operations.md#helm)。+ - 新增可选设置:`storage`(Redis)、`management_api`、`openviking_keys`、`tenancy`、+ `default_upstreams` 和 `default_profile`、`request_log_sink`、`capture_concurrency` 以及 `keep_alive_seconds`。+ 默认存储仍是 SQLite。+ - 新增 `X-OpenViking-Upstream-URL` 请求头,按 Base URL 从允许的上游中选择一个,+ 见[按请求指定上游](../gateway/07-upstreams.md#upstream-url-header)。+ - 无需修改配置的行为变化:独立网关 keep-alive 从 5 秒提高到 75 秒;+ 绑定公网地址的网关在启动时遇到 OpenViking 不可达或返回 5xx 会等待并重试;+ 空闲 SSE 流每 15 秒发送一条注释心跳;OpenViking 以 402 或 403 拒绝密钥的请求会被拒绝,+ 不再转发;保存时收到 OpenViking 401、且 `/health` 也返回 401 时,会以 `gateway_key_revoked`+ 暂停保存。+- **火山引擎 KMS `key_file`(升级需操作)**:`encryption.volcengine_kms.key_file` 现在对服务端和网关+ 都会生效;此前版本忽略该字段,根密钥始终位于 `~/.openviking/openviking-volcengine-root-key.enc`。+ 如果配置了 `key_file`,升级前把该文件移到配置的路径。配置的文件不存在而默认文件存在时,+ 启动会失败,不会生成新的根密钥。- **LangChain 导入迁移(不兼容变更)**:服务端不再提供`openviking.integrations.langchain` 及其转发模块,旧导入会立即失败,不提供弃用过渡期或兼容占位模块。请安装 `langchain-openviking`diff --git a/docs/zh/gateway/01-how-it-works.md b/docs/zh/gateway/01-how-it-works.mdindex b037ee2e9..250477c5a 100644--- a/docs/zh/gateway/01-how-it-works.md+++ b/docs/zh/gateway/01-how-it-works.md@@ -132,8 +132,8 @@ Relevant memory from OpenViking. It is this user's own saved history (past conve| 记忆放在哪 | 附加在最新用户消息末尾,而不是系统提示词里:系统提示词改一个字整份缓存就失效;附加在末尾并在之后原样放回,前缀始终不变。 | 网关必须可靠地记下每处补充的原文,记录丢失时缓存失效一次。 || 保存时机 | 晚一轮保存:下一条消息带回上一轮,才能确认用户保留了它。 | 最后一轮要等**最新回复等待时长**(默认 10 分钟)之后才保存。 || 长对话 | 由网关让同一个模型写摘要:只有网关知道模型实际收到了什么,摘要请求也大部分命中缓存。 | 触发压缩的那一轮多一次模型调用和计费;截断点之前的原文不再发给模型。 |-| 本地状态 | 单台主机上的 SQLite,不引入 Postgres、Redis 这类依赖,适合自部署。 | 网关不能多机互备,是模型调用路径上的单点。 |-| 客户端身份 | 网关签发自己的密钥,而不是直接用 OpenViking 密钥:可以单独吊销,同一个人的不同客户端可以绑定不同的上下文配置。 | 网关要保存用户的 OpenViking 密钥,因此应开启加密;网关密钥泄露,等于该用户的记忆泄露。 |+| 存储 | 默认 SQLite,无外部依赖;Redis 可以在多个主机之间共享状态。 | 多副本要求两个存储后端都使用共享 Redis,并使用相同的加密根密钥。 |+| 客户端身份 | 默认情况下,网关签发自己的密钥,而不是直接用 OpenViking 密钥:可以单独吊销,同一个人的不同客户端可以绑定不同的上下文配置。打开 `openviking_keys` 后,客户端也可以直接用 OpenViking API 密钥,使用账号默认的上下文配置和上游。 | 网关要保存用户的 OpenViking 密钥,因此应开启加密;网关密钥泄露,等于该用户的记忆泄露。直接使用的 OpenViking 密钥只能在 OpenViking 中吊销。 |## 下一步 {#next-steps}diff --git a/docs/zh/gateway/03-connect-clients.md b/docs/zh/gateway/03-connect-clients.mdindex 6424d284f..7d0aa77ad 100644--- a/docs/zh/gateway/03-connect-clients.md+++ b/docs/zh/gateway/03-connect-clients.md@@ -4,7 +4,7 @@ description: 把 Claude Code、Codex、聊天应用、SDK 等客户端接入 Ope# 把客户端接入 OpenViking 网关-本页按客户端给出具体配置,以及验证配置是否生效的方法。每个客户端都需要三样东西:网关地址、网关密钥,以及这把密钥绑定的一个已启用上游——它要支持客户端使用的协议,并提供客户端请求的模型。还没有网关密钥?先看[快速上手](02-quickstart.md)。+本页按客户端给出具体配置,以及验证配置是否生效的方法。每个客户端都需要三样东西:网关地址、网关密钥(部署方开启 `openviking_keys` 时,也可以用用户的 OpenViking API 密钥,见[直接使用 OpenViking API 密钥](09-gateway-keys.md#openviking-keys)),以及这把密钥绑定的一个已启用上游——它要支持客户端使用的协议,并提供客户端请求的模型。还没有网关密钥?先看[快速上手](02-quickstart.md)。以下两条限制对所有客户端都适用:@@ -32,12 +32,22 @@ description: 把 Claude Code、Codex、聊天应用、SDK 等客户端接入 Ope默认情况下,服务商的 API Key 由网关保管,客户端只需发送网关密钥。[上游](07-upstreams.md#upstreams)也可以把 **API Key 由谁提供**设为**每个客户端自带 API Key**(见[凭证](07-upstreams.md#credentials))。这时客户端仍把网关密钥填在原来填 API Key 的地方,同时在每个请求里用 `X-OpenViking-Upstream-Key` 请求头带上自己的服务商 API Key。在 Studio 中,**接入**标签页的**客户端自带服务商 API Key**卡片会列出哪些上游需要它。-缺了这个请求头,所有请求都会返回 401 `Upstream API key is missing`。各客户端的添加方式:+缺了这个请求头,所有请求都会返回 401 `Upstream API key is missing`。各客户端的添加方式见[在客户端里添加请求头](#add-a-header)。-| 客户端 | 如何发送 `X-OpenViking-Upstream-Key` |+## 覆盖上下文配置 {#override-profile-settings}++客户端可以用 `X-OpenViking-Context` 请求头,为新对话修改密钥所用上下文配置的设置。它的值是一个 JSON 对象,列出要修改的字段,例如 `{"recall":false}` 表示不召回,`{"disabled_tools":[]}` 表示提供全部 OpenViking 工具,包括会修改数据的工具。配置需要开启**允许客户端覆盖设置**(默认开启);请求头能包含什么、可能返回哪些错误,见[允许客户端覆盖设置](08-context-profiles.md#client-overrides)。各客户端的添加方式见[在客户端里添加请求头](#add-a-header)。++对话会沿用开始时的设置,所以修改后的请求头从下一段新对话起生效,例如换一个新的 `X-OpenViking-Session` 值。与所有 `X-OpenViking-*` 请求头一样,它不会转发给服务商。++## 在客户端里添加请求头 {#add-a-header}++上面两个请求头都要随每个请求发送。各客户端的添加方式:++| 客户端 | 如何添加请求头 || --- | --- |-| Claude Code | `export ANTHROPIC_CUSTOM_HEADERS='X-OpenViking-Upstream-Key: <provider-key>'` |-| Codex CLI | 在服务商配置里使用 `env_http_headers`,例如 `env_http_headers = { "X-OpenViking-Upstream-Key" = "PROVIDER_API_KEY" }`,并把服务商 API Key 导出为 `PROVIDER_API_KEY` |+| Claude Code | `export ANTHROPIC_CUSTOM_HEADERS='<Name>: <value>'`。有多个请求头时每行一个,例如 `export ANTHROPIC_CUSTOM_HEADERS=$'X-OpenViking-Upstream-Key: <provider-key>\nX-OpenViking-Context: {"recall":false}'` |+| Codex CLI | 在服务商配置里,固定值用 `http_headers`,例如 `http_headers = { "X-OpenViking-Context" = '{"recall":false}' }`;从环境变量读取用 `env_http_headers`,例如 `env_http_headers = { "X-OpenViking-Upstream-Key" = "PROVIDER_API_KEY" }`,并把服务商 API Key 导出为 `PROVIDER_API_KEY` || OpenAI 和 Anthropic SDK | 在客户端上设置 `default_headers`,或在每个请求里传 `extra_headers` || Open WebUI | 加到连接的自定义请求头里,与会话请求头放在一起 |diff --git a/docs/zh/gateway/06-manage-in-studio.md b/docs/zh/gateway/06-manage-in-studio.mdindex 219fe4467..cef097d70 100644--- a/docs/zh/gateway/06-manage-in-studio.md+++ b/docs/zh/gateway/06-manage-in-studio.md@@ -6,6 +6,8 @@ description: Studio 中 OpenViking 网关页面的使用方法:各标签页、本页面向在 Studio 里使用网关页面的人,说明各标签页的用途、谁能修改什么,以及保存的修改何时生效。用你的 OpenViking API 密钥打开 Studio([本地 dev 模式](02-quickstart.md#local-server-no-api-key)的服务无需密钥),在侧边栏选择 **OpenViking 网关**;独立部署的网关在自己的 `/studio/` 下提供 Studio。上游和上下文配置由同一 OpenViking 账号下的所有用户共享,网关密钥和请求日志则属于各个用户。+设置 [`management_api: false`](13-configuration.md#gateway-fields) 后,网关管理 API 不再可用,独立网关也不再提供 Studio。嵌入部署中,OpenViking Server 仍提供自己的 Studio,但网关页面会因 `/gateway/admin/access` 返回 404 而报错。修改后需要重启宿主。+## Studio 标签页 {#studio-tabs}网关页面共有六个标签页,每行都链接到详细说明该标签页的文档。diff --git a/docs/zh/gateway/07-upstreams.md b/docs/zh/gateway/07-upstreams.mdindex 0521f95d6..d10305521 100644--- a/docs/zh/gateway/07-upstreams.md+++ b/docs/zh/gateway/07-upstreams.md@@ -29,6 +29,15 @@ description: 添加和配置 OpenViking 网关转发请求的模型服务地址| 火山方舟 | 三种都有 | Chat Completions 和 Responses 为 `https://ark.cn-beijing.volces.com/api/v3`;Anthropic Messages 为 `https://ark.cn-beijing.volces.com/api/compatible` || BytePlus 方舟(海外站) | 三种都有 | Chat Completions 和 Responses 为 `https://ark.ap-southeast.bytepluses.com/api/v3`;Anthropic Messages 为 `https://ark.ap-southeast.bytepluses.com/api/compatible` |+## 部署默认上游 {#deployment-default-upstreams}++运维可以在网关配置中设置 `default_upstreams`,供[直接使用 OpenViking API 密钥](09-gateway-keys.md#openviking-keys)的客户端使用,见[配置示例](13-configuration.md#gateway-fields)。++- 仅在账号没有存储上游时生效。账号一旦存储任何上游,就整组替换部署默认值,即使存储的上游全部已停用。+- 部署默认值不会复制到账号存储中,也不会在 Studio 中显示。签发的网关密钥继续使用它们选定的已存储上游。+- 保持对象的 key(例如 `ark-chat`)稳定:它就是冻结到对话中、供后续轮次路由使用的上游 ID。+- 托管凭证写成 `"api_key": "$ARK_API_KEY"`,Helm 部署通过 `extraEnv` 从 Secret 注入 `ARK_API_KEY`。网关加载文件时展开环境变量引用,不要把明文 API 密钥写进 ConfigMap。+## 添加上游 {#add-an-upstream}1. 在**上游**标签页点**添加上游**,打开**新建上游**编辑页。页面分为**接口**、**凭证**、**模型**和**路由**四部分。@@ -149,6 +158,15 @@ Claude 订阅令牌(`sk-ant-oat…`)无论怎么勾选都会被拒绝,见[网关不做故障转移:选中的上游出错时,客户端收到这个错误;服务商无法访问时返回 502 "Model upstream is unavailable"。+### 按请求指定上游 {#upstream-url-header}++部署在网关前面的服务可以用 `X-OpenViking-Upstream-URL` 请求头为每个请求选择上游,客户端也可以发送这个请求头。它的值必须与密钥绑定的某个上游的 **Base URL** 相同(没有已存上游的 OpenViking 密钥,对应[部署默认上游](#deployment-default-upstreams)),只忽略末尾的 `/`。这个请求头把路由范围缩小到这些上游,再按常规的 API、模型和**优先级**规则从中选择,所以 Chat Completions 上游和 Responses 上游可以共用一个 Base URL。++- 没有绑定的上游使用这个 Base URL:请求返回 403 "Upstream URL is not allowed"。网关从不向未配置的地址发请求。+- 网关照常使用选中上游的凭证。**每个客户端自带 API Key** 时,API Key 来自 `X-OpenViking-Upstream-Key`;Coding Plan 上游未放行时仍会被拒绝。+- 对话改用另一个 Base URL 时转到那个上游,与停用原上游一样标为**上游已切换**。+- 不带这个请求头时,路由不变。与所有 `X-OpenViking-*` 请求头一样,它不会转发给服务商。+### 补全推理内容回传 {#restore-reasoning}客户端回传历史时,常常丢掉模型之前回复里的推理内容。**补全推理内容回传**在 DeepSeek、火山方舟和 BytePlus 方舟上默认开启,其他服务商默认关闭。diff --git a/docs/zh/gateway/08-context-profiles.md b/docs/zh/gateway/08-context-profiles.mdindex 3fa76fd2a..db17a4d88 100644--- a/docs/zh/gateway/08-context-profiles.md+++ b/docs/zh/gateway/08-context-profiles.md@@ -8,9 +8,11 @@ description: 创建上下文配置,决定 OpenViking 网关为每个网关密## 什么是上下文配置 {#context-profiles}-[上下文配置](../guides/15-gateway.md#key-terms)是一组有名字的记忆设置。每个[网关密钥](09-gateway-keys.md#gateway-keys)在签发时选定一份配置,一份配置可以供多个密钥使用。比如准备一份“Coding”配置,召回记忆、资源和技能;再准备一份“Chat”配置,只召回记忆,预算也小一些。+[上下文配置](../guides/15-gateway.md#key-terms)是一组有名字的记忆设置。每个[网关密钥](09-gateway-keys.md#gateway-keys)在签发时选定一份配置,一份配置可以供多个密钥使用。[直接使用 OpenViking API 密钥](09-gateway-keys.md#openviking-keys)的客户端使用账号中 ID 为 `default` 的配置(快速模式创建的那份),没有时使用部署的 `default_profile`;它们不计入使用这份配置的密钥。比如准备一份“Coding”配置,召回记忆、资源和技能;再准备一份“Chat”配置,只召回记忆,预算也小一些。-一份配置分为四个部分,下表中的默认值也就是推荐设置:+嵌入式 dev 模式在启动时将 `default_profile` 一次性写入 `default` 账号;之后修改 `ov.conf` 不会改变已保存的配置,请在 Studio 中修改。++除了名称和[允许客户端覆盖设置](#client-overrides)开关,一份配置分为四个部分,下表中的默认值也就是推荐设置:| 部分 | 作用 | 主要设置和默认值 || --- | --- | --- |@@ -26,13 +28,13 @@ description: 创建上下文配置,决定 OpenViking 网关为每个网关密### 创建、复制或删除配置 {#manage-profiles}1. 打开 **上下文配置** 标签页。标签页为空时,选择**使用推荐设置创建**可一键创建一份名为“默认”的配置,选择**自定义**则先打开编辑页。已有配置后,改用**新建配置**。-2. 在编辑页填写**名称**,为网关密钥选择配置时会显示这个名称。再按本页的说明调整各部分。+2. 在编辑页填写**名称**,为网关密钥选择配置时会显示这个名称。名称下方的**允许客户端覆盖设置**默认开启,见[允许客户端覆盖设置](#client-overrides)。再按本页的说明调整各部分。3. 选择**创建配置**;编辑已有配置时选择**保存**。之后能看到这份配置的卡片,上面概括了各部分的设置和使用它的密钥数(刚创建时显示**没有密钥在用**)。其他操作:- **复制一份**:在卡片上或编辑页的**更多操作**(⋯)菜单中,打开一份名为“… 副本”的拷贝。想做一份变体,这样最快。-- **恢复推荐设置**:在同一个菜单中,把各项恢复为推荐设置,保存后生效。+- **恢复推荐设置**:在同一个菜单中,把四个部分恢复为推荐设置,名称和**允许客户端覆盖设置**保持不变,保存后生效。- 有密钥在用的配置不能删除。先吊销这些密钥;如果还需要它们,先签发使用其他配置的新密钥来替换。- Studio 处于只读状态时,卡片上显示**查看**而不是**编辑**,也不能创建、复制或删除配置,见[解锁编辑](06-manage-in-studio.md#unlock-editing)。@@ -101,6 +103,24 @@ description: 创建上下文配置,决定 OpenViking 网关为每个网关密每项设置的 API 名称和取值范围见[配置参考](13-configuration.md#context-profile-settings)。+## 允许客户端覆盖设置 {#client-overrides}++**允许客户端覆盖设置**位于配置的**名称**下方,默认开启。开启后,客户端可以为对话修改这份配置的设置:在 `X-OpenViking-Context` 请求头里用 JSON 对象传入要修改的字段,字段名使用[配置参考](13-configuration.md#context-profile-settings)中的 API 名称。例如:++```text+X-OpenViking-Context: {"recall":false,"max_tokens":800,"context_types":["memory"]}+```++- **能改什么。** 除 `name` 和 `client_overrides` 以外的所有设置。请求头没有给出的字段沿用配置中的值。`{"disabled_tools":[]}` 表示提供全部 OpenViking 工具,包括会修改数据的工具和服务端以后新增的工具。+- **何时生效。** 与保存配置的修改一样,对话会沿用开始时的设置:只有对话第一个请求里的请求头决定设置。之后的请求头仍会校验,所以无效的请求头,或开关关闭后的任何请求头,仍会报错。+- **错误。** 开关关闭时,带这个请求头的请求一律返回 403 `context_override_not_allowed`,而不是按已保存的设置处理。开关开启时,请求头有下列情况之一会返回 400 `context_override_invalid`:+ - 不是 JSON 对象;+ - 出现未知字段或 `name`、`client_overrides`;+ - 取值越界。+- **请求日志。** [请求详情](10-overview-and-requests.md#request-details)中列出客户端在请求头里传入了哪些字段,只记名称,不记取值。++这个开关默认开启,所以持有使用这份配置的密钥的人可以修改任意字段,包括预算和会修改数据的工具。对 `default` 配置来说,这也包括所有[直接使用 OpenViking API 密钥](09-gateway-keys.md#openviking-keys)的客户端。需要锁定的配置请关闭它。各客户端如何发送这个请求头,见[覆盖上下文配置](03-connect-clients.md#override-profile-settings)。+## 下一步 {#next-steps}- [签发一个网关密钥](09-gateway-keys.md#issue-a-key),让它使用这份配置。diff --git a/docs/zh/gateway/09-gateway-keys.md b/docs/zh/gateway/09-gateway-keys.mdindex 911dcdea4..4c61d66ca 100644--- a/docs/zh/gateway/09-gateway-keys.md+++ b/docs/zh/gateway/09-gateway-keys.md@@ -16,6 +16,25 @@ description: 签发把客户端接入 OpenViking 网关的网关密钥,并在**密钥**标签页列出你自己的密钥;账号管理员和 root 能看到本账号的全部密钥,并多出一列 **OpenViking 用户**。**密钥**列只显示每把密钥的开头几个字符。+网关密钥是客户端可用的两种凭证之一。另一种是用户自己的 OpenViking API 密钥,需要部署方允许,见[直接使用 OpenViking API 密钥](#openviking-keys)。++## 直接使用 OpenViking API 密钥 {#openviking-keys}++部署方把 [`openviking_keys`](13-configuration.md#gateway-fields) 设为 `true` 后,客户端可以在填网关密钥的地方直接填用户的 OpenViking API 密钥。此时凡是不以 `ovgw_` 开头的密钥,都按 OpenViking API 密钥处理。这个开关默认关闭;关闭时这类密钥直接被拒绝,不会去问 OpenViking。++- **身份就是密钥本身的用户。** 首次请求时,网关先向 OpenViking 确认这把密钥:接受 admin 和 user 密钥,不接受 root 密钥。要换成另一位用户,客户端改用那位用户的密钥即可,没有用来切换身份的 header。+- **使用账号的默认设置。** 使用账号的 `default` [上下文配置](08-context-profiles.md#context-profiles)(没有时用内置默认值)和全部已启用的上游,不限模型。客户端仍可用 `X-OpenViking-Context` 请求头为对话修改这份配置的设置,见[允许客户端覆盖设置](08-context-profiles.md#client-overrides)。+- **网关像保存签发的密钥一样保存它**,所以记忆保存和日志都照常工作。请开启[加密](../guides/22-gateway-operations.md#encryption)。**密钥**标签页把它列为 **OpenViking API 密钥**,配置和上游显示为**账号默认**。+- **只有 OpenViking 能吊销它。** **密钥**标签页上没有它的**吊销**按钮。[删除用户的网关数据](#delete-a-users-gateway-data)会删掉网关保存的副本、日志和对话状态,但仍带着这把密钥的客户端照常可用,从头开始。要让它失效,请在 OpenViking 中重新生成密钥,或关闭 `openviking_keys`。密钥重新生成后,网关会在随后的请求中删除副本,与[网关密钥](#when-the-openviking-key-changes)相同。++默认的 `tenancy: account` 下,同一 OpenViking 账号和用户的密钥共享对话状态。使用 `tenancy: key` 后,每把 OpenViking 密钥都有独立分区,即使两个库返回相同的账号和用户身份也互相隔离。对话、召回、写回、模型绑定和请求日志都使用该分区。此模式要求设置 `management_api: false`,并在启动前配置 `default_upstreams` 和 `default_profile`;Studio 和管理路由不可用。++按密钥隔离时,轮换 OpenViking 密钥会进入新分区并开始新对话。排障时可以不输出密钥,直接计算分区名:`"k_" + hashlib.sha256(("openviking\0" + key).encode()).hexdigest()`。OpenViking 的真实账号身份单独保存,用于吊销检查。++缓存的 OpenViking 密钥及其用户记录,从创建时起经过配置的 `session_ttl_days` 后过期,请求不会续期。下一个请求会向 OpenViking 重新确认密钥并重建记录,分区和对话 scope 保持不变。签发的网关密钥没有这项 TTL。待写回内容和清理行为见[保留期限](11-security-and-data.md#retention)。++如果客户端需要自己的上下文配置、上游或允许的模型,或者需要单独吊销,请使用网关密钥。+## 签发密钥 {#issue-a-key}如果**密钥**标签页提示先添加上游或创建上下文配置,请先完成;自己没有权限时,联系部署网关的人。在全新的网关上,概览页**快速模式**卡片里的**一键生成密钥**可以一步完成这些准备并签发密钥,见[快速开始清单和快速模式](06-manage-in-studio.md#get-started-checklist)。@@ -71,7 +90,7 @@ description: 签发把客户端接入 OpenViking 网关的网关密钥,并在吊销密钥不会删除网关为用户保存的数据。要删除,账号管理员或 root 在**密钥**标签页打开该用户任意一把密钥的 **…** 菜单,选择**删除该用户的网关数据…**,再点**删除网关数据**确认。这一操作会:-- 吊销该用户的全部网关密钥,其客户端立即失去访问权限;+- 吊销该用户的全部网关密钥,其客户端立即失去访问权限;[直接使用该用户 OpenViking API 密钥](#openviking-keys)的客户端仍可使用,直到在 OpenViking 中重新生成这把密钥;- 删除网关为该用户保存的对话状态,包括尚未保存到 OpenViking 的内容;- 删除该用户的请求日志。diff --git a/docs/zh/gateway/10-overview-and-requests.md b/docs/zh/gateway/10-overview-and-requests.mdindex a24476a9c..b15ba2ea5 100644--- a/docs/zh/gateway/10-overview-and-requests.md+++ b/docs/zh/gateway/10-overview-and-requests.md@@ -10,7 +10,9 @@ description: 读懂 Studio 中 OpenViking 网关的“概览”和“请求日两个标签页读的都是网关的请求日志:每个经过网关的模型请求对应一条记录。普通用户只看到自己的请求,账号管理员和 root 看到整个账号的请求。概览里的数字也是从这些记录算出来的,所以统计范围和请求日志一致。-日志只记元数据,从不保存提示词、回复或记忆内容,详见[请求日志记什么](11-security-and-data.md#what-request-logs-record)。记录默认保留 30 天,见[保留期限](11-security-and-data.md#retention)。+设置 `request_log_sink: "stdout"` 后,新记录只写到 stdout。全新部署的请求日志页和概览中的请求统计保持为空;之前已存储的记录仍可见,直到过期。新请求请通过 [stdout 观测流程](../guides/22-gateway-operations.md#monitoring)查看。++日志只记元数据,从不保存提示词、回复或记忆内容,详见[请求日志记什么](11-security-and-data.md#what-request-logs-record)。存储中的记录默认保留 30 天;stdout 的保留期限由日志采集系统管理。见[保留期限](11-security-and-data.md#retention)。## 概览 {#overview}@@ -89,6 +91,7 @@ description: 读懂 Studio 中 OpenViking 网关的“概览”和“请求日- 上下文窗口用量,以及历史是否经过压缩、模型是否开启了新窗口- 保存状态和下次重试时间- OpenViking 工具详情,包括没有提供工具的原因+- 客户端在 `X-OpenViking-Context` 中传入的配置项,只记名称;它们只在对话的第一个请求中生效有异常的请求,展开后还会说明发生了什么、该怎么处理。diff --git a/docs/zh/gateway/11-security-and-data.md b/docs/zh/gateway/11-security-and-data.mdindex f6819d9a1..056bfb863 100644--- a/docs/zh/gateway/11-security-and-data.md+++ b/docs/zh/gateway/11-security-and-data.md@@ -4,27 +4,27 @@ description: OpenViking 网关存储什么、谁能访问、服务商能看到# OpenViking 网关安全与数据-本页写给审批网关部署的运维和安全评审人员,也写给想知道网关保存了自己哪些数据的用户。会话和记忆始终保存在 OpenViking 中,按 OpenViking 自己的规则管理;网关只在 `storage_path` 下的两个 SQLite 文件里保存自身配置、让对话继续所需的状态,以及只含元数据的请求日志。下面每一节回答一个评审问题,都可以单独链接。+本页写给审批网关部署的运维和安全评审人员,也写给想知道网关保存了自己哪些数据的用户。会话和记忆始终保存在 OpenViking 中,按 OpenViking 自己的规则管理;网关默认在本地 SQLite 中、也可以在配置的 Redis 后端中保存自身配置、让对话继续所需的状态,以及只含元数据的请求日志。下面每一节回答一个评审问题,都可以单独链接。## 按用户隔离 {#isolation-by-user}-每把[网关密钥](../guides/15-gateway.md#key-terms)绑定一位 OpenViking 用户。网关用这位用户自己的 OpenViking 密钥检索记忆、保存对话和调用工具,所以能做的事不会超出用户本人的权限。各用户的对话状态互相隔离。+每把[网关密钥](../guides/15-gateway.md#key-terms)绑定一位 OpenViking 用户。网关用这位用户自己的 OpenViking 密钥检索记忆、保存对话和调用工具,所以能做的事不会超出用户本人的权限。各用户的对话状态互相隔离。设置 `tenancy: key` 后,即使账号和用户身份相同,不同 OpenViking 密钥也有独立分区;轮换密钥会进入新分区。## 网关存储什么 {#what-the-gateway-stores}-网关保存的全部数据都在 `storage_path`(默认 `~/.openviking/gateway`)下的两个 SQLite 数据库里:+默认数据保存在 `storage_path`(默认 `~/.openviking/gateway`)下的两个 SQLite 数据库里。两个存储后端都可以分别改用 [Redis](13-configuration.md#storage):| 文件 | 内容 || --- | --- |-| `management.sqlite3` | 上游、上下文配置、网关密钥、请求日志,以及每个 Responses 响应由哪个上游创建 |-| `kernel.sqlite3` | 每段对话的状态:补充到消息中的记忆原文、OpenViking 工具的往返记录及其结果、摘要、等待保存的对话文本,以及开启**补全推理内容回传**时模型回复的推理内容 |+| `management.sqlite3`(或 Redis management) | 上游、上下文配置、网关密钥、使用默认 `store` sink 时的请求日志,以及每个 Responses 响应由哪个上游创建 |+| `kernel.sqlite3`(或 Redis kernel) | 每段对话的状态:补充到消息中的记忆原文、OpenViking 工具的往返记录及其结果、摘要、等待保存的对话文本,以及开启**补全推理内容回传**时模型回复的推理内容 |其中有些属于敏感数据:- `management.sqlite3` 存有上游 API Key、请求头的值,以及网关密钥绑定的 OpenViking 密钥。网关密钥本身只存哈希和一段短前缀。- `kernel.sqlite3` 逐字保存记忆原文,因为网关要靠它把之前几轮补充的内容[原样放回](01-how-it-works.md#replay)。-这两个文件只有运行网关的系统用户能读取。开启[加密](../guides/22-gateway-operations.md#encryption)后,存储的每个值也都会加密;加密关闭时,上面这些凭证以明文存储,只靠文件权限保护。+SQLite 文件只有运行网关的系统用户能读取;Redis 由网络和 ACL 配置控制访问。开启[加密](../guides/22-gateway-operations.md#encryption)后,存储的每个值也都会加密;加密关闭时,上面这些凭证以明文存储,由文件权限或 Redis 访问控制保护。所有副本必须从 Secret 挂载同一把加密根密钥;只读挂载缺少密钥条目时会拒绝启动。Redis 键名使用哈希,但索引可能包含原始账号、对象和会话标识,除值加密之外也应启用 TLS。## 请求日志记什么 {#what-request-logs-record}@@ -37,7 +37,7 @@ description: OpenViking 网关存储什么、谁能访问、服务商能看到| token 数、记忆条数和耗时 | 工具参数和结果 || 保存状态和异常 | 任何密钥 |-网关不写 HTTP 访问日志,错误信息也不回显提交的值。在 Studio 中查看日志,见[请求日志](10-overview-and-requests.md#requests)。+网关不写 HTTP 访问日志,错误信息也不回显提交的值。默认的 `store` sink 使请求日志可在 Studio 中查看,见[请求日志](10-overview-and-requests.md#requests)。`stdout` sink 将相同元数据连同账号和用户标识输出为明文 JSON;存储加密不作用于 stdout。日志采集和访问由部署环境管理,见[观测](../guides/22-gateway-operations.md#monitoring)。## 服务商能看到什么 {#what-providers-see}@@ -65,16 +65,38 @@ description: OpenViking 网关存储什么、谁能访问、服务商能看到## 保留期限 {#retention}-网关数据会自动过期,清理任务每小时运行一次:+网关数据会自动过期。SQLite 每小时执行清理,Redis 使用键 TTL:| 数据 | 保留时长 | 设置 || --- | --- | --- || 对话状态 | 最后一次使用后 30 天 | `session_ttl_days` |-| 请求日志 | 30 天 | `log_retention_days` |+| 缓存的 OpenViking 密钥及其用户记录 | 从创建时起经过配置的 TTL,不续期 | `session_ttl_days` |+| 存储的请求日志 | 30 天 | `log_retention_days` || Responses 响应与上游的对应关系 | 30 天 | `response_ttl_seconds` || OpenViking 中的会话和记忆 | 遵循 OpenViking 自己的规则 | — |-这些设置的最小值和配置位置见[网关字段](13-configuration.md#gateway-fields)。+OpenViking 密钥记录过期,或被使用 `volatile-lru` 的 Redis 后端驱逐后,写回任务因读不到凭据而以 `gateway_key_revoked` 暂停。用户的下一个请求会重建记录,并在同一 scope 中恢复写回。如果用户不再请求,最后一轮待写回内容不会存入 OpenViking。这些状态属于缓存,允许丢失。与吊销一样,现有的短时进程内缓存可能延迟观察到过期。++Redis 每个账号最多保留 10,000 条请求日志。读取时跳过早于 `log_retention_days` 的条目;这些条目仍留在存储中,直到被更新的条目挤出上限,或者该账号连续 `log_retention_days` 没有新日志。Redis 不需要每小时清理。Redis Responses 路由记录按 TTL 过期,删除用户时不扫描它们;被吊销的密钥无法访问这些记录。++这些设置的最小值和配置位置见[网关字段](13-configuration.md#gateway-fields)。 stdout 日志的保留和删除由日志采集器控制,与网关清理独立。++## Redis 对话状态 {#redis-conversation-state}++配置 `storage.kernel: redis` 后,对话状态按缓存保存,TTL 使用 `session_ttl_days`。写入会续期,只读记录不会续期。++驱逐会产生以下影响:++| 丢失的状态 | 影响 |+| --- | --- |+| 回放、召回记忆或恢复的推理 | 无法重放之前的决策,下一次请求发生缓存未命中。压缩摘要丢失后可能需要重新摘要,或使请求超过模型上下文限制。 |+| 待投递的 capture 文档 | 尚未保存的轮次可能丢失。从客户端历史重建时可能重复保存已经投递的消息;持有已丢失文档的 worker 会停止使用旧 lease。 |+| observation 或 thinking 状态 | 召回账本归零,之前的推理可能无法识别。 |+| 另一请求等待期间的工具回执 | 返回超时或结果未知。网关不会重试该操作;重试写操作前应先检查实际状态。 |++Redis 异步主从切换可能丢失最近的写入或 lease,偶尔导致 capture 重复。应持久化 Redis,以保留待投递数据和删除操作;恢复删除之前的快照会使已删除的数据重新可见。见 [Redis 内存策略](../guides/22-gateway-operations.md#redis-memory-policy)。++开启加密后,存储的值会加密。键名使用哈希,但索引成员包含原始 session ID,记录类型、版本、调度时间和 lease owner 仍是明文,应相应保护 Redis 的访问权限和备份。## 删除数据 {#deleting-data}@@ -86,7 +108,7 @@ description: OpenViking 网关存储什么、谁能访问、服务商能看到| root | 调用 `DELETE /gateway/admin/account/data?account_id=<account>` | 整个账号的网关数据 || 嵌入部署,自动进行 | 在 OpenViking 中删除用户或账号 | 对应的网关数据 |-独立部署没有自动删除这一步,数据会一直保留,直到被显式删除或[过期](#retention)。+独立部署没有自动删除这一步,数据会一直保留,直到被显式删除或[过期](#retention)。设置 [`management_api: false`](13-configuration.md#gateway-fields) 后,删除 API 也不可用:在 OpenViking 中删除用户不会通知独立网关,对话状态只能等 `session_ttl_days` 到期后清理。请求日志和响应映射按各自的保留期限过期。按账号隔离的嵌入部署仍保留 Server 的自动删除钩子。按密钥隔离时,钩子无法根据 OpenViking 的账号和用户 ID 找到 `k_` 分区,其缓存数据按上述保留期限清理。已存入 OpenViking 的记忆和会话不受这些操作影响。反过来,在 OpenViking 中删除一条记忆后,网关为进行中的对话保存的那份副本仍会被原样放回,直到对话过期;要立即清除,删除该用户的网关数据。@@ -94,7 +116,8 @@ description: OpenViking 网关存储什么、谁能访问、服务商能看到以下内容要一起备份:-- 整个 `storage_path` 目录:两个数据库及其 `-wal`、`-shm` 文件。+- Redis:启用 AOF,并把 Redis 持久化数据与加密根密钥一起备份。未启用持久化时,重启 Redis 会丢失管理配置和等待写回的对话数据。+- SQLite:整个 `storage_path` 目录:两个数据库及其 `-wal`、`-shm` 文件。- 开启加密时,还有 OpenViking 的加密根密钥(不是 root API 密钥),按[加密指南](../guides/08-encryption.md)的说明保管。要得到一致的副本,先停止网关,或者在运行中使用 SQLite 的在线备份:@@ -108,9 +131,9 @@ sqlite3 management.sqlite3 ".backup management.backup.sqlite3"| 丢失 | 后果 | 怎么办 || --- | --- | --- |-| `kernel.sqlite3` | 之前补充的记忆无法放回。每段进行中的对话会有一次服务商缓存未命中,Claude 对话会丢掉一次之前的思考内容([**记忆记录缺失**](12-troubleshooting.md#issues-on-degraded-requests)),尚未保存的轮次也会丢失。 | 无需处理,进行中的对话在一次未命中之后就会恢复 |-| `management.sqlite3` | 上游、上下文配置、密钥和请求日志全部丢失。 | 重新配置,并签发新密钥 |-| 加密根密钥(开启加密时) | 两个数据库中已加密的值都无法读取。 | 只能从空的 `storage_path` 重新开始 |+| `kernel.sqlite3`(或 Redis kernel) | 之前补充的记忆无法放回。每段进行中的对话会有一次服务商缓存未命中,Claude 对话会丢掉一次之前的思考内容([**记忆记录缺失**](12-troubleshooting.md#issues-on-degraded-requests)),尚未保存的轮次也会丢失。 | 无需处理,进行中的对话在一次未命中之后就会恢复 |+| `management.sqlite3`(或 Redis management) | 上游、上下文配置、密钥和请求日志全部丢失。 | 恢复备份,或重新配置并签发新密钥;OpenViking 密钥记录会在后续请求中重建 |+| 加密根密钥(开启加密时) | 两个数据库中已加密的值都无法读取。 | 从空的 `storage_path`(SQLite),或换用 ACL 键模式仍能覆盖的新 `storage.key_prefix`(例如 `ovgw:2:`),或删除旧前缀下的所有键(Redis)后重新开始 |## 下一步 {#next-steps}diff --git a/docs/zh/gateway/12-troubleshooting.md b/docs/zh/gateway/12-troubleshooting.mdindex 5e6aff880..a9553cd3b 100644--- a/docs/zh/gateway/12-troubleshooting.md+++ b/docs/zh/gateway/12-troubleshooting.md@@ -18,7 +18,7 @@ description: 根据现象、Studio 标签或错误码,找到 OpenViking 网关| 请求日志中某条请求的状态码为 400 及以上 | 服务商拒绝了请求或调用失败。 | [上游返回错误](#the-upstream-returned-an-error) || 某段对话没有召回,也没有保存 | 检测到 OpenViking 插件,网关把召回、保存和工具都让给了插件。 | 正常行为,避免同一份内容被补充、保存两次,见[两者同时使用时](../guides/15-gateway.md#when-both-are-in-use)。 || 请求不带记忆 | OpenViking 无法访问或超时、预算用完、没有相关内容等。 | [没有补充记忆](#no-memory-is-added) |-| 保存显示**重试中**,之后变成**已暂停** | OpenViking 拒绝保存或无法访问;或者这段对话的网关密钥已被吊销(`gateway_key_revoked`),例如用户的 OpenViking 密钥被重新生成过。 | OpenViking 恢复后网关会自动恢复保存。密钥被吊销时,重新签发网关密钥,用户的下一个请求会恢复保存。见[OpenViking 中看不到对话](#conversations-do-not-appear-in-openviking)。 |+| 保存显示**重试中**,之后变成**已暂停** | OpenViking 拒绝保存或无法访问;或者这段对话的网关密钥已被吊销(`gateway_key_revoked`),例如用户的 OpenViking 密钥被重新生成过。 | OpenViking 恢复后网关会自动恢复保存。原因为 `gateway_key_revoked` 时:签发的网关密钥需要重新签发,之后的下一个请求会恢复保存;直接使用的 OpenViking 密钥若记录过期、被驱逐或保存时收到 401,用户的下一个有效请求会恢复保存(account 租户模式;`tenancy: key` 下换用新密钥会开始新的对话)。见[OpenViking 中看不到对话](#conversations-do-not-appear-in-openviking)。 || 上下文配置开启了工具,对话里却没有 | 还没有能用工具的请求,第一个能用的请求加载工具清单失败,客户端没有回传完整历史,或者客户端自己接了 OpenViking 工具。 | 在请求日志里查看原因,见[什么时候不提供工具](04-openviking-tools.md#when-tools-are-not-offered)。客户端接了 OpenViking MCP 服务器时出现**客户端已接入 OpenViking 工具**(`tool_name_collision`)是正常的;其他原因修正后开始新对话。 || **首次调用缓存命中率**下降,或者概览提示缓存连续未命中 | 记忆无法原样放回、对话换了上游,或者客户端、中转服务改动了请求开头的内容。 | [首次调用缓存命中率下降](#the-first-call-cache-hit-rate-dropped) || 长对话被服务商以过长为由拒绝 | 网关不知道模型的实际窗口,压缩得太晚。 | [长对话超出上下文长度](#long-conversations-hit-the-context-limit) |@@ -79,11 +79,13 @@ Studio 无法为你加载网关时,会用一张设置卡片代替网关标签| 状态码和提示 | 原因和处理 || --- | --- || 401 "Invalid gateway key. It may have been revoked, or removed because its OpenViking API key was regenerated…" | 客户端没有发送网关密钥,发送了已吊销的密钥或服务商的 API Key,或者用户的 OpenViking API 密钥重新生成后,网关删除了这把密钥。检查客户端实际发送的密钥,必要时[重新签发](09-gateway-keys.md#issue-a-key)。 |+| 402 `openviking_http_402` "OpenViking service is not ordered for this API key.",403 `openviking_http_403` "OpenViking request failed." | 网关检查密钥时,OpenViking 拒绝了这把 OpenViking 密钥(或网关密钥背后的 OpenViking 密钥),例如服务未下单;请求不会转发。请恢复服务订购或密钥权限。 || 403 "Claude subscription OAuth credentials are not supported" | 客户端发送了 Claude 订阅令牌,例如 Claude Code 用订阅账号登录且没有设置 `ANTHROPIC_AUTH_TOKEN`;或者上游保存的就是订阅令牌。请改用 API Key。 || 403 "Model is not allowed by this key" | 模型不在密钥[允许的模型](09-gateway-keys.md#allowed-models)范围内。签发一把允许这个模型的密钥。 || 400 "Request model is missing"、415 "Compressed request bodies are not supported" | 只出现在限定了模型的密钥上:请求体必须写明模型,且不能经过压缩编码。 || 404 "This upstream is an exact endpoint for … only" | 密钥绑定的上游关闭了**拼接协议接口路径**(见[直接发往完整请求地址](07-upstreams.md#exact-endpoint)),只接受该协议的接口地址,而客户端调用了别的路径,例如 `/v1/models`。 || 404 "No allowed upstream matches this protocol and model" | 密钥绑定的已启用上游中,没有一个使用客户端调用的 API 并提供所请求的模型。检查上游的协议、模型和别名、是否启用,以及密钥绑定了哪些上游。 |+| 403 "Upstream URL is not allowed" | `X-OpenViking-Upstream-URL` 与密钥绑定的任何上游的 Base URL 都不相同。见[按请求指定上游](07-upstreams.md#upstream-url-header)。 || 401 "Upstream API key is missing" | 上游要求每个客户端在 `X-OpenViking-Upstream-Key` 中自带 API Key,或者由网关保管 API Key 的上游没有填写。见[凭证](07-upstreams.md#credentials)。 || 403 "Coding Plan upstreams are disabled; configure a model API key" | 上游被标记为 [Coding Plan 密钥](07-upstreams.md#coding-plan-keys)。改用模型 API Key,或者有意勾选**允许通过网关使用这个套餐**。 || 403 "Context policy is unavailable" | 密钥绑定的上下文配置已不存在。用现有的上下文配置重新签发密钥。 |@@ -140,7 +142,7 @@ OpenViking 异常期间,请求照常发给模型,只是不带记忆;保存| --- | --- | --- || 缺少最新的一轮 | 保存晚一轮:下一条消息到达时,上一轮才会出现;最后一轮要等**最新回复等待时长**(默认 10 分钟)。 | 稍等,或者发送下一条消息。 || **保存**列显示**已关闭** | 上下文配置不保存对话。 | 在上下文配置中打开保存;修改只对新对话生效(见[修改何时生效](06-manage-in-studio.md#when-changes-take-effect))。 |-| **重试中**或**已暂停** | 保存失败,展开的行会显示原因。 | 修复原因(例如让 OpenViking 恢复访问)后,网关会在 5 分钟内重试。原因为 `gateway_key_revoked` 时,重新签发网关密钥,下一个请求会恢复保存。对话一直暂停时,用**重新同步对话…**(见[重新同步对话](10-overview-and-requests.md#resync-a-conversation))。 |+| **重试中**或**已暂停** | 保存失败,展开的行会显示原因。 | 修复原因(例如让 OpenViking 恢复访问)后,网关会在 5 分钟内重试。原因为 `gateway_key_revoked` 时:签发的网关密钥需要重新签发,之后的下一个请求会恢复保存;OpenViking 密钥若记录过期、被驱逐或收到 401,下一个有效请求会恢复保存(account 租户模式;`tenancy: key` 下换用新密钥会开始新的对话)。对话一直暂停时,用**重新同步对话…**(见[重新同步对话](10-overview-and-requests.md#resync-a-conversation))。 || **检测到 OpenViking 插件**(`plugin_present`) | 检测到 OpenViking 插件的对话,网关不保存任何内容。 | 正常行为;同一个客户端在插件和网关之间二选一。 || 会话里只有部分对话 | 以下情况下,网关会把当前历史写进新的 `gateway-…` 会话:客户端编辑、重新生成或压缩了历史(`history_changed`、`history_changed_during_delivery`),已在**最新回复等待时长**之后保存的一轮又继续了(`continued_after_idle`),或者有人用了**重新同步对话…**(`manual_reset`)。之前的轮次留在旧会话里。 | 到旧会话里找,见[保存状态](10-overview-and-requests.md#saving-status)。 || 完全看不到 `gateway-…` 会话 | 你查看时用的 OpenViking 用户,不是网关密钥背后的那个用户。 | 换成那个用户查看。 |@@ -153,7 +155,7 @@ OpenViking 异常期间,请求照常发给模型,只是不带记忆;保存| 看到的情况 | 原因 | 处理 || --- | --- | --- || **记忆记录缺失**(`missing_injection_record`) | 网关存储丢失、从旧备份恢复,或者记录已过期,之前补充的记忆无法放回。 | 无需处理,进行中的对话在一次未命中之后就会恢复。 |-| **上游已切换**(`upstream_changed`) | 对话原来的上游被停用、没有绑定到客户端当前用的密钥,或者不再提供这个模型,于是对话转到了另一个上游。 | 重新启用这个上游,或者让客户端改用包含它的密钥,见[路由](07-upstreams.md#routing)。 |+| **上游已切换**(`upstream_changed`) | 对话原来的上游被停用、没有绑定到客户端当前用的密钥、与请求的 `X-OpenViking-Upstream-URL` 不符,或者不再提供这个模型,于是对话转到了另一个上游。 | 重新启用这个上游,或者让客户端改用包含它的密钥,见[路由](07-upstreams.md#routing)。 || **缓存参数有变化**(`ark_cache_parameters_changed`) | 在火山方舟或 BytePlus 方舟上,客户端在同一段对话里改变了模型、思考模式、采样参数、系统提示词或工具。 | 在同一段对话里保持这些参数不变。 || 没有标出异常 | 客户端本身可能每轮都在改动之前的消息或系统提示词,例如插入当前时间,网关无法修正。每次压缩、模型每次开启新的上下文窗口,也都会造成一次未命中,这是预期内的。 | 检查客户端的系统提示词里有没有每次都变的内容。 || **有 … 段长对话连续没有命中提示词缓存**,或者命中率一直是 0%,而服务商或中转服务后台的缓存记录有命中 | 上游没有把缓存用量传回网关,例如中转服务转换协议时丢掉了缓存字段。网关读取 `cache_read_input_tokens`、`prompt_tokens_details.cached_tokens`、`input_tokens_details.cached_tokens`、`prompt_cache_hit_tokens` 等常见字段。 | 让中转服务把缓存用量原样传回。 |@@ -211,6 +213,10 @@ OpenViking 异常期间,请求照常发给模型,只是不带记忆;保存| 回复未保存(`capture_parse_failure`) | 流式回复无法解析,这条回复没有保存,客户端不受影响。 | 无需处理,仅供了解。 || 密钥未校验(`revocation_check_unavailable`) | OpenViking 无法确认这把网关密钥,请求在没有检查是否已吊销的情况下照常处理。 | 检查 OpenViking 是否可达、运行是否正常。 |+## Redis 不可用 {#redis-unavailable}++启动在 Redis PING 处失败时,检查 `storage.redis.endpoints`、TLS 信任链和密码环境变量;官方镜像之外需要安装 `openviking[expiry]`。鉴权时返回纯文本 `Internal Server Error` 的 HTTP 500 也可能是 Redis 不可用,请查看 stderr。运行时 Redis 故障期间 `/health` 仍返回健康,不代表 Redis 连接正常。ACL 和超时配置见[存储后端](13-configuration.md#storage),持久化配置见 [Redis 内存策略](../guides/22-gateway-operations.md#redis-memory-policy)。+## 下一步 {#next-steps}- [网关概览与请求日志](10-overview-and-requests.md#requests):了解请求日志中每一列、每个标签和每种保存状态的含义。diff --git a/docs/zh/gateway/13-configuration.md b/docs/zh/gateway/13-configuration.mdindex c18df95fc..487bb99cf 100644--- a/docs/zh/gateway/13-configuration.md+++ b/docs/zh/gateway/13-configuration.md@@ -28,20 +28,86 @@ description: 查询 OpenViking 网关的配置字段、环境变量、上下文| `host` | 独立 | `127.0.0.1` | | 监听地址 || `port` | 独立 | `1935` | 1–65,535 | 监听端口 || `workers` | 独立 | `1` | 1–64 | worker 进程数 |+| `keep_alive_seconds` | 独立 | `75` | 大于 0 | 两次请求之间保留空闲 HTTP 连接的秒数;应大于负载均衡器的后端空闲超时 || `public_url` | 两者 | 空 | HTTP(S) URL,不带 `/gateway` | 客户端访问的对外地址,`/gateway` 由网关自己加。为空时,嵌入网关沿用 Server 的对外地址;两者都没有时,接入指南使用请求来源地址,MCP 文件上传和下载也不可用(`mcp_file_links` 为 `direct` 时除外)。见[对外地址](../guides/22-gateway-operations.md#public-address) || `mcp_file_links` | 两者 | `proxy` | `proxy`、`direct` | MCP 上传和下载工具返回的链接如何交给客户端。`proxy` 改写为 `public_url` 加 `/gateway/uploads` 或 `/gateway/downloads`,需要设置 `public_url`。`direct` 原样透传 OpenViking 的链接,需要 Server 的 `OPENVIKING_PUBLIC_BASE_URL`(或 `server.public_base_url`)是客户端能访问的地址 || `storage_path` | 两者 | `~/.openviking/gateway` | | 本地存储目录 |+| `storage` | 两者 | 两个后端均为 `sqlite` | 见[存储后端](#storage) | 分别选择后端,共用 Redis 连接配置 || `encryption` | 独立 | 不设置(明文) | 字段同 `ov.conf` 的 `encryption` 段 | 加密本地保存的数据,见[加密](../guides/22-gateway-operations.md#encryption);嵌入网关沿用 Server 的设置 |+| `management_api` | 两者 | `true` | `true`、`false` | 注册网关管理路由;关闭时也移除独立网关的 OpenViking 管理代理和 Studio,模型路由和 `/health` 继续可用 || `management_key` | 两者 | 空 | 至少 32 个字符 | 可选的[网关管理密钥](../guides/22-gateway-operations.md#gateway-management-key) |+| `openviking_keys` | 两者 | `false` | `true`、`false` | 允许客户端用用户的 OpenViking API 密钥代替网关密钥,使用账号的默认上下文配置和全部已启用的上游,见[直接使用 OpenViking API 密钥](09-gateway-keys.md#openviking-keys) |+| `tenancy` | 两者 | `account` | `account`、`key` | 按账号或按密钥隔离 OpenViking 密钥请求;`key` 要求 `management_api: false` |+| `default_upstreams` | 两者 | `{}` | 稳定 ID 到[上游设置](#upstream-settings)的对象映射 | 账号没有存储上游时供 OpenViking 密钥使用,见[部署默认上游](07-upstreams.md#deployment-default-upstreams) |+| `default_profile` | 两者 | 内置上下文配置默认值 | [上下文配置设置](#context-profile-settings) | 账号没有 ID 为 `default` 的配置时使用,也是嵌入式 dev 模式初始化写入的配置 || `min_server_version` | 两者 | `0.4.16` | 版本号 | 独立网关要求的 OpenViking Server 最低版本 |-| `session_ttl_days` | 两者 | `30` | 1 及以上 | 对话闲置多少天后过期 |+| `session_ttl_days` | 两者 | `30` | 1 及以上 | 对话闲置多少天后过期;也决定缓存的 OpenViking 密钥及其用户记录的固定寿命 || `response_ttl_seconds` | 两者 | `2592000`(30 天) | 60 及以上 | Responses 响应与上游的对应关系保留多少秒 |-| `log_retention_days` | 两者 | `30` | 1 及以上 | 请求日志保留天数 |+| `request_log_sink` | 两者 | `store` | `store`, `stdout` | 将请求和后台保存日志写入存储,或以每条一行 JSON 写到 stdout 并立即刷新;见[观测](../guides/22-gateway-operations.md#monitoring) |+| `log_retention_days` | 两者 | `30` | 1 及以上 | 存储中的请求日志保留天数;stdout 的保留期限由日志采集系统管理 || `max_body_bytes` | 两者 | `33554432`(32 MiB) | 1,024 及以上 | 请求和上传的大小上限,单位为字节 || `upstream_timeout_seconds` | 两者 | `600` | 大于 0 | 服务商请求超时 || `health_interval_seconds` | 两者 | `60` | 1 及以上 | 检查 OpenViking 状态的间隔秒数 |+| `capture_concurrency` | 两者 | `1` | 1 及以上 | 每个进程并发投递的会话数;停机时停止新 claim,最多等待在途投递 100 秒 || `client_rules` | 两者 | `{}`(只用内置规则) | 见[客户端规则](#client-rules) | 在网关内置的辅助请求和客户端插入消息识别规则上增删条目 |+例如,独立网关的 `gateway.conf` 可以在尚未配置任何账号时路由 OpenViking 密钥:++```json+{+ "openviking_url": "http://openviking:1933",+ "openviking_keys": true,+ "default_upstreams": {+ "ark-chat": {+ "name": "Ark Chat",+ "protocol": "chat",+ "base_url": "https://ark.cn-beijing.volces.com/api/v3",+ "api_key": "$ARK_API_KEY",+ "models": ["your-model-id"]+ }+ },+ "default_profile": {"max_tokens": 2400}+}+```++## 存储后端 {#storage}++默认使用本地 SQLite,无需外部服务。`storage.kernel` 和 `storage.management` 分别选择 `sqlite` 或 `redis`;Redis 后端共用一个客户端及 `storage.redis` 连接配置。使用 Redis 时安装 `pip install "openviking[expiry]"`,官方镜像已经包含依赖。网关 CI 覆盖 Redis 单机和 Cluster;Sentinel 配置可以通过校验,但不在网关 CI 覆盖范围内。++```json+{+ "storage": {+ "kernel": "redis",+ "management": "redis",+ "key_prefix": "ovgw:",+ "redis": {+ "mode": "standalone",+ "endpoints": ["rediss://redis.example.com:6379"],+ "username": "gateway",+ "password_env": "OPENVIKING_GATEWAY_REDIS_PASSWORD",+ "pool_size": 32,+ "command_timeout_ms": 5000+ }+ },+ "session_ttl_days": 7+}+```++`OPENVIKING_GATEWAY_STORAGE` 接受相同 `storage` 对象的 JSON。密码通过指定的环境变量注入,例如来自 Kubernetes Secret。`key_prefix` 默认为 `ovgw:`,不能包含 `{`、`}`、`*`、`?`、`[`、`]` 或 `\`;所有键都以该前缀加 `v1:` 开头。不同部署使用不同前缀。++`storage.redis` 复用 OpenViking 的 `RedisCacheConfig`:`mode`、`endpoints`、`username`、`password_env`、旧式 `password`、`db`、`pool_size`、`connect_timeout_ms`、`command_timeout_ms`、`default_ttl_seconds`、`tls_insecure_skip_verify`,以及 Sentinel 字段 `master_name`、`sentinel_username`、`sentinel_password_env`、`sentinel_password`。为容纳较大的对话值,网关把命令超时默认值从 20 改为 5000 毫秒;`default_ttl_seconds` 不控制网关保留期限。URL 只包含协议、主机和端口,凭据和数据库使用专门字段。Cluster 使用 `mode: "cluster"`、多个种子地址和 `db: 0`。TLS 由 `rediss://` 协议决定;私有 CA 通过证书卷和指向证书的 `SSL_CERT_FILE` 配置(Helm 使用 `extraVolumes`、`extraVolumeMounts`)。++为网关单独准备 Redis 实例,使用 `volatile-lru` 驱逐策略并启用 AOF;`redis.conf` 设置和监控项见 [Redis 内存策略](../guides/22-gateway-operations.md#redis-memory-policy)。++替换密码和前缀后,运行以下命令创建 ACL 用户。Cluster 必须在**每个节点**分别执行,因为 ACL 不在节点之间同步:++```bash+redis-cli ACL SETUSER gateway reset on '>replace-with-secret' '~ovgw:*' \+ +@read +@write +@scripting +@connection +@transaction +ping +time +scan +unlink+```++Cluster 还需授予 `'+cluster|slots' '+cluster|shards'`。Lua 脚本需要 `+time`;CI 会验证这些权限及前缀隔离。应用命令遇到连接错误不会自动重试,因为失败的写入可能已经到达 Redis。+## 环境变量 {#environment-variables}每个网关字段都能用环境变量设置,变量名是 `OPENVIKING_GATEWAY_` 加上大写的字段名,两种部署形态都适用:@@ -55,7 +121,7 @@ OPENVIKING_GATEWAY_MANAGEMENT_KEY='<management-key>'- 以 `tcp://` 或 `udp://` 开头的值会被忽略。这样,Kubernetes 为名为 `openviking-gateway` 的 Service 自动注入的变量(例如 `OPENVIKING_GATEWAY_PORT=tcp://…`)不会覆盖文件。- 文件中的值也可以写成 `"$VAR"`,从环境变量中取值。- `encryption` 块只能写在文件里。-- `client_rules` 用 JSON 传整段配置:`OPENVIKING_GATEWAY_CLIENT_RULES='{"auxiliary_patterns":{"add":["You are the Acme title writer"]}}'`。+- `client_rules`、`storage`、`default_upstreams` 和 `default_profile` 用 JSON 传整段配置,例如 `OPENVIKING_GATEWAY_CLIENT_RULES='{"auxiliary_patterns":{"add":["You are the Acme title writer"]}}'` 或 `OPENVIKING_GATEWAY_DEFAULT_PROFILE='{"max_tokens":2400}'`。- 容器通常不需要配置文件,用环境变量设置需要的字段即可。## 校验 {#validation}@@ -65,6 +131,7 @@ OPENVIKING_GATEWAY_MANAGEMENT_KEY='<management-key>'| `openviking_url` 和 `public_url` | 必须是 HTTP(S),不能含凭证、查询参数或 fragment || 上游的 `base_url` | 规则不同,见[接口](07-upstreams.md#endpoint) || `management_key` | 解析 `$VAR` 引用后至少 32 个字符;`$VAR` 没能解析时校验失败 |+| `tenancy` | `key` 要求 `management_api: false`;`openviking_keys` 关闭时此字段不生效 || `client_rules` | 新增的模式必须是合法的 Python 正则表达式;新增的标签名以英文字母开头,只能包含英文字母、数字、`_`、`.`、`:` 和 `-` || 未知字段 | 校验失败 || 已删除的字段 | 忽略,启动时打印警告:`encryption_key_env`,以及 `ov.conf` 中[迁移](../guides/22-gateway-operations.md#migration)列出的 v0.5 字段 |@@ -103,7 +170,7 @@ OPENVIKING_GATEWAY_MANAGEMENT_KEY='<management-key>'## 上下文配置的设置 {#context-profile-settings}-在 Studio 中:**上下文配置** → 打开一份配置。下面几张表按编辑器的分区排列,先写 Studio 中的名称,再写管理 API 中的名称(管理 API 把上下文配置称为 `policies`)。**名称**(`name`,默认 `Default`)是配置的显示名称;各分区的作用见[上下文配置](08-context-profiles.md#context-profiles)。+在 Studio 中:**上下文配置** → 打开一份配置。下面几张表按编辑器的分区排列,先写 Studio 中的名称,再写管理 API 中的名称(管理 API 把上下文配置称为 `policies`)。**名称**(`name`,默认 `Default`)是配置的显示名称;各分区的作用见[上下文配置](08-context-profiles.md#context-profiles)。**允许客户端覆盖设置**(`client_overrides`,默认 `true`)允许客户端用 `X-OpenViking-Context` 请求头为新对话修改其余所有设置,见[允许客户端覆盖设置](08-context-profiles.md#client-overrides)。### 召回记忆 {#profile-recall}@@ -123,7 +190,7 @@ OPENVIKING_GATEWAY_MANAGEMENT_KEY='<management-key>'| 检索文本长度 | `query_max_chars` | `8000` | 3–32,000 | 取消息的多少个字符作为检索文本。 || 按分类限量 | `quotas` | `{}`(关闭) | 键:`events`、`entities`、`preferences`、`experiences`、`resources`、`skills`;设置时至少一项大于 0(仅 Studio 校验) | 每个分类最多取的条数;只检索大于 0 的分类。 |-管理 API 保存 `context_types` 和 `quotas` 时不做校验。`quotas` 里出现未知的键时,OpenViking 会拒绝检索请求,导致每次召回都失败。+管理 API 保存 `context_types` 和 `quotas` 的键时不做校验。`quotas` 里出现未知的键时,OpenViking 会拒绝检索请求,导致每次召回都失败。### 保存对话 {#profile-saving}diff --git a/docs/zh/guides/15-gateway.md b/docs/zh/guides/15-gateway.mdindex 397e87811..9ffa53d84 100644--- a/docs/zh/guides/15-gateway.md+++ b/docs/zh/guides/15-gateway.md@@ -47,11 +47,11 @@ OpenViking 网关是一个模型 API 代理:客户端只要能修改 Base URL## 一张图看懂架构 {#architecture-at-a-glance}-+- **运行在哪**:开启后嵌入 OpenViking Server,和 Server 共用端口;也可以用 `openviking-gateway` 独立运行,连接已有的 OpenViking 服务(开源版或商业版)。两种方式下网关的所有 URL 都在 `/gateway` 下(例如 `/gateway/v1`),客户端路径相同,见[选择部署方式](22-gateway-operations.md#deployment-options)。- **和 OpenViking 的关系**:网关只调用 OpenViking 的公开接口,向量化和记忆提取都在 OpenViking 中完成。-- **数据在哪**:会话和记忆的正本在 OpenViking。网关本机只有两个 SQLite 文件(开启 OpenViking 加密时加密存储),一个存上游、密钥和配置,一个存对话状态,见[安全与数据](../gateway/11-security-and-data.md)。+- **数据在哪**:会话和记忆的正本在 OpenViking。网关默认使用两个 SQLite 文件,多副本部署可以改用共享 Redis。开启 OpenViking 加密后,两种后端中存储的值都会加密。见[安全与数据](../gateway/11-security-and-data.md)。- **出故障时**:OpenViking 不可用时,对话照常进行,只是不带记忆,保存会自动重试。网关停止服务时,经过它的模型调用全部失败。## 能得到什么,代价是什么 {#what-you-get-and-what-it-costs}diff --git a/docs/zh/guides/22-gateway-operations.md b/docs/zh/guides/22-gateway-operations.mdindex 13921b7c6..9e481d7a8 100644--- a/docs/zh/guides/22-gateway-operations.md+++ b/docs/zh/guides/22-gateway-operations.md@@ -25,7 +25,7 @@ description: 把 OpenViking 网关嵌入 Server、用 Docker Compose 或 Helm| OpenViking 版本 | 嵌入运行时和 Server 同版本发布,无需额外检查;独立运行时要求 OpenViking Server 0.4.16 或更高版本。 || 安装 | 网关包含在 OpenViking 核心包中。可选的 `gateway-fast` extra(`pip install "openviking[gateway-fast]"`)装上更快的事件循环和 HTTP 解析器。 || 登录身份 | 远程部署需要 OpenViking API 密钥,普通用户、账号管理员和 root 都能登录 Studio 的网关页面。本地 dev 模式不需要密钥,固定使用 `default/default` 身份。 |-| 存储 | 本地磁盘。网关的 SQLite 数据库只供一台主机使用,不支持网络文件系统或跨主机共享存储。 |+| 存储 | 单机使用本地磁盘上的 SQLite,多副本使用共享 Redis。Redis 需要 `pip install "openviking[expiry]"`,官方镜像已包含。 |## 选择部署方式 {#deployment-options}@@ -86,9 +86,20 @@ docker run -d -p 1933:1933 -v ~/.openviking:/app/.openviking \自带的 Caddy 把所有路径转发到 `openviking:1933`。可以继续用兼容端口 1934,也可以直接访问 Server 的 1933。配置 HTTPS 时,一条 `reverse_proxy openviking:1933` 就能承载 Studio、管理接口和模型流量,见[公网访问](12-public-access.md)。+独立容器需要挂载 `gateway.conf` 并使用网关命令。在文件中设置 `host: "0.0.0.0"`,以及启用 API key 认证的 `openviking_url`。选择包含所配置功能的镜像:++```bash+docker run -d --no-healthcheck -p 1935:1935 \+ -v "$PWD/gateway.conf:/etc/openviking/gateway.conf:ro" \+ -v gateway-data:/app/.openviking \+ ghcr.io/volcengine/openviking:'<gateway-image-tag>' openviking-gateway+```++`--no-healthcheck` 关闭镜像自带的 1933 端口 Server 探针。独立网关改用 `http://localhost:1935/health` 探测。+## Helm {#helm}-用 Helm chart 部署时,在 chart values 中设置 `gateway.enabled: true`。网关嵌入 server 容器,数据保存在 `<persistence.mountPath>/gateway`,Service 和 Ingress 都使用 Server 端口。保持 `replicaCount: 1`。+用嵌入式 `deploy/helm/openviking` chart 部署时,在 chart values 中设置 `gateway.enabled: true`。网关嵌入 server 容器,数据保存在 `<persistence.mountPath>/gateway`,Service 和 Ingress 都使用 Server 端口。保持 `replicaCount: 1`。```yamlgateway:@@ -105,6 +116,26 @@ config:NGINX annotations、创建 Secret 的命令和从 sidecar 版本升级的说明见 [chart README](https://github.com/volcengine/OpenViking/blob/main/deploy/helm/README.md#openviking-gateway)。+独立部署使用 `deploy/helm/openviking-gateway`。它有自己的 80 端口 Service,转发到 1935,并运行 `openviking-gateway`。`config` 值是独立的 `gateway.conf` 对象,chart 固定 `host`、`port` 和 `storage_path`。++在包含这些功能的版本发布之前,需要把 `image.tag` 设为包含它们的构建,见 [chart README](https://github.com/volcengine/OpenViking/blob/main/deploy/helm/README.md#standalone-openviking-gateway)。++```bash+helm upgrade --install gateway ./deploy/helm/openviking-gateway \+ --set-string image.tag='<gateway-image-tag>' \+ --set-string config.openviking_url=https://ov.example.com+```++默认使用单副本 SQLite、持久卷和 `Recreate` 更新策略。集群必须有默认 StorageClass,或配置 `persistence.storageClass`/`persistence.existingClaim`。设置 `persistence.enabled: false` 后,更换 Pod 会丢失 SQLite 状态,Helm NOTES 会显示警告。卸载会保留 PVC。扩容前必须把两个 provider 都改成 Redis,见[扩展](#scaling)。++chart 设置了 `session_ttl_days: 7` 和 `response_ttl_seconds: 604800`,比网关 30 天的默认值短;需要其他值时覆盖 `config.*`。每个 Pod 请求 500m CPU 和 1Gi 内存,上限为 2 CPU 和 4Gi;可按负载设置 `resources`。++独立 chart 的 `existingSecret` 接受 `management-key`、`redis-password` 和 `root-key`。前两项分别注入 `OPENVIKING_GATEWAY_MANAGEMENT_KEY` 和 `OPENVIKING_GATEWAY_REDIS_PASSWORD`;`config.storage.redis.password_env` 指向后者。local 和 KMS 加密把 `root-key` 只读挂载到 `/etc/openviking-gateway/keys/root-key`,并将 provider 的 `key_file` 指向它。安装前先按[加密](#encryption)生成密钥。上游凭证和 KMS AK/SK 在 `config` 中写 `$VAR`,通过 `extraEnv` 的 `secretKeyRef` 注入,不要将明文凭证写入 ConfigMap。++`extraVolumes` 和 `extraVolumeMounts` 支持私有 CA 文件;`extraEnv`、`podLabels`、`podAnnotations`、`nodeSelector`、`affinity`、`tolerations`、`imagePullSecrets` 用于部署环境的其他设置。ConfigMap 变化通过 `checksum/config` 触发滚动更新。外部 Secret 改动后需要重启 Deployment,让所有副本加载一致的凭证。++chart 不创建 Ingress。把代理指向它的 Service,并保持 `fullnameOverride`、`nameOverride` 和 release 名不变:Service 和 Deployment 同名,selector 是 `app.kubernetes.io/name` 与 `app.kubernetes.io/instance`。直接对外开放时,配置 `service.type: LoadBalancer` 和 `service.loadBalancerSourceRanges`。可选的 `networkPolicy.enabled` 将 1935 端口入站限制为 `networkPolicy.ingressFrom`,空列表会拒绝入站。放行代理实际的来源网段或 Pod selector,并在所用 CNI 上验证 kubelet 探针。+## 独立部署 {#standalone-deployment}独立网关不读取 `ov.conf`,只需要知道 OpenViking 的地址,已有的开源版或商业版服务不用改配置。@@ -133,12 +164,17 @@ NGINX annotations、创建 Secret 的命令和从 sidecar 版本升级的说明### 启动检查 {#startup-checks}-独立网关启动前会先访问一次 OpenViking:+选择 Redis 后端时,启动 PING 必须成功。地址、凭据错误或 Redis 不可达会使启动失败,Kubernetes 会重启容器;滚动发布使用 `maxUnavailable: 0`。运行时 Redis 故障不会改变 `/health`;鉴权阶段存储失败返回纯文本 HTTP 500,并在 stderr 输出异常栈。++独立网关开始监听前会先检查 OpenViking 的认证模式:- OpenViking 使用 trusted 认证时,网关拒绝启动。-- 绑定非回环地址时,必须确认 OpenViking 使用 `api_key` 认证才会启动;OpenViking 连不上或处于本地 dev 模式时,网关直接退出。请先启动 OpenViking,或者只绑定 `127.0.0.1`。+- 绑定非回环地址时,必须确认 OpenViking 使用 `api_key` 认证才会启动。连接失败或 HTTP 5xx 响应会输出告警,并在 1、2、4、8、16、30 秒后依次重试,后续等待上限为 30 秒。dev 模式、未知认证模式以及 HTTP 404 等其他错误仍会立即退出。+- 回环地址(`127.0.0.1`、`::1`、`localhost`)只探测一次,OpenViking 不可达时也能启动;仍然拒绝 trusted 认证。- 跨主机连接 OpenViking 时,请使用 TLS 或私有网络。+等待期间 HTTP 端口尚未监听。Kubernetes 的启动探针此时仍会失败,应按预期的 OpenViking 中断时长设置 `startupProbe` 预算(`periodSeconds × failureThreshold`)。例如 `periodSeconds: 2`、`failureThreshold: 150` 允许等待约 300 秒,之后 kubelet 会重启容器。网关自身不另设启动等待期限。+### 连接公共 OpenViking 服务 {#public-openviking-service}独立网关连接公共 OpenViking 服务 `https://api.vikingdb.cn-beijing.volces.com/openviking`、又没有设置管理密钥时,会对该服务的所有用户开放。启动日志会显示 `public_openviking_without_management_key` 告警,Studio 会显示**这台网关对所有 OpenViking 商业版用户开放**:任何持有该服务 API 密钥的人都能登录这台网关,并修改所在账号的上游。@@ -206,6 +242,10 @@ ov.example.com {| 读取超时 | 至少 600 秒 | 网关默认最多等待服务商 600 秒 || `/gateway/uploads` 和 `/gateway/downloads` 的日志 | 不记录查询字符串 | 其中带有一次性令牌 |+独立网关的 `keep_alive_seconds`(默认 75)应大于负载均衡器的后端空闲超时。++响应头发出后,空闲事件流每 15 秒发送一条 SSE 注释(`: keep-alive`),包括执行 OpenViking 工具期间。SSE 客户端会忽略注释,模型事件和捕获的回复不受影响。代理的空闲超时应大于 15 秒,并关闭响应缓冲。心跳只在完整事件的边界发送,上游压缩流禁用心跳,因此仍需保留上面的较长读取超时,以覆盖事件传到一半或响应头尚未到达时的等待。心跳间隔固定,不会延长服务商超时或工具的总时间限制。+对外发布前,先配置好认证和[对外地址](#public-address),见[公网访问](12-public-access.md)。## 密钥和凭证 {#keys-and-credentials}@@ -235,7 +275,7 @@ ov.example.com {- **`openviking-gateway init`**(独立):回答 **Require a management key to change upstreams and profiles?** 时选 yes,init 会生成一个 `ovgm_` 开头的值,只打印一次,并写入 `gateway.conf` 的 `management_key`。- **Studio**(嵌入,root):点**开启网关**后弹出的确认对话框里有一个复选框**只有持有网关管理密钥的人才能修改上游和上下文配置**,默认不勾选。勾选后,Studio 会生成一个 `ovgm_` 开头的值,写入 `ov.conf` 的 `gateway.management_key`(同时写入 `gateway.enabled: true`),并且只显示一次。- **手动设置**:值至少 32 个字符,可以用 `openssl rand -base64 32` 生成。写进 `management_key`,或者设置环境变量 `OPENVIKING_GATEWAY_MANAGEMENT_KEY`;两种部署下环境变量都优先于配置文件,见[配置参考](../gateway/13-configuration.md#configuration-reference)。-- **Compose 和 Helm**:Compose 会把 `OPENVIKING_GATEWAY_MANAGEMENT_KEY` 传进容器;Helm 从 `gateway.existingSecret` 指定的 Secret 中读取 `management-key` 字段。见 [Docker Compose](#docker-compose) 和 [Helm](#helm)。+- **Compose 和 Helm**:Compose 会把 `OPENVIKING_GATEWAY_MANAGEMENT_KEY` 传进容器;Helm 从 `gateway.existingSecret`(嵌入)或 `existingSecret`(独立)指定的 Secret 中读取 `management-key` 字段。见 [Docker Compose](#docker-compose) 和 [Helm](#helm)。管理密钥不提供命令行参数,因为命令行参数会出现在进程列表和 shell 历史里。设置、更换或去掉管理密钥后需要重启,这不会吊销已签发的网关密钥,也不会改动已有的上游和上下文配置。@@ -243,7 +283,7 @@ ov.example.com {没人记得[网关管理密钥](#gateway-management-key)时,按网关读取它的顺序查找:-1. 环境变量 `OPENVIKING_GATEWAY_MANAGEMENT_KEY`,它优先于配置文件。Compose 部署一般写在 `docker-compose.yml` 旁边的 `.env` 里;Helm 从 `gateway.existingSecret` 指定的 Secret 中读取 `management-key` 字段。+1. 环境变量 `OPENVIKING_GATEWAY_MANAGEMENT_KEY`,它优先于配置文件。Compose 部署一般写在 `docker-compose.yml` 旁边的 `.env` 里;Helm 从 `gateway.existingSecret`(嵌入)或 `existingSecret`(独立)指定的 Secret 中读取 `management-key` 字段。2. 没有设置环境变量时,看 `ov.conf` 的 `gateway.management_key`(嵌入)或 `gateway.conf` 的 `management_key`(独立)。值写成 `$VAR` 时,密钥在对应的环境变量里。嵌入部署的 root 还可以在 Studio 的**设置** → **服务端配置** → **文件编辑**中查看 `ov.conf`。`openviking-server init` 和 Studio **开启网关**生成的密钥都以明文保存在这里。@@ -257,7 +297,7 @@ ov.example.com {## 加密 {#encryption}-网关用 OpenViking 自己的加密功能保护已存的凭证和对话状态(见[加密指南](08-encryption.md))。加密关闭或没有配置时,网关以明文存储,只靠文件权限保护。+网关用 OpenViking 自己的加密功能保护已存的凭证和对话状态(见[加密指南](08-encryption.md))。加密关闭或没有配置时,网关以明文存储,依靠存储访问控制保护。- **嵌入**:网关沿用 Server 在 `ov.conf` 中的 `encryption` 段,不需要为网关单独设置。- **独立**:在 `gateway.conf` 中加一个 `encryption` 块,字段和 `ov.conf` 的 `encryption` 段完全相同,例如:@@ -273,6 +313,18 @@ ov.example.com {}```+共享部署的每个副本必须只读挂载同一份 root key。local provider 使用**十六进制文本**,不要生成原始字节:++```bash+umask 077+openssl rand -hex 32 > gateway-root-key+kubectl create secret generic gateway-credentials --from-file=root-key=gateway-root-key+```++设置 `existingSecret: gateway-credentials`、`config.encryption.enabled: true` 和 `config.encryption.provider: local`。需要时,在同一个 Secret 中添加 `management-key` 和 `redis-password`。++使用 `provider: volcengine_kms` 时,`root-key` 是 **KMS 密文文件**,不是十六进制文本。在受保护的本地可写目录中,把 `encryption.volcengine_kms.key_file` 设为绝对路径,通过环境变量引用提供 KMS 凭证,启动一次网关。启动成功后停止,将生成的文件放入 Secret 的 `root-key`。各副本使用一致的 KMS key ID 和凭证。文件不存在时,provider 会在首次使用时生成;只读 Secret 挂载下生成失败,网关会拒绝启动。Vault 将加密 root key 保存在 Vault 中,不使用这个文件挂载。+之后修改加密设置时:- **开启加密**不会出问题:已有的明文值照常可读,新写入的值会加密。@@ -283,19 +335,85 @@ v0.5 网关用自己的密钥加密数据,这些数据会在首次启动时转## 扩展 {#scaling}-一个存储目录只供一台主机上的一套部署使用,嵌入网关和独立网关不能共用同一目录。嵌入网关跟随 Server 的 worker 设置;独立网关用 `workers` 设置,取值 1–64。需要在服务商之间负载均衡、故障转移或限流时,把 LiteLLM 这类服务添加为上游。+SQLite 供一台主机上的一套部署使用,不要跨主机共享目录,也不要让嵌入网关和独立网关共用。独立进程支持 `workers: 1–64`,Kubernetes 中建议 `workers: 1`,通过增加 Pod 扩容。嵌入网关遵循 Server 的 worker 和副本限制。++独立网关使用多副本时,必须把 **`storage.kernel` 和 `storage.management` 都设为 `redis`**,共享同一份 `storage.redis` 连接与 `storage.key_prefix`,并只读挂载同一份加密 root key。任一 provider 是 SQLite 时,chart 会拒绝多副本。下面是双副本的起点,需要合并你的 URL 和 Secret 设置:++```yaml+replicaCount: 2+existingSecret: gateway-credentials+config:+ capture_concurrency: 4+ storage:+ kernel: redis+ management: redis+ key_prefix: "ovgw:"+ redis:+ mode: standalone+ endpoints: ["redis://redis:6379"]+ password_env: OPENVIKING_GATEWAY_REDIS_PASSWORD+ encryption:+ enabled: true+ provider: local+```++无管理面、按密钥隔离的部署再加上 `management_api: false`、`openviking_keys: true`、`tenancy: key`、`default_upstreams` 和 `request_log_sink: stdout`,见[直接使用 OpenViking API 密钥](../gateway/09-gateway-keys.md#openviking-keys)和[部署默认上游](../gateway/07-upstreams.md#deployment-default-upstreams)。没有管理 API 时,在 OpenViking 中删除用户不会通知网关,该用户的网关数据按[保留期限](../gateway/11-security-and-data.md#retention)过期。部署在它前面的服务遵循[宿主集成约定](#host-integration-contract)。++Redis `mode: standalone` 用于单个端点,包括托管代理;`mode: cluster` 用 Redis Cluster 端点且数据库必须为 0。TLS 用 `rediss://`,端点 URL 中不要写凭证。`pool_size` 限制每个进程同时执行的 Redis 命令数,超出的命令等待空闲连接。保持 `pool_size >= capture_concurrency + 8`。Redis 位于鉴权路径,整体不可用时请求返回 HTTP 500;需要高可用时使用主从和自动切换,内存和持久化按 [Redis 内存策略](#redis-memory-policy)配置。++Redis 部署使用 `RollingUpdate`,配置 `maxUnavailable: 0`、`maxSurge: 1`;多副本时创建 `maxUnavailable: 1` 的 PDB。通过 `affinity` 把副本分散到不同节点。各进程缓存管理记录,所以修改管理配置或吊销签发密钥后,其他副本最多 **2 秒**后生效。++所有探针都不带凭证访问 `/health`,只返回本地状态,不调用 OpenViking 或 Redis。startupProbe 预算为 300 秒(`2 × 150`)。启动完成后,OpenViking 故障不会使 Pod 摘流。++停机预算是 `15s preStop + upstream_timeout_seconds + 最多 100s capture 排空`。chart 默认的 `terminationGracePeriodSeconds: 660` 覆盖 preStop 和一条持续到默认 600 秒上游超时的流;capture 尚未排空就被 Kubernetes 终止时,其他副本会在 lease 到期后接手。要让 capture 在 Pod 被终止前排空,把它调到 `15 + upstream_timeout_seconds + 100`(默认超时下为 715)。++### 宿主集成约定 {#host-integration-contract}++部署在无管理面网关前面的服务(例如为每个请求选择模型端点的服务)转发客户端请求时,设置这些请求头:++| 请求头 | 取值 |+| --- | --- |+| `X-API-Key` 或 `Authorization: Bearer` | 客户端的 OpenViking API 密钥,原样透传 |+| `X-OpenViking-Upstream-URL` | 选中的端点,必须与某个 `default_upstreams` 条目的 `base_url` 相同;其他值返回 403,且不发出任何请求。见[按请求指定上游](../gateway/07-upstreams.md#upstream-url-header) |+| `X-OpenViking-Upstream-Key` | 服务商 API Key,用于 `auth_mode: passthrough` 的上游 |+| 其他请求头 | 客户端自己的请求头,例如 `X-OpenViking-Session` 和 `X-OpenViking-Context`,原样透传 |++网关把请求转发给服务商之前,会去掉所有 `X-OpenViking-*` 请求头、客户端凭证和逐跳请求头。++## Redis 内存策略 {#redis-memory-policy}++为网关单独准备 Redis 实例,不要与 OpenViking 的 `expiry_redis_host` 定时器存储共用。从下面的 `redis.conf` 开始,按负载设置 `maxmemory`:++```conf+maxmemory 2gb+maxmemory-policy volatile-lru+appendonly yes+appendfsync everysec+```++`volatile-lru` 只驱逐本来就会过期的数据:对话状态、replay、待投递 capture 和 OpenViking 密钥记录。每类数据丢失的影响见 [Redis 对话状态](../gateway/11-security-and-data.md#redis-conversation-state)。不要使用 `allkeys-*`:它也会驱逐没有 TTL 的数据,导致签发的密钥、上游和上下文配置消失,已删除的对话状态可能重新出现,待投递 capture 不再被调度。`noeviction` 也能运行,但内存满后写入失败,请求无法获得记忆增强。++监控 `evicted_keys` 的增速和内存用量;容量充足时不会发生驱逐。网关不检查驱逐策略或其他任何 Redis 设置。观察 capture 积压可用 `ZCARD <key_prefix>v1:k:{cap}:ready`,它统计已调度或正在处理的 capture,其中可能有少量稍后才清理的过期条目。Redis Cluster 中所有 capture 数据位于同一个分片,应为 OpenViking 故障期间的积压预留该分片容量。capture lease 使用 Redis 时钟,调度时间则来自网关宿主,各宿主应通过 NTP 保持时钟同步。++未启用持久化时,Redis 重启会删除网关的全部管理数据:已签发的网关密钥失效,上游和上下文配置需要重新设置。AOF 让这些数据、待投递 capture 和删除操作在重启后保留。在 Redis 7.2 上,禁用的 `default` 用户也要保留命令权限(例如 `user default off ~* &* +@all`):AOF 回放事务时会检查这些权限,缺少时回放的写入会因 `NOPERM` 失败。`appendfsync everysec` 仍可能丢失约一秒的写入,异步主从切换也可能丢失最近的写入。AOF 重写和快照期间需为写时复制预留内存。备份中可能保留其生成之后才删除的数据。## 观测与例行检查 {#monitoring}-网关不导出 Prometheus 之类的监控指标,也不写 HTTP 访问日志。运行状态通过 Studio 的[概览和请求日志](../gateway/10-overview-and-requests.md#overview)标签页查看,或者调用管理 API 的 `/gateway/admin/overview` 和 `/gateway/admin/logs`。+网关不导出 Prometheus 之类的监控指标。请求日志默认写入存储,可通过 Studio 的[概览和请求日志](../gateway/10-overview-and-requests.md#overview)标签页查看,或者调用管理 API 的 `/gateway/admin/overview` 和 `/gateway/admin/logs`。++在网关配置中设置 `request_log_sink: "stdout"`,或设置 `OPENVIKING_GATEWAY_REQUEST_LOG_SINK=stdout`,重启后新记录只写到 stdout。每个完成的模型请求和后台保存状态变更各产生一行 JSON,即使 stdout 接到管道也会立即刷新。每条记录包含 `time`(写入时的 Unix 秒数)、`account`、`user_id`(旧保存状态可能为 `null`),以及位于顶层的现有请求指标,如 `kind`、`status`、`input_tokens` 和 `cached_tokens`。不包含凭证、提示词或回复。采集系统负责这些记录的保留期限和访问权限;`log_retention_days` 只作用于存储中的日志。++当 `management_api: false` 关闭 Studio 和管理接口时,配置 stdout sink 并采集进程或容器日志进行观测。管理面开启但选择 stdout sink 时也采用同样流程:请求日志页和概览中的请求统计不会收到新记录。之前已存储的记录仍可见,直到过期。++从请求日志的顶层字段统计 reason 和首调缓存结果。对 capture 暂停(`kind: capture`)、队列增长、`openviking_http_429`、Redis 内存/驱逐和 HTTP 错误率设置告警。identify 拒绝发生在代理请求记录之前,所以从代理访问日志统计 401/402/403 和 Redis 故障引发的 500,具体 traceback 看网关 stderr。代理并发连接数可以近似表示在途流数。确认平台实际采集 stdout;只挂一个目录不会把它转成文件日志。### 例行检查 {#day-to-day-operations}- **进程存活:** `/health`。嵌入部署用的是 Server 的健康检查,独立部署用的是网关自己的。-- **网关健康:** **概览**标签页上的**首次调用缓存命中率**([含义](../gateway/10-overview-and-requests.md#overview))。明显下降时,见[首次调用缓存命中率下降](../gateway/12-troubleshooting.md#the-first-call-cache-hit-rate-dropped)。-- **单个请求:** 在**请求日志**标签页展开对应的行,见[请求日志](../gateway/10-overview-and-requests.md#requests)。+- **网关健康:** **概览**标签页上的**首次调用缓存命中率**([含义](../gateway/10-overview-and-requests.md#overview)),或从 stdout 指标计算:在同一账号和时间窗口内,筛选 `kind: "user"` 的记录,将 `first_upstream_cached_tokens` 的总和除以 `first_upstream_input_tokens` 的总和。某个字段缺失时,用该条记录的 `cached_tokens` 或 `input_tokens` 代替(未报告的用量按 0 计)。分母为零表示没有报告输入用量。这些字段位于顶层,不在嵌套的 `metrics` 对象中。命中率明显下降时,见[首次调用缓存命中率下降](../gateway/12-troubleshooting.md#the-first-call-cache-hit-rate-dropped)。+- **单个请求:** 在**请求日志**标签页展开对应的行,或按 `account`、`user_id` 和 `request_id` 查找 stdout 记录;见[请求日志](../gateway/10-overview-and-requests.md#requests)。后台保存事件的 `kind` 为 `capture`,通过哈希后的 `session` 标识对话。- **对外地址:** `public_url` 仍是客户端访问的地址,见[对外地址](#public-address)。-- **备份:** 存储目录;开启加密时还有加密根密钥,见[备份与恢复](../gateway/11-security-and-data.md#backups)。+- **备份:** SQLite 目录或 Redis 持久化/备份;开启加密时还有加密根密钥,见[备份与恢复](../gateway/11-security-and-data.md#backups)。## 升级 {#upgrades}@@ -303,6 +421,10 @@ v0.5 网关用自己的密钥加密数据,这些数据会在首次启动时转- 独立网关要求 OpenViking Server 不低于 `min_server_version`(0.4.16),否则无法签发密钥,保存重试也会以 `openviking_version_mismatch` 失败;记忆检索也可能失败,显示为 `openviking_http_<status>`。两者分开升级时,先升级 OpenViking,再升级网关。嵌入网关和 Server 同版本发布,不做这项检查。- 从 sidecar 或旧版独立网关升级,见[迁移](#migration)。+- SQLite 切换到 Redis 后,会话缓存从空开始。management 存储中的已签发 `ovgw_` 密钥、上游和上下文配置需要重建,没有提供迁移命令。使用 OpenViking key 时,可以通过部署默认值提供上游和上下文配置。+- Redis 键包含布局版本(`<storage.key_prefix>v1:`)。布局相同时,回滚可以继续读现有状态。将来布局版本变化时从空开始:会话数据按缓存处理,OpenViking key 记录在访问时重建,使用签发密钥的部署需要重新配置。不要假设存在跨版本数据迁移。+- 紧急停用时移除代理路由,或将网关 Deployment 缩到零。客户端可以把 Base URL 改回模型服务商,继续使用原模型凭证,此时没有网关记忆能力。`helm rollback` 的目标构建必须兼容当前配置字段和 Redis 布局。+## 从早期版本迁移 {#migration}以下步骤适用于从早期版本的 sidecar 或独立网关迁移到嵌入网关。第 4 步和第 7 步的细节见列表后面的两张表。@@ -315,7 +437,7 @@ v0.5 网关用自己的密钥加密数据,这些数据会在首次启动时转4. **改客户端地址和部署配置。** 网关的所有 URL 现在都在 `/gateway` 下,所以客户端要同时改端口和路径,旧路径不再提供服务,见[新地址](#new-addresses)。移除旧的 1935 Service 和 Ingress 路由、Compose 的 `gateway` 服务和 profile,以及 Helm 的 sidecar 配置 `gateway.workers`、`gateway.port`、`gateway.resources`。5. **首次启动会转换已存数据。** v0.5 网关用自己的密钥加密数据。新版网关(嵌入或独立)首次启动时,用这把旧密钥解密,再按当前的[加密](#encryption)设置重新写入;加密关闭时写成明文,所以想让数据继续加密,要在这次启动前开启 OpenViking 加密。- 旧密钥从环境变量 `OPENVIKING_GATEWAY_ENCRYPTION_KEY` 读取,或者从 `storage_path` 下的 `encryption.key` 读取。`encryption_key_env` 会被忽略:如果你曾用它指向别的环境变量,这次启动时把密钥导出为 `OPENVIKING_GATEWAY_ENCRYPTION_KEY`。存在旧的加密数据、两处却都没有密钥时,网关拒绝启动,错误信息会写明这两个位置。用 Helm 时,只在这次升级的版本中保留 `existingSecret` 里的 `encryption-key` 字段。启动成功后旧密钥不会再被读取,可以删掉这个环境变量、Secret 字段和 `encryption.key`。+ 旧密钥从环境变量 `OPENVIKING_GATEWAY_ENCRYPTION_KEY` 读取,或者从 `storage_path` 下的 `encryption.key` 读取。`encryption_key_env` 会被忽略:如果你曾用它指向别的环境变量,这次启动时把密钥导出为 `OPENVIKING_GATEWAY_ENCRYPTION_KEY`。存在旧的加密数据、两处却都没有密钥时,网关拒绝启动,错误信息会写明这两个位置。用嵌入式 Helm chart 时,只在这次升级的版本中保留 `gateway.existingSecret` 里的 `encryption-key` 字段。独立 chart 在这次升级时通过 `extraEnv` 注入迁移变量。启动成功后旧密钥不会再被读取,可以删掉这个环境变量、Secret 字段和 `encryption.key`。6. **移除共享 admin token。** `OPENVIKING_GATEWAY_ADMIN_TOKEN` **不会**被当作管理密钥。需要限制谁能修改上游和上下文配置时,显式设置 `management_key`,见[网关管理密钥](#gateway-management-key)。7. **核对上游地址。** 首次启动时,网关会改写一次已存上游的 Base URL,让每个上游继续请求升级前的同一个地址,见[已存上游地址的变化](#upstream-address-rewrite)。在**上游**标签页对每个上游点**测试**,确认它仍然可用。8. **了解日志和吊销的变化。** 请求日志新增用户列,没有用户的旧记录只出现在账号管理员和 root 的视图中。吊销密钥不再删除用户数据,显式删除和保留期照常生效。diff --git a/openviking/crypto/providers.py b/openviking/crypto/providers.pyindex 8c4987b84..cbeb50c10 100644--- a/openviking/crypto/providers.py+++ b/openviking/crypto/providers.py@@ -719,6 +719,16 @@ class VolcengineKMSProvider(BaseProvider):f"Failed to load existing root key from {self.key_file}. Cannot continue: {e}")+ # Releases before key_file was accepted ignored it and used the default path.+ default_key_file = Path.home() / ".openviking" / self.ROOT_KEY_FILENAME+ if default_key_file.exists():+ raise ConfigError(+ f"Root key file {self.key_file} does not exist, but {default_key_file} does. "+ "Earlier releases ignored volcengine_kms.key_file and stored the root key at the "+ f"default path; move it to {self.key_file}. If {default_key_file} belongs to "+ "another deployment, generate this key on a host without it."+ )+# Generate new root keyimport secretsdiff --git a/openviking/server/account_stores/redis_client.py b/openviking/server/account_stores/redis_client.pyindex f96f8c257..21a5d6d24 100644--- a/openviking/server/account_stores/redis_client.py+++ b/openviking/server/account_stores/redis_client.py@@ -69,7 +69,7 @@ class RedisClientHandle:await close()-def create_redis_client(raw_params: dict[str, object]) -> RedisClientHandle:+def create_redis_client(raw_params: dict[str, object], **options: Any) -> RedisClientHandle:"""Create a redis-py client for standalone, cluster, or Sentinel Redis."""try:config = RedisCacheConfig.model_validate(raw_params)@@ -90,6 +90,7 @@ def create_redis_client(raw_params: dict[str, object]) -> RedisClientHandle:"username": config.username or None,"password": password,"max_connections": config.pool_size,+ **options,}if config.mode == "standalone":diff --git a/openviking_cli/utils/config/encryption_config.py b/openviking_cli/utils/config/encryption_config.pyindex 501926c13..377468df5 100644--- a/openviking_cli/utils/config/encryption_config.py+++ b/openviking_cli/utils/config/encryption_config.py@@ -61,6 +61,7 @@ class VolcengineKMSEncryptionProviderConfig(BaseModel):region: str = Field(default="cn-beijing", description="Volcengine KMS region")access_key: Optional[str] = Field(default=None, description="Volcengine access key ID")secret_key: Optional[str] = Field(default=None, description="Volcengine secret access key")+ key_file: Optional[str] = Field(default=None, description="Path to encrypted root key file")class APIKeyHashingConfig(BaseModel):diff --git a/openviking_gateway/app.py b/openviking_gateway/app.pyindex a87479640..809cb7ba1 100644--- a/openviking_gateway/app.py+++ b/openviking_gateway/app.py@@ -10,35 +10,118 @@ their own routes and startup checks.import asyncioimport contextlibimport logging+import sysimport timefrom contextlib import asynccontextmanagerimport aiohttp+import orjsonfrom fastapi import FastAPI, HTTPException, Request, WebSocketfrom fastapi.exceptions import RequestValidationErrorfrom fastapi.responses import JSONResponse, Responsefrom starlette.exceptions import HTTPException as StarletteHTTPException-from .capture import CaptureWorker+from .capture import DELIVERY_SECONDS, CaptureWorkerfrom .client import VikingClient, VikingErrorfrom .config import PUBLIC_OPENVIKING_URLS, GatewayConfig, normalize_urlfrom .kernel import MemoryKernel-from .management import import_vlm_objects, register_management, request_credential-from .models import Policy+from .management import (+ import_vlm_objects,+ openviking_credential,+ register_management,+ request_credential,+)from .protocols import configure_rules-from .proxy import ProxyRequest, filtered_headers-from .storage import ManagementStore, SQLiteKernelStore, delete_account_data, delete_user_data+from .proxy import ProxyRequest, filtered_headers, resolve_binding+from .storage import (+ AsyncCodec,+ CachedManagement,+ SQLiteKernelStore,+ SQLiteManagementStore,+ delete_account_data,+ delete_user_data,+)logger = logging.getLogger(__name__)VIKING_DETAILS = {"openviking_unavailable": "OpenViking is unreachable.","openviking_unreachable": "OpenViking is unreachable.","openviking_http_401": "OpenViking rejected the API key.",+ "openviking_http_402": "OpenViking service is not ordered for this API key.","openviking_identity_missing": "OpenViking returned no identity for the API key.","trusted_mode_unsupported": "OpenViking Gateway does not support trusted authentication.","root_key_not_allowed": "A root API key cannot back a gateway key; use a user's API key.","openviking_version_mismatch": "OpenViking Server is older than this gateway requires.",}+CAPTURE_DRAIN_SECONDS = DELIVERY_SECONDS+++async def stdout_log(account, value, user_id=None):+ """Write each request record as JSON and flush it to the process output."""+ sys.stdout.buffer.write(+ orjson.dumps({"time": time.time(), "account": account, "user_id": user_id, **value}) + b"\n"+ )+ sys.stdout.buffer.flush()+++async def refresh_health(app):+ try:+ app.state.health = await app.state.viking.health(require_identity=False)+ app.state.viking.unavailable_reason = ""+ except VikingError as error:+ app.state.health = {"status": "degraded", "reason": error.reason}+ app.state.viking.unavailable_reason = error.reason+++async def health_loop(app, interval, sleep=asyncio.sleep):+ retry = 1+ reached = False+ while True:+ try:+ await refresh_health(app)+ if app.state.health.get("status") == "degraded":+ delay = retry+ # An embedded host starts OV after this loop: poll every second until then.+ if reached:+ retry = min(retry * 2, interval)+ else:+ delay = interval+ retry, reached = 1, True+ await sleep(delay)+ except Exception:+ logger.exception("OpenViking Gateway health check failed")+ await sleep(1)+++def open_stores(config: GatewayConfig, encryptor):+ """Construct storage ports and collect their resource cleanup."""+ close = contextlib.AsyncExitStack()+ settings = config.storage+ if "redis" in (settings.kernel, settings.management):+ try:+ from . import redis_store+ except ImportError:+ raise RuntimeError("storage provider 'redis' requires openviking[expiry]") from None+ handle = redis_store.connect(settings.redis)+ close.push_async_callback(handle.close)+ backend = redis_store.RedisBackend(+ handle.client, settings.key_prefix, AsyncCodec(encryptor)+ )+ if settings.kernel == "redis":+ store = redis_store.RedisKernelStore(backend, ttl=config.session_ttl_days * 86400)+ else:+ store = SQLiteKernelStore(config.directory / "kernel.sqlite3", encryptor)+ # SQLite threads may still wait on this loop for the encryptor.+ close.push_async_callback(asyncio.to_thread, store.close)+ if settings.management == "redis":+ management = redis_store.RedisManagementStore(+ backend, log_ttl=config.log_retention_days * 86400+ )+ else:+ management = SQLiteManagementStore(config.directory / "management.sqlite3", encryptor)+ close.push_async_callback(asyncio.to_thread, management.close)+ log = stdout_log if config.request_log_sink == "stdout" else None+ return store, CachedManagement(management, log=log), close.aclosedef create_app(config: GatewayConfig, *, openviking_url: str, vlm_source=None, encryptor=None):@@ -52,8 +135,7 @@ def create_app(config: GatewayConfig, *, openviking_url: str, vlm_source=None, e"gateway.client_rules removes entries the packaged rules do not have: %s","; ".join(unknown),)- store = SQLiteKernelStore(config.directory / "kernel.sqlite3", encryptor)- management = ManagementStore(config.directory / "management.sqlite3", encryptor)+ store, management, close = open_stores(config, encryptor)@asynccontextmanagerasync def lifespan(app):@@ -69,19 +151,29 @@ def create_app(config: GatewayConfig, *, openviking_url: str, vlm_source=None, eapp.state.viking = VikingClient(http, openviking_url, config.min_server_version)app.state.kernel = MemoryKernel(store, app.state.viking)app.state.worker = CaptureWorker(store, management, app.state.viking)- # The first probe runs in maintenance: an embedded server is not listening yet.+ # The first probe runs in the background: an embedded server is not listening yet.app.state.health = {"status": "starting"}- task = asyncio.create_task(maintenance(app))+ stopped = asyncio.Event()+ maintenance = [+ asyncio.create_task(health_loop(app, config.health_interval_seconds)),+ asyncio.create_task(cleanup_loop()),+ ]+ captures = [+ asyncio.create_task(capture_loop(app, stopped))+ for _ in range(config.capture_concurrency)+ ]try:yieldfinally:- task.cancel()- with contextlib.suppress(asyncio.CancelledError):- await task+ stopped.set()+ for task in maintenance:+ task.cancel()+ _, pending = await asyncio.wait(captures, timeout=CAPTURE_DRAIN_SECONDS)+ for task in pending:+ task.cancel()+ await asyncio.gather(*maintenance, *captures, return_exceptions=True)finally:- # Storage threads may still wait on this loop for the encryptor.- await asyncio.to_thread(store.close)- await asyncio.to_thread(management.close)+ await close()app = FastAPI(title="OpenViking Gateway",@@ -95,47 +187,34 @@ def create_app(config: GatewayConfig, *, openviking_url: str, vlm_source=None, eapp.state.vlm_source = vlm_sourceapp.state.warnings = (["public_openviking_without_management_key"]- if not config.management_key and normalize_url(openviking_url) in PUBLIC_OPENVIKING_URLS+ if config.management_api+ and not config.management_key+ and normalize_url(openviking_url) in PUBLIC_OPENVIKING_URLSelse [])- async def refresh_health(app):- try:- app.state.health = await app.state.viking.health(require_identity=False)- app.state.viking.unavailable_reason = ""- except VikingError as error:- app.state.health = {"status": "degraded", "reason": error.reason}- app.state.viking.unavailable_reason = error.reason-- async def maintenance(app):- health_at = 0- cleanup_at = 0- retry = 1- reached = False+ async def cleanup_loop():while True:try:- if time.monotonic() >= health_at:- await refresh_health(app)- if app.state.health.get("status") == "degraded":- health_at = time.monotonic() + retry- # An embedded host starts OV after this loop: poll every second until then.- if reached:- retry = min(retry * 2, config.health_interval_seconds)- else:- health_at = time.monotonic() + config.health_interval_seconds- retry, reached = 1, True- if time.monotonic() >= cleanup_at:- await store.expire(time.time() - config.session_ttl_days * 86400)- await management.expire_logs(time.time() - config.log_retention_days * 86400)- cleanup_at = time.monotonic() + 3600- if not await app.state.worker.once():- await asyncio.sleep(1)- except asyncio.CancelledError:- raise+ await store.expire(time.time() - config.session_ttl_days * 86400)+ await management.expire_logs(time.time() - config.log_retention_days * 86400)+ await asyncio.sleep(3600)except Exception:- logger.exception("OpenViking Gateway maintenance failed")+ logger.exception("OpenViking Gateway cleanup failed")await asyncio.sleep(1)+ async def capture_loop(app, stopped):+ while not stopped.is_set():+ try:+ if await app.state.worker.once():+ continue+ except Exception:+ logger.exception("OpenViking Gateway capture failed")+ try:+ await asyncio.wait_for(stopped.wait(), timeout=1)+ except asyncio.TimeoutError:+ pass+@app.exception_handler(RequestValidationError)async def invalid_request(_request, error):return JSONResponse(@@ -175,8 +254,12 @@ def create_app(config: GatewayConfig, *, openviking_url: str, vlm_source=None, ekey = request_credential(request)if key.startswith("sk-ant-oat"):raise HTTPException(403, "Claude subscription OAuth credentials are not supported")- credential = await management.authenticate(key)- invalid = "Invalid gateway key. It may have been revoked, or removed because its OpenViking API key was regenerated. Issue a new key in OpenViking Studio → Gateway → Keys."+ if config.openviking_keys and key and not key.startswith("ovgw_"):+ credential = await openviking_credential(app, key)+ invalid = "OpenViking rejected this API key. It may have been regenerated; use the user's current OpenViking API key."+ else:+ credential = await management.authenticate(key)+ invalid = "Invalid gateway key. It may have been revoked, or removed because its OpenViking API key was regenerated. Issue a new key in OpenViking Studio → Gateway → Keys."if not credential:raise HTTPException(401, invalid)if app.state.viking.unavailable_reason:@@ -185,15 +268,19 @@ def create_app(config: GatewayConfig, *, openviking_url: str, vlm_source=None, etry:identity = await app.state.viking.identify(credential["openviking_key"])except VikingError as error:+ if error.reason in ("openviking_http_402", "openviking_http_403"):+ raiseif error.reason != "openviking_http_401":- # Unconfirmed is not revoked: like recall, the request degrades instead.+ # Anything short of a refusal leaves revocation unconfirmed, including the+ # missing identity OV reports when its account store fails.return credential, "revocation_check_unavailable"identity = None# Dev identities are always default/default, so they say nothing about this key.if identity is None or (identity.get("auth_mode") != "dev"and (- identity["account_id"] != credential["account"]+ identity["account_id"]+ != credential.get("openviking_account", credential["account"])or identity["user_id"] != credential["user_id"])):@@ -201,21 +288,22 @@ def create_app(config: GatewayConfig, *, openviking_url: str, vlm_source=None, eraise HTTPException(401, invalid)return credential, None- register_management(app)+ if config.management_api:+ register_management(app)@app.get("/api/compatible/v1/models")@app.get("/api/v3/models")@app.get("/v1/models")async def models(request: Request):credential, _ = await authenticate(request)- values = await management.list(credential["account"], "upstreams")+ binding = await resolve_binding(management, config, credential)names = sorted({model- for u in values- if u["id"] in credential["upstream_ids"] and u.get("enabled", True)+ for u in binding.upstreams+ if u.get("enabled", True)for model in [*u.get("models", []), *u.get("aliases", {})]- if not credential["models"] or model in credential["models"]+ if not binding.models or model in binding.models})return {@@ -306,7 +394,9 @@ async def seed_defaults(app, account_id):if app.state.vlm_source and not await management.list(account_id, "upstreams"):await import_vlm_objects(app, account_id)if not await management.get(account_id, "policies", "default"):- await management.save(account_id, "policies", "default", Policy().model_dump())+ await management.save(+ account_id, "policies", "default", app.state.config.default_profile.model_dump()+ )async def delete_data(app, account_id, user_id=None):diff --git a/openviking_gateway/capture.py b/openviking_gateway/capture.pyindex edb908b0e..5ca7eef9e 100644--- a/openviking_gateway/capture.py+++ b/openviking_gateway/capture.py@@ -21,6 +21,7 @@ import orjsonfrom .archives import TERMINAL, observe_archivefrom .capture_store import Document, LeaseLost+from .client import VikingErrorfrom .models import Policyfrom .notices import without_noticesfrom .protocols import clean_text, is_user, string_type, text_content, unwrap_client@@ -30,6 +31,7 @@ from .tool_protocols import reply_chainlogger = logging.getLogger(__name__)MAX_ATTEMPTS = 5RECOVERY_SECONDS = 300+DELIVERY_SECONDS = 100 # below the 120 s claim leaseMAX_PREVIOUS = 5SOURCE = "gateway:"@@ -312,7 +314,7 @@ class CaptureWorker:if item is None:return Falsetry:- async with async_timeout.timeout(100):+ async with async_timeout.timeout(DELIVERY_SECONDS):await self.deliver(item)except (BranchChanged, LeaseLost):pass@@ -322,6 +324,10 @@ class CaptureWorker:previous = old.value.get("error", {})attempts = previous.get("attempts", 0) + 1reason = getattr(error, "reason", "delivery_failed")+ if reason == "openviking_http_401" and await self.revoked(old.value):+ await self.management.delete(+ old.value["account"], "keys", old.value["credential_id"]+ )failure = {"attempts": attempts,"reason": reason,@@ -340,6 +346,20 @@ class CaptureWorker:await self.queue.release(item)return True+ async def revoked(self, state):+ """Confirm a delivery 401 on /health, as authentication does, before dropping the key.++ OpenViking also answers 401 for upstream model failures such as an invalid VLM key.+ """+ key = await self.management.get(state["account"], "keys", state["credential_id"])+ if not key:+ return False+ try:+ await self.viking.identify(key["openviking_key"])+ except VikingError as error:+ return error.reason == "openviking_http_401"+ return False+async def log(self, item, state, status, reason):await self.management.log(state["account"],diff --git a/openviking_gateway/cli.py b/openviking_gateway/cli.pyindex a8cbc7530..1ca070983 100644--- a/openviking_gateway/cli.py+++ b/openviking_gateway/cli.py@@ -156,6 +156,7 @@ def main():host=config.host,port=config.port,workers=config.workers,+ timeout_keep_alive=config.keep_alive_seconds,log_level="info",# Signed upload tokens live in query strings; log request metadata only.access_log=False,diff --git a/openviking_gateway/config.py b/openviking_gateway/config.pyindex caeb6eabf..fd74eec83 100644--- a/openviking_gateway/config.py+++ b/openviking_gateway/config.py@@ -12,6 +12,8 @@ from urllib.parse import urlsplit, urlunsplitfrom pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator+from .models import Policy, Upstream+logger = logging.getLogger(__name__)ENVIRONMENT_PREFIX = "OPENVIKING_GATEWAY_"@@ -71,6 +73,24 @@ class ClientRules(BaseModel):return value+class StorageConfig(BaseModel):+ model_config = ConfigDict(extra="forbid")+ kernel: Literal["sqlite", "redis"] = "sqlite"+ management: Literal["sqlite", "redis"] = "sqlite"+ # Keep hash tags and SCAN patterns independent of the configured namespace.+ key_prefix: str = Field(default="ovgw:", pattern=r"^[^{}*?\[\]\\]*$")+ redis: dict = Field(default_factory=dict, repr=False, validate_default=True)++ @field_validator("redis")+ @classmethod+ def validate_redis(cls, value: dict) -> dict:+ from openviking_cli.utils.config.agfs_config import RedisCacheConfig++ if unknown := set(value) - set(RedisCacheConfig.model_fields):+ raise ValueError(f"unknown redis settings: {', '.join(sorted(unknown))}")+ return RedisCacheConfig.model_validate({"command_timeout_ms": 5000, **value}).model_dump()++class GatewayConfig(BaseModel):model_config = ConfigDict(extra="forbid")# Settings an upgraded configuration may still carry; rejecting them would stop the host.@@ -79,16 +99,32 @@ class GatewayConfig(BaseModel):public_url: str = ""mcp_file_links: Literal["proxy", "direct"] = "proxy"storage_path: str = "~/.openviking/gateway"+ management_api: bool = True+ storage: StorageConfig = Field(default_factory=StorageConfig)management_key: str = Field(default="", repr=False)+ # Accept OpenViking API keys in place of gateway keys, with the account's defaults.+ openviking_keys: bool = False+ tenancy: Literal["account", "key"] = "account"+ # Used where an account stores none: OpenViking keys and the "default" profile.+ default_upstreams: dict[str, Upstream] = Field(default_factory=dict, repr=False)+ default_profile: Policy = Field(default_factory=Policy)min_server_version: str = "0.4.16"session_ttl_days: int = Field(default=30, ge=1)response_ttl_seconds: int = Field(default=30 * 86400, ge=60)+ request_log_sink: Literal["store", "stdout"] = "store"log_retention_days: int = Field(default=30, ge=1)max_body_bytes: int = Field(default=32 * 1024 * 1024, ge=1024)upstream_timeout_seconds: float = Field(default=600, gt=0)health_interval_seconds: float = Field(default=60, ge=1)+ capture_concurrency: int = Field(default=1, ge=1)client_rules: ClientRules = Field(default_factory=ClientRules)+ @model_validator(mode="after")+ def validate_tenancy(self):+ if self.tenancy == "key" and self.management_api:+ raise ValueError("tenancy 'key' requires management_api: false")+ return self+@model_validator(mode="before")@classmethoddef apply_environment(cls, value):@@ -109,10 +145,12 @@ class GatewayConfig(BaseModel):value[field] = overridereturn value- @field_validator("client_rules", mode="before")+ @field_validator(+ "client_rules", "storage", "default_upstreams", "default_profile", mode="before"+ )@classmethod- def parse_client_rules(cls, value):- # OPENVIKING_GATEWAY_CLIENT_RULES carries the section as JSON.+ def parse_json(cls, value):+ # OPENVIKING_GATEWAY_<FIELD> carries these sections as JSON.return json.loads(value) if isinstance(value, str) else value@field_validator("public_url")@@ -152,6 +190,7 @@ class StandaloneGatewayConfig(GatewayConfig):host: str = "127.0.0.1"port: int = Field(default=1935, ge=1, le=65535)workers: int = Field(default=1, ge=1, le=64)+ keep_alive_seconds: float = Field(default=75, gt=0)# Same schema as ov.conf's top-level "encryption"; absent or disabled stores plaintext.encryption: dict | None = Field(default=None, repr=False)diff --git a/openviking_gateway/lua/hash_read.lua b/openviking_gateway/lua/hash_read.luanew file mode 100644index 000000000..0da4985f9--- /dev/null+++ b/openviking_gateway/lua/hash_read.lua@@ -0,0 +1,7 @@+-- KEYS: hashes. ARGV: fields -> {position, values...} per hash holding the first field+local rows = {}+for i, key in ipairs(KEYS) do+ local values = redis.call('HMGET', key, unpack(ARGV))+ if values[1] then table.insert(rows, {i, unpack(values)}) end+end+return rowsdiff --git a/openviking_gateway/lua/kernel_capture_claim.lua b/openviking_gateway/lua/kernel_capture_claim.luanew file mode 100644index 000000000..e5ab11361--- /dev/null+++ b/openviking_gateway/lua/kernel_capture_claim.lua@@ -0,0 +1,18 @@+-- KEYS: capture tombstone, capture, ready queue. ARGV: owner, lease ms, member -> {v, ver} or {}+local ready = redis.call('HGET', KEYS[2], 'ready')+if redis.call('EXISTS', KEYS[1]) == 1 or not ready then+ redis.call('ZREM', KEYS[3], ARGV[3])+ return {}+end+local clock = redis.call('TIME')+local now = clock[1] * 1000 + clock[2] / 1000+local lease = tonumber(redis.call('HGET', KEYS[2], 'lease') or '0')+ready = tonumber(ready) * 1000+if ready > now or lease >= now then+ redis.call('ZADD', KEYS[3], math.max(ready, lease), ARGV[3])+ return {}+end+lease = now + tonumber(ARGV[2])+redis.call('HSET', KEYS[2], 'lease', lease, 'owner', ARGV[1])+redis.call('ZADD', KEYS[3], math.max(ready, lease), ARGV[3])+return redis.call('HMGET', KEYS[2], 'v', 'ver')diff --git a/openviking_gateway/lua/kernel_capture_release.lua b/openviking_gateway/lua/kernel_capture_release.luanew file mode 100644index 000000000..e1eddd1cb--- /dev/null+++ b/openviking_gateway/lua/kernel_capture_release.lua@@ -0,0 +1,15 @@+-- KEYS: capture tombstone, capture, ready queue. ARGV: owner, member -> 0|1+if redis.call('EXISTS', KEYS[1]) == 1 then+ redis.call('ZREM', KEYS[3], ARGV[2])+ return 0+end+if redis.call('HGET', KEYS[2], 'owner') ~= ARGV[1] then return 0 end+redis.call('HDEL', KEYS[2], 'owner')+redis.call('HSET', KEYS[2], 'lease', 0)+local ready = redis.call('HGET', KEYS[2], 'ready')+if ready then+ redis.call('ZADD', KEYS[3], tonumber(ready) * 1000, ARGV[2])+else+ redis.call('ZREM', KEYS[3], ARGV[2])+end+return 1diff --git a/openviking_gateway/lua/kernel_capture_swap.lua b/openviking_gateway/lua/kernel_capture_swap.luanew file mode 100644index 000000000..55ba3197e--- /dev/null+++ b/openviking_gateway/lua/kernel_capture_swap.lua@@ -0,0 +1,22 @@+-- KEYS: capture tombstone, capture, ready. ARGV: version, value, ready, owner, ttl, member -> 0|1+if redis.call('EXISTS', KEYS[1]) == 1 then return redis.error_reply('OVGW_DELETED') end+local lease = tonumber(redis.call('HGET', KEYS[2], 'lease') or '0')+if ARGV[4] ~= '' then+ local clock = redis.call('TIME')+ local now = clock[1] * 1000 + clock[2] / 1000+ if redis.call('HGET', KEYS[2], 'owner') ~= ARGV[4] or lease <= now then+ return redis.error_reply('OVGW_LEASE_LOST')+ end+end+local version = tonumber(redis.call('HGET', KEYS[2], 'ver') or '0')+if version ~= tonumber(ARGV[1]) then return 0 end+redis.call('HSET', KEYS[2], 'v', ARGV[2], 'ver', version + 1)+redis.call('PEXPIRE', KEYS[2], ARGV[5])+if ARGV[3] == '' then+ redis.call('HDEL', KEYS[2], 'ready')+ redis.call('ZREM', KEYS[3], ARGV[6])+else+ redis.call('HSET', KEYS[2], 'ready', ARGV[3])+ redis.call('ZADD', KEYS[3], math.max(tonumber(ARGV[3]) * 1000, lease), ARGV[6])+end+return 1diff --git a/openviking_gateway/lua/kernel_keep.lua b/openviking_gateway/lua/kernel_keep.luanew file mode 100644index 000000000..af602052d--- /dev/null+++ b/openviking_gateway/lua/kernel_keep.lua@@ -0,0 +1,4 @@+-- KEYS: tombstone, replay and state keys. ARGV: ttl -> 1+if redis.call('EXISTS', KEYS[1]) == 1 then return redis.error_reply('OVGW_DELETED') end+for i = 2, #KEYS do redis.call('PEXPIRE', KEYS[i], ARGV[1]) end+return 1diff --git a/openviking_gateway/lua/kernel_load.lua b/openviking_gateway/lua/kernel_load.luanew file mode 100644index 000000000..63f608416--- /dev/null+++ b/openviking_gateway/lua/kernel_load.lua@@ -0,0 +1,30 @@+-- KEYS: replays (own last), state. ARGV: count, anchors, inherited, with state -> {rows, state}+local count = tonumber(ARGV[1])+local anchors, inherited = {}, {}+for _, anchor in ipairs(cjson.decode(ARGV[2])) do anchors[anchor] = true end+for _, kind in ipairs(cjson.decode(ARGV[3])) do inherited[kind] = true end+local rows = {}+for i = 1, count do+ local fields = {}+ for _, field in ipairs(redis.call('HKEYS', KEYS[i])) do+ local colon = string.find(field, ':', 1, true)+ local kind, anchor = string.sub(field, 1, colon - 1), string.sub(field, colon + 1)+ if kind ~= 'reply' and anchors[anchor] and (i == count or inherited[kind]) then+ table.insert(fields, field)+ end+ end+ -- Bound unpack arguments for sessions with many replay records.+ for first = 1, #fields, 256 do+ local last = math.min(first + 255, #fields)+ local values = redis.call('HMGET', KEYS[i], unpack(fields, first, last))+ for offset, value in ipairs(values) do+ table.insert(rows, {fields[first + offset - 1], value})+ end+ end+end+local state = {}+if ARGV[4] == '1' then+ local value = redis.call('HMGET', KEYS[count + 1], 'v', 'ver')+ if value[1] then state = value end+end+return {rows, state}diff --git a/openviking_gateway/lua/kernel_replay_put.lua b/openviking_gateway/lua/kernel_replay_put.luanew file mode 100644index 000000000..1d4370e64--- /dev/null+++ b/openviking_gateway/lua/kernel_replay_put.lua@@ -0,0 +1,9 @@+-- KEYS: tombstone, replay, reply index (replies). ARGV: field, value, ttl, session -> stored+if redis.call('EXISTS', KEYS[1]) == 1 then return redis.error_reply('OVGW_DELETED') end+redis.call('HSETNX', KEYS[2], ARGV[1], ARGV[2])+redis.call('PEXPIRE', KEYS[2], ARGV[3])+if #KEYS == 3 then+ redis.call('SADD', KEYS[3], ARGV[4])+ redis.call('PEXPIRE', KEYS[3], ARGV[3])+end+return redis.call('HGET', KEYS[2], ARGV[1])diff --git a/openviking_gateway/lua/kernel_replies_prune.lua b/openviking_gateway/lua/kernel_replies_prune.luanew file mode 100644index 000000000..840b78db3--- /dev/null+++ b/openviking_gateway/lua/kernel_replies_prune.lua@@ -0,0 +1,18 @@+-- KEYS: reply indexes, then replays. ARGV: ttl, n, then per index anchor, count, members -> live+local count, key, arg, result = tonumber(ARGV[2]), tonumber(ARGV[2]), 3, {}+for i = 1, count do+ local field, members, live = 'reply:' .. ARGV[arg], tonumber(ARGV[arg + 1]), {}+ arg = arg + 2+ for _ = 1, members do+ key = key + 1+ if redis.call('HEXISTS', KEYS[key], field) == 1 then+ table.insert(live, ARGV[arg])+ else+ redis.call('SREM', KEYS[i], ARGV[arg])+ end+ arg = arg + 1+ end+ if #live > 0 then redis.call('PEXPIRE', KEYS[i], ARGV[1]) end+ result[i] = live+end+return resultdiff --git a/openviking_gateway/lua/kernel_replies_read.lua b/openviking_gateway/lua/kernel_replies_read.luanew file mode 100644index 000000000..8805bff42--- /dev/null+++ b/openviking_gateway/lua/kernel_replies_read.lua@@ -0,0 +1,4 @@+-- KEYS: reply indexes. ARGV: none -> members per index+local rows = {}+for i, key in ipairs(KEYS) do rows[i] = redis.call('SMEMBERS', key) end+return rowsdiff --git a/openviking_gateway/lua/kernel_state_swap.lua b/openviking_gateway/lua/kernel_state_swap.luanew file mode 100644index 000000000..0ca9b2f45--- /dev/null+++ b/openviking_gateway/lua/kernel_state_swap.lua@@ -0,0 +1,7 @@+-- KEYS: tombstone, state. ARGV: version, value, ttl -> 0|1+if redis.call('EXISTS', KEYS[1]) == 1 then return redis.error_reply('OVGW_DELETED') end+local version = tonumber(redis.call('HGET', KEYS[2], 'ver') or '0')+if version ~= tonumber(ARGV[1]) then return 0 end+redis.call('HSET', KEYS[2], 'v', ARGV[2], 'ver', version + 1)+redis.call('PEXPIRE', KEYS[2], ARGV[3])+return 1diff --git a/openviking_gateway/lua/log_delete_user.lua b/openviking_gateway/lua/log_delete_user.luanew file mode 100644index 000000000..c3068384a--- /dev/null+++ b/openviking_gateway/lua/log_delete_user.lua@@ -0,0 +1,19 @@+-- KEYS: log, rebuild scratch. ARGV: h(user_id) -> rows kept+local ttl = redis.call('PTTL', KEYS[1])+local rows = redis.call('LRANGE', KEYS[1], 0, -1)+redis.call('UNLINK', KEYS[2])+local kept = 0+for _, row in ipairs(rows) do+ local user = string.match(row, '^[^%z]*%z([^%z]*)%z')+ if user ~= ARGV[1] then+ redis.call('RPUSH', KEYS[2], row)+ kept = kept + 1+ end+end+if kept == 0 then+ redis.call('UNLINK', KEYS[1])+else+ if ttl >= 0 then redis.call('PEXPIRE', KEYS[2], ttl) end+ redis.call('RENAME', KEYS[2], KEYS[1])+end+return keptdiff --git a/openviking_gateway/lua/log_push.lua b/openviking_gateway/lua/log_push.luanew file mode 100644index 000000000..ad17b1828--- /dev/null+++ b/openviking_gateway/lua/log_push.lua@@ -0,0 +1,5 @@+-- KEYS: log. ARGV: row, limit, ttl -> 1+redis.call('LPUSH', KEYS[1], ARGV[1])+redis.call('LTRIM', KEYS[1], 0, tonumber(ARGV[2]) - 1)+redis.call('PEXPIRE', KEYS[1], ARGV[3])+return 1diff --git a/openviking_gateway/lua/obj_delete.lua b/openviking_gateway/lua/obj_delete.luanew file mode 100644index 000000000..0487564e3--- /dev/null+++ b/openviking_gateway/lua/obj_delete.lua@@ -0,0 +1,12 @@+-- KEYS: object, index (indexed kinds). ARGV: id -> 1+redis.call('UNLINK', KEYS[1])+if KEYS[2] then+ redis.call('ZREM', KEYS[2], ARGV[1])+ local last = redis.call('ZREVRANGE', KEYS[2], 0, 0, 'WITHSCORES')+ if last[2] == 'inf' then+ redis.call('PERSIST', KEYS[2])+ elseif last[2] then+ redis.call('PEXPIREAT', KEYS[2], math.ceil(tonumber(last[2])))+ end+end+return 1diff --git a/openviking_gateway/lua/obj_save.lua b/openviking_gateway/lua/obj_save.luanew file mode 100644index 000000000..acc098047--- /dev/null+++ b/openviking_gateway/lua/obj_save.lua@@ -0,0 +1,23 @@+-- KEYS: object, index (indexed kinds). ARGV: id, value, h(user_id), ttl or '' -> {rev, PTTL}+local now = redis.call('TIME')+now = now[1] * 1000 + math.floor(now[2] / 1000)+local ttl = redis.call('PTTL', KEYS[1])+local rev = redis.call('HINCRBY', KEYS[1], 'rev', 1)+redis.call('HSET', KEYS[1], 'v', ARGV[2], 'u', ARGV[3])+if ARGV[4] ~= '' then+ ttl = tonumber(ARGV[4])+ redis.call('PEXPIRE', KEYS[1], ttl)+end+if KEYS[2] then+ local expires = '+inf'+ if ttl >= 0 then expires = now + ttl end+ redis.call('ZADD', KEYS[2], expires, ARGV[1])+ redis.call('ZREMRANGEBYSCORE', KEYS[2], '-inf', now)+ local last = redis.call('ZREVRANGE', KEYS[2], 0, 0, 'WITHSCORES')+ if last[2] == 'inf' then+ redis.call('PERSIST', KEYS[2])+ elseif last[2] then+ redis.call('PEXPIREAT', KEYS[2], math.ceil(tonumber(last[2])))+ end+end+return {rev, redis.call('PTTL', KEYS[1])}diff --git a/openviking_gateway/management.py b/openviking_gateway/management.pyindex 0ad8650f1..ae5405cf2 100644--- a/openviking_gateway/management.py+++ b/openviking_gateway/management.py@@ -19,10 +19,17 @@ from pydantic import ValidationErrorfrom .capture import reset_capturefrom .client import VikingErrorfrom .config import MOUNT_PATH-from .models import CaptureReset, KeyRequest, Policy, Upstream, UpstreamTestRequest+from .models import (+ CaptureReset,+ KeyRequest,+ Policy,+ Upstream,+ UpstreamTestRequest,+ validation_detail,+)from .overview import overview_summaryfrom .protocols import text_content-from .proxy import fill_key, upstream_headers, upstream_key, upstream_url+from .proxy import default_policy, fill_key, upstream_headers, upstream_key, upstream_urlfrom .records import RecordKind as Kfrom .storage import delete_account_data, delete_user_data, digestfrom .tool_catalog import select_tools@@ -113,13 +120,7 @@ async def read_body(request, model, prepare=None):payload = await request.json()return model.model_validate(prepare(payload) if prepare else payload)except ValidationError as error:- fail(- 422,- "invalid_configuration",- "; ".join(- item["msg"] for item in error.errors(include_input=False, include_context=False)- ),- )+ fail(422, "invalid_configuration", validation_detail(error))except ValueError:fail(422, "invalid_configuration")@@ -193,6 +194,41 @@ async def caller(request, *, require_identity=True, write=False):return Caller(account, credential, identity, manager, can_write)+async def register_user(app, account_id, user_id, ttl=None):+ """Record a new key's user and lift an earlier deletion of their gateway data."""+ for protocol in ("anthropic", "chat", "responses"):+ await app.state.store.allow_scope(digest(account_id + "\0" + user_id + "\0" + protocol))+ await app.state.management.save(account_id, "users", user_id, {"user_id": user_id}, ttl=ttl)+++async def openviking_credential(app, key):+ """Confirm and cache an OpenViking key with its deployment's tenant partition."""+ identifier = digest("openviking\0" + key)+ partitioned = app.state.config.tenancy == "key"+ if credential := await app.state.management.credential(identifier):+ # A tenancy change moves the key to another partition: confirm it again.+ if (credential["account"] == "k_" + identifier) == partitioned:+ return credential+ await app.state.management.delete(credential["account"], "keys", identifier)+ identity = await app.state.viking.health(key)+ account, user_id = identity["account_id"], identity["user_id"]+ if partitioned:+ account = "k_" + identifier+ ttl = app.state.config.session_ttl_days * 86400+ stored = {+ "source": "openviking",+ "openviking_account": identity["account_id"],+ "openviking_key": key,+ "user_id": user_id,+ # Current keys are "<account>.<user>.<secret>": only the secret tells them apart.+ "prefix": key.rsplit(".", 1)[-1][:8],+ "created_at": time.time(),+ }+ await app.state.management.save(account, "keys", identifier, stored, ttl=ttl)+ await register_user(app, account, user_id, ttl=ttl)+ return await app.state.management.credential(identifier)++async def import_vlm_objects(app, account_id):"""Save the host's VLM candidates as upstreams; a re-import keeps gateway-side edits."""management = app.state.management@@ -340,9 +376,9 @@ def register_management(app):async def delete_object(identifier: str, request: Request):who = await caller(request, require_identity=False, write=True)count = sum(- key["policy_id"] == identifier+ key.get("policy_id") == identifierif kind == "policies"- else identifier in key["upstream_ids"]+ else identifier in key.get("upstream_ids", [])for key in await management.list(who.account_id, "keys"))if count:@@ -437,13 +473,7 @@ def register_management(app):"created_at": time.time(),}result = await management.save(who.account_id, "keys", digest(secret), stored)- for protocol in ("anthropic", "chat", "responses"):- await store.allow_scope(- digest(who.account_id + "\0" + identity["user_id"] + "\0" + protocol)- )- await management.save(- who.account_id, "users", identity["user_id"], {"user_id": identity["user_id"]}- )+ await register_user(app, who.account_id, identity["user_id"])return {**public_object("keys", result), "key": secret}@router.post("/keys/{identifier}/capture/reset")@@ -494,11 +524,11 @@ def register_management(app):headers.setdefault("anthropic-version", "2023-06-01")tools = []if upstream.get("allow_gateway_tools", True):- policy = await management.get(who.account_id, "policies", "default")+ policy = await default_policy(management, app.state.config, who.account_id)try:tools = select_tools(await caller_tool_catalog(app, management, who),- policy or Policy().model_dump(),+ policy,)except VikingError:pass@@ -596,6 +626,10 @@ def public_object(kind, value, *, read_only=False):value["header_names"] = list(headers)if kind == "keys":value.pop("openviking_key", None)+ if value.get("source") == "openviking":+ # Listed in the shape of an issued key, but it stores no binding: resolve_binding+ # gives it the account's defaults per request.+ value.update(name="", policy_id="", upstream_ids=[], models=[])return valuediff --git a/openviking_gateway/models.py b/openviking_gateway/models.pyindex d684935eb..95dc54fb3 100644--- a/openviking_gateway/models.py+++ b/openviking_gateway/models.py@@ -1,12 +1,14 @@# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.# SPDX-License-Identifier: AGPL-3.0-from typing import Literal+from typing import Annotated, Literalfrom urllib.parse import urlsplit-from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator+from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator, model_validatorProtocolName = Literal["anthropic", "chat", "responses"]KEY_PLACEHOLDER = "{api_key}"+# Largest integer JSON readers, Studio included, hold exactly.+JSON_INT_MAX = 2**53# OpenViking MCP tools that change data; new profiles offer only the read-only ones.WRITE_TOOLS = (@@ -21,49 +23,60 @@ WRITE_TOOLS = ()+def validation_detail(error: ValidationError) -> str:+ """Each problem with the field it concerns, without echoing submitted values."""+ return "; ".join(+ ".".join(map(str, item["loc"])) + ": " + item["msg"] if item["loc"] else item["msg"]+ for item in error.errors(include_input=False, include_context=False)+ )++class CaptureReset(BaseModel):session: str = Field(min_length=1, max_length=128)protocol: ProtocolNameclass Policy(BaseModel):- model_config = ConfigDict(extra="forbid")+ # Session roots keep a copy as JSON, so numbers must be finite and integers exact there.+ model_config = ConfigDict(extra="forbid", allow_inf_nan=False)name: str = "Default"recall: bool = Trueprofile: bool = Trueprofile_max_tokens: int = Field(default=4000, ge=0, le=32000)capture: bool = Truecontext_types: list[str] = Field(default_factory=lambda: ["memory", "resource", "skill"])- quotas: dict[str, int] = Field(default_factory=dict)+ quotas: dict[str, Annotated[int, Field(ge=0, le=JSON_INT_MAX)]] = Field(default_factory=dict)max_tokens: int = Field(default=1600, ge=64, le=32000)- session_max_tokens: int = Field(default=30000, ge=0)+ session_max_tokens: int = Field(default=30000, ge=0, le=JSON_INT_MAX)score_threshold: float = Field(default=0.35, ge=0, le=1)recall_timeout: float = Field(default=2, gt=0, le=30)query_max_chars: int = Field(default=8000, ge=3, le=32000)# Start each turn's reply with a summary of what OpenViking injected; the model never sees it.show_recall: bool = False- commit_tokens: int = Field(default=20000, ge=1)+ commit_tokens: int = Field(default=20000, ge=1, le=JSON_INT_MAX)keep_recent_messages: int = Field(default=10, ge=0, le=1000)idle_seconds: float = Field(default=600, ge=1)compaction: bool = Truecompaction_threshold: float = Field(default=0.9, ge=0.5, le=0.98)summary_max_tokens: int = Field(default=8000, ge=1000, le=32000)# Fallback when the upstream lists no window for the model; 1M is assumed when unset.- context_window: int | None = Field(default=None, ge=1024)+ context_window: int | None = Field(default=None, ge=1024, le=JSON_INT_MAX)gateway_tools: bool = True# MCP tool names; tools the server adds later stay enabled.disabled_tools: list[str] = Field(default_factory=lambda: list(WRITE_TOOLS))# None means no limit, as in an agent harness's own tool loop.- tool_max_rounds: int | None = Field(default=None, ge=1)+ tool_max_rounds: int | None = Field(default=None, ge=1, le=JSON_INT_MAX)tool_timeout_seconds: float = Field(default=30, gt=0, le=120)tool_result_bytes: int = Field(default=65536, ge=1024, le=1048576)tool_total_seconds: float | None = Field(default=None, gt=0)- tool_total_tokens: int | None = Field(default=None, ge=1024)+ tool_total_tokens: int | None = Field(default=None, ge=1024, le=JSON_INT_MAX)show_tool_calls: bool = True# Experimental: the model starts fresh context windows itself (needs gateway tools).agent_windows: bool = Falsewindow_soft_ratio: float = Field(default=0.7, ge=0.3, le=0.95)window_hard_ratio: float = Field(default=0.85, ge=0.4, le=0.97)+ # Clients may override the other fields per conversation with X-OpenViking-Context.+ client_overrides: bool = True@model_validator(mode="before")@classmethoddiff --git a/openviking_gateway/protocols.py b/openviking_gateway/protocols.pyindex 8ca8fbba4..ecccb4bcf 100644--- a/openviking_gateway/protocols.py+++ b/openviking_gateway/protocols.py@@ -5,6 +5,7 @@What differs between wire protocols lives in their adapters in ``tool_protocols``."""+import asyncioimport hashlibimport jsonimport math@@ -493,6 +494,51 @@ def usage_of(value: dict, excludes_cache: bool = False) -> dict:}+# Stay below the common 60-second load-balancer idle timeout.+HEARTBEAT_SECONDS = 15+++async def heartbeat(chunks, seconds):+ """Yield None during idle periods while one task owns the source iterator."""+ queue, end = asyncio.Queue(1), object()++ async def pump():+ try:+ async for chunk in chunks:+ await queue.put(chunk)+ except asyncio.CancelledError as error:+ # A deadline can cancel queue.put while the source's timeout is suspended at yield.+ if throw := getattr(chunks, "athrow", None):+ await throw(error)+ raise+ finally:+ # Close suspended generators in the task that owns their timeout contexts.+ if close := getattr(chunks, "aclose", None):+ await close()++ def wake_consumer(task):+ # A full queue already wakes the consumer; completion must not block cleanup.+ if queue.empty():+ queue.put_nowait(end)++ task = asyncio.create_task(pump())+ task.add_done_callback(wake_consumer)+ try:+ while not task.done() or not queue.empty():+ try:+ chunk = await asyncio.wait_for(queue.get(), seconds)+ except asyncio.TimeoutError:+ yield None+ continue+ if chunk is end:+ break+ yield chunk+ await task+ finally:+ task.cancel()+ await asyncio.gather(task, return_exceptions=True)++class SSEDecoder:"""Incremental byte framing, including CRLF and frames split inside UTF-8."""diff --git a/openviking_gateway/proxy.py b/openviking_gateway/proxy.pyindex 891365f9a..dd64e974f 100644--- a/openviking_gateway/proxy.py+++ b/openviking_gateway/proxy.py@@ -8,17 +8,19 @@ import loggingimport timeimport uuidfrom dataclasses import replace+from typing import NamedTuplefrom urllib.parse import quote, unquote_plusimport aiohttpimport orjsonfrom fastapi import HTTPExceptionfrom fastapi.responses import Response, StreamingResponse+from pydantic import ValidationErrorfrom starlette.background import BackgroundTaskfrom .capture import CapturePipeline-from .models import KEY_PLACEHOLDER, Policy-from .protocols import SSEDecoder, parse_body+from .models import KEY_PLACEHOLDER, Policy, validation_detail+from .protocols import HEARTBEAT_SECONDS, SSEDecoder, heartbeat, parse_bodyfrom .storage import digestfrom .tool_executor import ToolExecutorfrom .tool_loop import HiddenToolLoop, ToolLoopError@@ -106,6 +108,35 @@ def upstream_key(upstream, incoming):return key+def context_error(detail, status=400, reason="context_override_invalid"):+ """An ``X-OpenViking-Context`` error, in the management API's ``{reason, detail}`` shape."""+ return HTTPException(status, {"reason": reason, "detail": detail})+++def context_override(policy, header):+ """The stored policy with the fields of an ``X-OpenViking-Context`` header applied."""+ if not policy.get("client_overrides", True):+ raise context_error(+ "This key's context profile does not accept X-OpenViking-Context.",+ 403,+ "context_override_not_allowed",+ )+ try:+ override = json.loads(header)+ except (ValueError, RecursionError):+ raise context_error("X-OpenViking-Context is not valid JSON")+ if not isinstance(override, dict):+ raise context_error("X-OpenViking-Context must be a JSON object")+ # The profile's name and its switch are not per-conversation settings.+ if blocked := override.keys() & {"name", "client_overrides"}:+ raise context_error("X-OpenViking-Context cannot set " + ", ".join(sorted(blocked)))+ try:+ merged = Policy.model_validate({**policy, **override}).model_dump()+ except ValidationError as error:+ raise context_error(validation_detail(error))+ return {**policy, **merged}, sorted(override)++def fill_key(url, key):return url.replace(KEY_PLACEHOLDER, quote(key, safe=""))@@ -153,6 +184,38 @@ def matches(upstream, protocol, model):)+class Binding(NamedTuple):+ policy: dict | None+ # Disabled ones included; callers skip them.+ upstreams: list[dict]+ # Empty allows every model.+ models: list[str]+++async def default_policy(management, config, account):+ """Use the account's default profile, or the deployment's when none is stored."""+ policy = await management.get(account, "policies", "default")+ return policy or config.default_profile.model_dump()+++async def resolve_binding(management, config, credential):+ """The context profile, upstreams and models a credential's requests use."""+ account = credential["account"]+ upstreams = await management.list(account, "upstreams")+ if credential.get("source") == "openviking":+ # An OpenViking key stores no binding: it uses the account's defaults.+ return Binding(+ await default_policy(management, config, account),+ upstreams or [{**u.model_dump(), "id": i} for i, u in config.default_upstreams.items()],+ [],+ )+ return Binding(+ await management.get(account, "policies", credential["policy_id"]),+ [u for u in upstreams if u["id"] in credential["upstream_ids"]],+ credential["models"],+ )++class ProxyRequest:def __init__(self, app, request, path, credential):self.app, self.request, self.credential = app, request, credential@@ -223,20 +286,28 @@ class ProxyRequest:except (ValueError, RecursionError):passself.model = routing.get("model", "") if isinstance(routing, dict) else ""+ binding = await resolve_binding(self.management, self.config, self.credential)# Calls on a stored response are pinned to its upstream and carry no model.- if self.credential["models"] and self.raw and not self.path.startswith("/v1/responses/"):+ if binding.models and self.raw and not self.path.startswith("/v1/responses/"):if self.request.headers.get("content-encoding", "identity").lower() != "identity":raise HTTPException(415, "Compressed request bodies are not supported")if not self.model or not isinstance(self.model, str):raise HTTPException(400, "Request model is missing")- if self.credential["models"] and self.model and self.model not in self.credential["models"]:+ if binding.models and self.model and self.model not in binding.models:raise HTTPException(403, "Model is not allowed by this key")self.metrics["model"] = self.model- self.upstreams = [- u- for u in await self.management.list(self.credential["account"], "upstreams")- if u["id"] in self.credential["upstream_ids"]- ]+ self.policy = binding.policy+ # The header is checked on every request that carries it, enhanced or not.+ header = self.request.headers.get("x-openviking-context")+ if header is not None and self.policy:+ self.policy, self.metrics["context_override"] = context_override(self.policy, header)+ self.upstreams = binding.upstreams+ # A host in front of the gateway may pick the upstream, but only an allowed one.+ url = self.request.headers.get("x-openviking-upstream-url")+ if url is not None:+ self.upstreams = [u for u in self.upstreams if u["base_url"] == url.rstrip("/")]+ if not self.upstreams:+ raise HTTPException(403, "Upstream URL is not allowed")# A stored response is pinned below; an exact responses endpoint may hold it.stored_response = self.path.startswith("/v1/responses/")candidates = sorted(@@ -263,6 +334,10 @@ class ProxyRequest:raise HTTPException(403, "Response upstream is no longer allowed")# Pinned upstream selection in the kernel is restricted to allowed models.self.candidates = candidates+ # A missing client key fails before the request freezes a session or calls OpenViking.+ # A conversation may stay pinned to a candidate with its own key; url() checks that one.+ if all(u.get("auth_mode") == "passthrough" for u in candidates):+ upstream_key(self.upstream, self.request.headers)async def prepare(self):if (@@ -271,10 +346,7 @@ class ProxyRequest:and tool_protocol(self.protocol).enhanced_supported(self.body)and not self.request.headers.get("content-encoding")):- policy = await self.management.get(- self.credential["account"], "policies", self.credential["policy_id"]- )- if not policy:+ if not self.policy:raise HTTPException(403, "Context policy is unavailable")self.body, self.prepared, metrics = await self.app.state.kernel.enhance(self.body,@@ -282,7 +354,7 @@ class ProxyRequest:dict(self.request.headers),self.credential,self.upstream,- policy,+ self.policy,self.path.endswith("count_tokens"),self.candidates,self.summarize,@@ -426,8 +498,12 @@ class ProxyRequest:async def stream():finished = False+ chunks = heartbeat(loop.run(response, send), HEARTBEAT_SECONDS)try:- async for chunk in loop.run(response, send):+ async for chunk in chunks:+ if chunk is None:+ yield b": keep-alive\n\n"+ continueawait self.relay()yield chunkfinished = True@@ -435,6 +511,7 @@ class ProxyRequest:self.metrics["degradation"] = "hidden_tool_loop_failed"yield loop.error(str(error))finally:+ await chunks.aclose()if not finished:capture.complete = Falseself.metrics.update(prepared.metrics)@@ -473,13 +550,19 @@ class ProxyRequest:response, capture = self.response, self.captureheaders = filtered_headers(response.headers)if "text/event-stream" in response.headers.get("content-type", ""):+ headers = {k: v for k, v in headers.items() if k.lower() != "content-length"}async def stream():decoder = SSEDecoder()observe = not response.headers.get("content-encoding")finished = False+ chunks = heartbeat(response.content.iter_any(), HEARTBEAT_SECONDS)try:- async for chunk in response.content.iter_any():+ async for chunk in chunks:+ if chunk is None:+ if observe and not decoder.buffer:+ yield b": keep-alive\n\n"+ continueif observe:try:# A chunk inside one event completes none: no reply to reread.@@ -493,6 +576,7 @@ class ProxyRequest:yield chunkfinished = Truefinally:+ await chunks.aclose()response.close()if not finished:capture.complete = Falsediff --git a/openviking_gateway/redis_store.py b/openviking_gateway/redis_store.pynew file mode 100644index 000000000..46a127f47--- /dev/null+++ b/openviking_gateway/redis_store.py@@ -0,0 +1,528 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Redis adapters: every write that must be atomic is one Lua script on one slot.++Keys below follow ``<key_prefix>v1:``; ``h`` is a 32-hex digest, ``{...}`` a Cluster hash+tag, TTLs are milliseconds, and the last column names the writing script or method.++m:{a<h(account)>}:o:<kind>:<h(id)> hash v, rev, u=h(user_id); object ttl obj_save, obj_delete+m:{a<h(account)>}:ix:<kind> zset id -> expiry ms, or +inf obj_save, obj_delete+m:{c<h(id)>} string a key's account; the key's ttl save, delete+m:{a<h(account)>}:log list ms NUL h(user_id) NUL value, log_push,+ newest first; log_ttl log_delete_user+kd:{<scope>}, kd:{cap}:<scope> string scope deletion tombstone expire, allow_scope+k:{<scope>}:rp:<h(session)> hash <kind>:<anchor> -> value; ttl kernel_replay_put,+ kernel_keep+k:{<scope>}:r:<anchor> set sessions with reply:<anchor>; kernel_replay_put,+ ttl kernel_replies_prune+k:{<scope>}:st:<h(key)> hash v, ver; ttl kernel_state_swap,+ kernel_keep+k:{cap}:<scope>:<h(session)> hash v, ver, ready (epoch s), lease kernel_capture_*+ (epoch ms), owner; ttl+k:{cap}:ready zset scope NUL session -> due ms kernel_capture_*++Capture keys share the ``{cap}`` slot so a claim can read the ready queue in one script; the+tombstone is mirrored there because a script may only touch one slot. For the same reason+the credential pointer is a plain SET after obj_save rather than part of it.+"""++import asyncio+import time+import uuid+from collections import OrderedDict, defaultdict+from pathlib import Path++import orjson+from redis import VERSION+from redis.asyncio.cluster import RedisCluster+from redis.asyncio.retry import Retry+from redis.backoff import NoBackoff+from redis.crc import key_slot+from redis.exceptions import ResponseError++from openviking.server.account_stores.redis_client import create_redis_client++from .capture_store import Document, LeaseLost+from .records import RecordKind as K+from .replay_store import INHERITED+from .storage import AsyncCodec, digest++LOG_LIMIT = 10000+INDEXED_KINDS = {"keys", "upstreams", "policies", "users"}+++def h(value):+ return digest(value)[:32]+++def connect(settings):+ """Open the gateway's client handle from ``storage.redis`` settings."""+ handle = create_redis_client(+ settings,+ decode_responses=False,+ # None enables Cluster's default retries, including writes with unknown outcomes.+ retry=Retry(NoBackoff(), 0),+ # redis-py 5 Cluster retries by its own counter rather than ``retry``.+ **(+ {"cluster_error_retry_attempts": 0}+ if VERSION < (6,) and settings["mode"] == "cluster"+ else {}+ ),+ )+ # redis-py pools raise once ``pool_size`` connections are busy; queue commands instead.+ gate, execute = asyncio.Semaphore(settings["pool_size"]), handle.client.execute_command++ async def execute_command(*args, **kwargs):+ async with gate:+ return await execute(*args, **kwargs)++ handle.client.execute_command = execute_command+ return handle+++class RedisBackend:+ def __init__(self, client, key_prefix, codec: AsyncCodec):+ self.client, self.prefix, self.codec = client, key_prefix + "v1:", codec+ self.scripts = {}++ def script(self, name):+ if name not in self.scripts:+ self.scripts[name] = self.client.register_script(+ (Path(__file__).parent / "lua" / f"{name}.lua").read_text()+ )+ return self.scripts[name]++ async def scan(self, pattern):+ if not isinstance(self.client, RedisCluster):+ async for key in self.client.scan_iter(match=pattern, count=500):+ yield key+ return+ await self.client.initialize()+ nodes = (+ [self.client.get_node_from_key(pattern)]+ if "{" in pattern+ else self.client.get_primaries()+ )+ for node in nodes:+ cursor = 0+ while True:+ cursors, keys = await self.client.scan(+ cursor, match=pattern, count=500, target_nodes=node+ )+ for key in keys:+ yield key+ cursor = cursors[node.name]+ if not cursor:+ break++ async def unlink(self, keys):+ slots = defaultdict(list)+ for key in keys:+ slots[key_slot(key.encode() if isinstance(key, str) else key)].append(key)+ for batch in slots.values():+ for start in range(0, len(batch), 500):+ # The Cluster convenience method fans out; explicit commands stay in one slot.+ await self.client.execute_command("UNLINK", *batch[start : start + 500])++ async def delete_matching(self, pattern):+ batch = []+ async for key in self.scan(pattern):+ batch.append(key)+ if len(batch) == 500:+ await self.unlink(batch)+ batch.clear()+ await self.unlink(batch)+++class RedisManagementStore:+ def __init__(self, backend: RedisBackend, log_ttl):+ self.backend, self.client, self.codec = backend, backend.client, backend.codec+ self.log_ttl = log_ttl++ def account_prefix(self, account):+ return self.backend.prefix + "m:{a" + h(account) + "}:"++ def object_key(self, account, kind, identifier):+ return self.account_prefix(account) + f"o:{kind}:{h(identifier)}"++ def credential_key(self, identifier):+ return self.backend.prefix + "m:{c" + h(identifier) + "}"++ def object_keys(self, account, kind, identifier):+ keys = [self.object_key(account, kind, identifier)]+ if kind in INDEXED_KINDS:+ keys.append(self.account_prefix(account) + f"ix:{kind}")+ return keys++ async def initialize(self):+ await self.client.ping()++ async def entry(self, identifier, value, revision):+ value = await self.codec.decode(value)+ if value.get("expires_at", float("inf")) <= time.time():+ return None+ return {**value, "id": identifier, "revision": int(revision)}++ async def get(self, account, kind, identifier):+ value, revision = await self.client.hmget(+ self.object_key(account, kind, identifier), "v", "rev"+ )+ return None if value is None else await self.entry(identifier, value, revision)++ async def list(self, account, kind, user_id=None):+ index = self.account_prefix(account) + f"ix:{kind}"+ identifiers = sorted(i.decode() for i in await self.client.zrange(index, 0, -1))+ if not identifiers:+ return []+ rows = await self.backend.script("hash_read")(+ keys=[self.object_key(account, kind, i) for i in identifiers], args=["v", "rev"]+ )+ values = [await self.entry(identifiers[i - 1], value, rev) for i, value, rev in rows]+ return [+ value+ for value in values+ if value is not None and (user_id is None or value.get("user_id") == user_id)+ ]++ async def save(self, account, kind, identifier, value, ttl=None):+ if ttl is not None:+ value = {**value, "expires_at": time.time() + ttl}+ revision, remaining = await self.backend.script("obj_save")(+ keys=self.object_keys(account, kind, identifier),+ args=[+ identifier,+ await self.codec.encode(value),+ h(value.get("user_id") or ""),+ "" if ttl is None else int(ttl * 1000),+ ],+ )+ if kind == "keys":+ # PTTL is -1 without an expiry and may reach 0 on an update that sets none.+ await self.client.set(+ self.credential_key(identifier),+ account,+ **({"px": max(1, remaining)} if remaining >= 0 else {}),+ )+ return {**value, "id": identifier, "revision": revision}++ async def delete(self, account, kind, identifier):+ await self.backend.script("obj_delete")(+ keys=self.object_keys(account, kind, identifier), args=[identifier]+ )+ if kind == "keys":+ await self.client.execute_command("DEL", self.credential_key(identifier))++ async def authenticate(self, key):+ return await self.credential(digest(key))++ async def credential(self, identifier):+ account = await self.client.get(self.credential_key(identifier))+ if account is None:+ return None+ value = await self.get(account.decode(), "keys", identifier)+ if value is None:+ return None+ value.pop("revision")+ return {**value, "account": account.decode()}++ async def log(self, account, value, user_id=None):+ key = self.account_prefix(account) + "log"+ prefix = f"{int(time.time() * 1000)}\0{h(user_id) if user_id is not None else ''}\0"+ await self.backend.script("log_push")(+ keys=[key],+ args=[+ prefix.encode() + await self.codec.encode(value),+ LOG_LIMIT,+ int(self.log_ttl * 1000),+ ],+ )++ async def logs(self, account, limit=200, user_id=None):+ key, values = self.account_prefix(account) + "log", []+ cutoff = (time.time() - self.log_ttl) * 1000+ user = None if user_id is None else h(user_id).encode()+ page = min(1000, limit) if user is None else 1000+ for start in range(0, LOG_LIMIT, page):+ rows = await self.client.lrange(key, start, start + page - 1)+ for row in rows:+ timestamp, owner, value = row.split(b"\0", 2)+ # Rows are newest first: the rest are older still.+ if int(timestamp) < cutoff:+ return values+ if user is None or owner == user:+ values.append({"time": int(timestamp) / 1000, **await self.codec.decode(value)})+ if len(values) >= limit:+ return values+ if len(rows) < page:+ break+ return values++ async def delete_user(self, account, user_id):+ for kind in ("keys", "users"):+ index = self.account_prefix(account) + f"ix:{kind}"+ async for identifier, _ in self.client.zscan_iter(index, count=500):+ identifier = identifier.decode()+ user = await self.client.hget(self.object_key(account, kind, identifier), "u")+ if user == h(user_id).encode():+ await self.delete(account, kind, identifier)+ key = self.account_prefix(account) + "log"+ await self.backend.script("log_delete_user")(+ keys=[key, key + ":rebuild"], args=[h(user_id)]+ )++ async def delete_account(self, account):+ identifiers = await self.client.zrange(self.account_prefix(account) + "ix:keys", 0, -1)+ await self.backend.delete_matching(self.account_prefix(account) + "*")+ await self.backend.unlink(+ [self.credential_key(identifier.decode()) for identifier in identifiers]+ )++ async def expire_logs(self, before):+ pass+++class RedisKernelStore:+ def __init__(self, backend, ttl):+ self.backend, self.client, self.codec = backend, backend.client, backend.codec+ self.prefix, self.ttl = backend.prefix, int(ttl * 1000)+ self.replay, self.state, self.capture = (+ RedisReplayStore(self),+ RedisStateStore(self),+ RedisCaptureQueue(self),+ )+ self.touched = OrderedDict()++ async def initialize(self):+ await self.client.ping()++ def tombstone(self, scope, capture=False):+ return f"{self.prefix}kd:{{cap}}:{scope}" if capture else f"{self.prefix}kd:{{{scope}}}"++ def replay_key(self, scope, session):+ return f"{self.prefix}k:{{{scope}}}:rp:{h(session)}"++ def state_key(self, scope, key):+ return f"{self.prefix}k:{{{scope}}}:st:{h(key)}"++ def capture_key(self, scope, session):+ return f"{self.prefix}k:{{cap}}:{scope}:{h(session)}"++ async def script(self, name, keys, args):+ try:+ return await self.backend.script(name)(keys=keys, args=args)+ except ResponseError as error:+ if "OVGW_DELETED" in str(error):+ raise RuntimeError("Gateway user data has been deleted") from error+ if "OVGW_LEASE_LOST" in str(error):+ raise LeaseLost from error+ raise++ async def touch(self, key):+ now = time.monotonic()+ if now - self.touched.get(key, float("-inf")) < 60:+ return+ self.touched[key] = now+ self.touched.move_to_end(key)+ if len(self.touched) > 2048:+ self.touched.popitem(last=False)+ await self.client.pexpire(key, self.ttl)++ async def load(self, scope, session, anchors, ancestors=()):+ replay, document = await asyncio.gather(+ self.replay.load(scope, session, anchors, ancestors, state=True),+ self.capture.get(scope, session),+ )+ return replay[0], replay[1], document++ async def keep(self, scope, sessions, keys):+ sessions = list(sessions)+ await self.script(+ "kernel_keep",+ [+ self.tombstone(scope),+ *[self.replay_key(scope, sid) for sid in sessions],+ *[self.state_key(scope, key) for key in keys],+ ],+ [self.ttl],+ )+ await asyncio.gather(*(self.touch(self.capture_key(scope, sid)) for sid in sessions))++ async def expire(self, before, scope=None):+ if scope is None:+ return+ await self.client.set(self.tombstone(scope), 1)+ await self.client.set(self.tombstone(scope, capture=True), 1)+ for pattern in (f"{self.prefix}k:{{{scope}}}:*", f"{self.prefix}k:{{cap}}:{scope}:*"):+ await self.backend.delete_matching(pattern)++ async def allow_scope(self, scope):+ await self.client.execute_command("DEL", self.tombstone(scope))+ await self.client.execute_command("DEL", self.tombstone(scope, capture=True))+++class RedisReplayStore:+ def __init__(self, store):+ self.store = store++ def index(self, scope, anchor):+ return f"{self.store.prefix}k:{{{scope}}}:r:{anchor}"++ async def load(self, scope, session, anchors, ancestors=(), state=False):+ owners = [*sorted(set(ancestors) - {session}), session]+ keys = [self.store.replay_key(scope, sid) for sid in owners]+ if state:+ keys.append(self.store.state_key(scope, session))+ rows, observation = await self.store.script(+ "kernel_load",+ keys,+ [len(owners), orjson.dumps(list(anchors)), orjson.dumps(sorted(INHERITED)), int(state)],+ )+ values = {}+ for field, value in rows:+ kind, anchor = field.decode().split(":", 1)+ values[kind, anchor] = await self.store.codec.decode(value)+ states = {}+ if observation:+ states[session] = Document(+ await self.store.codec.decode(observation[0]), int(observation[1])+ )+ return values, states++ async def read(self, scope, session, anchors, ancestors=()):+ return (await self.load(scope, session, anchors, ancestors))[0]++ async def replies(self, scope, anchors):+ # A script rather than a pipeline: with cluster_error_retry_attempts=0, redis-py 5's+ # ClusterPipeline.execute makes no attempts at all.+ indexes = [self.index(scope, anchor) for anchor in anchors]+ rows = await self.store.script("kernel_replies_read", indexes, [])+ indexed = [+ (anchor, index, sorted(members))+ for anchor, index, members in zip(anchors, indexes, rows, strict=True)+ if members+ ]+ if not indexed:+ return {}+ keys = [index for _, index, _ in indexed]+ args = [self.store.ttl, len(indexed)]+ for anchor, _, members in indexed:+ keys += [self.store.replay_key(scope, sid.decode()) for sid in members]+ args += [anchor, len(members), *members]+ live = await self.store.script("kernel_replies_prune", keys, args)+ return {+ anchor: {sid.decode() for sid in sids}+ for (anchor, _, _), sids in zip(indexed, live, strict=True)+ if sids+ }++ async def put(self, scope, session, kind, anchor, value):+ kind = K(kind)+ keys = [self.store.tombstone(scope), self.store.replay_key(scope, session)]+ if kind == K.REPLY:+ keys.append(self.index(scope, anchor))+ result = await self.store.script(+ "kernel_replay_put",+ keys,+ [+ f"{kind.value}:{anchor}",+ await self.store.codec.encode(value),+ self.store.ttl,+ session,+ ],+ )+ await self.store.touch(self.store.capture_key(scope, session))+ return await self.store.codec.decode(result)+++class RedisStateStore:+ def __init__(self, store):+ self.store = store++ async def read(self, scope, keys):+ keys = list(keys)+ if not keys:+ return {}+ rows = await self.store.script(+ "hash_read", [self.store.state_key(scope, key) for key in keys], ["v", "ver"]+ )+ return {+ keys[index - 1]: Document(await self.store.codec.decode(value), int(version))+ for index, value, version in rows+ }++ async def swap(self, scope, key, previous, value):+ return bool(+ await self.store.script(+ "kernel_state_swap",+ [self.store.tombstone(scope), self.store.state_key(scope, key)],+ [previous.version, await self.store.codec.encode(value), self.store.ttl],+ )+ )+++class RedisCaptureQueue:+ def __init__(self, store):+ self.store = store+ self.ready = f"{store.prefix}k:{{cap}}:ready"++ def keys(self, scope, session):+ return [+ self.store.tombstone(scope, capture=True),+ self.store.capture_key(scope, session),+ self.ready,+ ]++ async def get(self, scope, session):+ value, version = await self.store.client.hmget(+ self.store.capture_key(scope, session), "v", "ver"+ )+ return (+ Document(await self.store.codec.decode(value), int(version))+ if value is not None+ else Document()+ )++ async def swap(self, scope, session, previous, value, ready, owner=None):+ result = await self.store.script(+ "kernel_capture_swap",+ self.keys(scope, session),+ [+ previous.version,+ await self.store.codec.encode(value),+ "" if ready is None else repr(ready),+ owner or "",+ self.store.ttl,+ scope + "\0" + session,+ ],+ )+ if result:+ await self.store.touch(self.store.replay_key(scope, session))+ return bool(result)++ async def claim(self, lease_seconds=120):+ candidates = await self.store.client.zrangebyscore(+ self.ready, "-inf", time.time() * 1000, start=0, num=8+ )+ for member in candidates:+ scope, session = member.decode().split("\0", 1)+ owner = uuid.uuid4().hex+ result = await self.store.script(+ "kernel_capture_claim",+ self.keys(scope, session),+ [owner, lease_seconds * 1000, member],+ )+ if result:+ return {+ "scope": scope,+ "session": session,+ "owner": owner,+ "document": Document(await self.store.codec.decode(result[0]), int(result[1])),+ }+ return None++ async def release(self, item):+ await self.store.script(+ "kernel_capture_release",+ self.keys(item["scope"], item["session"]),+ [item["owner"], item["scope"] + "\0" + item["session"]],+ )diff --git a/openviking_gateway/standalone.py b/openviking_gateway/standalone.pyindex d1b3f0964..83e33df1c 100644--- a/openviking_gateway/standalone.py+++ b/openviking_gateway/standalone.py@@ -29,13 +29,25 @@ WARNINGS = {async def check_openviking(config: StandaloneGatewayConfig) -> dict:- """Probe OV once before serving; refuse trusted auth and unconfirmed public binds."""+ """Wait for transient OV failures before serving a confirmed public bind."""async with aiohttp.ClientSession(trust_env=False) as http:viking = VikingClient(http, config.openviking_url, config.min_server_version)- try:- health = await viking.health(require_identity=False)- except VikingError as error:- health = {"status": "degraded", "reason": error.reason}+ delay = 1+ while True:+ try:+ health = await viking.health(require_identity=False)+ except VikingError as error:+ if config.host not in LOOPBACK_HOSTS and error.status >= 500:+ logger.warning(+ "Waiting for OpenViking before binding publicly: %s; retrying in %ss",+ error.reason,+ delay,+ )+ await asyncio.sleep(delay)+ delay = min(delay * 2, 30)+ continue+ health = {"status": "degraded", "reason": error.reason}+ breakif health.get("reason") == "trusted_mode_unsupported":raise ValueError("OpenViking Gateway does not support trusted authentication")if config.host not in LOOPBACK_HOSTS and health.get("auth_mode") != "api_key":@@ -112,46 +124,48 @@ def create_standalone_app(config: StandaloneGatewayConfig, studio_dir=None):)return result- @app.get("/api/v1/admin/accounts")- @app.get("/api/v1/admin/accounts/{account_id}/users")- async def administration(request: Request, account_id: str | None = None):- credential = request_credential(request)- # Rejects trusted mode, where OV would authorize identity headers this route drops.- await state.viking.identify(credential)- path = "/api/v1/admin/accounts"- if account_id is not None:- path += "/" + quote(account_id, safe="") + "/users"- params = dict(request.query_params)- if account_id is not None:- params["include_credentials"] = "false"- if params:- path += "?" + urlencode(params)- result = await state.viking.request("GET", path, credential)- return {"status": "ok", "result": result}-- directory = studio_dir or studio_directory()- root = Path(directory).resolve() if directory else None-- @app.get("/")- async def home():- return RedirectResponse("/studio/")-- @app.get("/studio")- async def studio_redirect():- return RedirectResponse("/studio/")-- @app.get("/studio/{path:path}")- async def studio(path: str):- if root is None or not (root / "index.html").is_file():- raise HTTPException(503, "OpenViking Studio bundle is unavailable")- candidate = (root / path).resolve()- if not candidate.is_relative_to(root):- raise HTTPException(404)- if candidate.is_file():- return FileResponse(candidate)- if path.startswith("assets/"):- raise HTTPException(404)- return FileResponse(root / "index.html")+ if config.management_api:++ @app.get("/api/v1/admin/accounts")+ @app.get("/api/v1/admin/accounts/{account_id}/users")+ async def administration(request: Request, account_id: str | None = None):+ credential = request_credential(request)+ # Rejects trusted mode, where OV would authorize identity headers this route drops.+ await state.viking.identify(credential)+ path = "/api/v1/admin/accounts"+ if account_id is not None:+ path += "/" + quote(account_id, safe="") + "/users"+ params = dict(request.query_params)+ if account_id is not None:+ params["include_credentials"] = "false"+ if params:+ path += "?" + urlencode(params)+ result = await state.viking.request("GET", path, credential)+ return {"status": "ok", "result": result}++ directory = studio_dir or studio_directory()+ root = Path(directory).resolve() if directory else None++ @app.get("/")+ async def home():+ return RedirectResponse("/studio/")++ @app.get("/studio")+ async def studio_redirect():+ return RedirectResponse("/studio/")++ @app.get("/studio/{path:path}")+ async def studio(path: str):+ if root is None or not (root / "index.html").is_file():+ raise HTTPException(503, "OpenViking Studio bundle is unavailable")+ candidate = (root / path).resolve()+ if not candidate.is_relative_to(root):+ raise HTTPException(404)+ if candidate.is_file():+ return FileResponse(candidate)+ if path.startswith("assets/"):+ raise HTTPException(404)+ return FileResponse(root / "index.html")app.mount(MOUNT_PATH, gateway)return appdiff --git a/openviking_gateway/storage.py b/openviking_gateway/storage.pyindex 9486b1890..cb6822658 100644--- a/openviking_gateway/storage.py+++ b/openviking_gateway/storage.py@@ -1,6 +1,6 @@# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.# SPDX-License-Identifier: AGPL-3.0-"""SQLite adapters with optionally encrypted values. Writes have a dedicated executor."""+"""Storage ports and the SQLite adapters, with optionally encrypted values."""import asyncioimport hashlib@@ -44,8 +44,122 @@ class KernelStore(Protocol):capture: CaptureQueuestate: StateStore+ async def initialize(self) -> None: ...async def load(self, scope, session, anchors, ancestors=()) -> tuple: ...async def keep(self, scope, sessions, keys) -> None: ...+ async def expire(self, before, scope=None) -> None: ...+ async def allow_scope(self, scope) -> None: ...+++class ManagementStore(Protocol):+ """Management objects, credentials, and request logs."""++ async def initialize(self) -> None: ...+ async def list(self, account, kind, user_id=None) -> list[dict]: ...+ async def get(self, account, kind, identifier) -> dict | None: ...+ async def save(self, account, kind, identifier, value, ttl=None) -> dict: ...+ async def delete(self, account, kind, identifier) -> None: ...+ async def authenticate(self, key) -> dict | None: ...+ async def credential(self, identifier) -> dict | None: ...+ async def log(self, account, value, user_id=None) -> None: ...+ async def logs(self, account, limit=200, user_id=None) -> "list[dict]": ...+ async def delete_user(self, account, user_id) -> None: ...+ async def delete_account(self, account) -> None: ...+ async def expire_logs(self, before) -> None: ...+++class CachedManagement:+ """Share short-lived configuration and credential reads within one process."""++ def __init__(self, port: ManagementStore, log=None):+ self.port = port+ self.log = port.log if log is None else log+ self.cache = TTLCache(ttl=2, capacity=2048)++ async def initialize(self):+ await self.port.initialize()++ async def list(self, account, kind, user_id=None):+ if kind not in {"keys", "upstreams"}:+ return await self.port.list(account, kind, user_id)+ values = await self.cache.get(+ ("list", account, kind), lambda: self.port.list(account, kind)+ )+ return (+ [value for value in values if value.get("user_id") == user_id]+ if user_id is not None+ else values+ )++ async def get(self, account, kind, identifier):+ # Policies become immutable session snapshots: never freeze a TTL-stale value.+ if kind == "keys":+ return await self.cache.get(+ ("get", account, kind, identifier),+ lambda: self.port.get(account, kind, identifier),+ )+ return await self.port.get(account, kind, identifier)++ async def save(self, account, kind, identifier, value, ttl=None):+ saved = await self.port.save(account, kind, identifier, value, ttl)+ if kind in {"keys", "upstreams"}:+ self.cache.clear()+ return saved++ async def delete(self, account, kind, identifier):+ await self.port.delete(account, kind, identifier)+ if kind in {"keys", "upstreams"}:+ self.cache.clear()++ async def authenticate(self, key):+ return await self.credential(digest(key))++ async def credential(self, identifier):+ return await self.cache.get(("auth", identifier), lambda: self.port.credential(identifier))++ async def logs(self, account, limit=200, user_id=None):+ return await self.port.logs(account, limit, user_id)++ async def delete_user(self, account, user_id):+ await self.port.delete_user(account, user_id)+ self.cache.clear()++ async def delete_account(self, account):+ await self.port.delete_account(account)+ self.cache.clear()++ async def expire_logs(self, before):+ await self.port.expire_logs(before)+++def encrypted(value: bytes, encryptor) -> bool:+ """Whether ``value`` is ciphertext; raises if it is but no encryptor is configured."""+ # Values written before encryption was enabled stay readable as plaintext.+ if not value.startswith(MAGIC):+ return False+ if encryptor is None:+ raise RuntimeError(+ "Gateway data is encrypted; configure the encryption settings it was written with"+ )+ return True+++class AsyncCodec:+ """Encode Redis values with the same encryption as the SQLite adapters."""++ def __init__(self, encryptor=None):+ self.encryptor = encryptor++ async def encode(self, value: Any) -> bytes:+ data = orjson.dumps(value)+ if self.encryptor is not None:+ data = await self.encryptor.encrypt(ENCRYPTION_ACCOUNT, data)+ return data++ async def decode(self, value: bytes) -> Any:+ if encrypted(value, self.encryptor):+ value = await self.encryptor.decrypt(ENCRYPTION_ACCOUNT, value)+ return orjson.loads(value)class Database:@@ -123,13 +237,7 @@ class Database:return self.crypt(self.encryptor.encrypt(ENCRYPTION_ACCOUNT, data))def decode(self, value: bytes) -> Any:- # Values written before encryption was enabled stay readable as plaintext.- if value.startswith(MAGIC):- if self.encryptor is None:- raise RuntimeError(- "Gateway data is encrypted; configure the encryption settings it was "- "written with"- )+ if encrypted(value, self.encryptor):value = self.crypt(self.encryptor.decrypt(ENCRYPTION_ACCOUNT, value))return orjson.loads(value)@@ -319,11 +427,7 @@ class SQLiteKernelStore(Database):await self.run(allow, write=True)-class ManagementStore(Database):- def __init__(self, path, encryptor=None):- super().__init__(path, encryptor)- self.cache = TTLCache(ttl=2, capacity=2048)-+class SQLiteManagementStore(Database):async def initialize(self):def initialize():with self.connect() as c:@@ -391,10 +495,7 @@ class ManagementStore(Database):)]- if kind in {"keys", "upstreams"}:- values = await self.cache.get(("list", account, kind), lambda: self.run(read))- else:- values = await self.run(read)+ values = await self.run(read)return ([value for value in values if value.get("user_id") == user_id]if user_id is not None@@ -417,9 +518,6 @@ class ManagementStore(Database):return Nonereturn {**value, "id": identifier, "revision": row["revision"]}- # Policies become immutable session snapshots: never freeze a TTL-stale value.- if kind == "keys":- return await self.cache.get(("get", account, kind, identifier), lambda: self.run(read))return await self.run(read)async def save(self, account, kind, identifier, value, ttl=None):@@ -442,8 +540,6 @@ class ManagementStore(Database):c.commit()await self.run(save, write=True)- if kind in {"keys", "upstreams"}:- self.cache.clear()return await self.get(account, kind, identifier)async def delete(self, account, kind, identifier):@@ -455,24 +551,29 @@ class ManagementStore(Database):)await self.run(delete, write=True)- if kind in {"keys", "upstreams"}:- self.cache.clear()async def authenticate(self, key):- identifier = digest(key)+ return await self.credential(digest(key))++ async def credential(self, identifier):+ """The key record with this id in any account."""def read():with self.connect() as c:row = c.execute(- "SELECT account,value FROM objects WHERE kind='keys' AND id=?", (identifier,)+ "SELECT o.account,o.value,e.expires FROM objects o LEFT JOIN object_expiry e "+ "ON (o.account,o.kind,o.id)=(e.account,e.kind,e.id) "+ "WHERE o.kind='keys' AND o.id=?",+ (identifier,),).fetchone()- return (- {**self.decode(row["value"]), "account": row["account"], "id": identifier}- if row- else None- )+ if not row or (row["expires"] is not None and row["expires"] <= time.time()):+ return None+ value = self.decode(row["value"])+ if value.get("expires_at", float("inf")) <= time.time():+ return None+ return {**value, "account": row["account"], "id": identifier}- return await self.cache.get(("auth", identifier), lambda: self.run(read))+ return await self.run(read)async def log(self, account, value, user_id=None):def log():@@ -523,7 +624,6 @@ class ManagementStore(Database):c.commit()await self.run(delete, write=True)- self.cache.clear()async def expire_logs(self, before):def expire():@@ -550,15 +650,15 @@ class ManagementStore(Database):c.commit()await self.run(delete, write=True)- self.cache.clear()async def delete_user_data(management, store, account, user_id):"""Revoke keys and erase gateway state; OpenViking memory is unaffected."""- # Keys go first, so a response finishing meanwhile no longer finds one to record state for.- await management.delete_user(account, user_id)+ # Scopes are blocked first, so state a response records meanwhile is refused. Keys go+ # after: an OpenViking key's record, recreated by its next request, lifts the block again.for protocol in ("chat", "responses", "anthropic"):await store.expire(0, digest(account + "\0" + user_id + "\0" + protocol))+ await management.delete_user(account, user_id)async def delete_account_data(management, store, account):diff --git a/openviking_gateway/tool_executor.py b/openviking_gateway/tool_executor.pyindex 59823043d..d6627e9f1 100644--- a/openviking_gateway/tool_executor.py+++ b/openviking_gateway/tool_executor.py@@ -32,6 +32,7 @@ DOWNLOAD_URL = re.compile(r'https?://[^\s<>"\x27`]+/api/v1/content/download\?tokAUTO_DETECTED_NOTE = re.compile(r"\n*Note for the user: this (?:upload|download) URL was auto-detected[^\n]*")+UNKNOWN_OUTCOME = "Tool timed out or a previous attempt has an unknown outcome; inspect state before retrying writes"def error_result(text):@@ -204,12 +205,16 @@ class ToolExecutor:Document(claim, 1) if won else await get_state(self.store.state, scope, receipt_key))claim = receipt.value+ if not claim:+ return {**result, "content": UNKNOWN_OUTCOME, "failed": True}timeout = self.policy.get("tool_timeout_seconds", 30)try:async with async_timeout.timeout(timeout):if claim["owner"] != owner:while True:saved = await get_state(self.store.state, scope, receipt_key)+ if not saved.value:+ raise asyncio.TimeoutErrorif "content" in saved.value:return {**result,@@ -227,7 +232,7 @@ class ToolExecutor:)return {**result, "content": content, "failed": failed}except asyncio.TimeoutError:- content = "Tool timed out or a previous attempt has an unknown outcome; inspect state before retrying writes"+ content = UNKNOWN_OUTCOMEexcept (ValueError, TypeError, binascii.Error, VikingError, KeyError):# Validation and server errors can contain arguments and secrets.content = "Invalid tool arguments or OpenViking operation failed"diff --git a/pyproject.toml b/pyproject.tomlindex a2e6980ee..dc05a57ce 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -96,7 +96,7 @@ dependencies = [[project.optional-dependencies]expiry = [- "redis>=5,<7",+ "redis>=5.3.1,<7",]gateway-fast = ["uvloop>=0.21; sys_platform != 'win32'",@@ -109,12 +109,12 @@ mysql = []redis-mysql = ["aiomysql>=0.2.0,<1",- "redis>=5.0,<7",+ "redis>=5.3.1,<7","SQLAlchemy[asyncio]>=2.0.54,<2.1",]test = ["SQLAlchemy[asyncio]>=2.0,<2.1",- "redis>=5.0,<7",+ "redis>=5.3.1,<7","pytest>=7.0.0","pytest-asyncio>=0.21.0","pytest-xdist>=3.5.0",@@ -244,7 +244,7 @@ include = ["openviking*", "vikingbot*"]exclude = ["tests*", "docs*", "examples*"][tool.setuptools.package-data]-openviking_gateway = ["client-rules.json"]+openviking_gateway = ["client-rules.json", "lua/*.lua"]"openviking.scheduling.expiry" = ["lua/*.lua"]"vikingbot.studio.providers.feishu" = ["icon.png"]openviking = [diff --git a/scripts/gateway_chart_check.py b/scripts/gateway_chart_check.pynew file mode 100644index 000000000..14a14809e--- /dev/null+++ b/scripts/gateway_chart_check.py@@ -0,0 +1,98 @@+"""Render the standalone chart and validate its deployment and gateway configuration."""++import json+import subprocess+from pathlib import Path++import yaml++from openviking_gateway.config import StandaloneGatewayConfig++CHART = Path(__file__).resolve().parents[1] / "deploy/helm/openviking-gateway"+++def render(values, *overrides):+ result = subprocess.run(+ ["helm", "template", "gateway", str(CHART), "-f", str(CHART / "ci" / values), *overrides],+ check=True,+ capture_output=True,+ text=True,+ )+ resources = [item for item in yaml.safe_load_all(result.stdout) if item]+ configmap = next(item for item in resources if item["kind"] == "ConfigMap")+ config = StandaloneGatewayConfig.model_validate(json.loads(configmap["data"]["gateway.conf"]))+ assert (config.host, config.port, config.storage_path) == (+ "0.0.0.0",+ 1935,+ "/app/.openviking/gateway",+ )+ deployment = next(item for item in resources if item["kind"] == "Deployment")+ service = next(item for item in resources if item["kind"] == "Service")+ spec = deployment["spec"]+ pod = spec["template"]["spec"]+ assert service["spec"]["selector"] == spec["selector"]["matchLabels"]+ assert pod["terminationGracePeriodSeconds"] == 660+ for volume in pod["volumes"]:+ if volume["name"] == "root-key":+ assert volume["secret"]["defaultMode"] == 0o600+ assert pod["containers"][0]["lifecycle"]["preStop"]["exec"]["command"] == ["sleep", "15"]+ return resources, spec, config+++def main():+ metadata = yaml.safe_load((CHART / "Chart.yaml").read_text())+ default = subprocess.run(+ ["helm", "template", "gateway", str(CHART)], capture_output=True, text=True+ )+ if metadata["appVersion"] == "0.0.0-unreleased":+ assert default.returncode != 0 and "image.tag is required" in default.stderr+ else:+ assert default.returncode == 0, default.stderr+ assert f":v{metadata['appVersion']}" in default.stdout+ for name in ("sqlite.yaml", "redis.yaml"):+ subprocess.run(["helm", "lint", str(CHART), "-f", str(CHART / "ci" / name)], check=True)+ resources, spec, _ = render("sqlite.yaml")+ assert any(item["kind"] == "PersistentVolumeClaim" for item in resources)+ assert spec["strategy"]["type"] == "Recreate"+ resources, spec, config = render("redis.yaml")+ assert not any(item["kind"] == "PersistentVolumeClaim" for item in resources)+ assert spec["replicas"] == 2+ assert spec["strategy"] == {+ "type": "RollingUpdate",+ "rollingUpdate": {"maxUnavailable": 0, "maxSurge": 1},+ }+ assert any(item["kind"] == "PodDisruptionBudget" for item in resources)+ env = {item["name"] for item in spec["template"]["spec"]["containers"][0]["env"]}+ assert config.storage.redis["password_env"] in env+ assert config.encryption["local"]["key_file"] == "/etc/openviking-gateway/keys/root-key"+ _, _, config = render("redis.yaml", "--set", "config.encryption.provider=volcengine_kms")+ assert (+ config.encryption["volcengine_kms"]["key_file"] == "/etc/openviking-gateway/keys/root-key"+ )+ resources, spec, _ = render("sqlite.yaml", "--set", "persistence.enabled=false")+ assert not any(item["kind"] == "PersistentVolumeClaim" for item in resources)+ assert {"name": "data", "emptyDir": {}} in spec["template"]["spec"]["volumes"]+ for overrides in (+ [],+ ["--set", "config.storage.kernel=redis"],+ ["--set", "config.storage.management=redis"],+ ):+ result = subprocess.run(+ [+ "helm",+ "template",+ "gateway",+ str(CHART),+ "-f",+ str(CHART / "ci/sqlite-invalid.yaml"),+ *overrides,+ ],+ capture_output=True,+ text=True,+ )+ assert result.returncode != 0 and "SQLite storage requires replicaCount: 1" in result.stderr+ print("Gateway chart: deployment contracts and StandaloneGatewayConfig validation passed")+++if __name__ == "__main__":+ main()diff --git a/tests/gateway/README.md b/tests/gateway/README.mdindex 7b112d84c..cfb026dfa 100644--- a/tests/gateway/README.md+++ b/tests/gateway/README.md@@ -134,3 +134,93 @@ PYTHONPATH=. python scripts/gateway_benchmark.py --concurrency 300 --profile --o`--profile` relies on `scripts/gateway_profile.py` and slows the burst, so comparetimings from runs without it. Compare results only between runs on the same machine and Pythonversion.++## Redis storage contracts++`test_storage_ports.py` runs each storage contract against SQLite, Redis standalone and+Redis Cluster. Redis cases skip when their endpoint variable is absent; configured+endpoints must be reachable. Install `pip install "redis>=5.3.1,<7"` and run:++```bash+export OV_TEST_REDIS=redis://127.0.0.1:6379+export OV_TEST_REDIS_CLUSTER=redis://127.0.0.1:7000,redis://127.0.0.1:7001,redis://127.0.0.1:7002+export OV_TEST_REDIS_USERNAME=gateway+export OV_TEST_REDIS_PASSWORD=gateway-test-password+PYTHONPATH=. pytest tests/gateway/test_storage_ports.py --confcutdir=tests/gateway -o addopts=''+```++The gateway workflow starts Redis 7.2 standalone and a three-node Cluster and creates+the [documented ACL](../../docs/en/gateway/13-configuration.md#storage) on every node.+Each fixture uses a random `ovgw:test:<uuid>:` prefix and removes only its own keys.+CI runs the whole gateway suite on redis-py 6.4.0 and this file again on 5.3.1, the+oldest supported client; the client options are explained in+`openviking_gateway/redis_store.py`.++## kind deployment acceptance++`e2e/` runs the standalone Helm chart on a dedicated kind cluster with one control+plane and two workers. It uses a mock OpenViking server with two libraries that+both identify as `default/default`, three model protocols, and Redis with the+minimum gateway ACL. All credentials are synthetic. Each case owns a fresh+namespace, persistent Redis volume, and gateway release; cleanup only removes+those resources. Do not point this suite at a shared production cluster.++Install `kind` 0.27+, Docker 28+, kubectl, Helm 3, Python 3.10+, `pytest`, `httpx`,+`openai`, `anthropic`, and Codex CLI (`@openai/[email protected]`). The test+clients run on the host; `kubectl port-forward` targets individual gateway Pods.+The rolling-update load runs inside the cluster through its Service.++```bash+mkdir -p /tmp/ovgw-e2e+kind create cluster --name ovgw-e2e --config tests/gateway/e2e/kind.yaml \+ --kubeconfig /tmp/ovgw-e2e/kubeconfig --wait 120s+python tests/gateway/e2e/build_overlay.py --tag ovgw-e2e:local+docker pull redis:7.2-alpine+python tests/gateway/e2e/load_images.py --cluster ovgw-e2e ovgw-e2e:local redis:7.2-alpine+OV_TEST_KIND_KUBECONFIG=/tmp/ovgw-e2e/kubeconfig OV_TEST_GATEWAY_IMAGE=ovgw-e2e:local \+ pytest tests/gateway/e2e --confcutdir=tests/gateway/e2e -o addopts='' -v \+ --basetemp=/tmp/ovgw-e2e/results --junitxml=/tmp/ovgw-e2e/results.xml+kind delete cluster --name ovgw-e2e+```++Without `OV_TEST_KIND_KUBECONFIG`, every deployment case skips before calling+kubectl. Set `OV_TEST_KIND_REDIS=standalone` or `cluster` to select one backend;+by default both run. `OV_TEST_GATEWAY_CHART` can point to the chart in a+separate integration checkout. The image must include the+Redis gateway changes; the overlay helper copies the gateway package and every+changed Python dependency under `openviking/` and `openviking_cli/` relative to+the supplied release tag. It does not rebuild native extensions or Studio.++| Scenario | Standalone | Cluster |+| --- | --- | --- |+| 1. Eight alternating session turns | Yes | Yes |+| 2. Graceful deletion during a stream | Yes | Yes |+| 3. Truncation under a 25-second grace (negative control) | Yes | — |+| 4. Rollout with short, chat, keep-alive, and 60-second stream traffic | Yes | Yes |+| 5. Eviction under 30 MiB and credential reconstruction | Yes | — |+| 6. AOF restart with pending capture | Yes | — |+| 7. Data loss without AOF | Yes | — |+| 8. Isolation of libraries with the same OV identity | Yes | Yes |+| 9. Revocation, paused capture, and replacement key | Yes | — |+| 10. Startup recovery from 503; refusal of dev mode and 404 | Yes | — |+| 11. Forty-second silence with Python SDKs and Codex; compressed SSE | Yes | — |+| 12. One hundred captures with eight workers | Yes | Yes |+| 13. Existing unordered key returns 402 before upstream dispatch | Yes | — |+| 14. Hidden tool deduplication, missing receipts, and Responses chains | Yes | Yes |+| 15. Studio and management changes across the cache window | Yes | — |+| 16. Shared root key and missing-key startup failure | Yes | — |++Assertions inspect raw mock calls, source message IDs, Redis keys, Pod lifecycle,+and client completion markers. Missing SDKs, incomplete streams, and failed+infrastructure are failures when the suite is opted in. A Redis outage may+produce either a logged `memory_store_failure` passthrough or a plaintext+HTTP 500 at authentication; scenario 6 records the observed proportions.+Scenario 7 asserts loss of an undelivered tail when persistence is disabled.++The `gateway-e2e.yml` workflow runs nightly against `ghcr.io/volcengine/openviking:main`.+Manual dispatch can build the selected ref over a release image. Both paths+upload pytest results, per-scenario logs, and kind logs, then delete the cluster.+Cloud Redis failover, TLS, and real OV/model providers remain separate acceptance+checks. For a cgroup-v1 development host, use a local copy of `kind.yaml` with+`KubeletConfiguration.cgroupDriver: cgroupfs` and containerd's+`SystemdCgroup = false`; CI uses cgroup v2 without that host-specific patch.diff --git a/tests/gateway/conftest.py b/tests/gateway/conftest.pyindex cbdebb9e9..b05a0629e 100644--- a/tests/gateway/conftest.py+++ b/tests/gateway/conftest.py@@ -2,6 +2,9 @@import copyimport json+import os+import uuid+from contextlib import asynccontextmanagerfrom urllib.parse import parse_qs, urlsplitimport httpx@@ -15,7 +18,7 @@ from openviking_gateway.app import create_appfrom openviking_gateway.config import GatewayConfigfrom openviking_gateway.kernel import MemoryKernelfrom openviking_gateway.models import Policy-from openviking_gateway.storage import SQLiteKernelStore+from openviking_gateway.storage import SQLiteKernelStore, SQLiteManagementStoredef local_encryptor(key_file):@@ -197,7 +200,7 @@ async def make_due(store):@pytest_asyncio.fixture-async def running_gateway(tmp_path):+async def gateway_backend():captured = []writes = []override = {}@@ -359,7 +362,36 @@ async def running_gateway(tmp_path):site = web.TCPSite(runner, "127.0.0.1", 0)await site.start()base = f"http://127.0.0.1:{site._server.sockets[0].getsockname()[1]}"- config = GatewayConfig(storage_path=str(tmp_path))+ try:+ yield base, captured, writes, override+ finally:+ await runner.cleanup()+++def default_upstreams(base):+ """One upstream per protocol on the fake backend."""+ return {+ protocol: {+ "name": protocol,+ "protocol": protocol,+ "base_url": base if protocol == "anthropic" else base + "/v1",+ "api_key": "model-secret",+ "models": ["model", "error"],+ }+ for protocol in ("chat", "anthropic", "responses")+ }+++def gateway_config():+ return {}+++@asynccontextmanager+async def serve_gateway(tmp_path, gateway_backend, gateway_config):+ base, captured, writes, override = gateway_backend+ settings = {"storage_path": str(tmp_path), **gateway_config}+ config = GatewayConfig.model_validate(settings)app = create_app(config, openviking_url=base, encryptor=local_encryptor(tmp_path / "master.key"))@@ -371,36 +403,160 @@ async def running_gateway(tmp_path):base_url="http://gateway/gateway",) as client:admin = {"X-API-Key": "admin-key"}- for protocol in ("chat", "anthropic", "responses"):- response = await client.put(- f"/admin/upstreams/{protocol}",+ minted = None+ if config.management_api:+ for protocol, upstream in default_upstreams(base).items():+ response = await client.put(+ f"/admin/upstreams/{protocol}", headers=admin, json=upstream+ )+ assert response.status_code == 200, response.text+ assert (+ await client.put(+ "/admin/policies/default",+ headers=admin,+ json={"name": "Default", "gateway_tools": False},+ )+ ).status_code == 200+ minted = await client.post(+ "/admin/keys",headers=admin,json={- "name": protocol,- "protocol": protocol,- "base_url": base if protocol == "anthropic" else base + "/v1",- "api_key": "model-secret",- "models": ["model", "error"],+ "name": "test",+ "openviking_key": "user-key",+ "policy_id": "default",+ "upstream_ids": ["chat", "anthropic", "responses"],},)- assert response.status_code == 200, response.text- assert (- await client.put(- "/admin/policies/default",- headers=admin,- json={"name": "Default", "gateway_tools": False},- )- ).status_code == 200- minted = await client.post(- "/admin/keys",- headers=admin,- json={- "name": "test",- "openviking_key": "user-key",- "policy_id": "default",- "upstream_ids": ["chat", "anthropic", "responses"],- },- )- assert minted.status_code == 200, minted.text- yield app, client, admin, minted.json(), captured, writes- await runner.cleanup()+ assert minted.status_code == 200, minted.text+ minted = minted.json()+ yield app, client, admin, minted, captured, writes+++@pytest_asyncio.fixture+async def running_gateway(tmp_path, gateway_backend, gateway_config):+ async with serve_gateway(tmp_path, gateway_backend, gateway_config) as gateway:+ yield gateway+++def storage_encryptor(request, tmp_path):+ """Plaintext unless a test parametrizes it indirectly with True."""+ if getattr(request, "param", False):+ return local_encryptor(tmp_path / "storage-root.key")+ return None+++def redis_settings(provider):+ """``storage.redis`` settings for "redis" or "redis-cluster"; skips when unconfigured."""+ variable = "OV_TEST_REDIS_CLUSTER" if provider == "redis-cluster" else "OV_TEST_REDIS"+ if not (endpoints := os.environ.get(variable)):+ pytest.skip(f"{variable} is not set")+ pytest.importorskip("redis")+ return {+ "mode": "cluster" if provider == "redis-cluster" else "standalone",+ "endpoints": endpoints.split(","),+ "username": os.environ.get("OV_TEST_REDIS_USERNAME", ""),+ "password": os.environ.get("OV_TEST_REDIS_PASSWORD", ""),+ }+++@asynccontextmanager+async def open_redis_backend(provider, encryptor=None):+ from openviking_gateway.redis_store import RedisBackend, connect+ from openviking_gateway.storage import AsyncCodec++ handle = connect({**redis_settings(provider), "command_timeout_ms": 5000, "pool_size": 128})+ backend = RedisBackend(handle.client, f"ovgw:test:{uuid.uuid4().hex}:", AsyncCodec(encryptor))+ try:+ await handle.client.ping()+ yield backend+ finally:+ await backend.delete_matching(backend.prefix + "*")+ await handle.close()+++@asynccontextmanager+async def open_kernel_store(provider, tmp_path, encryptor=None):+ if provider == "sqlite":+ store = SQLiteKernelStore(tmp_path / "kernel-contract.sqlite3", encryptor)+ await store.initialize()+ try:+ yield store+ finally:+ store.close()+ return+ from openviking_gateway.redis_store import RedisKernelStore++ async with open_redis_backend(provider, encryptor) as backend:+ store = RedisKernelStore(backend, ttl=7 * 86400)+ await store.initialize()+ yield store+++@asynccontextmanager+async def open_management_store(provider, tmp_path, encryptor=None):+ if provider == "sqlite":+ store = SQLiteManagementStore(tmp_path / "management.sqlite3", encryptor)+ await store.initialize()+ try:+ yield store+ finally:+ store.close()+ return+ from openviking_gateway.redis_store import RedisManagementStore++ async with open_redis_backend(provider, encryptor) as backend:+ store = RedisManagementStore(backend, log_ttl=7 * 86400)+ await store.initialize()+ yield store+++# Each port lists its own providers, so a backend for one port adds one entry here.+@pytest_asyncio.fixture(params=["sqlite", "redis", "redis-cluster"])+async def kernel_store(request, tmp_path, storage_encryptor):+ async with open_kernel_store(request.param, tmp_path, storage_encryptor) as store:+ yield store+++@pytest_asyncio.fixture(params=["sqlite", "redis", "redis-cluster"])+async def management_store(request, tmp_path, storage_encryptor):+ async with open_management_store(request.param, tmp_path, storage_encryptor) as store:+ yield store+++@pytest_asyncio.fixture(params=["redis", "redis-cluster"])+async def redis_kernel_store(request, tmp_path):+ async with open_kernel_store(request.param, tmp_path) as store:+ yield store+++@pytest_asyncio.fixture(params=["redis", "redis-cluster"])+async def redis_management_store(request, tmp_path):+ async with open_management_store(request.param, tmp_path) as store:+ yield store+++async def corrupt_root(store, scope, session, value):+ """Overwrite the stored bytes of a session's root replay record."""+ if isinstance(store, SQLiteKernelStore):++ def corrupt():+ with store.connect() as connection:+ connection.execute("UPDATE replay SET value=? WHERE scope=?", (value, scope))++ await store.run(corrupt, write=True)+ else:+ await store.client.hset(store.replay_key(scope, session), "root:", value)+++async def evict_state(store, scope, key):+ """Drop a state record behind the store's back, as Redis eviction would."""+ if isinstance(store, SQLiteKernelStore):++ def remove():+ with store.connect() as connection:+ connection.execute("DELETE FROM state WHERE scope=? AND key=?", (scope, key))++ await store.run(remove, write=True)+ else:+ await store.client.execute_command("DEL", store.state_key(scope, key))diff --git a/tests/gateway/e2e/__init__.py b/tests/gateway/e2e/__init__.pynew file mode 100644index 000000000..d71bc1a62--- /dev/null+++ b/tests/gateway/e2e/__init__.py@@ -0,0 +1 @@+"""Gateway deployment acceptance tests."""diff --git a/tests/gateway/e2e/build_overlay.py b/tests/gateway/e2e/build_overlay.pynew file mode 100644index 000000000..082963ca5--- /dev/null+++ b/tests/gateway/e2e/build_overlay.py@@ -0,0 +1,63 @@+"""Build a release image with the gateway and changed pure-Python dependencies."""++import argparse+import subprocess+import tempfile+from pathlib import Path+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--base-ref", default="v0.5.2", help="release tag of the base image")+ parser.add_argument("--base", help="base image; defaults to the --base-ref release image")+ parser.add_argument("--tag", default="ovgw-e2e:local")+ parser.add_argument("--source-root", type=Path, default=Path(__file__).resolve().parents[3])+ args = parser.parse_args()+ args.base = args.base or f"ghcr.io/volcengine/openviking:{args.base_ref}"+ root = args.source_root.resolve()+ files = subprocess.check_output(+ [+ "git",+ "diff",+ "--name-only",+ "--diff-filter=AM",+ args.base_ref,+ "--",+ "openviking",+ "openviking_cli",+ ],+ cwd=root,+ text=True,+ ).splitlines()+ site = "/app/.venv/lib/python3.13/site-packages/"+ lines = [f"FROM {args.base}", f"COPY openviking_gateway/ {site}openviking_gateway/"]+ for name in files:+ if name.endswith(".py"):+ lines.append(f"COPY {name} {site}{name}")+ lines.append(+ 'RUN python -I -c "import redis; from openviking_gateway.config import GatewayConfig; '+ "assert 'storage' in GatewayConfig.model_fields; "+ "from pathlib import Path; import openviking_gateway; "+ "assert list((Path(openviking_gateway.__file__).parent / 'lua').glob('*.lua'))\""+ )+ with tempfile.NamedTemporaryFile(mode="w", suffix=".Dockerfile") as dockerfile:+ dockerfile.write("\n".join(lines) + "\n")+ dockerfile.flush()+ subprocess.run(+ [+ "docker",+ "build",+ "--platform",+ "linux/amd64",+ "-t",+ args.tag,+ "-f",+ dockerfile.name,+ str(root),+ ],+ check=True,+ )+++if __name__ == "__main__":+ main()diff --git a/tests/gateway/e2e/conftest.py b/tests/gateway/e2e/conftest.pynew file mode 100644index 000000000..760534abb--- /dev/null+++ b/tests/gateway/e2e/conftest.py@@ -0,0 +1,50 @@+"""Opt-in kind fixtures: each scenario owns a namespace and all of its resources."""++import os+from pathlib import Path++import pytest++from .harness import Harness+++def pytest_configure(config):+ config.addinivalue_line(+ "markers", "standalone: scenario excluded from the Redis Cluster matrix"+ )+++def pytest_generate_tests(metafunc):+ if "harness" in metafunc.fixturenames:+ modes = os.getenv("OV_TEST_KIND_REDIS", "standalone,cluster").split(",")+ if any(mode not in {"standalone", "cluster"} for mode in modes):+ raise pytest.UsageError(+ "OV_TEST_KIND_REDIS must be standalone, cluster, or both separated by a comma"+ )+ metafunc.parametrize("harness", modes, indirect=True)+++def pytest_collection_modifyitems(config, items):+ excluded = [+ item+ for item in items+ if item.get_closest_marker("standalone") and item.callspec.params["harness"] == "cluster"+ ]+ if excluded:+ config.hook.pytest_deselected(items=excluded)+ items[:] = [item for item in items if item not in excluded]+++def harness(request, tmp_path):+ kubeconfig = os.getenv("OV_TEST_KIND_KUBECONFIG")+ if not kubeconfig:+ pytest.skip("set OV_TEST_KIND_KUBECONFIG to run the isolated kind suite")+ assert Path(kubeconfig).is_file(), f"kubeconfig does not exist: {kubeconfig}"+ instance = Harness(kubeconfig, request.param, tmp_path)+ try:+ instance.start()+ yield instance+ finally:+ instance.collect_logs()+ instance.close()diff --git a/tests/gateway/e2e/harness.py b/tests/gateway/e2e/harness.pynew file mode 100644index 000000000..56500cfd6--- /dev/null+++ b/tests/gateway/e2e/harness.py@@ -0,0 +1,587 @@+"""Kubernetes resources and subprocess clients for the gateway acceptance matrix."""++import base64+import copy+import hashlib+import json+import os+import secrets+import socket+import subprocess+import time+import uuid+from contextlib import contextmanager+from pathlib import Path++import httpx++ROOT = Path(__file__).resolve().parents[3]+HERE = Path(__file__).parent+# Redis 7.2 checks the disabled default user's ACL while replaying AOF MULTI/EXEC.+ACL = """user default off ~* &* +@all+user admin on >e2e-admin ~* &* +@all+user gateway on >e2e-gateway ~ovgw:* +@read +@write +@scripting +@connection +@transaction +ping +time +scan +unlink +cluster|slots +cluster|shards+"""+++def wait_for(check, timeout=90, interval=0.5):+ deadline = time.monotonic() + timeout+ last = None+ while time.monotonic() < deadline:+ try:+ last = check()+ if last:+ return last+ except (httpx.HTTPError, subprocess.CalledProcessError) as error:+ last = error+ time.sleep(interval)+ raise AssertionError(f"condition not met within {timeout}s: {last!r}")+++def merge(target, changes):+ for key, value in changes.items():+ if isinstance(value, dict) and isinstance(target.get(key), dict):+ merge(target[key], value)+ else:+ target[key] = copy.deepcopy(value)+++class Harness:+ def __init__(self, kubeconfig, mode, directory):+ self.kubeconfig, self.mode, self.directory = kubeconfig, mode, directory+ self.namespace = "ovgw-e2e-" + uuid.uuid4().hex[:10]+ self.image = os.getenv("OV_TEST_GATEWAY_IMAGE", "ghcr.io/volcengine/openviking:main")+ self.forwards = {}+ repository, tag = self.image.rsplit(":", 1)+ self.values = {+ "fullnameOverride": "gateway",+ "replicaCount": 2,+ "image": {"repository": repository, "tag": tag, "pullPolicy": "IfNotPresent"},+ "existingSecret": "gateway-secrets",+ "service": {"port": 1935},+ "resources": {+ "requests": {"cpu": "100m", "memory": "128Mi"},+ "limits": {"cpu": "2", "memory": "512Mi"},+ },+ "affinity": {+ "podAntiAffinity": {+ "preferredDuringSchedulingIgnoredDuringExecution": [+ {+ "weight": 100,+ "podAffinityTerm": {+ "labelSelector": {+ "matchLabels": {"app.kubernetes.io/instance": "gateway"}+ },+ "topologyKey": "kubernetes.io/hostname",+ },+ }+ ]+ }+ },+ "config": {+ "openviking_url": "http://mock-ov:1933",+ "openviking_keys": True,+ "tenancy": "key",+ "management_api": False,+ "capture_concurrency": 4,+ "request_log_sink": "stdout",+ "health_interval_seconds": 1,+ "default_profile": {+ "idle_seconds": 5,+ "gateway_tools": False,+ "profile": False,+ "show_recall": False,+ },+ "default_upstreams": {+ protocol: {+ "name": protocol,+ "protocol": protocol,+ "base_url": "http://mock-ark:8080"+ if protocol == "anthropic"+ else "http://mock-ark:8080/v1",+ "api_key": "mock-upstream-secret",+ "models": [+ "mock",+ "mock-silent",+ "mock-long",+ "mock-tools",+ "mock-silent-gzip",+ ],+ }+ for protocol in ("chat", "anthropic", "responses")+ },+ "storage": {+ "kernel": "redis",+ "management": "redis",+ "key_prefix": "ovgw:",+ "redis": {+ "mode": mode,+ "endpoints": ["redis://redis-0.redis:6379"],+ "username": "gateway",+ # The chart maps the Secret's redis-password entry to this variable.+ "password_env": "OPENVIKING_GATEWAY_REDIS_PASSWORD",+ "command_timeout_ms": 1000,+ },+ },+ },+ }++ def command(self, command, *, input=None, timeout=180, check=True, binary=False):+ result = subprocess.run(+ command, input=input, capture_output=True, text=not binary, timeout=timeout, check=False+ )+ if check and result.returncode:+ raise AssertionError(+ f"command failed ({result.returncode}): {command}\n{result.stdout}\n{result.stderr}"+ )+ return result.stdout++ def kubectl(self, *args, **kwargs):+ return self.command(+ ["kubectl", "--kubeconfig", self.kubeconfig, "-n", self.namespace, *map(str, args)],+ **kwargs,+ )++ def apply(self, *items):+ return self.kubectl(+ "apply",+ "-f",+ "-",+ input=json.dumps({"apiVersion": "v1", "kind": "List", "items": items}),+ )++ def start(self):+ nodes = json.loads(self.kubectl("get", "nodes", "-o", "json"))["items"]+ assert len(nodes) == 3, "the suite requires one control-plane and two workers"+ self.apply({"apiVersion": "v1", "kind": "Namespace", "metadata": {"name": self.namespace}})+ self.apply(+ {+ "apiVersion": "v1",+ "kind": "Secret",+ "metadata": {"name": "gateway-secrets"},+ "data": {"root-key": base64.b64encode(secrets.token_hex(32).encode()).decode()},+ "stringData": {"redis-password": "e2e-gateway"},+ },+ {+ "apiVersion": "v1",+ "kind": "ConfigMap",+ "metadata": {"name": "e2e-mocks"},+ "data": {p.name: p.read_text() for p in (HERE / "mocks").glob("*.py")},+ },+ {+ "apiVersion": "v1",+ "kind": "ConfigMap",+ "metadata": {"name": "redis-config"},+ "data": {"users.acl": ACL},+ },+ )+ for service, port, file in (+ ("mock-ov", 1933, "mock_ov.py"),+ ("mock-ark", 8080, "mock_ark.py"),+ ):+ self.apply(+ {+ "apiVersion": "apps/v1",+ "kind": "Deployment",+ "metadata": {"name": service},+ "spec": {+ "replicas": 1,+ "selector": {"matchLabels": {"app": service}},+ "template": {+ "metadata": {"labels": {"app": service}},+ "spec": {+ "containers": [+ {+ "name": "mock",+ "image": self.image,+ "imagePullPolicy": "IfNotPresent",+ "command": ["python", "-u", "/mocks/" + file],+ "ports": [{"containerPort": port}],+ "readinessProbe": {+ "tcpSocket": {"port": port},+ "periodSeconds": 1,+ },+ "volumeMounts": [{"name": "mocks", "mountPath": "/mocks"}],+ }+ ],+ "volumes": [{"name": "mocks", "configMap": {"name": "e2e-mocks"}}],+ },+ },+ },+ },+ {+ "apiVersion": "v1",+ "kind": "Service",+ "metadata": {"name": service},+ "spec": {"selector": {"app": service}, "ports": [{"port": port}]},+ },+ )+ self.start_redis()+ for deployment in ("mock-ov", "mock-ark"):+ self.kubectl("rollout", "status", "deployment/" + deployment, "--timeout=120s")+ self.redeploy({})+ pods = self.pod_objects()+ assert len({pod["spec"]["nodeName"] for pod in pods}) == 2, (+ "gateway replicas must occupy different workers"+ )+ for pod in self.pods():+ self.url(pod)+ self.url("service/mock-ov", 1933)+ self.url("service/mock-ark", 8080)++ def start_redis(self):+ args = [+ "redis-server",+ "--aclfile",+ "/config/users.acl",+ "--appendonly",+ "yes",+ "--appendfsync",+ "always",+ "--save",+ "",+ "--dir",+ "/data",+ "--maxmemory",+ "96mb",+ "--maxmemory-policy",+ "volatile-lru",+ ]+ if self.mode == "cluster":+ args += [+ "--cluster-enabled",+ "yes",+ "--cluster-config-file",+ "nodes.conf",+ "--cluster-node-timeout",+ "3000",+ ]+ self.apply(+ {+ "apiVersion": "v1",+ "kind": "Service",+ "metadata": {"name": "redis"},+ "spec": {+ "clusterIP": "None",+ "publishNotReadyAddresses": True,+ "selector": {"app": "redis"},+ "ports": [{"port": 6379}],+ },+ },+ {+ "apiVersion": "apps/v1",+ "kind": "StatefulSet",+ "metadata": {"name": "redis"},+ "spec": {+ "serviceName": "redis",+ "replicas": 3 if self.mode == "cluster" else 1,+ "selector": {"matchLabels": {"app": "redis"}},+ "template": {+ "metadata": {"labels": {"app": "redis"}},+ "spec": {+ "containers": [+ {+ "name": "redis",+ "image": "redis:7.2-alpine",+ "args": args,+ "readinessProbe": {+ "tcpSocket": {"port": 6379},+ "periodSeconds": 1,+ },+ "volumeMounts": [+ {"name": "data", "mountPath": "/data"},+ {"name": "config", "mountPath": "/config"},+ ],+ }+ ],+ "volumes": [{"name": "config", "configMap": {"name": "redis-config"}}],+ },+ },+ "volumeClaimTemplates": [+ {+ "metadata": {"name": "data"},+ "spec": {+ "accessModes": ["ReadWriteOnce"],+ "resources": {"requests": {"storage": "256Mi"}},+ },+ }+ ],+ },+ },+ )+ self.kubectl("rollout", "status", "statefulset/redis", "--timeout=150s")+ if self.mode == "cluster":+ script = (+ "nodes=\"\"; for n in 0 1 2; do ip=$(getent hosts redis-$n.redis | awk '{print $1; exit}'); "+ 'nodes="$nodes $ip:6379"; done; redis-cli --user admin -a e2e-admin '+ "--cluster create $nodes --cluster-replicas 0 --cluster-yes"+ )+ self.apply(+ {+ "apiVersion": "batch/v1",+ "kind": "Job",+ "metadata": {"name": "redis-init"},+ "spec": {+ "backoffLimit": 0,+ "template": {+ "spec": {+ "restartPolicy": "Never",+ "containers": [+ {+ "name": "init",+ "image": "redis:7.2-alpine",+ "command": ["sh", "-ec", script],+ }+ ],+ }+ },+ },+ }+ )+ self.kubectl("wait", "--for=condition=complete", "job/redis-init", "--timeout=90s")+ wait_for(lambda: "cluster_state:ok" in self.redis("CLUSTER", "INFO"))++ def redeploy(self, config, values=None, wait=True):+ merge(self.values["config"], config)+ merge(self.values, values or {})+ path = self.directory / "values.json"+ path.write_text(json.dumps(self.values))+ chart = os.getenv("OV_TEST_GATEWAY_CHART", str(ROOT / "deploy/helm/openviking-gateway"))+ self.command(+ [+ "helm",+ "--kubeconfig",+ self.kubeconfig,+ "upgrade",+ "--install",+ "gateway",+ chart,+ "-n",+ self.namespace,+ "-f",+ str(path),+ ],+ timeout=120,+ )+ if wait:+ self.kubectl("rollout", "status", "deployment/gateway", "--timeout=180s", timeout=190)+ wait_for(lambda: len(self.pods()) == 2)++ def pod_objects(self):+ return [+ p+ for p in json.loads(+ self.kubectl(+ "get", "pods", "-l", "app.kubernetes.io/instance=gateway", "-o", "json"+ )+ )["items"]+ if not p["metadata"].get("deletionTimestamp")+ and p["status"].get("phase") == "Running"+ and all(c.get("ready") for c in p["status"].get("containerStatuses", []))+ ]++ def pods(self):+ return sorted(p["metadata"]["name"] for p in self.pod_objects())++ def url(self, resource, port=1935):+ resource = resource if "/" in resource else "pod/" + resource+ cached = self.forwards.get(resource)+ if cached and cached[0].poll() is None:+ return cached[1]+ with socket.socket() as sock:+ sock.bind(("127.0.0.1", 0))+ local = sock.getsockname()[1]+ log = open(self.directory / (resource.replace("/", "-") + ".forward.log"), "w+")+ process = subprocess.Popen(+ [+ "kubectl",+ "--kubeconfig",+ self.kubeconfig,+ "-n",+ self.namespace,+ "port-forward",+ resource,+ f"{local}:{port}",+ ],+ stdout=log,+ stderr=log,+ )+ url = f"http://127.0.0.1:{local}"+ self.forwards[resource] = (process, url, log)++ def ready():+ assert process.poll() is None, f"port-forward exited: {resource}"+ log.flush()+ return "Forwarding from" in Path(log.name).read_text()++ wait_for(ready, timeout=30)+ return url++ def request(self, pod, method, path, key="key-a", **kwargs):+ headers = {"Authorization": "Bearer " + key, **kwargs.pop("headers", {})}+ return httpx.request(method, self.url(pod) + path, headers=headers, timeout=90, **kwargs)++ @contextmanager+ def stream(self, pod, body, key="key-a", headers=None):+ with httpx.stream(+ "POST",+ self.url(pod) + "/gateway/v1/chat/completions",+ json=body,+ headers={"Authorization": "Bearer " + key, **(headers or {})},+ timeout=100,+ ) as response:+ response.raise_for_status()+ yield response++ def mock(self, service, method, path, **kwargs):+ port = 1933 if service == "ov" else 8080+ return httpx.request(+ method, self.url("service/mock-" + service, port) + path, timeout=30, **kwargs+ )++ def redis_bytes(self, *args, pod="redis-0"):+ return self.kubectl(+ "exec",+ pod,+ "--",+ "redis-cli",+ "--no-auth-warning",+ "--raw",+ "-c",+ "--user",+ "admin",+ "-a",+ "e2e-admin",+ *args,+ binary=True,+ ).rstrip(b"\n")++ def redis(self, *args, **kwargs):+ return self.redis_bytes(*args, **kwargs).decode()++ def redis_keys(self, pattern):+ keys = set()+ for n in range(3 if self.mode == "cluster" else 1):+ keys.update(self.redis("--scan", "--pattern", pattern, pod=f"redis-{n}").splitlines())+ return sorted(keys)++ def logs(self):+ return self.kubectl(+ "logs",+ "-l",+ "app.kubernetes.io/instance=gateway",+ "--all-containers=true",+ "--prefix",+ "--tail=-1",+ )++ def collect_logs(self):+ for service in ("ov", "ark"):+ try:+ response = self.mock(service, "GET", "/_records")+ (self.directory / f"mock-{service}.json").write_text(response.text)+ except (AssertionError, httpx.HTTPError):+ pass+ for name, args in {+ "pods": ("get", "pods", "-o", "wide"),+ "events": ("get", "events"),+ "gateway": (+ "logs",+ "-l",+ "app.kubernetes.io/instance=gateway",+ "--prefix",+ "--tail=-1",+ ),+ "redis": ("logs", "statefulset/redis", "--tail=100"),+ }.items():+ try:+ (self.directory / f"{name}.log").write_text(+ self.kubectl(*args, check=False, timeout=20)+ )+ except subprocess.TimeoutExpired:+ pass++ def close(self):+ for process, _, log in self.forwards.values():+ process.terminate()+ process.wait(timeout=10)+ log.close()+ self.kubectl("delete", "namespace", self.namespace, "--wait=false", check=False, timeout=30)+++CHAT = "/gateway/v1/chat/completions"+MODELS = "/gateway/v1/models"+ADMIN = "/gateway/admin"+++def digest(value):+ return hashlib.sha256(value.encode()).hexdigest()+++def account(key):+ return "k_" + digest("openviking\0" + key)+++def scope(key="key-a", protocol="chat"):+ return digest(account(key) + "\0default\0" + protocol)+++def records(harness, service="ov"):+ response = harness.mock(service, "GET", "/_records")+ response.raise_for_status()+ return response.json()+++def control(harness, path, **body):+ response = harness.mock("ov", "POST", path, json=body)+ response.raise_for_status()+++def chat(harness, pod, session, messages, key="key-a", model="mock", **policy):+ headers = {"X-OpenViking-Session": session}+ if policy:+ headers["X-OpenViking-Context"] = json.dumps(policy)+ response = harness.request(+ pod,+ "POST",+ CHAT,+ key=key,+ headers=headers,+ json={"model": model, "messages": messages, "stream": False},+ )+ assert response.status_code == 200, response.text+ reply = response.json()["choices"][0]["message"]+ assert reply.get("content"), response.text+ return {"role": "assistant", "content": reply["content"]}+++def document(harness, redis_key):+ value = harness.redis("HGET", redis_key, "v").strip()+ return json.loads(value) if value else {}+++def credential_keys(harness, key):+ identifier = digest("openviking\0" + key)+ return harness.redis_keys(f"*m:*:o:keys:{digest(identifier)[:32]}")+++def session_keys(harness, session, key="key-a", protocol="chat"):+ suffix = digest(digest(session))[:32]+ tenant = scope(key, protocol)+ replay = harness.redis_keys(f"*k:{{{tenant}}}:rp:{suffix}")+ capture = harness.redis_keys(f"*k:{{cap}}:{tenant}:{suffix}")+ assert len(replay) == len(capture) == 1, (replay, capture)+ assert "root:" in harness.redis("HKEYS", replay[0]).splitlines()+ return replay[0], capture[0]+++def written_messages(snapshot, library="library-a"):+ return [+ message+ for session in snapshot["libraries"][library]["sessions"].values()+ for message in session["messages"]+ ]+++def message_text(message):+ return "".join(part.get("text", "") for part in message["parts"] if part["type"] == "text")diff --git a/tests/gateway/e2e/kind.yaml b/tests/gateway/e2e/kind.yamlnew file mode 100644index 000000000..ae8cd3041--- /dev/null+++ b/tests/gateway/e2e/kind.yaml@@ -0,0 +1,6 @@+kind: Cluster+apiVersion: kind.x-k8s.io/v1alpha4+nodes:+ - role: control-plane+ - role: worker+ - role: workerdiff --git a/tests/gateway/e2e/load_images.py b/tests/gateway/e2e/load_images.pynew file mode 100644index 000000000..73d2d65dc--- /dev/null+++ b/tests/gateway/e2e/load_images.py@@ -0,0 +1,46 @@+"""Load only the requested images into one explicitly named kind cluster."""++import argparse+import subprocess+import tempfile+from pathlib import Path+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--cluster", required=True)+ parser.add_argument("--kind", default="kind")+ parser.add_argument("images", nargs="+")+ args = parser.parse_args()+ nodes = subprocess.check_output(+ [args.kind, "get", "nodes", "--name", args.cluster], text=True+ ).splitlines()+ with tempfile.TemporaryDirectory(prefix="ovgw-e2e-images-") as temporary:+ archive = Path(temporary) / "images.tar"+ subprocess.run(+ ["docker", "save", "--platform", "linux/amd64", "-o", str(archive), *args.images],+ check=True,+ )+ for node in nodes:+ with archive.open("rb") as source:+ subprocess.run(+ [+ "docker",+ "exec",+ "-i",+ node,+ "ctr",+ "--namespace=k8s.io",+ "images",+ "import",+ "--no-unpack",+ "--snapshotter=overlayfs",+ "-",+ ],+ stdin=source,+ check=True,+ )+++if __name__ == "__main__":+ main()diff --git a/tests/gateway/e2e/mocks/mock_ark.py b/tests/gateway/e2e/mocks/mock_ark.pynew file mode 100644index 000000000..549916803--- /dev/null+++ b/tests/gateway/e2e/mocks/mock_ark.py@@ -0,0 +1,283 @@+"""Inspectable provider fixture: three protocols, delayed streams and hidden tools."""++import argparse+import asyncio+import hashlib+import json+import time+import zlib++from aiohttp import web++MODELS = ["mock", "mock-silent", "mock-long", "mock-tools", "mock-silent-gzip"]+TEXT = "mock response complete"+++def tool_pending(body):+ """Request a gateway search once per user turn, including replayed histories."""+ for item in reversed(body.get("messages", [])):+ if item.get("role") == "tool":+ return False+ if item.get("role") == "user":+ break+ return any(+ tool.get("function", {}).get("name") == "openviking_search"+ for tool in body.get("tools", [])+ )+++def reply(protocol, body, number):+ model = body.get("model", "mock")+ if protocol == "chat":+ message = {"role": "assistant", "content": TEXT}+ use_tool = "tools" in model and not body.get("stream") and tool_pending(body)+ if use_tool:+ users = [item for item in body["messages"] if item.get("role") == "user"]+ fingerprint = json.dumps(users, sort_keys=True).encode()+ call_id = "call_mock_" + hashlib.sha256(fingerprint).hexdigest()[:16]+ function = {"name": "openviking_search", "arguments": '{"query":"blue"}'}+ message = {+ "role": "assistant",+ "content": None,+ "tool_calls": [{"id": call_id, "type": "function", "function": function}],+ }+ return {+ "id": f"chatcmpl_mock_{number}",+ "object": "chat.completion",+ "created": int(time.time()),+ "model": model,+ "choices": [+ {+ "index": 0,+ "message": message,+ "finish_reason": "tool_calls" if use_tool else "stop",+ }+ ],+ "usage": {"prompt_tokens": 20, "completion_tokens": 3, "total_tokens": 23},+ }+ if protocol == "anthropic":+ return {+ "id": f"msg_mock_{number}",+ "type": "message",+ "role": "assistant",+ "model": model,+ "content": [{"type": "text", "text": TEXT}],+ "stop_reason": "end_turn",+ "stop_sequence": None,+ "usage": {"input_tokens": 20, "output_tokens": 3},+ }+ return {+ "id": f"resp_mock_{number}",+ "object": "response",+ "created_at": int(time.time()),+ "status": "completed",+ "model": model,+ "output": [+ {+ "type": "message",+ "id": f"msg_mock_{number}",+ "role": "assistant",+ "status": "completed",+ "content": [+ {"type": "output_text", "text": TEXT, "annotations": [], "logprobs": []}+ ],+ }+ ],+ "error": None,+ "incomplete_details": None,+ "instructions": None,+ "parallel_tool_calls": True,+ "tools": [],+ "tool_choice": "auto",+ "usage": {+ "input_tokens": 20,+ "output_tokens": 3,+ "total_tokens": 23,+ "input_tokens_details": {"cached_tokens": 0},+ "output_tokens_details": {"reasoning_tokens": 0},+ },+ }+++def events(protocol, value):+ """Build complete provider event sequences without relying on gateway parsers."""+ parts = ("mock ", "response ", "complete")+ if protocol == "chat":+ base = {k: value[k] for k in ("id", "created", "model")}+ base["object"] = "chat.completion.chunk"++ def chunk(delta, finish=None):+ return {**base, "choices": [{"index": 0, "delta": delta, "finish_reason": finish}]}++ return [+ chunk({"role": "assistant", "content": ""}),+ *(chunk({"content": part}) for part in parts),+ chunk({}, value["choices"][0]["finish_reason"]),+ {**base, "choices": [], "usage": value["usage"]},+ ]+ if protocol == "anthropic":+ block = {+ "type": "content_block_start",+ "index": 0,+ "content_block": {"type": "text", "text": ""},+ }+ return [+ {+ "type": "message_start",+ "message": {+ **value,+ "content": [],+ "stop_reason": None,+ "usage": {"input_tokens": 20, "output_tokens": 0},+ },+ },+ block,+ *(+ {+ "type": "content_block_delta",+ "index": 0,+ "delta": {"type": "text_delta", "text": p},+ }+ for p in parts+ ),+ {"type": "content_block_stop", "index": 0},+ {+ "type": "message_delta",+ "delta": {"stop_reason": value["stop_reason"], "stop_sequence": None},+ "usage": {"output_tokens": 3},+ },+ {"type": "message_stop"},+ ]+ item = value["output"][0]+ part = item["content"][0]+ fields = {"output_index": 0, "item_id": item["id"], "content_index": 0}+ result = [+ *(+ {"type": name, "response": {**value, "status": "in_progress", "output": []}}+ for name in ("response.created", "response.in_progress")+ ),+ {+ "type": "response.output_item.added",+ "output_index": 0,+ "item": {**item, "status": "in_progress", "content": []},+ },+ {"type": "response.content_part.added", **fields, "part": {**part, "text": ""}},+ *(+ {"type": "response.output_text.delta", **fields, "delta": p, "logprobs": []}+ for p in parts+ ),+ {"type": "response.output_text.done", **fields, "text": TEXT, "logprobs": []},+ {"type": "response.content_part.done", **fields, "part": part},+ {"type": "response.output_item.done", "output_index": 0, "item": item},+ {"type": "response.completed", "response": value},+ ]+ return [{**event, "sequence_number": number} for number, event in enumerate(result)]+++def create_app():+ records = []+ responses = {}+ counter = 0++ async def handle(request):+ nonlocal counter+ if request.path == "/_records":+ return web.json_response({"requests": records})+ if request.path.endswith("/models"):+ return web.json_response(+ {+ "object": "list",+ "data": [+ {"id": name, "object": "model", "created": 0, "owned_by": "mock"}+ for name in MODELS+ ],+ }+ )+ paths = {+ "/v1/chat/completions": "chat",+ "/v1/messages": "anthropic",+ "/v1/responses": "responses",+ }+ if request.path not in paths or request.method != "POST":+ raise web.HTTPNotFound()+ body = await request.json()+ counter += 1+ record = {+ "path": request.path,+ "key": request.headers.get("X-API-Key", request.headers.get("Authorization", "")),+ "source_pod": request.remote,+ "body": body,+ "status": 200,+ }+ records.append(record)+ protocol = paths[request.path]+ effective = body+ if protocol == "responses":+ items = body.get("input", [])+ items = [{"role": "user", "content": items}] if isinstance(items, str) else items+ if previous := body.get("previous_response_id"):+ prior = responses.get((record["key"], previous))+ if prior is None:+ record["status"] = 404+ return web.json_response(+ {"error": {"message": "Unknown previous_response_id"}}, status=404+ )+ items = [*prior, *items]+ record["effective_input"] = items+ effective = {**body, "input": items}+ value = reply(protocol, effective, counter)++ def remember():+ if protocol == "responses":+ responses[record["key"], value["id"]] = [+ *record["effective_input"],+ *value["output"],+ ]++ if not body.get("stream"):+ remember()+ return web.json_response(value)+ model = body.get("model", "mock")+ headers = {"Content-Type": "text/event-stream", "Cache-Control": "no-cache"}+ compressor = None+ if "gzip" in model:+ headers["Content-Encoding"] = "gzip"+ compressor = zlib.compressobj(wbits=31)+ response = web.StreamResponse(headers=headers)+ await response.prepare(request)+ sequence = events(protocol, value)+ try:+ for index, event in enumerate(sequence):+ # Pause only after a complete SSE event has reached the client.+ if "silent" in model and index == 2:+ await asyncio.sleep(40)+ if "long" in model and index:+ await asyncio.sleep(60 / (len(sequence) - 1))+ frame = "" if protocol == "chat" else f"event: {event['type']}\n"+ data = (frame + "data: " + json.dumps(event) + "\n\n").encode()+ if compressor:+ data = compressor.compress(data) + compressor.flush(zlib.Z_SYNC_FLUSH)+ await response.write(data)+ if protocol == "chat":+ data = b"data: [DONE]\n\n"+ await response.write(compressor.compress(data) if compressor else data)+ if compressor:+ await response.write(compressor.flush())+ await response.write_eof()+ remember()+ except ConnectionResetError:+ # Truncation tests disconnect mid-stream on purpose.+ pass+ return response++ app = web.Application(client_max_size=32 * 1024**2)+ app.router.add_route("*", "/{path:.*}", handle)+ return app+++if __name__ == "__main__":+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--host", default="0.0.0.0")+ parser.add_argument("--port", type=int, default=8080)+ args = parser.parse_args()+ web.run_app(create_app(), host=args.host, port=args.port, access_log=None)diff --git a/tests/gateway/e2e/mocks/mock_ov.py b/tests/gateway/e2e/mocks/mock_ov.pynew file mode 100644index 000000000..37a2cf23b--- /dev/null+++ b/tests/gateway/e2e/mocks/mock_ov.py@@ -0,0 +1,271 @@+"""OpenViking fixture with per-library data and inspectable fault controls.++GET /_records exposes requests and libraries. POST /_fail accepts on and status;+/_revoke and /_unorder accept key. /_auth_mode accepts mode; /_tool_delay accepts+seconds. Every library deliberately identifies as default/default.+"""++import argparse+import asyncio+import copy+import json+import os+import time++from aiohttp import web++KEYS = {"key-a": "library-a", "key-a-new": "library-a", "key-b": "library-b"}+TOOLS = [+ {+ "name": "search",+ "description": "Search this library's memories.",+ "inputSchema": {+ "type": "object",+ "properties": {"query": {"type": "string"}},+ "required": ["query"],+ },+ }+]+++def ok(value):+ return web.json_response({"status": "ok", "result": value})+++def failure(status, code):+ return web.json_response({"status": "error", "error": {"code": code}}, status=status)+++def create_app():+ requests, libraries = [], {}+ revoked, unordered = set(), set()+ control = {"auth_mode": "api_key", "fail": None, "tool_delay": 0}++ def library(name):+ return libraries.setdefault(+ name, {"sessions": {}, "recalls": [], "tool_calls": [], "archives": {}}+ )++ async def controls(request):+ if request.path == "/_records":+ return web.json_response({"requests": requests, "libraries": libraries})+ if request.method != "POST":+ raise web.HTTPMethodNotAllowed(request.method, ["POST"])+ body = await request.json() if request.can_read_body else {}+ if request.path == "/_fail":+ control["fail"] = int(body.get("status", 503)) if body.get("on", True) else None+ elif request.path == "/_revoke":+ revoked.add(body["key"])+ elif request.path == "/_unorder":+ unordered.add(body["key"])+ elif request.path == "/_auth_mode":+ control["auth_mode"] = body["mode"]+ elif request.path == "/_tool_delay":+ control["tool_delay"] = float(body["seconds"])+ else:+ raise web.HTTPNotFound()+ return web.json_response({"status": "ok", **control})++ @web.middleware+ async def record_and_auth(request, handler):+ if request.path.startswith("/_"):+ return await controls(request)+ body = await request.json() if request.can_read_body else {}+ key = request.headers.get("X-API-Key", "")+ name = KEYS.get(key)+ record = {+ "source_pod": request.remote,+ "key": key,+ "method": request.method,+ "path": request.path,+ "body": body,+ "status": None,+ }+ requests.append(record)+ request["record"], request["body"] = record, body+ fault = control["fail"]+ known_path = request.path in {+ "/health",+ "/mcp",+ "/api/v1/system/status",+ "/api/v1/skills",+ "/api/v1/fs/ls",+ "/api/v1/content/read",+ "/api/v1/search/search",+ "/api/v1/sessions",+ } or request.path.startswith("/api/v1/sessions/")+ if fault:+ response = failure(fault, "UNAVAILABLE")+ elif not known_path:+ response = failure(404, "NOT_FOUND")+ elif control["auth_mode"] != "dev" and (key in revoked or (not name and key)):+ response = failure(401, "UNAUTHENTICATED")+ elif control["auth_mode"] != "dev" and key in unordered and request.path == "/health":+ response = failure(402, "ProductUnordered")+ elif not name and not key and request.path != "/health" and control["auth_mode"] != "dev":+ response = failure(401, "UNAUTHENTICATED")+ else:+ request["library"] = library(name or "library-a")+ request["library_name"] = name or "library-a"+ try:+ response = await handler(request)+ except web.HTTPException as error:+ record["status"] = error.status+ raise+ record["status"] = response.status+ return response++ def recall_result(request, body):+ name = request["library_name"]+ entry = {+ "uri": f"viking://user/default/memories/{name}.md",+ "text": f"Memory from {name}: blue cluster.",+ "score": 1.0,+ }+ entries = [] if entry["uri"] in body.get("exclude_uris", []) else [entry]+ return {+ "entries": entries,+ "rendered": "\n\n".join(e["uri"] + "\n" + e["text"] for e in entries),+ }++ async def handle(request):+ path, body, data = request.path, request["body"], request["library"]+ if path == "/health":+ result = {+ "status": "ok",+ "healthy": True,+ "version": "0.5.2",+ "auth_mode": control["auth_mode"],+ }+ if KEYS.get(request["record"]["key"]):+ result.update(account_id="default", user_id="default", role="admin")+ return web.json_response(result)+ if path == "/api/v1/system/status":+ return ok({"user": "default"})+ if path == "/api/v1/skills":+ return ok({"skills": []})+ if path == "/api/v1/fs/ls":+ return ok(+ [{"name": "default", "isDir": True}]+ if request.query.get("uri") == "viking://user"+ else []+ )+ if path == "/api/v1/search/search":+ result = recall_result(request, body)+ data["recalls"].append({**request["record"], "result": result, "status": 200})+ return ok(result)+ if path == "/api/v1/sessions" and request.method == "POST":+ sid = body["session_id"]+ if sid in data["sessions"]:+ return failure(409, "CONFLICT")+ data["sessions"][sid] = {+ "session_id": sid,+ "messages": [],+ "pending": [],+ "commits": [],+ }+ return ok({"session_id": sid})+ if path.startswith("/api/v1/sessions/"):+ parts = path.split("/")+ sid = parts[4]+ session = data["sessions"].get(sid)+ if session is None:+ return failure(404, "NOT_FOUND")+ if path.endswith("/messages/batch") and request.method == "POST":+ session["messages"].extend(copy.deepcopy(body["messages"]))+ session["pending"].extend(copy.deepcopy(body["messages"]))+ return ok(+ {+ "added": len(body["messages"]),+ "pending_tokens": len(json.dumps(session["pending"])) // 3,+ }+ )+ if path.endswith("/commit") and request.method == "POST":+ keep = max(0, int(body.get("keep_recent_count", 0)))+ archived = session["pending"][:-keep] if keep else session["pending"][:]+ session["pending"] = session["pending"][-keep:] if keep else []+ uri = f"viking://user/default/sessions/{sid}/history/archive_{len(session['commits']) + 1:03d}"+ commit = {+ "archive_uri": uri,+ "messages": archived,+ "keep_recent_count": keep,+ "key": request["record"]["key"],+ "time": time.time(),+ }+ session["commits"].append(commit)+ data["archives"][uri] = archived+ return ok({"archive_uri": uri})+ if request.method == "GET":+ return ok(+ {+ "session_id": sid,+ "pending_tokens": len(json.dumps(session["pending"])) // 3+ if session["pending"]+ else 0,+ "messages": session["pending"],+ }+ )+ if path == "/api/v1/content/read":+ uri = request.query.get("uri", "")+ if uri.removesuffix("/.done") in data["archives"] and uri.endswith("/.done"):+ return ok("")+ if uri in data["archives"]:+ return ok(json.dumps(data["archives"][uri]))+ return failure(404, "NOT_FOUND")+ if path == "/mcp":+ method, params = body.get("method"), body.get("params", {})+ if method == "tools/list":+ result = {"tools": TOOLS}+ elif method == "tools/call":+ call = {+ **request["record"],+ "name": params.get("name"),+ "arguments": params.get("arguments", {}),+ }+ data["tool_calls"].append(call)+ await asyncio.sleep(control["tool_delay"])+ if params.get("name") != "search":+ return web.json_response(+ {+ "jsonrpc": "2.0",+ "id": body.get("id"),+ "error": {"code": -32602, "message": "Unknown tool"},+ }+ )+ result = {+ "content": [+ {+ "type": "text",+ "text": recall_result(request, params.get("arguments", {}))["rendered"],+ }+ ],+ "isError": False,+ }+ elif method == "initialize":+ result = {+ "protocolVersion": "2025-06-18",+ "capabilities": {"tools": {}},+ "serverInfo": {"name": "mock-ov", "version": "1"},+ }+ else:+ return web.json_response(+ {+ "jsonrpc": "2.0",+ "id": body.get("id"),+ "error": {"code": -32601, "message": "Method not found"},+ }+ )+ return web.json_response({"jsonrpc": "2.0", "id": body.get("id"), "result": result})+ raise web.HTTPNotFound()++ app = web.Application(middlewares=[record_and_auth], client_max_size=32 * 1024**2)+ app.router.add_route("*", "/{path:.*}", handle)+ return app+++if __name__ == "__main__":+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--host", default="0.0.0.0")+ parser.add_argument("--port", type=int, default=int(os.environ.get("PORT", "1933")))+ args = parser.parse_args()+ web.run_app(create_app(), host=args.host, port=args.port, access_log=None)diff --git a/tests/gateway/e2e/sdk_probe.py b/tests/gateway/e2e/sdk_probe.pynew file mode 100644index 000000000..bf3dd3e97--- /dev/null+++ b/tests/gateway/e2e/sdk_probe.py@@ -0,0 +1,187 @@+"""Run actual OpenAI, Anthropic and Codex stream parsers against a gateway URL."""++import argparse+import asyncio+import json+import os+import shutil+import tempfile+import time+from pathlib import Path+++async def probe(base_url, api_key, model="mock-silent", minimum_seconds=39, read_timeout=20):+ """Return parser results; any missing dependency or failed assertion fails the probe."""+ import anthropic+ import openai++ base_url = base_url.rstrip("/")+ expected = "mock response complete"++ async def sdk(kind):+ started = time.monotonic()+ options = {"api_key": api_key, "max_retries": 0, "timeout": read_timeout}+ if kind == "anthropic":+ async with anthropic.AsyncAnthropic(base_url=base_url, **options) as client:+ async with client.messages.stream(+ model=model, max_tokens=64, messages=[{"role": "user", "content": "Hi"}]+ ) as stream:+ text = "".join([part async for part in stream.text_stream])+ message = await stream.get_final_message()+ assert message.stop_reason == "end_turn", message.stop_reason+ else:+ async with openai.AsyncOpenAI(base_url=base_url + "/v1", **options) as client:+ if kind == "openai-chat":+ stream = await client.chat.completions.create(+ model=model, messages=[{"role": "user", "content": "Hi"}], stream=True+ )+ chunks = [chunk async for chunk in stream]+ text = "".join(+ chunk.choices[0].delta.content or "" for chunk in chunks if chunk.choices+ )+ assert any(+ chunk.choices and chunk.choices[0].finish_reason == "stop"+ for chunk in chunks+ )+ else:+ async with client.responses.stream(+ model=model, input="Hi", store=False+ ) as stream:+ async for _ in stream:+ pass+ final = await stream.get_final_response()+ assert final.status == "completed", final.status+ text = final.output_text+ elapsed = time.monotonic() - started+ assert text == expected, (kind, text)+ assert elapsed >= minimum_seconds, (kind, elapsed, minimum_seconds)+ return {+ "client": kind,+ "status": "passed",+ "text": text,+ "elapsed_seconds": round(elapsed, 3),+ }++ async def codex():+ executable = shutil.which("codex")+ if executable is None:+ raise RuntimeError("codex executable is required for the Codex parser probe")+ started = time.monotonic()+ provider = {+ "name": "Gateway e2e",+ "base_url": base_url + "/v1",+ "env_key": "OV_E2E_CODEX_API_KEY",+ "wire_api": "responses",+ # Codex times parsed events; SSE comments only renew the HTTP byte timeout.+ "stream_idle_timeout_ms": max(60000, int(read_timeout * 1000)),+ }+ provider_toml = (+ "{" + ",".join(f"{key}={json.dumps(value)}" for key, value in provider.items()) + "}"+ )+ with tempfile.TemporaryDirectory(prefix="gateway-sdk-probe-") as directory:+ command = [+ executable,+ "exec",+ "--ignore-user-config",+ "--ignore-rules",+ "--ephemeral",+ "--skip-git-repo-check",+ "--json",+ "--cd",+ directory,+ "--sandbox",+ "read-only",+ "--model",+ model,+ "--config",+ 'model_provider="gateway_e2e"',+ "--config",+ "model_providers.gateway_e2e=" + provider_toml,+ "--config",+ 'model_reasoning_effort="low"',+ "Reply briefly without calling any tools.",+ ]+ process = await asyncio.create_subprocess_exec(+ *command,+ env={**os.environ, "OV_E2E_CODEX_API_KEY": api_key},+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ )+ try:+ stdout, stderr = await asyncio.wait_for(+ process.communicate(), max(120, minimum_seconds + 60)+ )+ except BaseException:+ if process.returncode is None:+ process.kill()+ await process.wait()+ raise+ if process.returncode:+ raise RuntimeError(f"Codex exit {process.returncode}: {stderr.decode()[-2000:]}")+ events = [json.loads(line) for line in stdout.splitlines() if line.strip()]+ messages = [+ event["item"].get("text", "")+ for event in events+ if event.get("type") == "item.completed"+ and event.get("item", {}).get("type") == "agent_message"+ ]+ assert expected in messages, messages+ assert any(event.get("type") == "turn.completed" for event in events), events+ elapsed = time.monotonic() - started+ assert elapsed >= minimum_seconds, ("codex", elapsed, minimum_seconds)+ return {+ "client": "codex",+ "status": "passed",+ "text": expected,+ "elapsed_seconds": round(elapsed, 3),+ "stream_idle_timeout_seconds": provider["stream_idle_timeout_ms"] / 1000,+ }++ outcomes = await asyncio.gather(+ sdk("openai-chat"),+ sdk("openai-responses"),+ sdk("anthropic"),+ codex(),+ return_exceptions=True,+ )+ labels = ("openai-chat", "openai-responses", "anthropic", "codex")+ results = [+ {"client": label, "status": "failed", "error": f"{type(value).__name__}: {value}"}+ if isinstance(value, BaseException)+ else value+ for label, value in zip(labels, outcomes, strict=True)+ ]+ return {+ "versions": {"openai": openai.__version__, "anthropic": anthropic.__version__},+ "model": model,+ "minimum_seconds": minimum_seconds,+ "read_timeout_seconds": read_timeout,+ "results": results,+ "passed": all(result["status"] == "passed" for result in results),+ }+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--base-url", required=True, help="Gateway origin, without /v1")+ parser.add_argument("--api-key-env", default="OV_TEST_API_KEY")+ parser.add_argument("--model", default="mock-silent")+ parser.add_argument("--minimum-seconds", type=float, default=39)+ parser.add_argument("--read-timeout", type=float, default=20)+ parser.add_argument("--output", type=Path)+ args = parser.parse_args()+ key = os.environ.get(args.api_key_env)+ if not key:+ parser.error(f"Set {args.api_key_env} to a gateway test key")+ report = asyncio.run(+ probe(args.base_url, key, args.model, args.minimum_seconds, args.read_timeout)+ )+ rendered = json.dumps(report, indent=2)+ if args.output:+ args.output.write_text(rendered + "\n")+ print(rendered)+ return 0 if report["passed"] else 1+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/gateway/e2e/test_resilience.py b/tests/gateway/e2e/test_resilience.pynew file mode 100644index 000000000..ad6009fa5--- /dev/null+++ b/tests/gateway/e2e/test_resilience.py@@ -0,0 +1,425 @@+"""Streaming, rollout, cache failure and startup acceptance scenarios."""++import asyncio+import json+import time+from concurrent.futures import ThreadPoolExecutor++import httpx+import pytest++from .harness import (+ CHAT,+ chat,+ control,+ credential_keys,+ document,+ records,+ session_keys,+ wait_for,+ written_messages,+)+from .sdk_probe import probe+++def stream_body(model="mock-long", messages=None):+ return {+ "model": model,+ "stream": True,+ "messages": messages or [{"role": "user", "content": "stream continuity"}],+ }+++def read_stream(+ harness, pod, model="mock-silent", session="stream", after_first=None, messages=None+):+ lines, timestamps = [], []+ try:+ with harness.stream(+ pod, stream_body(model, messages), headers={"X-OpenViking-Session": session}+ ) as response:+ encoding = response.headers.get("content-encoding")+ for line in response.iter_lines():+ if line:+ lines.append(line)+ timestamps.append(time.monotonic())+ if len(lines) == 1 and after_first:+ after_first()+ except httpx.RemoteProtocolError:+ return {"lines": lines, "times": timestamps, "truncated": True}+ return {"lines": lines, "times": timestamps, "encoding": encoding, "truncated": False}+++def test_02_default_grace_finishes_stream_and_other_pod_delivers(harness):+ harness.redeploy({"default_profile": {"idle_seconds": 45}})+ victim, _ = harness.pods()+ victim_ip = next(+ p["status"]["podIP"] for p in harness.pod_objects() if p["metadata"]["name"] == victim+ )+ history = [{"role": "user", "content": "first pending turn"}]+ history.append(chat(harness, victim, "graceful", history))+ history.append({"role": "user", "content": "finish during termination"})+ result = read_stream(+ harness,+ victim,+ session="graceful",+ messages=history,+ after_first=lambda: harness.kubectl("delete", "pod", victim, "--wait=false"),+ )+ assert "data: [DONE]" in result["lines"] and not result["truncated"]+ snapshot = wait_for(+ lambda: value if len(written_messages(value := records(harness))) == 4 else None,+ timeout=110,+ )+ assert len(snapshot["libraries"]["library-a"]["sessions"]) == 1+ writes = [r for r in snapshot["requests"] if r["path"].endswith("/messages/batch")]+ assert all(r["source_pod"] != victim_ip for r in writes), writes+ ids = [+ source for r in writes for m in r["body"]["messages"] for source in m["source_message_ids"]+ ]+ assert len(ids) == len(set(ids)) == 4+++def test_03_short_grace_truncates_stream_without_splitting_next_turn(harness):+ victim, _ = harness.pods()+ result = read_stream(+ harness,+ victim,+ model="mock-long",+ session="short-grace",+ after_first=lambda: harness.kubectl(+ "delete", "pod", victim, "--grace-period=25", "--wait=false"+ ),+ )+ assert "data: [DONE]" not in result["lines"], "the negative control must outlive the 25s grace"+ assert result["times"][-1] - result["times"][0] < 40+ pod = next(p for p in harness.pods() if p != victim)+ chat(harness, pod, "short-grace", [{"role": "user", "content": "continue after truncation"}])+ _, capture = session_keys(harness, "short-grace")+ wait_for(lambda: not document(harness, capture).get("pending"))+ sessions = records(harness)["libraries"]["library-a"]["sessions"]+ assert len(sessions) == 1+ assert len(next(iter(sessions.values()))["messages"]) == 2+++ROLLOUT_CLIENT = """+import asyncio, http.client, json, time+import aiohttp+base = "http://gateway:1935"+headers = {"Authorization": "Bearer key-a"}+results = {"short": 0, "chat": 0, "keepalive": 0, "keepalive_reuses": 0, "keepalive_connections": 0, "raw_keepalive_reused": False, "errors": [], "done": False}+async def lane(name):+ async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(force_close=True)) as client:+ for i in range(120):+ try:+ if name == "short":+ response = await client.get(base + "/health")+ else:+ response = await client.post(base + "/gateway/v1/chat/completions", headers=headers,+ json={"model":"mock", "messages":[{"role":"user","content":str(i)}]})+ await response.read()+ assert response.status == 200, response.status+ results[name] += 1+ except Exception as error:+ results["errors"].append([name, type(error).__name__, str(error)])+ await asyncio.sleep(.5)+async def keepalive():+ trace = aiohttp.TraceConfig()+ async def reused(session, context, params):+ results["keepalive_reuses"] += 1+ async def created(session, context, params):+ results["keepalive_connections"] += 1+ trace.on_connection_reuseconn.append(reused)+ trace.on_connection_create_end.append(created)+ async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(keepalive_timeout=75),+ timeout=aiohttp.ClientTimeout(total=15), trace_configs=[trace]) as client:+ for _ in range(10):+ try:+ async with client.get(base + "/health") as response:+ await response.read()+ assert response.status == 200+ results["keepalive"] += 1+ except Exception as error:+ results["errors"].append(["keepalive", type(error).__name__, str(error)])+ await asyncio.sleep(6)+async def long_stream():+ async with aiohttp.ClientSession() as client:+ async with client.post(base + "/gateway/v1/chat/completions", headers=headers,+ json={"model":"mock-long","stream":True,"messages":[{"role":"user","content":"long rollout"}]}) as r:+ assert r.status == 200+ body = await r.text()+ results["done"] = "data: [DONE]" in body+def raw_idle_reuse():+ connection = http.client.HTTPConnection("RAW_GATEWAY_HOST", 1935, timeout=15)+ try:+ connection.request("GET", "/health")+ response = connection.getresponse()+ response.read()+ assert response.status == 200+ original = connection.sock+ assert original is not None+ time.sleep(6)+ connection.request("GET", "/health")+ response = connection.getresponse()+ response.read()+ assert response.status == 200 and connection.sock is original+ results["raw_keepalive_reused"] = True+ finally:+ connection.close()+async def main():+ await asyncio.to_thread(raw_idle_reuse)+ await asyncio.gather(lane("short"), lane("chat"), keepalive(), long_stream())+ print(json.dumps(results))+asyncio.run(main())+"""+++def test_04_rollout_preserves_three_traffic_lanes_and_long_stream(harness):+ runner = json.loads(harness.kubectl("get", "pods", "-l", "app=mock-ov", "-o", "json"))["items"][+ 0+ ]["metadata"]["name"]+ with ThreadPoolExecutor() as executor:+ running = executor.submit(+ harness.kubectl,+ "exec",+ "-i",+ runner,+ "--",+ "python",+ "-",+ input=ROLLOUT_CLIENT.replace(+ "RAW_GATEWAY_HOST", harness.pod_objects()[0]["status"]["podIP"]+ ),+ timeout=110,+ )+ wait_for(+ lambda: any(+ r["body"].get("model") == "mock-long" for r in records(harness, "ark")["requests"]+ )+ )+ harness.kubectl("rollout", "restart", "deployment/gateway")+ result = json.loads(running.result(timeout=115))+ (harness.directory / "rollout-traffic.json").write_text(json.dumps(result, indent=2))+ assert result["errors"] == [], result+ assert (result["short"], result["chat"], result["keepalive"]) == (120, 120, 10), result+ # A real pool observes the FIN when a draining Pod closes an idle connection.+ assert result["raw_keepalive_reused"], result+ assert result["keepalive_reuses"] >= 7, result+ assert 1 <= result["keepalive_connections"] <= 3, result+ assert result["done"], result+ harness.kubectl("rollout", "status", "deployment/gateway", "--timeout=120s")+++def test_05_eviction_keeps_permanent_state_and_recovers_credentials(harness):+ pods = harness.pods()+ permanent = "ovgw:v1:m:{a-e2e}:o:policies:permanent"+ tombstone = "ovgw:v1:kd:{deleted-e2e}"+ ready = "ovgw:v1:k:{cap}:ready"+ harness.redis("HSET", permanent, "v", '{"name":"permanent"}', "rev", 1)+ harness.redis("SET", tombstone, 1)+ harness.redis("CONFIG", "SET", "maxmemory", "30mb")+ big = "retained context " * 8192++ def send(number):+ return chat(+ harness,+ pods[number % 2],+ f"eviction-{number}",+ [{"role": "user", "content": f"{number}: {big}"}],+ idle_seconds=120,+ )++ with ThreadPoolExecutor(max_workers=12) as executor:+ list(executor.map(send, range(200)))+ stats = dict(+ line.split(":", 1) for line in harness.redis("INFO", "stats").splitlines() if ":" in line+ )+ assert int(stats["evicted_keys"]) > 0, stats+ assert harness.redis("EXISTS", permanent) == "1"+ assert harness.redis("EXISTS", tombstone) == "1"+ assert harness.redis("TTL", permanent) == harness.redis("TTL", tombstone) == "-1"+ assert harness.redis("TYPE", ready) == "zset" and harness.redis("TTL", ready) == "-1"+ chat(harness, pods[1], "eviction-0", [{"role": "user", "content": "continue after eviction"}])+ harness.redis("CONFIG", "SET", "maxmemory", "96mb")+ chat(+ harness,+ pods[0],+ "credential-rebuild",+ [{"role": "user", "content": "pending before key deletion"}],+ )+ _, capture = session_keys(harness, "credential-rebuild")+ for key in credential_keys(harness, "key-a"):+ harness.redis("DEL", key)+ wait_for(+ lambda: (+ (document(harness, capture).get("error") or {}).get("reason") == "gateway_key_revoked"+ ),+ timeout=40,+ )+ chat(+ harness,+ pods[1],+ "credential-rebuild",+ [{"role": "user", "content": "new request restores key"}],+ )+ assert credential_keys(harness, "key-a")+ wait_for(+ lambda: (+ not document(harness, capture).get("error")+ and not document(harness, capture).get("pending")+ ),+ timeout=90,+ )+ assert "KeyError" not in harness.logs()+++def stop_redis(harness, aof):+ harness.kubectl("scale", "statefulset/redis", "--replicas=0")+ harness.kubectl("wait", "--for=delete", "pod/redis-0", "--timeout=40s")+ if not aof:+ value = json.loads(harness.kubectl("get", "statefulset/redis", "-o", "json"))+ args = value["spec"]["template"]["spec"]["containers"][0]["args"]+ args[args.index("--appendonly") + 1] = "no"+ harness.kubectl(+ "patch",+ "statefulset/redis",+ "--type=json",+ "-p",+ json.dumps(+ [{"op": "replace", "path": "/spec/template/spec/containers/0/args", "value": args}]+ ),+ )+++def outage_requests(harness, pod):+ counts = {"degraded": 0, "authentication_500": 0}+ for number in range(5):+ response = harness.request(+ pod,+ "POST",+ CHAT,+ json={+ "model": "mock",+ "messages": [{"role": "user", "content": f"redis outage {number}"}],+ },+ )+ if response.status_code == 200:+ counts["degraded"] += 1+ else:+ assert response.status_code == 500 and response.headers["content-type"].startswith(+ "text/plain"+ ), response.text+ counts["authentication_500"] += 1+ (harness.directory / "redis-outage.json").write_text(json.dumps(counts))+ if counts["degraded"]:+ assert "memory_store_failure" in harness.logs()+ return counts+++def test_06_aof_restart_preserves_management_tombstones_and_pending_capture(harness):+ harness.redeploy({"default_profile": {"idle_seconds": 45}})+ pod = harness.pods()[0]+ chat(harness, pod, "aof-tail", [{"role": "user", "content": "persist this pending tail"}])+ _, capture = session_keys(harness, "aof-tail")+ keys = credential_keys(harness, "key-a")+ tombstone = "ovgw:v1:kd:{aof-deleted-scope}"+ harness.redis("SET", tombstone, 1)+ stop_redis(harness, aof=True)+ outage_requests(harness, pod)+ harness.kubectl("scale", "statefulset/redis", "--replicas=1")+ harness.kubectl("rollout", "status", "statefulset/redis", "--timeout=90s")+ assert harness.redis("EXISTS", tombstone) == "1"+ assert all(harness.redis("EXISTS", key) == "1" for key in keys)+ assert document(harness, capture)+ wait_for(lambda: len(written_messages(records(harness))) >= 2, timeout=90)+ assert not document(harness, capture).get("pending")+++def test_07_restart_without_aof_loses_tail_but_recreates_key(harness):+ harness.redeploy({"default_profile": {"idle_seconds": 120}})+ pod = harness.pods()[0]+ chat(harness, pod, "lost-tail", [{"role": "user", "content": "nonpersistent pending tail"}])+ _, capture = session_keys(harness, "lost-tail")+ old_keys = harness.redis_keys("ovgw:*")+ assert old_keys and document(harness, capture)["pending"]+ stop_redis(harness, aof=False)+ harness.kubectl("scale", "statefulset/redis", "--replicas=1")+ harness.kubectl("rollout", "status", "statefulset/redis", "--timeout=90s")+ assert harness.redis("DBSIZE") == "0"+ chat(harness, pod, "fresh-after-restart", [{"role": "user", "content": "recreated credential"}])+ assert credential_keys(harness, "key-a") and not document(harness, capture)+ assert all(+ all(c["restartCount"] == 0 for c in p["status"]["containerStatuses"])+ for p in harness.pod_objects()+ )+++def rollout_candidates(harness, marker):+ pods = json.loads(+ harness.kubectl("get", "pods", "-l", "app.kubernetes.io/instance=gateway", "-o", "json")+ )["items"]+ return [p for p in pods if p["metadata"].get("annotations", {}).get("e2e-startup") == marker]+++def test_10_startup_waits_for_503_but_rejects_dev_and_404(harness):+ control(harness, "/_fail", status=503)+ harness.redeploy({}, {"podAnnotations": {"e2e-startup": "unavailable"}}, wait=False)+ pods = wait_for(lambda: rollout_candidates(harness, "unavailable"))+ pod = pods[0]["metadata"]["name"]+ wait_for(lambda: "waiting" in harness.kubectl("logs", pod, check=False).lower(), timeout=45)+ time.sleep(5)+ status = rollout_candidates(harness, "unavailable")[0]["status"]+ assert all(c["restartCount"] == 0 for c in status.get("containerStatuses", []))+ assert not any(c.get("ready") for c in status.get("containerStatuses", []))+ restored = time.monotonic()+ control(harness, "/_fail", on=False)+ # Time only the waiting pod's recovery; the rest of the rollout starts pods from scratch.+ wait_for(lambda: pod in harness.pods(), timeout=40)+ assert time.monotonic() - restored < 30+ harness.kubectl("rollout", "status", "deployment/gateway", "--timeout=120s", timeout=130)+ for marker, config in (+ ("dev", {}),+ ("notfound", {"openviking_url": "http://mock-ov:1933/notfound"}),+ ):+ control(harness, "/_auth_mode", mode="dev" if marker == "dev" else "api_key")+ harness.redeploy(config, {"podAnnotations": {"e2e-startup": marker}}, wait=False)++ def refused(marker=marker):+ for candidate in rollout_candidates(harness, marker):+ for container in candidate["status"].get("containerStatuses", []):+ terminated = container.get("state", {}).get("terminated") or container.get(+ "lastState", {}+ ).get("terminated")+ if terminated and terminated["exitCode"] != 0:+ return candidate++ wait_for(refused, timeout=35)+++def test_11_sse_heartbeats_preserve_actual_client_parsers(harness):+ pod = harness.pods()[0]+ with ThreadPoolExecutor(max_workers=2) as executor:+ plain = executor.submit(read_stream, harness, pod, "mock-silent", "heartbeat-raw")+ encoded = executor.submit(read_stream, harness, pod, "mock-silent-gzip", "heartbeat-gzip")+ result = asyncio.run(probe(harness.url(pod) + "/gateway", "key-a"))+ (harness.directory / "sdk-probe.json").write_text(json.dumps(result, indent=2))+ assert result["passed"], result+ plain, encoded = plain.result(), encoded.result()+ comments = [+ stamp+ for line, stamp in zip(plain["lines"], plain["times"], strict=True)+ if line.startswith(":")+ ]+ assert len(comments) >= 2, plain+ assert 10 <= comments[0] - plain["times"][0] <= 20+ assert 10 <= comments[1] - comments[0] <= 20+ assert "data: [DONE]" in plain["lines"]+ assert encoded["encoding"] == "gzip"+ assert not any(line.startswith(":") for line in encoded["lines"])+ assert "data: [DONE]" in encoded["lines"]diff --git a/tests/gateway/e2e/test_sessions.py b/tests/gateway/e2e/test_sessions.pynew file mode 100644index 000000000..ee823da48--- /dev/null+++ b/tests/gateway/e2e/test_sessions.py@@ -0,0 +1,436 @@+"""Cross-pod session, tenant, delivery and encryption acceptance scenarios."""++import json+import time+from collections import Counter+from concurrent.futures import ThreadPoolExecutor++import pytest++from .harness import (+ ADMIN,+ CHAT,+ MODELS,+ account,+ chat,+ control,+ credential_keys,+ document,+ message_text,+ records,+ scope,+ session_keys,+ wait_for,+ written_messages,+)+++def assert_delivery(snapshot, expected, library="library-a", key="key-a"):+ messages = written_messages(snapshot, library)+ assert [(m["role"], message_text(m)) for m in messages] == [+ (m["role"], m["content"]) for m in expected+ ]+ # Inspect HTTP batches too: a mock that deduplicates IDs must not hide duplicate delivery.+ writes = [+ message+ for request in snapshot["requests"]+ if request["key"] == key+ and request["path"].endswith("/messages/batch")+ and request["status"] == 200+ for message in request["body"]["messages"]+ ]+ ids = [source for message in writes for source in message["source_message_ids"]]+ assert len(ids) == len(expected)+ assert set(Counter(ids).values()) == {1}+ assert writes == messages+++def test_01_session_continues_across_pods(harness):+ pods = harness.pods()+ assert len(pods) == 2+ models = [harness.request(pod, "GET", MODELS, key="key-a") for pod in pods]+ assert [r.status_code for r in models] == [200, 200]+ assert models[0].json() == models[1].json()+ messages = []+ for turn in range(8):+ messages.append({"role": "user", "content": f"continuity turn {turn}"})+ messages.append(chat(harness, pods[turn % 2], "eight-turns", messages))+ replay, capture = session_keys(harness, "eight-turns")+ wait_for(lambda: not document(harness, capture).get("pending"))+ snapshot = records(harness)+ assert len(snapshot["libraries"]["library-a"]["sessions"]) == 1+ assert_delivery(snapshot, messages)+ assert harness.redis_keys(f"*k:{{{scope()}}}:rp:*") == [replay]+ assert harness.redis_keys(f"*k:{{cap}}:{scope()}:*") == [capture]+ assert document(harness, capture)["previous"] == []+++def test_08_same_identity_libraries_are_isolated(harness):+ pods = harness.pods()+ histories = {"key-a": [], "key-b": []}+ for turn in range(2):+ for index, key in enumerate(histories):+ history = histories[key]+ history.append({"role": "user", "content": f"private {key} turn {turn}"})+ history.append(chat(harness, pods[(turn + index) % 2], "same-client-id", history, key))+ captures = {}+ for key in histories:+ _, captures[key] = session_keys(harness, "same-client-id", key)+ wait_for(lambda key=key: not document(harness, captures[key]).get("pending"))+ assert captures["key-a"] != captures["key-b"]+ snapshot = records(harness)+ for key, library in (("key-a", "library-a"), ("key-b", "library-b")):+ assert len(snapshot["libraries"][library]["sessions"]) == 1+ assert_delivery(snapshot, histories[key], library, key)+ recalls = snapshot["libraries"][library]["recalls"]+ assert len(recalls) == 2, recalls+ assert all(key in json.dumps(recall) for recall in recalls)+ assert document(harness, captures[key])["account"] == account(key)+ ark = records(harness, "ark")["requests"]+ for request in ark:+ text = json.dumps(request["body"])+ own = "library-a" if "private key-a" in text else "library-b"+ other = "library-b" if own == "library-a" else "library-a"+ assert own in text and other not in text, text+ log = harness.logs()+ assert account("key-a") in log and account("key-b") in log+++def test_09_revocation_pauses_capture_and_replacement_uses_new_partition(harness):+ pods = harness.pods()+ chat(harness, pods[0], "revoked-tail", [{"role": "user", "content": "pending secret"}])+ _, capture = session_keys(harness, "revoked-tail")+ assert document(harness, capture)["pending"]+ control(harness, "/_revoke", key="key-a")+ wait_for(+ lambda: (+ (document(harness, capture).get("error") or {}).get("reason") == "gateway_key_revoked"+ ),+ )+ snapshot = records(harness)+ refused = [r for r in snapshot["requests"] if r["key"] == "key-a" and r["status"] == 401]+ assert any(r["path"].startswith("/api/v1/sessions") for r in refused), refused+ assert not credential_keys(harness, "key-a")+ response = harness.request(+ pods[1],+ "POST",+ CHAT,+ key="key-a",+ json={+ "model": "mock",+ "messages": [{"role": "user", "content": "refused"}],+ },+ )+ assert response.status_code == 401, response.text+ count = sum(r["key"] == "key-a" for r in records(harness)["requests"])+ # Exceed the first failure retry interval, proving the paused tail is not retried.+ time.sleep(12)+ assert sum(r["key"] == "key-a" for r in records(harness)["requests"]) == count+ chat(+ harness, pods[1], "revoked-tail", [{"role": "user", "content": "replacement"}], "key-a-new"+ )+ _, replacement = session_keys(harness, "revoked-tail", "key-a-new")+ assert replacement != capture+ assert document(harness, replacement)["account"] == account("key-a-new")+ assert document(harness, capture)["error"]["retry_at"] is None+++def test_12_capture_workers_deliver_one_hundred_sessions_once(harness):+ pods = harness.pods()+ for pod in pods:+ assert harness.request(pod, "GET", "/health").status_code == 200+ started = time.monotonic()++ def send(number):+ message = {"role": "user", "content": f"capture race {number:03d}"}+ answer = chat(harness, pods[number % 2], f"capture-race-{number}", [message])+ return message, answer++ with ThreadPoolExecutor(max_workers=32) as executor:+ expected = list(executor.map(send, range(100)))+ snapshot = wait_for(+ lambda: s if len(written_messages(s := records(harness))) == 200 else None,+ timeout=120,+ )+ assert time.monotonic() - started < 180+ sessions = snapshot["libraries"]["library-a"]["sessions"]+ assert len(sessions) == 100+ delivered = {+ message_text(value["messages"][0]): value["messages"] for value in sessions.values()+ }+ assert len(delivered) == 100+ for question, answer in expected:+ assert [(m["role"], message_text(m)) for m in delivered[question["content"]]] == [+ ("user", question["content"]),+ ("assistant", answer["content"]),+ ]+ writes = [r for r in snapshot["requests"] if r["path"].endswith("/messages/batch")]+ ids = [+ source for r in writes for m in r["body"]["messages"] for source in m["source_message_ids"]+ ]+ assert len(ids) == 200 and set(Counter(ids).values()) == {1}+ assert len({r["source_pod"] for r in writes}) == 2+ captures = harness.redis_keys(f"*k:{{cap}}:{scope()}:*")+ assert len(captures) == 100+ for capture in captures:+ value = document(harness, capture)+ assert value["pending"] == [] and not value["error"]+ assert len(harness.redis_keys(f"*k:{{{scope()}}}:rp:*")) == 100+++def test_13_unordered_existing_key_never_reaches_upstream(harness):+ pods = harness.pods()+ chat(harness, pods[0], "ordered", [{"role": "user", "content": "initial request"}])+ assert credential_keys(harness, "key-a")+ control(harness, "/_unorder", key="key-a")+ before = len(records(harness, "ark")["requests"])+ response = harness.request(+ pods[1],+ "POST",+ CHAT,+ key="key-a",+ json={+ "model": "mock",+ "messages": [{"role": "user", "content": "unpaid request"}],+ },+ )+ assert response.status_code == 402, response.text+ assert len(records(harness, "ark")["requests"]) == before+ chat(harness, pods[1], "other-key", [{"role": "user", "content": "still ordered"}], "key-b")+ assert len(records(harness, "ark")["requests"]) == before + 1+++def test_14_tools_and_responses_cross_pods_with_evicted_receipt(harness):+ harness.redeploy(config={"default_profile": {"gateway_tools": True}})+ pods = harness.pods()+ question = {"role": "user", "content": "look up blue"}+ answer = chat(harness, pods[0], "hidden-tools", [question], model="mock-tools")+ chat(harness, pods[1], "hidden-tools", [question], model="mock-tools")+ calls = records(harness)["libraries"]["library-a"]["tool_calls"]+ assert len(calls) == 1, calls+ chat(+ harness,+ pods[1],+ "hidden-tools",+ [+ question,+ answer,+ {+ "role": "user",+ "content": "look up blue again",+ },+ ],+ model="mock-tools",+ )+ assert len(records(harness)["libraries"]["library-a"]["tool_calls"]) == 2+ _, capture = session_keys(harness, "hidden-tools")+ assert document(harness, capture)["previous"] == []+ previous = None+ for turn in range(4):+ body = {"model": "mock", "input": [{"role": "user", "content": f"response chain {turn}"}]}+ if previous:+ body["previous_response_id"] = previous+ response = harness.request(+ pods[turn % 2],+ "POST",+ "/gateway/v1/responses",+ key="key-a",+ json=body,+ headers={"X-OpenViking-Session": "responses-chain"},+ )+ assert response.status_code == 200, response.text+ previous = response.json()["id"]+ assert previous+ chain = [r for r in records(harness, "ark")["requests"] if r["path"] == "/v1/responses"]+ assert len(chain) == 4+ for turn, request in enumerate(chain):+ effective = json.dumps(request["effective_input"])+ assert all(f"response chain {earlier}" in effective for earlier in range(turn + 1))+ control(harness, "/_tool_delay", seconds=8)+ retry_history = [{"role": "user", "content": "evict this in-flight tool receipt"}]+ baseline = len(records(harness)["libraries"]["library-a"]["tool_calls"])+ with ThreadPoolExecutor(max_workers=2) as executor:+ first = executor.submit(+ chat, harness, pods[0], "evicted-tool", retry_history, model="mock-tools"+ )+ wait_for(+ lambda: len(records(harness)["libraries"]["library-a"]["tool_calls"]) == baseline + 1,+ interval=0.2,+ )+ receipts = [+ key+ for key in harness.redis_keys(f"*k:{{{scope()}}}:st:*")+ if "owner" in document(harness, key) and "content" not in document(harness, key)+ ]+ assert len(receipts) == 1, receipts+ before = len(records(harness, "ark")["requests"])+ second = executor.submit(+ chat, harness, pods[1], "evicted-tool", retry_history, model="mock-tools"+ )+ wait_for(lambda: len(records(harness, "ark")["requests"]) > before, interval=0.2)+ # The second provider response is immediate; allow its receipt waiter to start.+ time.sleep(0.5)+ assert not first.done() and not second.done()+ assert harness.redis("DEL", receipts[0]).strip() == "1"+ second.result(timeout=10)+ first.result(timeout=15)+ assert len(records(harness)["libraries"]["library-a"]["tool_calls"]) == baseline + 1+ retry_requests = records(harness, "ark")["requests"][before:]+ assert any("unknown outcome" in json.dumps(r["body"]) for r in retry_requests)+ assert "KeyError" not in harness.logs()+++def test_15_management_updates_and_revocations_propagate(harness):+ harness.redeploy(config={"management_api": True, "tenancy": "account", "management_key": ""})+ pods = harness.pods()+ studio = harness.request(pods[0], "GET", "/studio/", key="key-a")+ assert studio.status_code == 200 and "text/html" in studio.headers["content-type"]+ upstream = {+ "name": "managed",+ "protocol": "chat",+ "base_url": "http://mock-ark:8080/v1",+ "api_key": "managed-test-key",+ "models": ["mock"],+ }+ response = harness.request(+ pods[0], "PUT", ADMIN + "/upstreams/managed", key="key-a", json=upstream+ )+ assert response.status_code == 200, response.text+ response = harness.request(+ pods[0],+ "PUT",+ ADMIN + "/policies/default",+ key="key-a",+ json={"name": "Default", "idle_seconds": 5},+ )+ assert response.status_code == 200, response.text+ issued = harness.request(+ pods[0],+ "POST",+ ADMIN + "/keys",+ key="key-a",+ json={+ "name": "issued",+ "openviking_key": "key-a",+ "policy_id": "default",+ "upstream_ids": ["managed"],+ },+ )+ assert issued.status_code == 200, issued.text+ secret, identifier = issued.json()["key"], issued.json()["id"]+ chat(harness, pods[1], "managed-before", [{"role": "user", "content": "before update"}], secret)+ upstream["models"] = ["mock", "mock-tools"]+ response = harness.request(+ pods[0], "PUT", ADMIN + "/upstreams/managed", key="key-a", json=upstream+ )+ assert response.status_code == 200, response.text+ time.sleep(2.2)+ response = harness.request(pods[1], "GET", MODELS, key=secret)+ assert response.status_code == 200, response.text+ assert {row["id"] for row in response.json()["data"]} == {"mock", "mock-tools"}+ response = harness.request(pods[0], "DELETE", ADMIN + f"/keys/{identifier}", key="key-a")+ assert response.status_code == 200, response.text+ before = len(records(harness, "ark")["requests"])+ time.sleep(2.2)+ response = harness.request(+ pods[1],+ "POST",+ CHAT,+ key=secret,+ json={+ "model": "mock",+ "messages": [{"role": "user", "content": "after revoke"}],+ },+ )+ assert response.status_code == 401, response.text+ assert len(records(harness, "ark")["requests"]) == before+++def test_16_shared_root_key_decrypts_across_pods_and_missing_key_blocks_start(harness):+ harness.redeploy(config={"encryption": {"enabled": True, "provider": "local"}})++ # Plaintext Pods keep claiming captures during preStop and cannot decrypt them.+ def gateway_pods():+ listing = harness.kubectl(+ "get", "pods", "-l", "app.kubernetes.io/instance=gateway", "-o", "json"+ )+ return json.loads(listing)["items"]++ wait_for(lambda: len(gateway_pods()) == 2)+ pods = harness.pods()+ messages = [{"role": "user", "content": "encrypted session private marker"}]+ messages.append(chat(harness, pods[0], "encrypted-session", messages))+ replay, capture = session_keys(harness, "encrypted-session")+ assert (+ harness.redis(+ "EVAL",+ "return string.sub(redis.call('HGET',KEYS[1],ARGV[1]),1,4)",+ "1",+ replay,+ "root:",+ ).strip()+ == "OVE1"+ )+ root_hash = harness.redis(+ "EVAL", "return redis.sha1hex(redis.call('HGET',KEYS[1],ARGV[1]))", "1", replay, "root:"+ ).strip()+ messages.append({"role": "user", "content": "continue encrypted session"})+ messages.append(chat(harness, pods[1], "encrypted-session", messages))+ wait_for(lambda: len(written_messages(records(harness))) == 4)+ snapshot = records(harness)+ assert len(snapshot["libraries"]["library-a"]["sessions"]) == 1+ assert_delivery(snapshot, messages)+ assert session_keys(harness, "encrypted-session") == (replay, capture)+ assert (+ harness.redis(+ "EVAL", "return redis.sha1hex(redis.call('HGET',KEYS[1],ARGV[1]))", "1", replay, "root:"+ ).strip()+ == root_hash+ )+ harness.kubectl(+ "patch",+ "secret",+ "gateway-secrets",+ "--type=json",+ "-p",+ '[{"op":"remove","path":"/data/root-key"}]',+ )+ harness.redeploy(+ config={}, values={"podAnnotations": {"e2e/missing-root-key": "true"}}, wait=False+ )+ old = set(pods)++ # A new ReplicaSet cannot mount the root-key Secret item once the key is removed.+ def rejected_pod():+ result = json.loads(+ harness.kubectl("get", "pods", "-l", "app.kubernetes.io/instance=gateway", "-o", "json")+ )+ for pod in result["items"]:+ if pod["metadata"]["name"] in old:+ continue+ events = harness.kubectl(+ "get",+ "events",+ "--field-selector",+ "involvedObject.name=" + pod["metadata"]["name"],+ "-o",+ "json",+ )+ statuses = pod["status"].get("containerStatuses", [])+ if (+ "FailedMount" in events+ and "root-key" in events+ and not any(s.get("ready") for s in statuses)+ ):+ return pod+ return None++ rejected = wait_for(rejected_pod, timeout=90)+ assert not any(+ c.get("type") == "Ready" and c.get("status") == "True"+ for c in rejected["status"].get("conditions", [])+ )diff --git a/tests/gateway/test_capture_delivery.py b/tests/gateway/test_capture_delivery.pyindex ec8bbd4af..2a82a6eb5 100644--- a/tests/gateway/test_capture_delivery.py+++ b/tests/gateway/test_capture_delivery.py@@ -486,3 +486,67 @@ def test_history_hint_lists_sessions_and_follows_the_frozen_read_tool():assert history_hint("alice", ["new"], tools, False) == ""assert history_hint("alice", [], tools, True) == ""assert history_hint("alice", ["new"], grep_off, True) == ""+++async def test_delivery_401_removes_key_pauses_and_resumes_on_new_request(+ setup_kernel, credential, policy+):+ from openviking_gateway.client import VikingError++ _, store, viking, encryption = setup_kernel+ policy.update(recall=False, commit_tokens=1000000)+ chat = Conversation(setup_kernel, credential, policy)+ worker = await worker_for(store, encryption, credential, viking)+ first = await chat.reply([answer("Completed before revocation")])+ await make_due(store)+ original_write, original_identify, calls = viking.write, viking.identify, []++ async def refused(*args):+ calls.append(args)+ raise VikingError("openviking_http_401", 401)++ viking.write = refused+ viking.identify = refused+ assert await worker.once()+ # The write's 401 is confirmed on /health before the key is dropped.+ assert len(calls) == 2+ assert await worker.management.get("tenant", "keys", credential["id"]) is None+ assert (await chat.state(first))["error"]["reason"] == "openviking_http_401"+ await make_due(store)+ assert await worker.once()+ state = await chat.state(first)+ assert state["error"]["reason"] == "gateway_key_revoked"+ assert state["error"]["retry_at"] is None+ for _ in range(3):+ assert not await worker.once()+ assert len(calls) == 2+ await worker.management.save("tenant", "keys", credential["id"], credential)+ viking.write, viking.identify = original_write, original_identify+ await chat.say("Resume with a valid key")+ assert not (await chat.state(first))["error"]+ await make_due(store)+ assert await worker.once()+ assert viking.writes and not (await chat.state(first))["pending"]+ worker.management.close()+++async def test_delivery_401_keeps_key_when_health_accepts_it(setup_kernel, credential, policy):+ from openviking_gateway.client import VikingError++ _, store, viking, encryption = setup_kernel+ policy.update(recall=False, commit_tokens=1000000)+ chat = Conversation(setup_kernel, credential, policy)+ worker = await worker_for(store, encryption, credential, viking)+ first = await chat.reply([answer("OpenViking's own model key is invalid")])+ await make_due(store)++ async def refused(*args):+ raise VikingError("openviking_http_401", 401)++ viking.write = refused+ assert await worker.once()+ assert await worker.management.get("tenant", "keys", credential["id"])+ state = await chat.state(first)+ assert state["error"]["reason"] == "openviking_http_401"+ assert state["error"]["retry_at"] is not None+ worker.management.close()diff --git a/tests/gateway/test_context_overrides.py b/tests/gateway/test_context_overrides.pynew file mode 100644index 000000000..7998537ea--- /dev/null+++ b/tests/gateway/test_context_overrides.py@@ -0,0 +1,201 @@+"""X-OpenViking-Context: per-request overrides of the key's context profile."""++import json++import orjson+import pytest++CHAT = "/v1/chat/completions"+++def headers(key, session, context=None):+ values = {"Authorization": "Bearer " + key["key"], "X-OpenViking-Session": session}+ if context is not None:+ values["X-OpenViking-Context"] = (+ context if isinstance(context, str) else json.dumps(context)+ )+ return values+++def message(text):+ return {"model": "model", "messages": [{"role": "user", "content": text}]}+++def openviking_calls(app):+ """Record the OpenViking paths the gateway calls, besides its health checks."""+ calls = []++ async def handler(request):+ if request.path.startswith("/api/"):+ calls.append(request.path)++ app.state.test_backend["handler"] = handler+ return calls+++async def test_override_takes_effect_and_is_logged(running_gateway):+ app, client, admin, key, seen, _ = running_gateway+ calls = openviking_calls(app)+ response = await client.post(CHAT, headers=headers(key, "plain"), json=message("Deploy?"))+ assert response.status_code == 200, response.text+ assert "/api/v1/search/search" in calls+ calls.clear()+ response = await client.post(+ CHAT, headers=headers(key, "no-recall", {"recall": False}), json=message("Deploy?")+ )+ assert response.status_code == 200, response.text+ assert "/api/v1/search/search" not in calls+ assert "x-openviking-context" not in {name.lower() for name in seen[-1][2]}+ logs = (await client.get("/admin/logs", headers=admin)).json()+ assert logs[0]["context_override"] == ["recall"]+ assert "context_override" not in logs[1]+++async def test_empty_disabled_tools_offers_write_tools(running_gateway):+ _, client, _, key, seen, _ = running_gateway++ async def offered(session, context):+ response = await client.post(+ CHAT, headers=headers(key, session, context), json=message("Save a note")+ )+ assert response.status_code == 200, response.text+ return {tool["function"]["name"] for tool in orjson.loads(seen[-1][1]).get("tools", [])}++ read_only = await offered("read-only", {"gateway_tools": True})+ assert "openviking_find" in read_only and "openviking_write" not in read_only+ every = await offered("all-tools", {"gateway_tools": True, "disabled_tools": []})+ assert {"openviking_write", "openviking_add_resource"} <= every+++ "context",+ [+ "{",+ "[]",+ {"bogus": 1},+ {"max_tokens": 10},+ {"window_soft_ratio": 0.9},+ {"name": "Other"},+ {"client_overrides": False},+ '{"idle_seconds": 1e999}',+ '{"session_max_tokens": NaN}',+ {"commit_tokens": 10**30},+ {"quotas": {"events": -1}},+ ],+)+async def test_invalid_override_is_rejected(running_gateway, context):+ app, client, _, key, seen, _ = running_gateway+ calls = openviking_calls(app)+ response = await client.post(CHAT, headers=headers(key, "bad", context), json=message("Hi"))+ assert response.status_code == 400+ assert response.json()["reason"] == "context_override_invalid"+ assert not seen and not calls+++async def test_override_needs_the_profile_switch(running_gateway):+ _, client, admin, key, seen, _ = running_gateway+ response = await client.put(+ "/admin/policies/default",+ headers=admin,+ json={"name": "Locked", "gateway_tools": False, "client_overrides": False},+ )+ assert response.status_code == 200, response.text+ response = await client.post(+ CHAT, headers=headers(key, "locked", {"recall": False}), json=message("Hi")+ )+ assert response.status_code == 403+ assert response.json()["reason"] == "context_override_not_allowed"+ assert not seen+ response = await client.post(CHAT, headers=headers(key, "locked"), json=message("Hi"))+ assert response.status_code == 200, response.text+ # Requests the gateway passes through unchanged check the header too.+ response = await client.post(+ CHAT,+ headers={**headers(key, "locked", "garbage"), "Content-Encoding": "identity"},+ json=message("Hi"),+ )+ assert response.status_code == 403+++async def test_profiles_saved_before_the_switch_accept_overrides(running_gateway):+ app, client, _, key, _, _ = running_gateway+ policy = await app.state.management.get("tenant", "policies", "default")+ policy.pop("client_overrides")+ await app.state.management.save("tenant", "policies", "default", policy)+ response = await client.post(+ CHAT, headers=headers(key, "legacy", {"recall": False}), json=message("Hi")+ )+ assert response.status_code == 200, response.text+++async def test_large_stored_settings_keep_working(running_gateway):+ app, client, _, key, _, _ = running_gateway+ policy = await app.state.management.get("tenant", "policies", "default")+ large = {"quotas": {"events": 5000}, "tool_max_rounds": 20000, "session_max_tokens": 2 * 10**9}+ await app.state.management.save("tenant", "policies", "default", {**policy, **large})+ calls = openviking_calls(app)+ response = await client.post(CHAT, headers=headers(key, "large"), json=message("Deploy?"))+ assert response.status_code == 200, response.text+ assert "/api/v1/search/search" in calls+ response = await client.post(+ CHAT, headers=headers(key, "large-override", {"recall": False}), json=message("Hi")+ )+ assert response.status_code == 200, response.text+++async def test_conversation_keeps_the_policy_it_started_with(running_gateway):+ app, client, _, key, _, _ = running_gateway+ calls = openviking_calls(app)+ body = message("Deploy?")+ response = await client.post(CHAT, headers=headers(key, "frozen", {"recall": False}), json=body)+ assert response.status_code == 200, response.text+ body["messages"] += [+ {"role": "assistant", "content": "hello"},+ {"role": "user", "content": "And the cluster?"},+ ]+ response = await client.post(CHAT, headers=headers(key, "frozen", {"recall": True}), json=body)+ assert response.status_code == 200, response.text+ assert "/api/v1/search/search" not in calls+++async def test_missing_passthrough_key_fails_before_side_effects(running_gateway):+ app, client, _, key, seen, _ = running_gateway+ upstream = await app.state.management.get("tenant", "upstreams", "chat")+ await app.state.management.save(+ "tenant", "upstreams", "chat", {**upstream, "api_key": "", "auth_mode": "passthrough"}+ )+ calls = openviking_calls(app)+ response = await client.post(CHAT, headers=headers(key, "byok"), json=message("Hi"))+ assert response.status_code == 401+ assert not seen and not calls+ with app.state.store.connect() as c:+ assert not list(c.execute("SELECT 1 FROM replay"))+ response = await client.post(+ CHAT,+ headers={**headers(key, "byok"), "X-OpenViking-Upstream-Key": "client-secret"},+ json=message("Hi"),+ )+ assert response.status_code == 200, response.text+ assert seen[-1][2]["Authorization"] == "Bearer client-secret"+++async def test_pinned_conversation_keeps_its_upstream_key(running_gateway):+ app, client, _, key, seen, _ = running_gateway+ body = message("Hi")+ response = await client.post(CHAT, headers=headers(key, "pinned"), json=body)+ assert response.status_code == 200, response.text+ # A higher-priority passthrough upstream added later does not take over the conversation.+ chat = await app.state.management.get("tenant", "upstreams", "chat")+ await app.state.management.save(+ "tenant",+ "upstreams",+ "anthropic",+ {**chat, "id": "anthropic", "api_key": "", "auth_mode": "passthrough", "priority": 10},+ )+ body["messages"] += [+ {"role": "assistant", "content": "hello"},+ {"role": "user", "content": "And now?"},+ ]+ response = await client.post(CHAT, headers=headers(key, "pinned"), json=body)+ assert response.status_code == 200, response.text+ assert seen[-1][2]["Authorization"] == "Bearer model-secret"diff --git a/tests/gateway/test_deployment_defaults.py b/tests/gateway/test_deployment_defaults.pynew file mode 100644index 000000000..7f9673258--- /dev/null+++ b/tests/gateway/test_deployment_defaults.py@@ -0,0 +1,178 @@+"""Deployment defaults route OpenViking keys without account configuration."""++import json++import pytest+from pydantic import ValidationError++from openviking_gateway.app import seed_defaults+from openviking_gateway.cli import load_config+from openviking_gateway.config import GatewayConfig+from openviking_gateway.records import RecordKind as K+from openviking_gateway.storage import digest++HEADERS = {"Authorization": "Bearer other", "X-OpenViking-Session": "deployment"}+BODY = {"model": "deployed", "messages": [{"role": "user", "content": "Deploy the cluster?"}]}+CHAT = "/v1/chat/completions"+++def gateway_config(gateway_backend):+ return {+ "openviking_keys": True,+ "default_upstreams": {+ "deployment-chat": {+ "name": "Deployment chat",+ "protocol": "chat",+ "base_url": gateway_backend[0] + "/v1",+ "api_key": "deployment-secret",+ "models": ["deployed"],+ }+ },+ "default_profile": {+ "name": "Deployment profile",+ "recall": False,+ "profile": False,+ "capture": False,+ "gateway_tools": False,+ "max_tokens": 777,+ },+ }+++async def test_empty_account_routes_and_freezes_the_deployment_upstream(running_gateway):+ app, client, _, _, captured, _ = running_gateway+ response = await client.get("/v1/models", headers=HEADERS)+ assert response.status_code == 200, response.text+ assert [item["id"] for item in response.json()["data"]] == ["deployed"]+ response = await client.post(CHAT, headers=HEADERS, json=BODY)+ assert response.status_code == 200, response.text+ assert captured[-1][2]["Authorization"] == "Bearer deployment-secret"+ records = await app.state.store.replay.read(+ digest("other\0alice\0chat"), digest("deployment"), [""]+ )+ assert records[K.ROOT, ""]["upstream_id"] == "deployment-chat"+ assert records[K.ROOT, ""]["policy"]["max_tokens"] == 777+ assert await app.state.management.list("other", "upstreams") == []+ assert await app.state.management.get("other", "policies", "default") is None++[email protected]("enabled", [True, False])+async def test_stored_upstreams_replace_all_deployment_upstreams(running_gateway, enabled):+ app, client, _, _, _, _ = running_gateway+ upstream = app.state.config.default_upstreams["deployment-chat"].model_dump()+ await app.state.management.save(+ "other", "upstreams", "stored", {**upstream, "models": ["stored-model"], "enabled": enabled}+ )+ response = await client.get("/v1/models", headers=HEADERS)+ assert response.status_code == 200, response.text+ assert [item["id"] for item in response.json()["data"]] == (["stored-model"] if enabled else [])+ response = await client.post(CHAT, headers=HEADERS, json=BODY)+ assert response.status_code == 404+ response = await client.post(CHAT, headers=HEADERS, json={**BODY, "model": "stored-model"})+ assert response.status_code == (200 if enabled else 404), response.text++[email protected]("stored", [False, True])+async def test_default_profile_precedence_and_client_overrides(running_gateway, stored):+ app, client, _, _, _, _ = running_gateway+ calls = []++ async def handler(request):+ calls.append(request.path)++ app.state.test_backend["handler"] = handler+ if stored:+ await app.state.management.save(+ "other",+ "policies",+ "default",+ {**app.state.config.default_profile.model_dump(), "recall": True, "max_tokens": 888},+ )+ response = await client.post(CHAT, headers=HEADERS, json=BODY)+ assert response.status_code == 200, response.text+ assert ("/api/v1/search/search" in calls) == stored+ calls.clear()+ response = await client.post(+ CHAT,+ headers={+ **HEADERS,+ "X-OpenViking-Session": "override",+ "X-OpenViking-Context": json.dumps({"recall": not stored}),+ },+ json=BODY,+ )+ assert response.status_code == 200, response.text+ assert ("/api/v1/search/search" in calls) != stored+ records = await app.state.store.replay.read(+ digest("other\0alice\0chat"), digest("override"), [""]+ )+ assert records[K.ROOT, ""]["policy"]["max_tokens"] == (888 if stored else 777)+++async def test_seed_uses_deployment_profile_and_preserves_saved_changes(running_gateway):+ app = running_gateway[0]+ await seed_defaults(app, "fresh")+ saved = await app.state.management.get("fresh", "policies", "default")+ assert saved["name"] == "Deployment profile" and saved["max_tokens"] == 777+ await app.state.management.save("fresh", "policies", "default", {**saved, "max_tokens": 999})+ await seed_defaults(app, "fresh")+ assert (await app.state.management.get("fresh", "policies", "default"))["max_tokens"] == 999+++ "settings",+ [+ {"default_upstreams": {"chat": {"protocol": "chat", "base_url": "https://model.test"}}},+ {+ "default_upstreams": {+ "chat": {+ "name": "Chat",+ "protocol": "chat",+ "base_url": "https://model.test",+ "id": "chat",+ }+ }+ },+ {"default_profile": {"unknown_setting": True}},+ ],+)+def test_invalid_defaults_fail_when_loading_config(tmp_path, monkeypatch, settings):+ path = tmp_path / "gateway.conf"+ path.write_text(json.dumps({"openviking_url": "https://ov.test", **settings}))+ monkeypatch.setenv("OPENVIKING_GATEWAY_CONFIG_FILE", str(path))+ with pytest.raises(ValidationError):+ load_config()+++def test_json_environment_overrides_and_file_secret_expansion(tmp_path, monkeypatch):+ path = tmp_path / "gateway.conf"+ upstream = {"name": "Chat", "protocol": "chat", "base_url": "https://model.test/v1"}+ path.write_text(+ json.dumps(+ {+ "openviking_url": "https://ov.test",+ "default_upstreams": {"chat": {**upstream, "api_key": "$MODEL_API_KEY"}},+ "default_profile": {"max_tokens": 800},+ }+ )+ )+ monkeypatch.setenv("OPENVIKING_GATEWAY_CONFIG_FILE", str(path))+ monkeypatch.setenv("MODEL_API_KEY", "secret-from-environment")+ assert load_config().default_upstreams["chat"].api_key == "secret-from-environment"+ monkeypatch.setenv(+ "OPENVIKING_GATEWAY_DEFAULT_UPSTREAMS", json.dumps({"replacement": upstream})+ )+ monkeypatch.setenv("OPENVIKING_GATEWAY_DEFAULT_PROFILE", '{"max_tokens":900}')+ monkeypatch.setenv("OPENVIKING_GATEWAY_CLIENT_RULES", '{"plugin_tags":{"add":["example"]}}')+ config = load_config()+ assert list(config.default_upstreams) == ["replacement"]+ assert config.default_profile.max_tokens == 900+ assert config.client_rules.plugin_tags.add == ["example"]+ assert "default_upstreams" not in repr(config)+++def test_defaults_preserve_existing_configuration():+ config = GatewayConfig()+ assert config.default_upstreams == {}+ assert config.default_profile.name == "Default"diff --git a/tests/gateway/test_kernel.py b/tests/gateway/test_kernel.pyindex 773dd38a7..109df794e 100644--- a/tests/gateway/test_kernel.py+++ b/tests/gateway/test_kernel.py@@ -32,7 +32,7 @@ from openviking_gateway.protocols import (prefix_chain,text_content,)-from openviking_gateway.storage import ManagementStore, SQLiteKernelStore+from openviking_gateway.storage import SQLiteKernelStore, SQLiteManagementStorefrom openviking_gateway.tool_protocols import ResponseCapture@@ -461,7 +461,7 @@ async def test_plugin_stop_is_sticky_but_replays_existing_prefix(setup_kernel, casync def test_capture_confirms_branch_and_isolates_forks(setup_kernel, credential, policy):kernel, store, viking, key = setup_kernel- management = ManagementStore(store.path.parent / "management.sqlite3", key)+ management = SQLiteManagementStore(store.path.parent / "management.sqlite3", key)await management.initialize()await management.save("tenant", "keys", credential["id"], credential)body = {"messages": [{"role": "user", "content": "How do I deploy?"}]}diff --git a/tests/gateway/test_kms_key_file.py b/tests/gateway/test_kms_key_file.pynew file mode 100644index 000000000..c50bcba26--- /dev/null+++ b/tests/gateway/test_kms_key_file.py@@ -0,0 +1,27 @@+"""Standalone configuration preserves the mounted KMS root key path."""++from pathlib import Path++from openviking.crypto.providers import create_root_key_provider+from openviking_gateway.config import StandaloneGatewayConfig+++def test_standalone_kms_key_file_reaches_provider():+ key_file = "/etc/openviking-gateway/keys/root-key"+ config = StandaloneGatewayConfig(+ openviking_url="https://ov.example.com",+ encryption={+ "enabled": True,+ "provider": "volcengine_kms",+ "volcengine_kms": {+ "region": "cn-beijing",+ "access_key": "test-access-key",+ "secret_key": "test-secret-key",+ "key_id": "test-key-id",+ "key_file": key_file,+ },+ },+ )+ assert config.encryption["volcengine_kms"]["key_file"] == key_file+ provider = create_root_key_provider("volcengine_kms", config.encryption)+ assert provider.key_file == Path(key_file)diff --git a/tests/gateway/test_management.py b/tests/gateway/test_management.pyindex 923e8d45e..0179c4724 100644--- a/tests/gateway/test_management.py+++ b/tests/gateway/test_management.py@@ -7,7 +7,7 @@ import httpximport pytestfrom aiohttp import web-from openviking_gateway.app import create_app, seed_defaults+from openviking_gateway.app import create_app, health_loop, seed_defaultsfrom openviking_gateway.config import StandaloneGatewayConfigfrom openviking_gateway.standalone import check_openviking, create_standalone_appfrom openviking_gateway.storage import digest@@ -764,13 +764,11 @@ async def test_connection_test_is_available_for_missing_key_and_blocked_plan(runassert not [path for path, _, _ in captured if path.endswith("/chat/completions")][email protected]("mode", ["unavailable", "trusted", "unknown"])[email protected]("mode", ["trusted", "unknown"])async def test_public_standalone_requires_confirmed_api_key_auth(tmp_path, monkeypatch, mode):from openviking_gateway.client import VikingClient, VikingErrorasync def health(self, *args, **kwargs):- if mode == "unavailable":- raise VikingError("openviking_unavailable")if mode == "trusted":raise VikingError("trusted_mode_unsupported", 403)return {"status": "ok"}@@ -1002,42 +1000,28 @@ async def test_keys_are_immutable_and_errors_explain_themselves(running_gateway)}-async def test_degraded_probe_backs_off_until_success(tmp_path, monkeypatch):- import asyncio- import time+async def test_degraded_probe_backs_off_until_success():from types import SimpleNamespace- from openviking_gateway import app as module- from openviking_gateway.client import VikingClient, VikingError- from openviking_gateway.config import GatewayConfig+ from openviking_gateway.client import VikingError- clock, probes, results = [0.0], [], [False, False, True, False, False, False, False]+ delays, results = [], [False, False, True, False, False, False, False]- def monotonic():- clock[0] += 0.125- return clock[0]-- async def health(self, *args, **kwargs):- probes.append(clock[0])- if results and not results.pop(0):+ async def health(**kwargs):+ if not results.pop(0):raise VikingError("openviking_unavailable")return {"status": "ok"}- async def once():- await asyncio.sleep(0)- return True+ async def sleep(delay):+ delays.append(delay)+ if not results:+ raise asyncio.CancelledError- monkeypatch.setattr(VikingClient, "health", health)- monkeypatch.setattr(module, "time", SimpleNamespace(monotonic=monotonic, time=time.time))- config = GatewayConfig(storage_path=str(tmp_path), health_interval_seconds=4)- app = create_app(config, openviking_url="http://unused")- async with app.router.lifespan_context(app):- app.state.worker.once = once- while results:- await asyncio.sleep(0)- gaps = [round(b - a) for a, b in zip(probes, probes[1:], strict=False)]+ app = SimpleNamespace(state=SimpleNamespace(viking=SimpleNamespace(health=health)))+ with pytest.raises(asyncio.CancelledError):+ await health_loop(app, 4, sleep)# Every second until OV first answers; later outages back off 1, 2, 4 capped at the interval.- assert gaps[:6] == [1, 1, 4, 1, 2, 4]+ assert delays == [1, 1, 4, 1, 2, 4, 4]async def test_upstream_test_fills_url_key_and_reaches_exact_endpoints(running_gateway):diff --git a/tests/gateway/test_management_switch.py b/tests/gateway/test_management_switch.pynew file mode 100644index 000000000..3fcef894c--- /dev/null+++ b/tests/gateway/test_management_switch.py@@ -0,0 +1,137 @@+"""Disabling management removes administration and Studio while keeping model traffic."""++import httpx+import pytest++from openviking_gateway.app import create_app+from openviking_gateway.config import (+ PUBLIC_OPENVIKING_URLS,+ EmbeddedGatewayConfig,+ GatewayConfig,+ StandaloneGatewayConfig,+)+from openviking_gateway.standalone import create_standalone_app++HEADERS = {"X-API-Key": "user-key"}+BODY = {"model": "model", "messages": [{"role": "user", "content": "Hello"}]}+++def gateway_config(gateway_backend):+ return {+ "management_api": False,+ "openviking_keys": True,+ "default_upstreams": {+ "chat": {+ "name": "Chat",+ "protocol": "chat",+ "base_url": gateway_backend[0] + "/v1",+ "api_key": "model-secret",+ "models": ["model"],+ }+ },+ "default_profile": {"gateway_tools": False},+ }+++async def test_management_disabled_keeps_default_upstreams(running_gateway):+ app, client, admin, minted, captured, _ = running_gateway+ assert minted is None+ for method, path in (+ ("GET", "/admin/access"),+ ("GET", "/admin/upstreams"),+ ("PUT", "/admin/policies/default"),+ ("POST", "/admin/keys"),+ ("DELETE", "/admin/users/alice/data"),+ ("DELETE", "/admin/account/data"),+ ):+ response = await client.request(method, path, headers=admin)+ assert response.status_code == 404, (method, path, response.text)+ for path in ("/v1/models", "/api/v3/models", "/api/compatible/v1/models"):+ response = await client.get(path, headers=HEADERS)+ assert response.status_code == 200, response.text+ assert [item["id"] for item in response.json()["data"]] == ["model"]+ response = await client.post("/v1/chat/completions", headers=HEADERS, json=BODY)+ assert response.status_code == 200, response.text+ assert captured[-1][2]["Authorization"] == "Bearer model-secret"+ assert await app.state.management.list("tenant", "upstreams") == []+ assert await app.state.management.get("tenant", "policies", "default") is None+++async def test_standalone_disables_administration_and_studio(+ tmp_path, gateway_backend, gateway_config, monkeypatch+):+ (tmp_path / "index.html").write_text("<html>Studio</html>")+ monkeypatch.setenv("OPENVIKING_WEB_STUDIO_DIR", str(tmp_path))+ config = StandaloneGatewayConfig.model_validate(+ {"storage_path": str(tmp_path), "openviking_url": gateway_backend[0], **gateway_config}+ )+ app = create_standalone_app(config, studio_dir=tmp_path)+ async with (+ app.router.lifespan_context(app),+ httpx.AsyncClient(+ transport=httpx.ASGITransport(app=app), base_url="http://gateway"+ ) as client,+ ):+ for path in (+ "/gateway/admin/access",+ "/api/v1/admin/accounts",+ "/api/v1/admin/accounts/tenant/users",+ "/",+ "/studio",+ "/studio/",+ "/studio/gateway/keys",+ "/studio/assets/app.js",+ ):+ response = await client.get(path, headers={"X-API-Key": "admin-key"})+ assert response.status_code == 404, (path, response.text)+ response = await client.get("/health")+ assert response.status_code == 200+ assert response.json()["service"] == "openviking-gateway"+ response = await client.get("/gateway/v1/models", headers=HEADERS)+ assert response.status_code == 200+ assert [item["id"] for item in response.json()["data"]] == ["model"]+ response = await client.post("/gateway/v1/chat/completions", headers=HEADERS, json=BODY)+ assert response.status_code == 200, response.text+++async def test_embedded_management_can_be_disabled(tmp_path, gateway_backend, gateway_config):+ config = EmbeddedGatewayConfig.model_validate(+ {"enabled": True, "storage_path": str(tmp_path), **gateway_config}+ )+ app = create_app(config, openviking_url=gateway_backend[0])+ async with (+ app.router.lifespan_context(app),+ httpx.AsyncClient(+ transport=httpx.ASGITransport(app=app, root_path="/gateway"),+ base_url="http://server/gateway",+ ) as client,+ ):+ assert (await client.get("/admin/access", headers=HEADERS)).status_code == 404+ assert (await client.get("/v1/models", headers=HEADERS)).status_code == 200++[email protected]("enabled", [True, False])+def test_public_management_warning_follows_switch(tmp_path, caplog, enabled):+ config = StandaloneGatewayConfig(+ storage_path=str(tmp_path),+ openviking_url=next(iter(PUBLIC_OPENVIKING_URLS)),+ management_api=enabled,+ )+ app = create_standalone_app(config)+ warnings = app.routes[-1].app.state.warnings+ assert warnings == (["public_openviking_without_management_key"] if enabled else [])+ assert ("public_openviking_without_management_key" in caplog.text) == enabled+++ "config_type", [GatewayConfig, EmbeddedGatewayConfig, StandaloneGatewayConfig]+)+def test_management_defaults_on_and_accepts_environment(config_type, monkeypatch):+ settings = (+ {"openviking_url": "http://ov.test"} if config_type is StandaloneGatewayConfig else {}+ )+ monkeypatch.delenv("OPENVIKING_GATEWAY_MANAGEMENT_API", raising=False)+ assert config_type.model_validate(settings).management_api is True+ monkeypatch.setenv("OPENVIKING_GATEWAY_MANAGEMENT_API", "false")+ assert config_type.model_validate({**settings, "management_api": True}).management_api is Falsediff --git a/tests/gateway/test_openviking_keys.py b/tests/gateway/test_openviking_keys.pynew file mode 100644index 000000000..1bc8f63d7--- /dev/null+++ b/tests/gateway/test_openviking_keys.py@@ -0,0 +1,251 @@+"""OpenViking API keys used directly as gateway keys (``openviking_keys``)."""++import pytest+from conftest import make_due++from openviking_gateway.models import Policy+from openviking_gateway.proxy import resolve_binding+from openviking_gateway.storage import digest++OV_KEY = "bob-key"+RECORD = digest("openviking\0" + OV_KEY)+++def bearer(key):+ return {"Authorization": "Bearer " + key}+++def record_openviking_calls(app):+ """Collect the key of every OpenViking call; the fake backend still answers them."""+ calls = []++ async def handler(request):+ if request.path.startswith(("/health", "/api/", "/mcp")):+ calls.append((request.path, request.headers.get("X-API-Key")))+ return None++ app.state.test_backend["handler"] = handler+ return calls+++def gateway_config(request):+ return getattr(request, "param", {"openviking_keys": True})++[email protected]("gateway_config", [{"openviking_keys": False}], indirect=True)+async def test_switch_off_rejects_openviking_keys_without_calling_openviking(running_gateway):+ app, client, _, _, _, _ = running_gateway+ calls = record_openviking_calls(app)+ for headers in (bearer(OV_KEY), {"x-api-key": OV_KEY}):+ assert (await client.get("/v1/models", headers=headers)).status_code == 401+ # No credential at all is never an OpenViking key.+ assert (await client.get("/v1/models")).status_code == 401+ assert calls == []+ assert await app.state.management.credential(RECORD) is None+++async def test_first_request_creates_the_record_and_registers_the_user(running_gateway):+ app, client, admin, _, _, _ = running_gateway+ management, store = app.state.management, app.state.store+ # Deleted gateway data blocks the user's scopes until a key is created again.+ assert (await client.delete("/admin/users/bob/data", headers=admin)).status_code == 200+ assert await management.get("tenant", "users", "bob") is None+ response = await client.get("/v1/models", headers={"x-api-key": OV_KEY})+ assert response.status_code == 200, response.text+ record = await management.credential(RECORD)+ assert record["account"] == "tenant"+ assert {k: record[k] for k in ("source", "openviking_key", "user_id", "prefix")} == {+ "source": "openviking",+ "openviking_key": OV_KEY,+ "user_id": "bob",+ "prefix": "bob-key",+ }+ assert not {"name", "policy_id", "upstream_ids", "models"} & set(record)+ user = await management.get("tenant", "users", "bob")+ assert user.pop("expires_at") > record["created_at"]+ assert user == {+ "user_id": "bob",+ "id": "bob",+ "revision": 1,+ }+ with store.connect() as c:+ assert not c.execute("SELECT * FROM deleted_scopes").fetchall()+++async def test_request_during_user_data_deletion_does_not_block_the_key(running_gateway):+ app, client, admin, _, _, _ = running_gateway+ management = app.state.management+ body = {"model": "model", "messages": [{"role": "user", "content": "hi"}]}++ async def degradation():+ response = await client.post("/v1/chat/completions", headers=bearer(OV_KEY), json=body)+ assert response.status_code == 200, response.text+ return (await management.logs("tenant", user_id="bob"))[0].get("degradation")++ assert await degradation() is None+ delete_user = management.delete_user++ async def interleaved(account, user_id):+ # The client keeps sending requests while its user's data is being deleted.+ await degradation()+ await delete_user(account, user_id)+ await degradation()++ management.delete_user = interleaved+ assert (await client.delete("/admin/users/bob/data", headers=admin)).status_code == 200+ assert await degradation() is None+ assert await management.credential(RECORD)+++async def test_capture_worker_delivers_with_the_stored_key(running_gateway):+ app, client, _, _, _, writes = running_gateway+ calls = record_openviking_calls(app)+ headers = {**bearer(OV_KEY), "X-OpenViking-Session": "direct"}+ messages = [{"role": "user", "content": "Remember the blue cluster"}]+ for _ in range(2):+ response = await client.post(+ "/v1/chat/completions", headers=headers, json={"model": "model", "messages": messages}+ )+ assert response.status_code == 200, response.text+ messages += [+ {"role": "assistant", "content": "hello"},+ {"role": "user", "content": "And the red one"},+ ]+ await make_due(app.state.store)+ for _ in range(5):+ if writes:+ break+ await app.state.worker.once()+ assert writes+ session_keys = {key for path, key in calls if path.startswith("/api/v1/sessions")}+ assert session_keys == {OV_KEY}+++async def test_revoked_openviking_key_deletes_the_record(running_gateway):+ app, client, _, _, _, _ = running_gateway+ assert (await client.get("/v1/models", headers=bearer(OV_KEY))).status_code == 200+ app.state.test_backend["health_status"] = {OV_KEY: 401}+ app.state.viking.identities.clear()+ response = await client.get("/v1/models", headers=bearer(OV_KEY))+ assert response.status_code == 401+ assert response.json()["detail"].startswith("OpenViking rejected this API key.")+ assert await app.state.management.credential(RECORD) is None+ # Without a record, OpenViking is asked again and still rejects the key.+ response = await client.get("/v1/models", headers=bearer(OV_KEY))+ assert response.status_code == 401+ assert response.json()["reason"] == "openviking_http_401"+ assert await app.state.management.credential(RECORD) is None+++async def test_binding_is_every_enabled_upstream_of_the_account(running_gateway):+ app, client, admin, key, _, _ = running_gateway+ upstream = (await client.get("/admin/upstreams/chat", headers=admin)).json()+ for identifier, models, enabled in (+ ("extra", ["extra-model"], True),+ ("off", ["off-model"], False),+ ):+ response = await client.put(+ f"/admin/upstreams/{identifier}",+ headers=admin,+ json={+ "name": identifier,+ "protocol": "chat",+ "base_url": upstream["base_url"],+ "api_key": "model-secret",+ "models": models,+ "enabled": enabled,+ },+ )+ assert response.status_code == 200, response.text++ async def model_names(headers):+ response = await client.get("/v1/models", headers=headers)+ assert response.status_code == 200, response.text+ return [item["id"] for item in response.json()["data"]]++ assert await model_names(bearer(OV_KEY)) == ["error", "extra-model", "model"]+ assert await model_names(bearer(key["key"])) == ["error", "model"]+ body = {"model": "extra-model", "messages": [{"role": "user", "content": "hi"}]}+ response = await client.post("/v1/chat/completions", headers=bearer(OV_KEY), json=body)+ assert response.status_code == 200, response.text+ response = await client.post("/v1/chat/completions", headers=bearer(key["key"]), json=body)+ assert response.status_code == 404+ body["model"] = "off-model"+ response = await client.post("/v1/chat/completions", headers=bearer(OV_KEY), json=body)+ assert response.status_code == 404+++async def test_binding_falls_back_to_policy_defaults(running_gateway):+ management, config = running_gateway[0].state.management, running_gateway[0].state.config+ binding = await resolve_binding(+ management, config, {"source": "openviking", "account": "empty"}+ )+ assert binding == (Policy().model_dump(), [], [])+ binding = await resolve_binding(+ management, config, {"source": "openviking", "account": "tenant"}+ )+ assert binding.policy["name"] == "Default" and not binding.policy["gateway_tools"]+++async def test_keys_listing_and_object_deletion_with_openviking_records(running_gateway):+ app, client, admin, key, _, _ = running_gateway+ assert (await client.get("/v1/models", headers=bearer(OV_KEY))).status_code == 200+ listed = (await client.get("/admin/keys", headers=admin)).json()+ record = next(item for item in listed if item["id"] == RECORD)+ assert record["source"] == "openviking" and record["user_id"] == "bob"+ assert {k: record[k] for k in ("name", "prefix", "policy_id", "upstream_ids", "models")} == {+ "name": "",+ "prefix": "bob-key",+ "policy_id": "",+ "upstream_ids": [],+ "models": [],+ }+ assert "openviking_key" not in record+ # The user sees their own record too.+ own = (await client.get("/admin/keys", headers={"X-API-Key": OV_KEY})).json()+ assert [item["id"] for item in own] == [RECORD]++ assert (+ await client.put("/admin/policies/spare", headers=admin, json={"name": "Spare"})+ ).status_code == 200+ assert (await client.delete("/admin/policies/spare", headers=admin)).status_code == 200+ # The issued key still counts; the OpenViking record does not.+ response = await client.delete("/admin/upstreams/chat", headers=admin)+ assert response.status_code == 409 and response.json()["key_count"] == 1+ assert (await client.delete("/admin/keys/" + key["id"], headers=admin)).status_code == 200+ assert (await client.delete("/admin/upstreams/chat", headers=admin)).status_code == 200+ assert (await client.delete("/admin/policies/default", headers=admin)).status_code == 200+ # Without a default profile the record still routes, with Policy() defaults.+ assert (await client.get("/v1/models", headers=bearer(OV_KEY))).status_code == 200+++async def test_context_header_overrides_the_default_profile(running_gateway):+ app, client, admin, _, _, _ = running_gateway+ calls = record_openviking_calls(app)+ body = {"model": "model", "messages": [{"role": "user", "content": "Deploy?"}]}++ async def chat(session, context):+ headers = {**bearer(OV_KEY), "X-OpenViking-Session": session}+ headers["X-OpenViking-Context"] = context+ calls.clear()+ return await client.post("/v1/chat/completions", headers=headers, json=body)++ response = await chat("recall", '{"recall":true}')+ assert response.status_code == 200, response.text+ assert any(path == "/api/v1/search/search" for path, _ in calls)+ response = await chat("no-recall", '{"recall":false}')+ assert response.status_code == 200, response.text+ assert not any(path == "/api/v1/search/search" for path, _ in calls)+ logs = await app.state.management.logs("tenant", user_id="bob")+ assert logs[0]["context_override"] == ["recall"]++ response = await client.put(+ "/admin/policies/default",+ headers=admin,+ json={"name": "Locked", "gateway_tools": False, "client_overrides": False},+ )+ assert response.status_code == 200, response.text+ response = await chat("locked", '{"recall":false}')+ assert response.status_code == 403+ assert response.json()["reason"] == "context_override_not_allowed"diff --git a/tests/gateway/test_openviking_rejections.py b/tests/gateway/test_openviking_rejections.pynew file mode 100644index 000000000..65a5163d8--- /dev/null+++ b/tests/gateway/test_openviking_rejections.py@@ -0,0 +1,44 @@+"""Explicit OpenViking refusals stop dispatch even when the key is already cached."""++import pytest++from openviking_gateway.storage import digest+++def gateway_config():+ return {"openviking_keys": True}++[email protected]("kind", ["openviking", "issued"])[email protected]("status", [402, 403, 404, 429, 503])+async def test_existing_keys_respect_refusals_and_degrade_only_when_unconfirmed(+ running_gateway, kind, status+):+ app, client, _, issued, captured, _ = running_gateway+ token = "bob-key" if kind == "openviking" else issued["key"]+ ov_key = "bob-key" if kind == "openviking" else "user-key"+ identifier = digest("openviking\0" + token) if kind == "openviking" else issued["id"]+ headers = {"Authorization": "Bearer " + token}+ assert (await client.get("/v1/models", headers=headers)).status_code == 200+ assert await app.state.management.credential(identifier)+ app.state.test_backend["health_status"] = {ov_key: status}+ app.state.viking.identities.clear()+ before = len(captured)+ response = await client.post(+ "/v1/chat/completions",+ headers=headers,+ json={"model": "model", "messages": [{"role": "user", "content": "Is this allowed?"}]},+ )+ if status in {402, 403}:+ assert response.status_code == status, response.text+ assert response.json()["reason"] == f"openviking_http_{status}"+ assert len(captured) == before+ if status == 402:+ assert "not ordered" in response.json()["detail"]+ else:+ assert response.status_code == 200, response.text+ assert len(captured) == before + 1+ logs = await app.state.management.logs("tenant")+ assert any(log.get("degradation") == "revocation_check_unavailable" for log in logs)+ assert await app.state.management.credential(identifier)diff --git a/tests/gateway/test_reply_inheritance.py b/tests/gateway/test_reply_inheritance.pyindex 28cea8c97..bf7e51d1f 100644--- a/tests/gateway/test_reply_inheritance.py+++ b/tests/gateway/test_reply_inheritance.py@@ -10,7 +10,7 @@ from test_review_regressions import worker_forfrom openviking_gateway.records import RecordKind as Kfrom openviking_gateway.state_store import get_state-from openviking_gateway.storage import SCHEMA_VERSION, ManagementStore, SQLiteKernelStore+from openviking_gateway.storage import SCHEMA_VERSION, SQLiteKernelStore, SQLiteManagementStorefrom openviking_gateway.tool_protocols import ResponseCapture, hidden_chainQUESTION = {"role": "user", "content": "How do I deploy?"}@@ -395,7 +395,7 @@ async def test_expiry_removes_stale_sessions_records_and_documents(@pytest.mark.parametrize("old", [1, 2, 3, 4, SCHEMA_VERSION + 1])[email protected]("kind", [SQLiteKernelStore, ManagementStore])[email protected]("kind", [SQLiteKernelStore, SQLiteManagementStore])async def test_storage_rejects_other_schema_versions(tmp_path, setup_kernel, kind, old):"""Versions 1-4 were stamped on older pre-release layouts and must not pass."""_, _, _, encryption = setup_kerneldiff --git a/tests/gateway/test_request_log_sink.py b/tests/gateway/test_request_log_sink.pynew file mode 100644index 000000000..a63eca25b--- /dev/null+++ b/tests/gateway/test_request_log_sink.py@@ -0,0 +1,116 @@+"""Request logs select storage or promptly flushed JSON on stdout."""++import json+import sys+import time++import pytest+from aiohttp import web+from conftest import make_due++[email protected](params=["store", "stdout"])+def gateway_config(request):+ return {"request_log_sink": request.param}+++async def test_requests_use_selected_sink(running_gateway, capsys):+ app, client, admin, issued, _, _ = running_gateway+ stdout = app.state.config.request_log_sink == "stdout"+ key = issued["key"]+ request_ids = set()+ for index, (stream, model, status) in enumerate(+ [(False, "model", 200), (True, "model", 200), (False, "error", 429)]+ ):+ session = f"private-session-{index}"+ response = await client.post(+ "/v1/chat/completions",+ headers={"Authorization": f"Bearer {key}", "X-OpenViking-Session": session},+ json={+ "model": model,+ "stream": stream,+ "messages": [{"role": "user", "content": "private prompt\n你好"}],+ },+ )+ assert response.status_code == status, response.text+ output = capsys.readouterr().out+ stored = (await client.get("/admin/logs", headers=admin)).json()+ if stdout:+ assert len(output.splitlines()) == 1+ record = json.loads(output)+ assert record["account"] == "tenant" and record["user_id"] == "alice"+ assert stored == []+ assert await app.state.management.port.logs("tenant") == []+ else:+ assert output == ""+ assert len(stored) == index + 1+ record = stored[0]+ assert 0 <= time.time() - record["time"] < 10+ assert record["model"] == model and record["status"] == status+ assert record["kind"] == "user" and record["protocol"] == "chat"+ assert record["duration_ms"] >= 0+ if stream:+ assert record["input_tokens"] == 123 and record["cached_tokens"] == 100+ request_ids.add(record["request_id"])+ for secret in (key, "user-key", "model-secret", session, "private prompt"):+ assert secret not in output + json.dumps(stored)+ assert len(request_ids) == 3+ overview = (await client.get("/admin/overview", headers=admin)).json()+ assert overview["requests"] == (0 if stdout else 3)+++async def test_capture_events_use_selected_sink(running_gateway, capsys):+ app, client, _, issued, _, writes = running_gateway+ response = await client.post(+ "/v1/chat/completions",+ headers={"Authorization": "Bearer " + issued["key"], "X-OpenViking-Session": "capture"},+ json={"model": "model", "messages": [{"role": "user", "content": "Remember this"}]},+ )+ assert response.status_code == 200, response.text+ capsys.readouterr()++ async def unavailable(request):+ if request.path.startswith("/api/v1/sessions"):+ return web.Response(status=503)++ for handler, status, reason in [+ (unavailable, "retrying", "openviking_http_503"),+ (None, "active", "delivery_recovered"),+ ]:+ app.state.test_backend["handler"] = handler+ await make_due(app.state.store)+ assert await app.state.worker.once()+ output = capsys.readouterr().out+ stored = await app.state.management.logs("tenant")+ if app.state.config.request_log_sink == "stdout":+ assert len(output.splitlines()) == 1+ record = json.loads(output)+ assert record["account"] == "tenant" and record["user_id"] == "alice"+ assert stored == []+ else:+ assert output == ""+ record = stored[0]+ assert record["kind"] == "capture"+ assert record["capture_status"] == status and record["capture_reason"] == reason+ for secret in (issued["key"], "user-key", "model-secret", "Remember this"):+ assert secret not in output + json.dumps(stored)+ assert writes+++async def test_stdout_flushes_each_line(monkeypatch):+ from types import SimpleNamespace++ from openviking_gateway.app import stdout_log++ calls = []+ buffer = SimpleNamespace(+ write=lambda data: calls.append(data), flush=lambda: calls.append("flush")+ )+ monkeypatch.setattr(sys, "stdout", SimpleNamespace(buffer=buffer))+ await stdout_log("tenant\n你好", {"kind": "capture"})+ line, flushed = calls+ assert line.endswith(b"\n") and line.count(b"\n") == 1+ record = json.loads(line)+ assert record["account"] == "tenant\n你好" and record["user_id"] is None+ assert record["kind"] == "capture" and record["time"] <= time.time()+ assert flushed == "flush"diff --git a/tests/gateway/test_review_regressions.py b/tests/gateway/test_review_regressions.pyindex 04864471b..eea015512 100644--- a/tests/gateway/test_review_regressions.py+++ b/tests/gateway/test_review_regressions.py@@ -10,7 +10,7 @@ from conftest import make_due, replay_recordsfrom openviking_gateway.capture import MAX_ATTEMPTS, CaptureWorkerfrom openviking_gateway.client import VikingErrorfrom openviking_gateway.protocols import plugin_present-from openviking_gateway.storage import ManagementStore, SQLiteKernelStore+from openviking_gateway.storage import SQLiteKernelStore, SQLiteManagementStorefrom openviking_gateway.tool_protocols import ResponseCapture@@ -37,7 +37,7 @@ def history(turns):async def worker_for(store, encryption, credential, viking):- management = ManagementStore(store.path.parent / "management.sqlite3", encryption)+ management = SQLiteManagementStore(store.path.parent / "management.sqlite3", encryption)await management.initialize()await management.save("tenant", "keys", credential["id"], credential)return CaptureWorker(store, management, viking)@@ -428,7 +428,7 @@ async def test_anonymous_greetings_cannot_share_capture_or_archive(async def test_management_get_uses_one_row_and_response_expiry(setup_kernel, monkeypatch):_, store, _, encryption = setup_kernel- management = ManagementStore(store.path.parent / "management.sqlite3", encryption)+ management = SQLiteManagementStore(store.path.parent / "management.sqlite3", encryption)await management.initialize()for i in range(30):await management.save("tenant", "responses", str(i), {"upstream_id": "test"}, ttl=100)diff --git a/tests/gateway/test_runtime.py b/tests/gateway/test_runtime.pynew file mode 100644index 000000000..d97ce8331--- /dev/null+++ b/tests/gateway/test_runtime.py@@ -0,0 +1,117 @@+"""Capture runs concurrently and drains before gateway resources close."""++import asyncio++import pytest+from conftest import make_due, serve_gateway++from openviking_gateway import app as app_module+++def gateway_config():+ return {"capture_concurrency": 2, "health_interval_seconds": 1}+++async def queue_conversation(gateway, session):+ app, client, _, minted, _, _ = gateway+ response = await client.post(+ "/v1/chat/completions",+ headers={+ "Authorization": "Bearer " + minted["key"],+ "X-OpenViking-Session": session,+ "X-OpenViking-Context": '{"recall":false,"profile":false}',+ },+ json={"model": "model", "messages": [{"role": "user", "content": session}]},+ )+ assert response.status_code == 200, response.text+ await make_due(app.state.store)+++async def test_two_commits_are_in_flight_together(running_gateway):+ app = running_gateway[0]+ entered, release = asyncio.Event(), asyncio.Event()+ health = asyncio.Event()+ sessions = set()++ async def handler(request):+ if request.path == "/health" and not request.headers.get("X-API-Key") and entered.is_set():+ health.set()+ if request.path.endswith("/commit"):+ sessions.add(request.path.split("/")[4])+ if len(sessions) == 2:+ entered.set()+ await release.wait()++ app.state.test_backend["handler"] = handler+ try:+ await queue_conversation(running_gateway, "first")+ await queue_conversation(running_gateway, "second")+ await asyncio.wait_for(entered.wait(), 3)+ await asyncio.wait_for(health.wait(), 3)+ assert len(sessions) == 2+ assert len(running_gateway[5]) == 2+ finally:+ release.set()++[email protected]("stuck", [False, True], ids=["drain", "timeout"])+async def test_shutdown_stops_claiming_and_closes_after_delivery(+ tmp_path, gateway_backend, gateway_config, monkeypatch, stuck+):+ entered, release = asyncio.Event(), asyncio.Event()+ commits, cancelled, claims = [], [], []+ completed = []+ monkeypatch.setattr(app_module, "CAPTURE_DRAIN_SECONDS", 0.02 if stuck else 3)+ if not stuck:++ async def release_on_shutdown(*args):+ # Shutdown cancels the health loop before it waits on captures, so delivery+ # finishes only once draining has started.+ try:+ await asyncio.Event().wait()+ finally:+ release.set()++ monkeypatch.setattr(app_module, "health_loop", release_on_shutdown)++ async def handler(request):+ if request.path.endswith("/commit"):+ commits.append(request.path.split("/")[4])+ if len(commits) == 2:+ entered.set()+ await release.wait()++ try:+ async with serve_gateway(tmp_path, gateway_backend, gateway_config) as gateway:+ app = gateway[0]+ commit, claim = app.state.viking.commit, app.state.store.capture.claim++ async def observed_commit(*args, **kwargs):+ try:+ result = await commit(*args, **kwargs)+ completed.append(args[1])+ return result+ except asyncio.CancelledError:+ cancelled.append(args[1])+ raise++ async def observed_claim(*args, **kwargs):+ claims.append(True)+ return await claim(*args, **kwargs)++ app.state.test_backend["handler"] = handler+ monkeypatch.setattr(app.state.viking, "commit", observed_commit)+ monkeypatch.setattr(app.state.store.capture, "claim", observed_claim)+ await queue_conversation(gateway, "first")+ await queue_conversation(gateway, "second")+ await asyncio.wait_for(entered.wait(), 3)+ await queue_conversation(gateway, "unclaimed")+ claims_before_shutdown = len(claims)+ finally:+ release.set()+ assert app.state.http.closed+ assert len(commits) == 2+ assert len(claims) == claims_before_shutdown+ assert len(cancelled) == (2 if stuck else 0)+ assert len(completed) == (0 if stuck else 2)diff --git a/tests/gateway/test_sse_heartbeat.py b/tests/gateway/test_sse_heartbeat.pynew file mode 100644index 000000000..2f8250315--- /dev/null+++ b/tests/gateway/test_sse_heartbeat.py@@ -0,0 +1,321 @@+"""SSE heartbeats preserve framing, capture, deadlines and cancellation."""++import asyncio+import gzip+from types import SimpleNamespace+from unittest.mock import AsyncMock, Mock++import async_timeout+import orjson+import pytest+from aiohttp import web+from test_app import enable_tools+from test_native_tools import PATHS, native_events, native_response, request_body, wire_response++from openviking_gateway import proxy+from openviking_gateway.protocols import SSEDecoder, heartbeat+from openviking_gateway.tool_loop import HiddenToolLoop+from openviking_gateway.tool_protocols import ResponseCapture+from openviking_gateway.tool_protocols.common import sse++KEEP_ALIVE = b": keep-alive\n\n"+++def upstream(source, **headers):+ """The aiohttp response fields the proxy reads, streaming ``source``."""+ return SimpleNamespace(+ headers={"content-type": "text/event-stream", **headers},+ content=SimpleNamespace(iter_any=source),+ close=Mock(),+ status=200,+ )+++def passthrough(response):+ """The ProxyRequest fields observe_response reads."""+ return SimpleNamespace(+ response=response,+ capture=ResponseCapture("chat"),+ metrics={},+ relay=AsyncMock(),+ finish=AsyncMock(),+ )+++async def test_busy_source_preserves_bytes():+ data = [b'data: {"text":"', b'hello"}\n\n', b"data: [DONE]\n\n"]++ async def source():+ for chunk in data:+ yield chunk++ assert [chunk async for chunk in heartbeat(source(), 1)] == data+++async def test_idle_source_keeps_one_task_and_propagates_timeout():+ tasks, output = [], []++ async def source():+ async with async_timeout.timeout(0.06):+ for chunk in (b"first", b"second"):+ tasks.append(asyncio.current_task())+ yield chunk+ await asyncio.sleep(0.02)+ await asyncio.Event().wait()++ with pytest.raises(asyncio.TimeoutError):+ async with async_timeout.timeout(1):+ async for chunk in heartbeat(source(), 0.005):+ output.append(chunk)+ assert [chunk for chunk in output if chunk is not None] == [b"first", b"second"]+ assert None in output+ assert tasks[0] is tasks[1] and tasks[0].done()++[email protected]("error", [ValueError("upstream failed"), asyncio.CancelledError()])+async def test_source_failure_wakes_consumer_without_waiting_for_heartbeat(error):+ async def source():+ yield b"first"+ await asyncio.sleep(0.01)+ raise error++ async with async_timeout.timeout(1):+ with pytest.raises(type(error)):+ async for _ in heartbeat(source(), 15):+ pass+++async def test_deadline_during_backpressure_reaches_source_timeout_context():+ async def source():+ async with async_timeout.timeout(0.03):+ for _ in range(10):+ yield b"chunk"++ stream = heartbeat(source(), 15)+ assert await anext(stream) == b"chunk"+ await asyncio.sleep(0.06)+ async with async_timeout.timeout(1):+ with pytest.raises(asyncio.TimeoutError):+ async for _ in stream:+ pass++[email protected]("backpressure", [False, True])+async def test_closing_consumer_cancels_and_closes_source(backpressure):+ advanced, closed, tasks = [], [], []++ async def source():+ tasks.append(asyncio.current_task())+ try:+ async with async_timeout.timeout(1):+ for number in range(100):+ advanced.append(number)+ yield b"chunk"+ if not backpressure:+ await asyncio.Event().wait()+ finally:+ closed.append(asyncio.current_task())++ stream = heartbeat(source(), 0.005)+ assert await anext(stream) == b"chunk"+ await asyncio.sleep(0.02)+ assert len(advanced) <= 3+ async with async_timeout.timeout(1):+ await stream.aclose()+ assert closed == tasks and tasks[0].done()++[email protected]("encoding", [None, "gzip"])[email protected]("split", [False, True])+async def test_passthrough_heartbeats_only_at_uncompressed_event_boundaries(+ monkeypatch, encoding, split+):+ monkeypatch.setattr(proxy, "HEARTBEAT_SECONDS", 0.005)+ first = sse({"choices": [{"delta": {"content": "hello"}, "finish_reason": None}]})+ last = sse({"choices": [{"delta": {}, "finish_reason": "stop"}]})+ original = first + last+ data = gzip.compress(original) if encoding else original+ cut = 8 if split else len(first)++ async def source():+ yield data[:cut]+ await asyncio.sleep(0.03)+ yield data[cut:]++ headers = {"content-length": str(len(data))}+ if encoding:+ headers["content-encoding"] = encoding+ response = upstream(source, **headers)+ request = passthrough(response)+ outgoing = await proxy.ProxyRequest.observe_response(request)+ chunks = [chunk async for chunk in outgoing.body_iterator]+ assert (KEEP_ALIVE in chunks) == (not split and not encoding)+ assert b"".join(chunk for chunk in chunks if chunk != KEEP_ALIVE) == data+ assert "content-length" not in outgoing.headers+ output = b"".join(chunks)+ decoded = [+ value+ for frame in SSEDecoder().feed(gzip.decompress(output) if encoding else output)+ if (value := SSEDecoder.data(frame))+ ]+ assert decoded == [SSEDecoder.data(frame) for frame in SSEDecoder().feed(original)]+ assert response.close.called+ if not encoding:+ assert request.capture.complete+ assert request.capture.message["content"] == "hello"++[email protected]("asgi_disconnect", [False, True])+async def test_disconnect_closes_passthrough_response_and_pump(monkeypatch, asgi_disconnect):+ monkeypatch.setattr(proxy, "HEARTBEAT_SECONDS", 0.005)+ closed, tasks = [], []++ async def source():+ tasks.append(asyncio.current_task())+ try:+ await asyncio.Event().wait()+ yield b"unreachable"+ finally:+ closed.append(True)++ response = upstream(source)+ request = passthrough(response)+ outgoing = await proxy.ProxyRequest.observe_response(request)+ if asgi_disconnect:+ disconnected = asyncio.Event()++ async def send(message):+ if message.get("body") == KEEP_ALIVE:+ disconnected.set()++ async def receive():+ await disconnected.wait()+ return {"type": "http.disconnect"}++ await outgoing({"type": "http", "asgi": {"spec_version": "2.0"}}, receive, send)+ else:+ assert await anext(outgoing.body_iterator) == KEEP_ALIVE+ await outgoing.body_iterator.aclose()+ assert closed and tasks[0].done() and response.close.called+ assert not request.capture.complete++[email protected]("protocol", ["responses", "anthropic"])+async def test_disconnect_closes_hidden_loop_response_and_its_timeout_context(protocol):+ tasks = []++ async def source():+ tasks.append(asyncio.current_task())+ yield sse(native_events(protocol, native_response(protocol, 1))[0])+ await asyncio.Event().wait()++ response = upstream(source)+ prepared = SimpleNamespace(+ body=request_body(protocol, True),+ protocol=protocol,+ root={"policy": {"tool_total_seconds": 1}},+ metrics={},+ tools_active=True,+ reply_lead="",+ )+ loop = HiddenToolLoop(+ prepared, SimpleNamespace(allowed={"openviking_search"}), None, ResponseCapture(protocol)+ )+ stream = heartbeat(loop.run(response, None), 0.005)+ assert await anext(stream)+ await stream.aclose()+ assert response.close.called and tasks[0].done() and not loop.capture.complete++[email protected]("protocol", ["responses", "anthropic"])[email protected]("timeout", [False, True])+async def test_hidden_tools_heartbeat_and_total_deadline(+ running_gateway, monkeypatch, protocol, timeout+):+ monkeypatch.setattr(proxy, "HEARTBEAT_SECONDS", 0.005)+ app, client, admin, key, _, _ = running_gateway+ await enable_tools(+ client, admin, show_tool_calls=False, tool_total_seconds=0.05 if timeout else None+ )+ calls, captures = [], []+ original_finish = proxy.ProxyRequest.finish++ async def finish(request):+ captures.append(request.capture)+ await original_finish(request)++ monkeypatch.setattr(proxy.ProxyRequest, "finish", finish)++ async def backend(request):+ if request.path == "/mcp":+ await asyncio.sleep(0.1)+ return web.json_response({"id": 1, "result": {"content": []}})+ if request.path == PATHS[protocol]:+ calls.append(await request.json())+ value = native_response(protocol, len(calls), owned=len(calls) == 1)+ return await wire_response(request, protocol, value, True)+ return None++ app.state.test_backend["handler"] = backend+ async with async_timeout.timeout(2):+ response = await client.post(+ PATHS[protocol],+ headers={"Authorization": "Bearer " + key["key"]},+ json=request_body(protocol, True),+ )+ assert response.status_code == 200+ assert KEEP_ALIVE in response.content+ events = [+ value for frame in SSEDecoder().feed(response.content) if (value := SSEDecoder.data(frame))+ ]+ assert len(calls) == (1 if timeout else 2)+ assert captures[-1].complete == (not timeout)+ if timeout:+ assert b"Hidden tool request timed out" in response.content+ assert events[-1]["type"] == ("response.failed" if protocol == "responses" else "error")+ else:+ assert b"answer-2" in orjson.dumps(captures[-1].output)+ assert events[-1]["type"] == (+ "response.completed" if protocol == "responses" else "message_stop"+ )+ assert captures[-1].usage["output_tokens"] == 40++[email protected]("protocol", ["responses", "anthropic"])+async def test_gateway_passthrough_preserves_events_and_capture(+ running_gateway, monkeypatch, protocol+):+ monkeypatch.setattr(proxy, "HEARTBEAT_SECONDS", 0.005)+ app, client, _, key, _, _ = running_gateway+ expected = native_events(protocol, native_response(protocol, 1))+ captures = []+ original_finish = proxy.ProxyRequest.finish++ async def finish(request):+ captures.append(request.capture)+ await original_finish(request)++ monkeypatch.setattr(proxy.ProxyRequest, "finish", finish)++ async def backend(request):+ if request.path != PATHS[protocol]:+ return None+ response = web.StreamResponse(headers={"Content-Type": "text/event-stream"})+ await response.prepare(request)+ await response.write(sse(expected[0]))+ await asyncio.sleep(0.03)+ await response.write(b"".join(sse(event) for event in expected[1:]))+ return response++ app.state.test_backend["handler"] = backend+ response = await client.post(+ PATHS[protocol],+ headers={"Authorization": "Bearer " + key["key"]},+ json=request_body(protocol, True),+ )+ assert KEEP_ALIVE in response.content+ actual = [+ value for frame in SSEDecoder().feed(response.content) if (value := SSEDecoder.data(frame))+ ]+ assert actual == expected+ assert captures[-1].complete and captures[-1].usage["output_tokens"] == 20diff --git a/tests/gateway/test_standalone_startup.py b/tests/gateway/test_standalone_startup.pynew file mode 100644index 000000000..a14e5fe60--- /dev/null+++ b/tests/gateway/test_standalone_startup.py@@ -0,0 +1,109 @@+"""Standalone startup waits for transient failures and configures HTTP keep-alive."""++import json+import logging+import sys+from unittest.mock import AsyncMock, Mock, call++import pytest++from openviking_gateway import cli, standalone+from openviking_gateway.client import VikingError+from openviking_gateway.config import StandaloneGatewayConfig++[email protected](autouse=True)+def clean_environment(monkeypatch):+ for field in StandaloneGatewayConfig.model_fields:+ monkeypatch.delenv("OPENVIKING_GATEWAY_" + field.upper(), raising=False)+++def probe(monkeypatch):+ health, sleep = AsyncMock(), AsyncMock()+ monkeypatch.setattr(standalone.VikingClient, "health", health)+ monkeypatch.setattr(standalone.asyncio, "sleep", sleep)+ return health, sleep+++ "error",+ [+ VikingError("openviking_unavailable"),+ VikingError("openviking_http_500", 500),+ ],+)+async def test_public_startup_waits_with_capped_backoff(probe, caplog, error):+ health, sleep = probe+ ready = {"status": "ok", "auth_mode": "api_key"}+ health.side_effect = [error] * 7 + [ready]+ config = StandaloneGatewayConfig(openviking_url="http://ov.test", host="0.0.0.0")++ assert await standalone.check_openviking(config) == ready++ assert health.await_args_list == [call(require_identity=False)] * 8+ assert sleep.await_args_list == [call(delay) for delay in (1, 2, 4, 8, 16, 30, 30)]+ assert len(caplog.records) == 7+ assert all(record.levelno == logging.WARNING for record in caplog.records)+ assert error.reason in caplog.text+++ "result, message",+ [+ ({"auth_mode": "dev"}, "successful synchronous probe"),+ ({"status": "ok"}, "successful synchronous probe"),+ (VikingError("trusted_mode_unsupported", 403), "does not support trusted"),+ ],+)+async def test_public_recovery_still_requires_api_key_auth(probe, result, message):+ health, sleep = probe+ health.side_effect = [VikingError("openviking_http_503", 503), result]+ config = StandaloneGatewayConfig(openviking_url="http://ov.test", host="0.0.0.0")++ with pytest.raises(ValueError, match=message):+ await standalone.check_openviking(config)++ sleep.assert_awaited_once_with(1)+ assert health.await_count == 2++[email protected]("status", [302, 403, 404, 429])+async def test_public_startup_rejects_nontransient_http_errors(probe, status):+ health, sleep = probe+ health.side_effect = VikingError(f"openviking_http_{status}", status)+ config = StandaloneGatewayConfig(openviking_url="http://ov.test", host="0.0.0.0")++ with pytest.raises(ValueError, match="successful synchronous probe"):+ await standalone.check_openviking(config)++ health.assert_awaited_once_with(require_identity=False)+ sleep.assert_not_awaited()++[email protected]("host", ["127.0.0.1", "::1", "localhost"])+async def test_loopback_startup_does_not_wait(probe, host):+ health, sleep = probe+ health.side_effect = VikingError("openviking_unavailable")+ config = StandaloneGatewayConfig(openviking_url="http://ov.test", host=host)++ assert await standalone.check_openviking(config) == {+ "status": "degraded",+ "reason": "openviking_unavailable",+ }+ health.assert_awaited_once_with(require_identity=False)+ sleep.assert_not_awaited()+++def test_main_passes_keep_alive_to_uvicorn(tmp_path, monkeypatch):+ path = tmp_path / "gateway.conf"+ path.write_text(json.dumps({"openviking_url": "http://ov.test", "keep_alive_seconds": 90.5}))+ monkeypatch.setattr(sys, "argv", ["openviking-gateway", "--config", str(path)])+ check, run = AsyncMock(), Mock()+ monkeypatch.setattr(cli, "check_openviking", check)+ monkeypatch.setattr("uvicorn.run", run)++ cli.main()++ check.assert_awaited_once()+ assert run.call_args.kwargs["timeout_keep_alive"] == 90.5diff --git a/tests/gateway/test_storage_migration.py b/tests/gateway/test_storage_migration.pyindex fc427dabb..d9c398667 100644--- a/tests/gateway/test_storage_migration.py+++ b/tests/gateway/test_storage_migration.py@@ -11,8 +11,8 @@ from cryptography.fernet import Fernet, InvalidTokenfrom openviking.crypto.encryptor import MAGICfrom openviking_gateway.storage import (- ManagementStore,SQLiteKernelStore,+ SQLiteManagementStore,delete_account_data,delete_user_data,digest,@@ -136,7 +136,7 @@ EXPECTED = {str(i): (r[3], 7 + (r[2] != r[3])) for i, r in enumerate(UPSTREAMS)}async def test_v5_migration_reencodes_every_table(v5_storage, encrypted):directory, _ = v5_storageencryptor = local_encryptor(directory / "master.key") if encrypted else None- management = ManagementStore(directory / "management.sqlite3", encryptor)+ management = SQLiteManagementStore(directory / "management.sqlite3", encryptor)kernel = SQLiteKernelStore(directory / "kernel.sqlite3", encryptor)try:await management.initialize()@@ -189,7 +189,7 @@ async def test_legacy_key_from_environment(v5_storage, monkeypatch):async def test_missing_legacy_key_refuses_startup(v5_storage, name):directory, _ = v5_storage(directory / "encryption.key").unlink()- store = (ManagementStore if name == "management.sqlite3" else SQLiteKernelStore)(+ store = (SQLiteManagementStore if name == "management.sqlite3" else SQLiteKernelStore)(directory / name)try:@@ -205,7 +205,7 @@ async def test_empty_v5_stores_need_no_legacy_key(tmp_path):for name, layout in (("management.sqlite3", V5_MANAGEMENT), ("kernel.sqlite3", V5_KERNEL)):with sqlite3.connect(tmp_path / name) as c:c.executescript(layout)- management = ManagementStore(tmp_path / "management.sqlite3")+ management = SQLiteManagementStore(tmp_path / "management.sqlite3")kernel = SQLiteKernelStore(tmp_path / "kernel.sqlite3")try:await management.initialize()@@ -221,7 +221,7 @@ async def test_failed_migration_rolls_back_schema_and_objects(v5_storage):path = directory / "management.sqlite3"with sqlite3.connect(path) as c:c.execute("UPDATE objects SET value=? WHERE id='8'", (b"corrupt",))- store = ManagementStore(path)+ store = SQLiteManagementStore(path)try:with pytest.raises(InvalidToken):await store.initialize()@@ -238,7 +238,7 @@ async def test_failed_migration_rolls_back_schema_and_objects(v5_storage):async def test_workers_can_migrate_same_v5_database(v5_storage):directory, _ = v5_storageencryptor = local_encryptor(directory / "master.key")- workers = [ManagementStore(directory / "management.sqlite3", encryptor) for _ in range(6)]+ workers = [SQLiteManagementStore(directory / "management.sqlite3", encryptor) for _ in range(6)]try:await asyncio.gather(*(worker.initialize() for worker in workers))for worker in workers:@@ -250,13 +250,13 @@ async def test_workers_can_migrate_same_v5_database(v5_storage):async def test_enabling_encryption_later_keeps_plaintext_readable(tmp_path):path = tmp_path / "management.sqlite3"- plain = ManagementStore(path)+ plain = SQLiteManagementStore(path)try:await plain.initialize()await plain.save("a", "upstreams", "old", {"name": "old"})finally:plain.close()- encrypted = ManagementStore(path, local_encryptor(tmp_path / "master.key"))+ encrypted = SQLiteManagementStore(path, local_encryptor(tmp_path / "master.key"))try:await encrypted.initialize()await encrypted.save("a", "upstreams", "new", {"name": "new"})@@ -267,7 +267,7 @@ async def test_enabling_encryption_later_keeps_plaintext_readable(tmp_path):rows = dict(c.execute("SELECT id,value FROM objects"))assert rows["new"].startswith(MAGIC) and orjson.loads(rows["old"]) == {"name": "old"}# Disabling encryption again cannot silently read the encrypted rows.- plain = ManagementStore(path)+ plain = SQLiteManagementStore(path)try:with pytest.raises(RuntimeError, match="encrypted"):await plain.list("a", "upstreams")@@ -277,7 +277,7 @@ async def test_enabling_encryption_later_keeps_plaintext_readable(tmp_path):@pytest.mark.asyncioasync def test_user_filtering_and_deletion_preserves_other_users(tmp_path):- management = ManagementStore(tmp_path / "management.sqlite3")+ management = SQLiteManagementStore(tmp_path / "management.sqlite3")kernel = SQLiteKernelStore(tmp_path / "kernel.sqlite3")try:await management.initialize()diff --git a/tests/gateway/test_storage_ports.py b/tests/gateway/test_storage_ports.pyindex d60b09172..30d45870a 100644--- a/tests/gateway/test_storage_ports.py+++ b/tests/gateway/test_storage_ports.py@@ -1,12 +1,18 @@-"""Exercise the kernel with single-key KV primitives, without any SQL API."""+"""Storage port contracts, run against every backend, plus Redis-specific behavior."""import asyncio-import copyimport time-import uuid+from unittest.mock import AsyncMockimport pytest-from conftest import FakeViking+from conftest import (+ FakeViking,+ corrupt_root,+ evict_state,+ open_kernel_store,+ open_redis_backend,+ redis_settings,+)from openviking_gateway.capture import CaptureWorkerfrom openviking_gateway.capture_store import Document, LeaseLost@@ -14,116 +20,12 @@ from openviking_gateway.kernel import MemoryKernelfrom openviking_gateway.models import Policyfrom openviking_gateway.records import RecordKind as Kfrom openviking_gateway.replay_store import INHERITED-from openviking_gateway.storage import ManagementStore, digest+from openviking_gateway.storage import CachedManagement, SQLiteManagementStore, digestfrom openviking_gateway.tool_protocols import ResponseCapture-class KVReplay:- def __init__(self):- self.values = {}-- async def read(self, scope, session, anchors, ancestors=()):- rows = sorted(- (owner == session, owner, k, a, v)- for (s, owner, k, a), v in self.values.items()- if s == scope- and a in anchors- and k != K.REPLY- and (owner == session or owner in ancestors and k in INHERITED)- )- return {(k, a): copy.deepcopy(v) for _, _, k, a, v in rows}-- async def replies(self, scope, anchors):- owners = {}- for s, owner, k, a in self.values:- if s == scope and k == K.REPLY and a in anchors:- owners.setdefault(a, set()).add(owner)- return owners-- async def put(self, scope, session, kind, anchor, value):- return copy.deepcopy(- self.values.setdefault((scope, session, kind, anchor), copy.deepcopy(value))- )---class KVState:- def __init__(self):- self.values = {}-- async def read(self, scope, keys):- return {- key: copy.deepcopy(self.values[scope, key])- for key in keys- if (scope, key) in self.values- }-- async def swap(self, scope, key, previous, value):- current = self.values.get((scope, key), Document())- if current.version != previous.version:- return False- self.values[scope, key] = Document(copy.deepcopy(value), previous.version + 1)- return True---class KVQueue(KVState):- def __init__(self):- super().__init__()- self.ready, self.leases = {}, {}-- async def get(self, scope, session):- return copy.deepcopy(self.values.get((scope, session), Document()))-- async def swap(self, scope, session, previous, value, ready, owner=None):- key = scope, session- lease = self.leases.get(key, (None, 0))- if owner is not None and (lease[0] != owner or lease[1] <= time.time()):- raise LeaseLost- if not await super().swap(scope, session, previous, value):- return False- self.ready[key] = ready- return True-- async def claim(self, lease_seconds=120):- for key, ready in self.ready.items():- if (- ready is not None- and ready <= time.time()- and self.leases.get(key, (None, 0))[1] < time.time()- ):- owner = uuid.uuid4().hex- self.leases[key] = owner, time.time() + lease_seconds- return {- "scope": key[0],- "session": key[1],- "owner": owner,- "document": await self.get(*key),- }- return None-- async def release(self, item):- key = item["scope"], item["session"]- if self.leases[key][0] == item["owner"]:- self.leases.pop(key)---class KVPorts:- def __init__(self):- self.replay, self.state, self.capture = KVReplay(), KVState(), KVQueue()-- async def load(self, scope, session, anchors, ancestors=()):- return (- await self.replay.read(scope, session, anchors, ancestors),- await self.state.read(scope, [session]),- await self.capture.get(scope, session),- )-- async def keep(self, scope, sessions, keys):- pass--[email protected]("protocol", ["chat", "anthropic", "responses"])-async def test_kernel_and_capture_work_with_kv_ports(credential, protocol):- ports, viking = KVPorts(), FakeViking()+async def exercise_kernel_capture(ports, credential, protocol):+ viking = FakeViking()kernel = MemoryKernel(ports, viking)class Management:@@ -194,22 +96,10 @@ async def test_kernel_and_capture_work_with_kv_ports(credential, protocol):assert fork.capture_target != p.capture_targetassert await worker.once() and await worker.once()assert len(set(viking.write_sessions)) == 2- assert set(K) == {- K.ROOT,- K.INJECTION,- K.DISABLED,- K.TOOLS,- K.TOOLS_CLOSED,- K.CLIENT_TOOLS,- K.HIDDEN,- K.REPLACEMENT,- K.REPLY,- K.REASONING,- }-async def test_expired_lease_cannot_write_or_release_new_owner(setup_kernel):- _, store, _, _ = setup_kernel+async def test_expired_lease_cannot_write_or_release_new_owner(kernel_store):+ store = kernel_storeawait store.capture.swap("scope", "session", Document(), {"work": 1}, 0)expired = await store.capture.claim(lease_seconds=-1)active = await store.capture.claim()@@ -271,35 +161,10 @@ async def test_batched_reads_keep_scope_isolation_and_handle_cancellation(assert len(batches) == 2-async def test_corrupt_record_does_not_fail_other_reads_in_batch(setup_kernel):- from openviking.crypto import CorruptedCiphertextError- from openviking.crypto.encryptor import MAGIC-- _, store, _, _ = setup_kernel- for scope in ("damaged", "healthy"):- await store.replay.put(scope, "session", K.ROOT, "", {"scope": scope})-- def corrupt():- with store.connect() as connection:- connection.execute(- "UPDATE replay SET value=? WHERE scope=?",- (MAGIC + b"invalid ciphertext", "damaged"),- )-- await store.run(corrupt, write=True)- damaged, healthy = await asyncio.gather(- store.load("damaged", "session", [""]),- store.load("healthy", "session", [""]),- return_exceptions=True,- )- assert isinstance(damaged, CorruptedCiphertextError)- assert healthy[0][K.ROOT, ""] == {"scope": "healthy"}--async def test_new_session_does_not_freeze_other_process_stale_policy(setup_kernel, credential):kernel, store, _, encryption = setup_kernel- writer = ManagementStore(store.path.parent / "management.sqlite3", encryption)- reader = ManagementStore(writer.path, encryption)+ writer = SQLiteManagementStore(store.path.parent / "management.sqlite3", encryption)+ reader = CachedManagement(SQLiteManagementStore(writer.path, encryption))await writer.initialize()await reader.initialize()try:@@ -320,12 +185,13 @@ async def test_new_session_does_not_freeze_other_process_stale_policy(setup_kernassert not (await store.capture.get(request.scope, request.session)).valuefinally:writer.close()- reader.close()+ reader.port.close()async def test_response_bookkeeping_preserves_configuration_cache(setup_kernel, monkeypatch):_, store, _, encryption = setup_kernel- management = ManagementStore(store.path.parent / "management.sqlite3", encryption)+ port = SQLiteManagementStore(store.path.parent / "management.sqlite3", encryption)+ management = CachedManagement(port)await management.initialize()try:await management.save("tenant", "keys", digest("downstream"), {"name": "key"})@@ -334,19 +200,717 @@ async def test_response_bookkeeping_preserves_configuration_cache(setup_kernel,await management.list("tenant", "upstreams")await management.save("tenant", "responses", "response", {"upstream_id": "model"}, ttl=1)await management.expire_logs(0)- read = management.run- reads = []-- async def counted(fn, *args, **kwargs):- if not kwargs.get("write"):- reads.append(fn)- return await read(fn, *args, **kwargs)-- monkeypatch.setattr(management, "run", counted)+ credential = AsyncMock(wraps=port.credential)+ upstreams = AsyncMock(wraps=port.list)+ monkeypatch.setattr(port, "credential", credential)+ monkeypatch.setattr(port, "list", upstreams)assert (await management.authenticate("downstream"))["name"] == "key"assert (await management.list("tenant", "upstreams"))[0]["name"] == "model"- assert not reads+ credential.assert_not_awaited()+ upstreams.assert_not_awaited()await management.delete("tenant", "keys", digest("downstream"))assert await management.authenticate("downstream") is Nonefinally:- management.close()+ port.close()++[email protected]("kind", ["keys", "upstreams"])+async def test_cached_lists_filter_users_and_reload_after_another_process_writes(+ tmp_path, monkeypatch, kind+):+ port = SQLiteManagementStore(tmp_path / "management.sqlite3")+ management = CachedManagement(port)+ await management.initialize()+ try:+ for user in ("alice", "bob"):+ await management.save("tenant", kind, user, {"user_id": user})+ assert [v["id"] for v in await management.list("tenant", kind, "alice")] == ["alice"]+ assert [v["id"] for v in await management.list("tenant", kind, "bob")] == ["bob"]+ await port.delete("tenant", kind, "bob")+ assert len(await management.list("tenant", kind)) == 2+ monotonic = time.monotonic+ monkeypatch.setattr(time, "monotonic", lambda: monotonic() + 3)+ assert [v["id"] for v in await management.list("tenant", kind)] == ["alice"]+ finally:+ port.close()++[email protected]("operation", ["save", "delete", "delete_user", "delete_account"])+async def test_management_writes_invalidate_cached_credentials(tmp_path, operation):+ port = SQLiteManagementStore(tmp_path / "management.sqlite3")+ management = CachedManagement(port)+ await management.initialize()+ try:+ identifier = digest("key")+ await management.save("tenant", "keys", identifier, {"user_id": "alice"})+ assert (await management.authenticate("key"))["user_id"] == "alice"+ if operation == "save":+ await management.save("tenant", "keys", identifier, {"user_id": "bob"})+ assert (await management.authenticate("key"))["user_id"] == "bob"+ else:+ args = {+ "delete": ("tenant", "keys", identifier),+ "delete_user": ("tenant", "alice"),+ "delete_account": ("tenant",),+ }+ await getattr(management, operation)(*args[operation])+ assert await management.authenticate("key") is None+ finally:+ port.close()++[email protected]("failing", ["SQLiteKernelStore", "SQLiteManagementStore"])+async def test_app_closes_both_stores_when_initialization_fails(tmp_path, monkeypatch, failing):+ import threading++ from openviking_gateway import app, storage+ from openviking_gateway.config import GatewayConfig++ closed = []+ loop_thread = threading.get_ident()+ close_database = storage.Database.close++ def close(self):+ assert threading.get_ident() != loop_thread+ closed.append(type(self).__name__)+ close_database(self)++ async def fail(self):+ raise RuntimeError("initialization failed")++ monkeypatch.setattr(storage.Database, "close", close)+ monkeypatch.setattr(getattr(storage, failing), "initialize", fail)+ gateway = app.create_app(GatewayConfig(storage_path=str(tmp_path)), openviking_url="http://ov")+ with pytest.raises(RuntimeError, match="initialization failed"):+ async with gateway.router.lifespan_context(gateway):+ pytest.fail("initialization should fail before serving requests")+ assert sorted(closed) == ["SQLiteKernelStore", "SQLiteManagementStore"]+++async def test_management_order_filter_and_revision(management_store):+ for identifier in ("z", "é", "a", "{foreign}:*"):+ await management_store.save("account", "upstreams", identifier, {"user_id": "one"})+ await management_store.save("account", "upstreams", "other", {"user_id": "two"})+ rows = await management_store.list("account", "upstreams", user_id="one")+ assert [row["id"] for row in rows] == ["a", "z", "{foreign}:*", "é"]+ assert (await management_store.save("account", "upstreams", "a", {"name": "new"}))[+ "revision"+ ] == 2+ assert await management_store.list("elsewhere", "upstreams") == []+++async def test_management_expiration_and_recreation(management_store):+ await management_store.save("account", "keys", "short", {"user_id": "one"}, ttl=0.08)+ await management_store.save("account", "keys", "short", {"user_id": "one", "updated": True})+ await asyncio.sleep(0.1)+ assert await management_store.get("account", "keys", "short") is None+ assert await management_store.credential("short") is None+ await management_store.expire_logs(0)+ assert await management_store.list("account", "keys") == []+ await management_store.save("account", "keys", "short", {"user_id": "one"}, ttl=1)+ await management_store.delete("account", "keys", "short")+ await management_store.save("account", "keys", "short", {"user_id": "one"})+ await asyncio.sleep(0.01)+ assert await management_store.credential("short") is not None+++async def test_management_payload_expiry_applies_without_ttl(management_store):+ await management_store.save("account", "keys", "id", {"expires_at": time.time() - 1})+ assert await management_store.get("account", "keys", "id") is None+ assert await management_store.credential("id") is None+++async def test_management_credential_and_cached_wrapper(management_store):+ from openviking_gateway.storage import CachedManagement++ cached = CachedManagement(management_store)+ identifier = digest("secret")+ await cached.save("other-account", "keys", identifier, {"user_id": "one"})+ assert (await cached.authenticate("secret"))["account"] == "other-account"+ await cached.delete("other-account", "keys", identifier)+ assert await cached.authenticate("secret") is None+ await cached.save("other-account", "keys", identifier, {"user_id": "one"})+ assert (await cached.credential(identifier))["id"] == identifier+++ "storage_encryptor", [False, True], ids=["plaintext", "encrypted"], indirect=True+)+async def test_management_delete_user_and_account(management_store):+ for user in ("one", "two"):+ await management_store.save("account", "keys", user, {"user_id": user})+ await management_store.save("account", "users", user, {"user_id": user})+ await management_store.log("account", {"message": user}, user_id=user)+ await management_store.save("account", "policies", "default", {"name": "keep"})+ await management_store.save("other", "keys", "separate", {"user_id": "one"})+ assert (await management_store.logs("account", user_id="one"))[0]["message"] == "one"+ await management_store.delete_user("account", "one")+ assert await management_store.credential("one") is None+ assert [row["id"] for row in await management_store.list("account", "users")] == ["two"]+ assert [row["message"] for row in await management_store.logs("account")] == ["two"]+ assert await management_store.get("account", "policies", "default")+ await management_store.delete_account("account")+ assert await management_store.credential("two") is None+ assert await management_store.logs("account") == []+ assert await management_store.list("account", "policies") == []+ assert await management_store.credential("separate")+++async def test_management_large_value(management_store):+ value = {"text": "v" * (8 * 1024 * 1024)}+ await management_store.save("account", "responses", "large", value, ttl=5)+ assert (await management_store.get("account", "responses", "large"))["text"] == value["text"]+++async def test_redis_ttl_removes_partition_and_reverse_index(redis_management_store):+ store, backend = redis_management_store, redis_management_store.backend+ await store.save("expiring", "keys", "short", {"user_id": "one"}, ttl=0.08)+ await store.save("expiring", "users", "one", {"user_id": "one"}, ttl=0.08)+ await asyncio.sleep(0.12)+ assert [key async for key in backend.scan(backend.prefix + "*")] == []+++async def test_redis_missing_credential_object_does_not_remove_index(redis_management_store):+ store, backend = redis_management_store, redis_management_store.backend+ await store.save("account", "keys", "key", {"user_id": "one"})+ await backend.client.execute_command("DEL", store.object_key("account", "keys", "key"))+ assert await store.credential("key") is None+ assert await backend.client.get(store.credential_key("key")) == b"account"+ await asyncio.gather(+ *(store.save("account", "keys", "key", {"user_id": "one"}) for _ in range(10))+ )+ assert all(await asyncio.gather(*(store.credential("key") for _ in range(20))))+++async def test_redis_logs_are_bounded_and_user_deletion_preserves_ttl(redis_management_store):+ store, backend = redis_management_store, redis_management_store.backend+ key = store.account_prefix("account") + "log"+ # Seed old entries in one command; the next production write must enforce the cap.+ await backend.client.lpush(key, *([b"0\0\0{}"] * 10005))+ await store.log("account", {"message": "keep"}, user_id="two")+ await store.log("account", {"message": "remove"}, user_id="one")+ assert await backend.client.llen(key) == 10000+ await backend.client.pexpire(key, 2000)+ await store.delete_user("account", "one")+ assert 0 < await backend.client.pttl(key) <= 2000+ assert [r["message"] for r in await store.logs("account", user_id="two")] == ["keep"]+ assert await store.logs("account", user_id="one") == []+++async def test_redis_script_reload_and_scoped_scan(redis_management_store):+ store, backend = redis_management_store, redis_management_store.backend+ await store.save("account", "keys", "key", {"user_id": "one"})+ script = backend.script("obj_save")+ script.sha = "0" * 40 # Force NOSCRIPT without flushing scripts used by other test workers.+ assert (await store.save("account", "keys", "key", {"user_id": "one"}))["revision"] == 2+ prefix = store.account_prefix("account")+ assert len([key async for key in backend.scan(prefix + "*")]) == 2+++ "settings",+ [+ {"redis": {"pool_sze": 10}},+ {"key_prefix": "bad{tag}:"},+ {"key_prefix": "bad*"},+ {"redis": {"endpoints": ["redis://user:password@localhost:6379"]}},+ ],+)+def test_storage_configuration_fails_while_loading(settings, tmp_path, monkeypatch):+ import json++ from pydantic import ValidationError++ from openviking_gateway.cli import load_config++ path = tmp_path / "gateway.conf"+ path.write_text(json.dumps({"openviking_url": "http://ov", "storage": settings}))+ monkeypatch.setenv("OPENVIKING_GATEWAY_CONFIG_FILE", str(path))+ with pytest.raises(ValidationError):+ load_config()+++def test_storage_redis_defaults():+ from openviking_gateway.config import GatewayConfig++ assert GatewayConfig().storage.redis["command_timeout_ms"] == 5000++[email protected]("provider", ["redis", "redis-cluster"])+async def test_redis_commands_beyond_pool_size_wait_for_a_connection(provider):+ from openviking_gateway.redis_store import connect++ handle = connect({**redis_settings(provider), "command_timeout_ms": 5000, "pool_size": 2})+ try:+ assert await asyncio.gather(*(handle.client.ping() for _ in range(20))) == [True] * 20+ finally:+ await handle.close()+++async def test_async_codec_reads_sqlite_ciphertext_and_plaintext(tmp_path):+ from conftest import local_encryptor++ from openviking_gateway.storage import AsyncCodec, SQLiteManagementStore++ encryptor = local_encryptor(tmp_path / "root.key")+ codec = AsyncCodec(encryptor)+ other_replica = AsyncCodec(local_encryptor(tmp_path / "root.key"))+ database = SQLiteManagementStore(tmp_path / "management.sqlite3", encryptor)+ try:+ value = {"secret": "memory"}+ encrypted = await database.run(database.encode, value)+ assert await codec.decode(encrypted) == value+ assert await other_replica.decode(await codec.encode(value)) == value+ assert await database.run(database.decode, await codec.encode(value)) == value+ assert await codec.decode(b'{"plain":true}') == {"plain": True}+ with pytest.raises(RuntimeError, match="Gateway data is encrypted"):+ await AsyncCodec().decode(encrypted)+ finally:+ database.close()++[email protected]("operation", ["save", "log"])+async def test_redis_does_not_repeat_a_write_after_losing_its_response(+ redis_management_store, monkeypatch, operation+):+ from redis.asyncio import Redis+ from redis.asyncio.cluster import ClusterNode, RedisCluster+ from redis.exceptions import ConnectionError++ store, backend = redis_management_store, redis_management_store.backend+ await store.save("account", "upstreams", "object", {"value": "before"})+ target = ClusterNode if isinstance(backend.client, RedisCluster) else Redis+ parse_response = target.parse_response+ attempts = []++ async def lose_response(client, connection, command, **kwargs):+ response = await parse_response(client, connection, command, **kwargs)+ if command.upper() == "EVALSHA":+ attempts.append(command)+ if len(attempts) == 1:+ await connection.disconnect()+ raise ConnectionError("socket lost after Redis committed the write")+ return response++ monkeypatch.setattr(target, "parse_response", lose_response)+ with pytest.raises(ConnectionError):+ if operation == "save":+ await store.save("account", "upstreams", "object", {"value": "after"})+ else:+ await store.log("account", {"message": "once"})+ assert len(attempts) == 1+ if operation == "save":+ assert (await store.get("account", "upstreams", "object"))["revision"] == 2+ else:+ assert len(await store.logs("account")) == 1++[email protected]("protocol", ["chat", "anthropic", "responses"])+async def test_kernel_capture_backend_contract(kernel_store, credential, protocol):+ await exercise_kernel_capture(kernel_store, credential, protocol)+++async def test_replay_put_if_absent_is_atomic(kernel_store):+ store = kernel_store+ results = await asyncio.gather(+ *(store.replay.put("scope", "session", K.ROOT, "", {"winner": i}) for i in range(50))+ )+ assert all(value == results[0] for value in results)+ assert results[0] in [{"winner": i} for i in range(50)]+ assert await store.replay.put("scope", "session", K.ROOT, "", {"winner": -1}) == results[0]+ assert await store.replay.read("other", "session", [""]) == {}+++async def test_replay_inheritance_and_reply_index(kernel_store):+ store = kernel_store+ for sid in ("z-parent", "a-parent", "child"):+ for kind in K:+ await store.replay.put("scope", sid, kind, "anchor", {"owner": sid})+ values = await store.replay.read("scope", "child", ["anchor"], ["z-parent", "a-parent"])+ assert set(values) == {(kind, "anchor") for kind in K if kind != K.REPLY}+ assert all(value == {"owner": "child"} for value in values.values())+ inherited = await store.replay.read("scope", "new-child", ["anchor"], ["z-parent", "a-parent"])+ assert inherited == {(kind, "anchor"): {"owner": "z-parent"} for kind in INHERITED}+ assert await store.replay.read("scope", "child", []) == {}+ assert await store.replay.replies("scope", ["anchor", "missing"]) == {+ "anchor": {"a-parent", "z-parent", "child"}+ }+++async def test_state_cas_versions_and_load_snapshot(kernel_store):+ store = kernel_store+ results = await asyncio.gather(+ *(store.state.swap("scope", "session", Document(), {"winner": i}) for i in range(50))+ )+ assert sum(results) == 1+ first = (await store.state.read("scope", ["session"]))["session"]+ assert first.version == 1+ assert await store.state.swap("scope", "session", first, {"updated": True})+ assert not await store.state.swap("scope", "session", first, {"stale": True})+ assert not await store.state.swap("scope", "session", Document(), {})+ assert await store.capture.swap("scope", "session", Document(), {"pending": [1]}, None)+ capture = await store.capture.get("scope", "session")+ assert capture.version == 1+ assert await store.capture.swap("scope", "session", capture, {"pending": []}, None)+ assert not await store.capture.swap("scope", "session", capture, {"stale": True}, 0)+ assert not await store.capture.swap("scope", "session", Document(), {}, 0)+ await store.replay.put("scope", "session", K.ROOT, "", {"root": True})+ replay, state, capture = await store.load("scope", "session", [""])+ assert replay == {(K.ROOT, ""): {"root": True}}+ assert state == {"session": Document({"updated": True}, 2)}+ assert capture == Document({"pending": []}, 2)+ assert await store.state.read("other", ["session"]) == {}+ assert await store.state.read("scope", []) == {}+++async def test_capture_ready_zero_lease_and_release(kernel_store):+ store = kernel_store+ for sid in ("one", "two"):+ assert await store.capture.swap("scope", sid, Document(), {"sid": sid}, 0)+ assert await store.capture.swap("scope", "idle", Document(), {}, None)+ assert await store.capture.swap("scope", "future", Document(), {}, time.time() + 3600)+ first, second = await asyncio.gather(store.capture.claim(), store.capture.claim())+ assert {first["session"], second["session"]} == {"one", "two"}+ assert first["owner"] != second["owner"]+ assert first["document"].version == second["document"].version == 1+ assert await store.capture.claim() is None+ await store.capture.release(first)+ again = await store.capture.claim()+ assert again["session"] == first["session"]+ assert again["owner"] != first["owner"]+ await store.capture.release(first)+ assert await store.capture.claim() is None+ assert await store.capture.swap(+ "scope", again["session"], again["document"], {"done": True}, None, owner=again["owner"]+ )+ await store.capture.release(again)+ assert await store.capture.claim() is None+++async def test_scope_delete_blocks_concurrent_writes(kernel_store):+ store = kernel_store+ await store.replay.put("scope", "session", K.REPLY, "reply", {})+ await store.capture.swap("scope", "session", Document(), {"work": 1}, 0)+ await store.state.swap("scope", "session", Document(), {"state": 1})+ operations = [store.expire(0, "scope")]+ for i in range(20):+ operations.extend(+ (+ store.replay.put("scope", f"s{i}", K.ROOT, "", {}),+ store.capture.swap("scope", f"s{i}", Document(), {}, 0),+ store.state.swap("scope", f"s{i}", Document(), {}),+ )+ )+ results = await asyncio.gather(*operations, return_exceptions=True)+ assert all(+ not isinstance(value, Exception)+ or (isinstance(value, RuntimeError) and str(value) == "Gateway user data has been deleted")+ for value in results+ )+ for sid in ["session", *[f"s{i}" for i in range(20)]]:+ assert await store.load("scope", sid, ["", "reply"]) == ({}, {}, Document())+ for operation in (+ store.replay.put("scope", "late", K.ROOT, "", {}),+ store.state.swap("scope", "late", Document(), {}),+ store.capture.swap("scope", "late", Document(), {}, 0),+ store.keep("scope", ["late"], ["late"]),+ ):+ with pytest.raises(RuntimeError, match="Gateway user data has been deleted"):+ await operation+ await store.allow_scope("scope")+ await store.replay.put("scope", "late", K.ROOT, "", {})+ assert await store.state.swap("scope", "late", Document(), {})+ assert await store.capture.swap("scope", "late", Document(), {}, 0)+++ "storage_encryptor", [False, True], ids=["plaintext", "encrypted"], indirect=True+)+async def test_large_kernel_value_and_load_failure_isolation(kernel_store, storage_encryptor):+ from openviking.crypto import CorruptedCiphertextError+ from openviking.crypto.encryptor import MAGIC++ store = kernel_store+ large = {"text": "x" * (8 * 1024 * 1024)}+ assert await store.replay.put("healthy", "session", K.ROOT, "", large) == large+ await store.replay.put("damaged", "session", K.ROOT, "", {})+ await corrupt_root(store, "damaged", "session", MAGIC + b"invalid")+ damaged, healthy = await asyncio.gather(+ store.load("damaged", "session", [""]),+ store.load("healthy", "session", [""]),+ return_exceptions=True,+ )+ if storage_encryptor is None:+ assert isinstance(damaged, RuntimeError)+ assert "configure the encryption settings" in str(damaged)+ else:+ assert isinstance(damaged, CorruptedCiphertextError)+ assert healthy[0][K.ROOT, ""] == large+++async def test_redis_eviction_prunes_replies_and_loses_leases(redis_kernel_store, monkeypatch):+ store = redis_kernel_store+ await store.replay.put("scope", "parent", K.REPLY, "anchor", {})+ await store.replay.put("scope", "parent", K.REPLACEMENT, "anchor", {"summary": "old"})+ await store.replay.put("scope", "sibling", K.REPLY, "anchor", {})+ await store.replay.put("scope", "other", K.REPLY, "second", {})+ assert await store.replay.replies("scope", ["anchor", "second"]) == {+ "anchor": {"parent", "sibling"},+ "second": {"other"},+ }+ await store.client.execute_command("DEL", store.replay_key("scope", "parent"))+ await store.client.execute_command("DEL", store.replay_key("scope", "sibling"))+ await store.replay.put("scope", "parent", K.ROOT, "", {})+ scripts, script = [], store.script++ async def counted(name, keys, args):+ scripts.append(name)+ return await script(name, keys, args)++ monkeypatch.setattr(store, "script", counted)+ assert await store.replay.replies("scope", ["anchor", "missing", "second"]) == {+ "second": {"other"}+ }+ # Two round trips, whatever the number of anchors.+ assert scripts == ["kernel_replies_read", "kernel_replies_prune"]+ assert await store.client.smembers(store.replay.index("scope", "anchor")) == set()+ assert await store.replay.read("scope", "child", ["anchor"], ["parent"]) == {}+ assert await store.capture.swap("scope", "session", Document(), {"work": 1}, 0)+ item = await store.capture.claim()+ await store.client.execute_command("DEL", store.capture_key("scope", "session"))+ with pytest.raises(LeaseLost):+ await store.capture.swap(+ "scope", "session", item["document"], {}, None, owner=item["owner"]+ )+ await store.capture.release(item)+ assert await store.capture.get("scope", "session") == Document()+ await store.client.zadd(store.capture.ready, {"scope\0session": 0})+ assert await store.capture.claim() is None+ assert await store.client.zcard(store.capture.ready) == 0+ assert await store.capture.swap("scope", "session", Document(), {}, 0)+ assert (await store.capture.get("scope", "session")).version == 1+ assert await store.state.swap("scope", "state", Document(), {"old": True})+ old = (await store.state.read("scope", ["state"]))["state"]+ await store.client.execute_command("DEL", store.state_key("scope", "state"))+ assert not await store.state.swap("scope", "state", old, {})+ assert await store.state.swap("scope", "state", Document(), {"new": True})+ assert (await store.state.read("scope", ["state"]))["state"].version == 1+++async def test_redis_ttl_refresh_is_throttled_and_reads_do_not_refresh(redis_kernel_store):+ store = redis_kernel_store+ await store.capture.swap("scope", "session", Document(), {}, None)+ await store.replay.put("scope", "session", K.REPLY, "anchor", {})+ await store.state.swap("scope", "session", Document(), {})+ rp, cap, state = (+ store.replay_key("scope", "session"),+ store.capture_key("scope", "session"),+ store.state_key("scope", "session"),+ )+ index = store.replay.index("scope", "anchor")+ for key in (rp, cap, state, index):+ await store.client.pexpire(key, 5000)+ await store.load("scope", "session", ["anchor"])+ await store.state.read("scope", ["session"])+ for key in (rp, cap, state, index):+ assert 0 < await store.client.pttl(key) <= 5000+ await store.replay.put("scope", "session", K.ROOT, "", {})+ assert await store.client.pttl(rp) > 5000+ assert await store.client.pttl(cap) <= 5000+ store.touched[cap] = time.monotonic() - 61+ await store.replay.put("scope", "session", K.ROOT, "", {})+ assert await store.client.pttl(cap) > 5000+ await store.client.pexpire(rp, 5000)+ store.touched[rp] = time.monotonic() - 61+ old = await store.capture.get("scope", "session")+ assert await store.capture.swap("scope", "session", old, {}, None)+ assert await store.client.pttl(rp) > 5000+ await store.client.pexpire(cap, 5000)+ store.touched[cap] = time.monotonic() - 61+ await store.keep("scope", ["session"], ["session"])+ assert await store.client.pttl(cap) > 5000+ assert await store.client.pttl(state) > 5000+ assert await store.replay.replies("scope", ["anchor"]) == {"anchor": {"session"}}+ assert await store.client.pttl(index) > 5000+ await store.expire(time.time() + 86400)+ assert (await store.capture.get("scope", "session")).version == 2+ for key in (rp, cap, state, index):+ await store.client.pexpire(key, 1)+ await asyncio.sleep(0.02)+ assert await store.load("scope", "session", ["", "anchor"]) == ({}, {}, Document())+ assert await store.replay.replies("scope", ["anchor"]) == {}++[email protected]("evicted_read", [1, 2])+async def test_evicted_tool_receipt_returns_unknown_without_repeating(+ kernel_store, credential, monkeypatch, evicted_read+):+ from types import SimpleNamespace+ from unittest.mock import AsyncMock++ import orjson++ from openviking_gateway.tool_executor import UNKNOWN_OUTCOME, ToolExecutor++ store = kernel_store+ call = {"id": "write-1", "function": {"name": "openviking_write", "arguments": "{}"}}+ prepared = SimpleNamespace(+ scope="scope",+ session="session",+ chain=[],+ root={+ "policy": {"tool_timeout_seconds": 30},+ "tools": [{"function": {"name": "openviking_write", "parameters": {}}}],+ },+ )+ receipt_key = "tool:session:" + digest(orjson.dumps(call).decode())+ await store.state.swap(+ "scope", receipt_key, Document(), {"owner": "another-worker", "time": time.time()}+ )+ read, reads = store.state.read, 0++ async def evict(scope, keys):+ nonlocal reads+ reads += 1+ if reads == evicted_read:+ await evict_state(store, scope, receipt_key)+ return await read(scope, keys)++ monkeypatch.setattr(store.state, "read", evict)+ executor = ToolExecutor(None, store, prepared, credential, "", 1024)+ execute = AsyncMock()+ monkeypatch.setattr(executor, "_call", execute)+ result = await executor.execute(call)+ assert result == {+ "role": "tool",+ "tool_call_id": "write-1",+ "content": UNKNOWN_OUTCOME,+ "failed": True,+ }+ assert reads == evicted_read+ execute.assert_not_called()+ assert await read("scope", [receipt_key]) == {}+++async def test_redis_claim_uses_server_time_and_repairs_ready_score(+ redis_kernel_store, monkeypatch+):+ from types import SimpleNamespace++ from openviking_gateway import redis_store++ store, now = redis_kernel_store, time.time()+ monkeypatch.setattr(+ redis_store, "time", SimpleNamespace(time=lambda: now + 3600, monotonic=time.monotonic)+ )+ await store.capture.swap("scope", "later", Document(), {}, now + 600)+ await store.client.zadd(store.capture.ready, {"scope\0later": 0})+ assert await store.capture.claim() is None+ assert await store.client.zscore(store.capture.ready, "scope\0later") == pytest.approx(+ (now + 600) * 1000+ )+ await store.capture.swap("scope", "now", Document(), {}, 0)+ item = await store.capture.claim(lease_seconds=120)+ assert item["session"] == "now"+ seconds, micros = await store.client.time()+ lease = float(await store.client.hget(store.capture_key("scope", "now"), "lease"))+ assert 115_000 < lease - (seconds * 1000 + micros / 1000) <= 120_000+ old = item["document"]+ assert await store.capture.swap("scope", "now", old, {"pending": True}, 0, owner=item["owner"])+ assert await store.client.zscore(store.capture.ready, "scope\0now") == lease+ await store.capture.release(item)+ assert await store.client.zscore(store.capture.ready, "scope\0now") == 0+++async def test_redis_scope_delete_unlinks_keys_and_keeps_tombstones(redis_kernel_store):+ store = redis_kernel_store+ await store.replay.put("scope", "session", K.ROOT, "", {})+ await store.capture.swap("scope", "session", Document(), {}, 0)+ await store.expire(0, "scope")+ assert [key async for key in store.backend.scan(f"{store.prefix}k:{{scope}}:*")] == []+ assert [key async for key in store.backend.scan(f"{store.prefix}k:{{cap}}:scope:*")] == []+ assert await store.client.pttl(store.tombstone("scope")) == -1+ assert await store.client.pttl(store.tombstone("scope", capture=True)) == -1+++async def test_cluster_scope_delete_scans_only_own_primaries(tmp_path, monkeypatch):+ async with open_kernel_store("redis-cluster", tmp_path) as store:+ scope, sid = "scope", "{foreign}:*:?[]\\\0unicode-用户"+ await store.replay.put(scope, sid, K.ROOT, "", {})+ await store.capture.swap(scope, sid, Document(), {}, 0)+ await store.state.swap(scope, sid, Document(), {})+ await store.replay.put("other", sid, K.ROOT, "", {"survives": True})+ scans, scan = [], store.client.scan++ async def observed(*args, **kwargs):+ scans.append((kwargs["match"], kwargs["target_nodes"]))+ return await scan(*args, **kwargs)++ monkeypatch.setattr(store.client, "scan", observed)+ await store.expire(0, scope)+ assert scans+ for pattern, node in scans:+ assert node is store.client.get_node_from_key(pattern)+ assert pattern in {f"{store.prefix}k:{{scope}}:*", f"{store.prefix}k:{{cap}}:scope:*"}+ assert await store.load(scope, sid, [""]) == ({}, {}, Document())+ assert (await store.replay.read("other", sid, [""]))[K.ROOT, ""] == {"survives": True}+++async def test_replay_load_handles_many_anchors(kernel_store):+ store = kernel_store+ for i in range(300):+ await store.replay.put("scope", "session", K.INJECTION, f"anchor:{i}", {"i": i})+ values = await store.replay.read("scope", "session", [f"anchor:{i}" for i in range(300)])+ assert values == {(K.INJECTION, f"anchor:{i}"): {"i": i} for i in range(300)}++[email protected]("provider", ["redis", "redis-cluster"])+async def test_open_stores_shares_redis_and_reads_across_instances(provider, tmp_path, monkeypatch):+ from openviking_gateway import redis_store+ from openviking_gateway.app import open_stores+ from openviking_gateway.config import GatewayConfig++ handles, connect = [], redis_store.connect++ def opened(settings):+ handles.append(connect(settings))+ handles[-1].close = AsyncMock(wraps=handles[-1].close)+ return handles[-1]++ async with open_redis_backend(provider) as backend:+ monkeypatch.setattr(redis_store, "connect", opened)+ config = GatewayConfig(+ storage_path=str(tmp_path),+ session_ttl_days=2,+ log_retention_days=3,+ storage={+ "kernel": "redis",+ "management": "redis",+ "key_prefix": backend.prefix.removesuffix("v1:"),+ "redis": redis_settings(provider),+ },+ )+ store, management, close = open_stores(config, None)+ try:+ await store.initialize()+ await management.initialize()+ assert store.client is management.port.client+ assert store.ttl == 2 * 86400 * 1000+ assert management.port.log_ttl == 3 * 86400+ assert not list(tmp_path.glob("*.sqlite3"))+ await store.replay.put("scope", "session", K.ROOT, "", {"created": "first"})+ await store.state.swap("scope", "session", Document(), {"observed": True})+ await store.capture.swap("scope", "session", Document(), {"pending": True}, 0)+ peer = redis_store.RedisKernelStore(backend, ttl=2 * 86400)+ assert await peer.load("scope", "session", [""]) == (+ {(K.ROOT, ""): {"created": "first"}},+ {"session": Document({"observed": True}, 1)},+ Document({"pending": True}, 1),+ )+ claimed = await peer.capture.claim()+ assert claimed["session"] == "session"+ assert await store.capture.claim() is None+ finally:+ await close()+ [handle] = handles+ handle.close.assert_awaited_once()diff --git a/tests/gateway/test_tenancy.py b/tests/gateway/test_tenancy.pynew file mode 100644index 000000000..3c70c6096--- /dev/null+++ b/tests/gateway/test_tenancy.py@@ -0,0 +1,258 @@+"""OpenViking key partitions isolate state and expire without changing session identity."""++import asyncio+import json+import time+from types import SimpleNamespace++import pytest+from aiohttp import web+from conftest import default_upstreams, make_due++from openviking_gateway import storage+from openviking_gateway.cli import load_config+from openviking_gateway.config import GatewayConfig+from openviking_gateway.storage import digest++KEYS = ("library-a", "library-b")+++def gateway_config(request, gateway_backend):+ return {+ "management_api": False,+ "default_upstreams": default_upstreams(gateway_backend[0]),+ "openviking_keys": True,+ "tenancy": "key",+ "session_ttl_days": 7,+ "default_profile": {"gateway_tools": False},+ **getattr(request, "param", {}),+ }+++def bearer(key):+ return {"Authorization": "Bearer " + key}+++async def credential(app, key):+ return await app.state.management.credential(digest("openviking\0" + key))+++async def chat(client, key, messages):+ response = await client.post(+ "/v1/chat/completions",+ headers={**bearer(key), "X-OpenViking-Session": "shared-name"},+ json={"model": "model", "messages": messages},+ )+ assert response.status_code == 200, response.text+ return response+++async def test_same_identity_keys_isolate_recall_capture_models_and_logs(running_gateway):+ app, client, _, minted, captured, writes = running_gateway+ assert minted is None+ calls = []++ async def handler(request):+ calls.append((request.path, request.headers.get("X-API-Key"), await request.read()))+ if request.path == "/api/v1/search/search":+ key = request.headers["X-API-Key"]+ return web.json_response({"result": {"entries": [], "rendered": "memory-" + key}})+ return None++ app.state.test_backend["handler"] = handler+ records = []+ for key in KEYS:+ assert (await client.get("/v1/models", headers=bearer(key))).status_code == 200+ records.append(await credential(app, key))+ assert records[0]["account"] != records[1]["account"]+ assert {r["openviking_account"] for r in records} == {"tenant"}+ assert {r["user_id"] for r in records} == {"alice"}+ for record, key in zip(records, KEYS, strict=True):+ upstream = app.state.config.default_upstreams["chat"].model_dump()+ await app.state.management.save(+ record["account"], "upstreams", "chat", {**upstream, "models": ["model", key]}+ )+ models = (await client.get("/v1/models", headers=bearer(key))).json()["data"]+ assert {m["id"] for m in models} == {"model", key}+ await chat(client, key, [{"role": "user", "content": "private-" + key}])+ body = captured[-1][1].decode()+ assert "memory-" + key in body+ assert all("memory-" + other not in body for other in KEYS if other != key)+ session, targets = digest("shared-name"), {}+ for record in records:+ scope = digest(record["account"] + "\0alice\0chat")+ document = await app.state.store.capture.get(scope, session)+ targets[document.value["account"]] = document.value["ov_session"]+ assert len(set(targets.values())) == 2+ await make_due(app.state.store)+ for _ in range(6):+ if len(writes) == 2:+ break+ await app.state.worker.once()+ assert len(writes) == 2+ for record, key in zip(records, KEYS, strict=True):+ delivered = [+ json.loads(body)+ for path, used_key, body in calls+ if path == f"/api/v1/sessions/{targets[record['account']]}/messages/batch"+ and used_key == key+ ]+ assert len(delivered) == 1+ assert "private-" + key in json.dumps(delivered)+ assert all(+ "private-" + other not in json.dumps(delivered) for other in KEYS if other != key+ )+ logs = await app.state.management.logs(record["account"])+ assert logs and all(log.get("degradation") is None for log in logs)+ assert {log["session"] for log in logs} == {session}+ assert await app.state.management.logs("tenant") == []++[email protected]("gateway_config", [{"tenancy": "account"}], indirect=True)+async def test_account_tenancy_shares_a_users_session(running_gateway):+ app, client, _, _, _, _ = running_gateway+ for key in KEYS:+ await chat(client, key, [{"role": "user", "content": "same message"}])+ record = await credential(app, key)+ assert record["account"] == record["openviking_account"] == "tenant"+ shared = await app.state.store.capture.get(digest("tenant\0alice\0chat"), digest("shared-name"))+ assert shared.value["pending"]+++ ("gateway_config", "after"),+ [({"tenancy": "account"}, "key"), ({"tenancy": "key"}, "account")],+ ids=["account-to-key", "key-to-account"],+ indirect=["gateway_config"],+)+async def test_tenancy_change_moves_a_stored_key_to_its_partition(running_gateway, after):+ app, client, _, _, _, _ = running_gateway+ identifier = digest("openviking\0" + KEYS[0])+ partitions = {"account": "tenant", "key": "k_" + identifier}+ before = partitions[app.state.config.tenancy]+ assert (await client.get("/v1/models", headers=bearer(KEYS[0]))).status_code == 200+ assert (await credential(app, KEYS[0]))["account"] == before+ app.state.config.tenancy = after+ assert (await client.get("/v1/models", headers=bearer(KEYS[0]))).status_code == 200+ assert (await credential(app, KEYS[0]))["account"] == partitions[after]+ assert await app.state.management.get(before, "keys", identifier) is None++[email protected]("field", ["account_id", "user_id"])+async def test_changed_identity_revokes_key_partition(running_gateway, field):+ app, client, _, _, _, _ = running_gateway+ assert (await client.get("/v1/models", headers=bearer(KEYS[0]))).status_code == 200++ async def handler(request):+ if request.path == "/health":+ identity = {+ "version": "0.4.16",+ "auth_mode": "api_key",+ "role": "user",+ "account_id": "tenant",+ "user_id": "alice",+ field: "changed",+ }+ return web.json_response(identity)+ return None++ app.state.test_backend["handler"] = handler+ app.state.viking.identities.clear()+ assert (await client.get("/v1/models", headers=bearer(KEYS[0]))).status_code == 401+ assert await credential(app, KEYS[0]) is None+++async def test_dev_identity_does_not_revoke_key_partition(running_gateway):+ app, client, _, _, _, _ = running_gateway+ assert (await client.get("/v1/models", headers=bearer(KEYS[0]))).status_code == 200+ before = await credential(app, KEYS[0])+ app.state.test_backend["auth_mode"] = "dev"+ app.state.viking.identities.clear()+ assert (await client.get("/v1/models", headers=bearer(KEYS[0]))).status_code == 200+ assert await credential(app, KEYS[0]) == before++[email protected]("source", ["openviking", "issued"])[email protected]("changed", [False, True])[email protected]("gateway_config", [{"tenancy": "account"}], indirect=True)+async def test_legacy_and_issued_records_compare_the_stored_account(+ running_gateway, source, changed+):+ app, client, _, _, _, _ = running_gateway+ key = KEYS[0] if source == "openviking" else "ovgw_legacy"+ identifier = digest("openviking\0" + key) if source == "openviking" else digest(key)+ await app.state.management.save(+ "other" if changed else "tenant",+ "keys",+ identifier,+ {+ "source": source,+ "openviking_key": KEYS[0],+ "user_id": "alice",+ "policy_id": "default",+ "upstream_ids": [],+ "models": [],+ },+ )+ response = await client.get("/v1/models", headers=bearer(key))+ assert response.status_code == (401 if changed else 200), response.text+ assert bool(await app.state.management.credential(identifier)) is not changed+++async def test_fixed_key_and_user_ttl_rebuilds_the_same_scope(running_gateway, monkeypatch):+ app, client, _, _, _, _ = running_gateway+ management = app.state.management+ now = time.time()+ monkeypatch.setattr(storage, "time", SimpleNamespace(time=lambda: now))+ history = [{"role": "user", "content": "keep this session"}]+ await chat(client, KEYS[0], history)+ before = await credential(app, KEYS[0])+ user = await management.get(before["account"], "users", "alice")+ assert before["expires_at"] == user["expires_at"] == now + 7 * 86400+ scope, session = digest(before["account"] + "\0alice\0chat"), digest("shared-name")+ initial = await app.state.store.capture.get(scope, session)+ now += 86400+ assert (await client.get("/v1/models", headers=bearer(KEYS[0]))).status_code == 200+ assert (await credential(app, KEYS[0]))["expires_at"] == before["expires_at"]+ assert (await management.get(before["account"], "users", "alice")) == user+ now += 6 * 86400+ management.cache.clear()+ assert await credential(app, KEYS[0]) is None+ assert await management.get(before["account"], "users", "alice") is None+ history += [{"role": "assistant", "content": "hello"}, {"role": "user", "content": "next"}]+ await chat(client, KEYS[0], history)+ after = await credential(app, KEYS[0])+ assert after["account"] == before["account"]+ assert after["expires_at"] == now + 7 * 86400+ assert (await management.get(after["account"], "users", "alice"))["expires_at"] == after[+ "expires_at"+ ]+ assert (await app.state.store.capture.get(scope, session)).value["ov_session"] == initial.value[+ "ov_session"+ ]+++async def test_concurrent_first_requests_create_one_partition(running_gateway):+ app, client, _, _, _, _ = running_gateway+ responses = await asyncio.gather(+ *(client.get("/v1/models", headers=bearer(KEYS[0])) for _ in range(12))+ )+ assert {r.status_code for r in responses} == {200}+ record = await credential(app, KEYS[0])+ assert len(await app.state.management.list(record["account"], "keys")) == 1+ assert len(await app.state.management.list(record["account"], "users")) == 1+++def test_tenancy_constraint_is_checked_when_loading_config(tmp_path, monkeypatch):+ path = tmp_path / "gateway.conf"+ path.write_text(json.dumps({"openviking_url": "http://localhost:1933", "tenancy": "key"}))+ monkeypatch.setenv("OPENVIKING_GATEWAY_CONFIG_FILE", str(path))+ with pytest.raises(ValueError, match="tenancy 'key' requires management_api: false"):+ load_config()+ monkeypatch.setenv("OPENVIKING_GATEWAY_MANAGEMENT_API", "false")+ assert load_config().tenancy == "key"+ assert load_config().openviking_keys is False+ assert GatewayConfig().tenancy == "account"+ with pytest.raises(ValueError):+ GatewayConfig(tenancy="resource", management_api=False)diff --git a/tests/gateway/test_upstream_selection.py b/tests/gateway/test_upstream_selection.pynew file mode 100644index 000000000..8b46ab476--- /dev/null+++ b/tests/gateway/test_upstream_selection.py@@ -0,0 +1,121 @@+"""A host in front of the gateway picks the upstream with ``X-OpenViking-Upstream-URL``."""++import pytest++CHAT = "/v1/chat/completions"+BODY = {"model": "deployed", "messages": [{"role": "user", "content": "Deploy the cluster?"}]}+++def gateway_config(gateway_backend):+ base = gateway_backend[0]++ def upstream(protocol, path, **fields):+ return {+ "name": protocol,+ "protocol": protocol,+ "base_url": base + path,+ "api_key": "deployment-secret",+ "models": ["deployed"],+ **fields,+ }++ return {+ "openviking_keys": True,+ "default_upstreams": {+ "chat": upstream("chat", "/v1", priority=1),+ "responses": upstream("responses", "/v1"),+ "alt": upstream("chat", "/alt/v1", api_key="", auth_mode="passthrough"),+ "plan": upstream("chat", "/plan/v1", coding_plan=True),+ "alt-responses": upstream("responses", "/alt/v1", priority=5),+ },+ "default_profile": {+ "name": "Deployment profile",+ "recall": False,+ "profile": False,+ "capture": False,+ "gateway_tools": False,+ },+ }+++def headers(url=None, **extra):+ selected = {"X-OpenViking-Upstream-URL": url} if url else {}+ return {"Authorization": "Bearer other", **selected, **extra}+++async def test_header_selects_an_allowed_upstream_and_is_not_forwarded(running_gateway):+ app, client, _, _, captured, _ = running_gateway+ base = app.state.config.default_upstreams["alt"].base_url+ response = await client.post(CHAT, headers=headers(), json=BODY)+ assert response.status_code == 200, response.text+ assert captured[-1][0] == "/v1/chat/completions"+ assert captured[-1][2]["Authorization"] == "Bearer deployment-secret"+ # A trailing slash is the only difference tolerated; the key is the passthrough one.+ selected = headers(base + "/", **{"X-OpenViking-Upstream-Key": "host-key"})+ response = await client.post(CHAT, headers=selected, json=BODY)+ assert response.status_code == 200, response.text+ path, _, forwarded = captured[-1]+ assert path == "/alt/v1/chat/completions"+ assert forwarded["Authorization"] == "Bearer host-key"+ assert not any(name.lower().startswith("x-openviking-") for name in forwarded)+++ "url", ["https://unlisted.example/v1", "{base}/v1/chat", "{base}/other/v1"]+)+async def test_unconfigured_url_is_rejected_without_contacting_it(running_gateway, url):+ app, client, _, _, captured, _ = running_gateway+ base = app.state.config.default_upstreams["chat"].base_url.removesuffix("/v1")+ response = await client.post(CHAT, headers=headers(url.format(base=base)), json=BODY)+ assert response.status_code == 403+ assert response.json()["detail"] == "Upstream URL is not allowed"+ assert captured == []+++async def test_upstreams_sharing_a_url_are_picked_by_protocol(running_gateway):+ app, client, _, _, captured, _ = running_gateway+ url = app.state.config.default_upstreams["chat"].base_url+ request = {"model": "deployed", "input": "Deploy?"}+ response = await client.post("/v1/responses", headers=headers(), json=request)+ assert response.status_code == 200, response.text+ assert captured[-1][0] == "/alt/v1/responses"+ response = await client.post("/v1/responses", headers=headers(url), json=request)+ assert response.status_code == 200, response.text+ assert captured[-1][0] == "/v1/responses"+ response = await client.post(CHAT, headers=headers(url), json=BODY)+ assert response.status_code == 200, response.text+ assert captured[-1][0] == "/v1/chat/completions"+ logs = await app.state.management.logs("other")+ assert sorted(log["upstream_id"] for log in logs) == ["alt-responses", "chat", "responses"]+++async def test_selected_coding_plan_upstream_is_still_refused(running_gateway):+ app, client, _, _, captured, _ = running_gateway+ url = app.state.config.default_upstreams["plan"].base_url+ response = await client.post(CHAT, headers=headers(url), json=BODY)+ assert response.status_code == 403+ assert "Coding Plan" in response.json()["detail"]+ assert captured == []+++async def test_url_change_mid_session_degrades_to_the_new_upstream(running_gateway):+ app, client, _, _, captured, _ = running_gateway+ upstreams = app.state.config.default_upstreams+ session = {"X-OpenViking-Session": "moved"}+ response = await client.post(+ CHAT, headers=headers(upstreams["chat"].base_url, **session), json=BODY+ )+ assert response.status_code == 200, response.text+ reply = {"role": "assistant", "content": "hello"}+ follow = {"role": "user", "content": "And then?"}+ moved = headers(+ upstreams["alt"].base_url, **session, **{"X-OpenViking-Upstream-Key": "host-key"}+ )+ body = {**BODY, "messages": [*BODY["messages"], reply, follow]}+ response = await client.post(CHAT, headers=moved, json=body)+ assert response.status_code == 200, response.text+ assert captured[-1][0] == "/alt/v1/chat/completions"+ logs = await app.state.management.logs("other")+ moved_log = next(log for log in logs if log["upstream_id"] == "alt")+ assert moved_log["degradation"] == "upstream_changed"diff --git a/tests/unit/crypto/test_providers_mock.py b/tests/unit/crypto/test_providers_mock.pyindex 309e53537..ccc2a8825 100644--- a/tests/unit/crypto/test_providers_mock.py+++ b/tests/unit/crypto/test_providers_mock.py@@ -325,6 +325,23 @@ class TestVolcengineKMSProviderMock:await volcengine_mock_provider.get_root_key()assert volcengine_mock_provider._encrypt_with_kms.call_count == 2+ @pytest.mark.asyncio+ async def test_missing_key_file_never_shadows_the_default_root_key(+ self, volcengine_mock_provider, tmp_path, monkeypatch+ ):+ """A key_file that earlier releases ignored must not replace the key they created."""+ monkeypatch.setenv("HOME", str(tmp_path))+ default_key_file = tmp_path / ".openviking" / VolcengineKMSProvider.ROOT_KEY_FILENAME+ default_key_file.parent.mkdir()+ default_key_file.write_bytes(b"existing-root-key")+ volcengine_mock_provider.key_file = tmp_path / "configured" / "root-key.enc"+ volcengine_mock_provider._encrypt_with_kms = AsyncMock()++ with pytest.raises(ConfigError, match="move it to"):+ await volcengine_mock_provider.get_root_key()+ volcengine_mock_provider._encrypt_with_kms.assert_not_called()+ assert not volcengine_mock_provider.key_file.exists()+class TestCrossProviderEnvelope:"""Tests for cross-provider envelope behavior."""diff --git a/uv.lock b/uv.lockindex 3bc66e331..389011902 100644--- a/uv.lock+++ b/uv.lock@@ -3814,9 +3814,9 @@ requires-dist = [{ name = "ragas", marker = "extra == 'test'", specifier = ">=0.1.0" },{ name = "rapidfuzz", specifier = ">=3.14,<4" },{ name = "readability-lxml", marker = "extra == 'bot'", specifier = ">=0.8.0" },- { name = "redis", marker = "extra == 'expiry'", specifier = ">=5,<7" },- { name = "redis", marker = "extra == 'redis-mysql'", specifier = ">=5.0,<7" },- { name = "redis", marker = "extra == 'test'", specifier = ">=5.0,<7" },+ { name = "redis", marker = "extra == 'expiry'", specifier = ">=5.3.1,<7" },+ { name = "redis", marker = "extra == 'redis-mysql'", specifier = ">=5.3.1,<7" },+ { name = "redis", marker = "extra == 'test'", specifier = ">=5.3.1,<7" },{ name = "requests", specifier = ">=2.33.0" },{ name = "rich", marker = "extra == 'bot'", specifier = ">=13.0.0" },{ name = "ruff", marker = "extra == 'dev'", specifier = ">=0.1.0" },diff --git a/web-studio/src/i18n/locales/en/gateway/connect.ts b/web-studio/src/i18n/locales/en/gateway/connect.tsindex fa410378e..a4b2037a3 100644--- a/web-studio/src/i18n/locales/en/gateway/connect.ts+++ b/web-studio/src/i18n/locales/en/gateway/connect.ts@@ -235,6 +235,15 @@ const connect = {upstreams: 'Upstreams that need it: {{names}}',none: 'None of your upstreams needs it right now.',},+ context: {+ title: 'Override profile settings',+ description:+ "A client can change its key's context profile for a new conversation by sending the profile fields to change as a JSON object in this header.",+ tools:+ '`{"disabled_tools":[]}` offers every OpenViking tool, including the ones that change data.',+ scope:+ 'The settings a conversation starts with stay for the rest of it. Profiles with “Let clients override settings” turned off reject the header.',+ },plugin: {title: 'Using an OpenViking plugin too?',description:diff --git a/web-studio/src/i18n/locales/en/gateway/keys.ts b/web-studio/src/i18n/locales/en/gateway/keys.tsindex e180ba237..55c397bf8 100644--- a/web-studio/src/i18n/locales/en/gateway/keys.ts+++ b/web-studio/src/i18n/locales/en/gateway/keys.ts@@ -31,6 +31,10 @@ const keys = {missing: 'Missing',missingProfile: 'This context profile no longer exists',missingUpstream: 'This upstream no longer exists',+ openviking: {+ name: 'OpenViking API key',+ defaults: 'Account default',+ },extra: '+{{count}}',actions: {revokeKey: 'Revoke “{{name}}”',@@ -48,8 +52,12 @@ const keys = {title: "Delete {{user}}'s gateway data?",description_one:"This revokes {{user}}'s gateway key and deletes their request logs and the conversation state the gateway keeps for this user, including turns not yet saved to OpenViking. Their clients lose access immediately. Memories already in OpenViking are not affected.",+ description_zero:+ 'This deletes the request logs of {{user}} and the conversation state the gateway keeps for this user, including turns not yet saved to OpenViking. Memories already in OpenViking are not affected.',description_other:'This revokes all {{count}} gateway keys of {{user}} and deletes their request logs and the conversation state the gateway keeps for this user, including turns not yet saved to OpenViking. Their clients lose access immediately. Memories already in OpenViking are not affected.',+ directKey:+ 'Clients using their OpenViking API key directly keep working until it is regenerated in OpenViking.',confirm: 'Delete gateway data',done: "Deleted {{user}}'s gateway data",},diff --git a/web-studio/src/i18n/locales/en/gateway/profiles.ts b/web-studio/src/i18n/locales/en/gateway/profiles.tsindex 30f311638..5a373b737 100644--- a/web-studio/src/i18n/locales/en/gateway/profiles.ts+++ b/web-studio/src/i18n/locales/en/gateway/profiles.ts@@ -66,6 +66,11 @@ const profiles = {placeholder: 'e.g. Coding',description: 'Shown when you choose a profile for a gateway key.',},+ clientOverrides: {+ label: 'Let clients override settings',+ description:+ 'Clients can change any setting below for a new conversation with the X-OpenViking-Context header, including budgets and tools that change data. Turn this off for a profile that must stay as saved.',+ },recall: {title: 'Recall memory',description:diff --git a/web-studio/src/i18n/locales/en/gateway/requests.ts b/web-studio/src/i18n/locales/en/gateway/requests.tsindex be122ea57..be73282ed 100644--- a/web-studio/src/i18n/locales/en/gateway/requests.ts+++ b/web-studio/src/i18n/locales/en/gateway/requests.ts@@ -100,6 +100,7 @@ const requests = {toolsSkipped: 'Not offered: {{reason}}',toolRounds:'Rounds: {{rounds}} · extra model calls: {{calls}} · tokens added: about {{tokens}}',+ contextOverride: 'Sent in X-OpenViking-Context',whatHappened: 'What happened',whatToDo: 'What to do',httpError:diff --git a/web-studio/src/i18n/locales/zh-CN/gateway/connect.ts b/web-studio/src/i18n/locales/zh-CN/gateway/connect.tsindex e8371ef27..46f41ad0c 100644--- a/web-studio/src/i18n/locales/zh-CN/gateway/connect.ts+++ b/web-studio/src/i18n/locales/zh-CN/gateway/connect.ts@@ -228,6 +228,15 @@ const connect = {upstreams: '需要它的上游:{{names}}',none: '目前没有上游需要它。',},+ context: {+ title: '覆盖上下文配置',+ description:+ '客户端可以在这个请求头里用 JSON 对象传入要修改的配置字段,为新对话覆盖密钥的上下文配置。',+ tools:+ '`{"disabled_tools":[]}` 表示提供全部 OpenViking 工具,包括会修改数据的工具。',+ scope:+ '对话开始时的设置会沿用到对话结束。关闭了“允许客户端覆盖设置”的配置会拒绝这个请求头。',+ },plugin: {title: '同时在用 OpenViking 插件?',description:diff --git a/web-studio/src/i18n/locales/zh-CN/gateway/keys.ts b/web-studio/src/i18n/locales/zh-CN/gateway/keys.tsindex ea8a1f5cc..13cce1ecb 100644--- a/web-studio/src/i18n/locales/zh-CN/gateway/keys.ts+++ b/web-studio/src/i18n/locales/zh-CN/gateway/keys.ts@@ -30,6 +30,10 @@ const keys = {missing: '已删除',missingProfile: '这个上下文配置已不存在',missingUpstream: '这个上游已不存在',+ openviking: {+ name: 'OpenViking API 密钥',+ defaults: '账号默认',+ },extra: '+{{count}}',actions: {revokeKey: '吊销“{{name}}”',@@ -47,8 +51,12 @@ const keys = {title: '删除 {{user}} 的网关数据?',description_one:'这会吊销 {{user}} 的网关密钥,并删除网关为该用户保存的对话状态(包括尚未保存到 OpenViking 的内容)和请求日志。该用户的客户端会立即失去访问权限。已经存入 OpenViking 的记忆不受影响。',+ description_zero:+ '这会删除网关为 {{user}} 保存的对话状态(包括尚未保存到 OpenViking 的内容)和请求日志。已经存入 OpenViking 的记忆不受影响。',description_other:'这会吊销 {{user}} 的全部 {{count}} 个网关密钥,并删除网关为该用户保存的对话状态(包括尚未保存到 OpenViking 的内容)和请求日志。该用户的客户端会立即失去访问权限。已经存入 OpenViking 的记忆不受影响。',+ directKey:+ '直接使用其 OpenViking API 密钥的客户端仍可使用,直到在 OpenViking 中重新生成这把密钥。',confirm: '删除网关数据',done: '已删除 {{user}} 的网关数据',},diff --git a/web-studio/src/i18n/locales/zh-CN/gateway/profiles.ts b/web-studio/src/i18n/locales/zh-CN/gateway/profiles.tsindex 816f54be6..334d44086 100644--- a/web-studio/src/i18n/locales/zh-CN/gateway/profiles.ts+++ b/web-studio/src/i18n/locales/zh-CN/gateway/profiles.ts@@ -62,6 +62,11 @@ const profiles = {placeholder: '例如:编程',description: '为网关密钥选择配置时显示这个名称。',},+ clientOverrides: {+ label: '允许客户端覆盖设置',+ description:+ '客户端可以用 X-OpenViking-Context 请求头为新对话修改下面的任意设置,包括预算和会修改数据的工具。配置需要保持原样时,请关闭此项。',+ },recall: {title: '召回记忆',description:diff --git a/web-studio/src/i18n/locales/zh-CN/gateway/requests.ts b/web-studio/src/i18n/locales/zh-CN/gateway/requests.tsindex d5129e749..208e5e431 100644--- a/web-studio/src/i18n/locales/zh-CN/gateway/requests.ts+++ b/web-studio/src/i18n/locales/zh-CN/gateway/requests.ts@@ -93,6 +93,7 @@ const requests = {toolsSkipped: '未提供:{{reason}}',toolRounds:'轮数 {{rounds}} · 额外模型调用 {{calls}} 次 · 约增加 {{tokens}} Token',+ contextOverride: 'X-OpenViking-Context 中传入的配置项',whatHappened: '发生了什么',whatToDo: '如何处理',httpError: '上游返回了 HTTP {{status}},客户端收到了这个错误。',diff --git a/web-studio/src/routes/gateway/-components/connect-page.test.tsx b/web-studio/src/routes/gateway/-components/connect-page.test.tsxindex 27454347a..b60674311 100644--- a/web-studio/src/routes/gateway/-components/connect-page.test.tsx+++ b/web-studio/src/routes/gateway/-components/connect-page.test.tsx@@ -212,6 +212,7 @@ describe('ConnectPage', () => {).toEqual([gatewayDocsUrl('conversations', 'en'),gatewayDocsUrl('providerKey', 'en'),+ gatewayDocsUrl('contextHeader', 'en'),gatewayDocsUrl('pluginDetected', 'en'),])})diff --git a/web-studio/src/routes/gateway/-components/connect-page.tsx b/web-studio/src/routes/gateway/-components/connect-page.tsxindex 802e13f9c..e958a94b0 100644--- a/web-studio/src/routes/gateway/-components/connect-page.tsx+++ b/web-studio/src/routes/gateway/-components/connect-page.tsx@@ -1,6 +1,11 @@import type * as React from 'react'import { Link, getRouteApi } from '@tanstack/react-router'-import { KeyRoundIcon, MessagesSquareIcon, PuzzleIcon } from 'lucide-react'+import {+ KeyRoundIcon,+ MessagesSquareIcon,+ PuzzleIcon,+ SlidersHorizontalIcon,+} from 'lucide-react'import { useTranslation } from 'react-i18next'import { Button } from '#/components/ui/button'@@ -40,6 +45,8 @@ const HEADER_SENDERS: Record<string, string> = {const UPSTREAM_KEY_EXAMPLE = `${UPSTREAM_KEY_HEADER}: <provider-api-key>`const PLUGIN_HEADER_EXAMPLE = 'X-OpenViking-Plugin: <plugin-name>'+const CONTEXT_HEADER_EXAMPLE =+ 'X-OpenViking-Context: {"recall":false,"max_tokens":800}'/*** Gateway address and client setup guides (`?client=` picks the client,@@ -70,9 +77,10 @@ export function ConnectPage() {baseUrl={info.data.base_url}upstreams={upstreams.data}/>- <div className="grid gap-4 xl:grid-cols-3">+ <div className="grid gap-4 lg:grid-cols-2"><IdentityCard /><PassthroughCard upstreams={upstreams.data} />+ <ContextCard /><PluginCard /></div></>@@ -261,6 +269,24 @@ function PassthroughCard({ upstreams }: { upstreams?: Upstream[] }) {)}+function ContextCard() {+ const { t } = useTranslation('gateway')+ return (+ <ReferenceCard+ icon={<SlidersHorizontalIcon />}+ title={t('connect.context.title')}+ description={t('connect.context.description')}+ docs="contextHeader"+ >+ <CodeBlock code={CONTEXT_HEADER_EXAMPLE} wrap />+ <p>+ <CodeText text={t('connect.context.tools')} />+ </p>+ <p>{t('connect.context.scope')}</p>+ </ReferenceCard>+ )+}+function PluginCard() {const { t } = useTranslation('gateway')return (diff --git a/web-studio/src/routes/gateway/-components/keys-page.test.tsx b/web-studio/src/routes/gateway/-components/keys-page.test.tsxindex 7e40376ff..2f5466198 100644--- a/web-studio/src/routes/gateway/-components/keys-page.test.tsx+++ b/web-studio/src/routes/gateway/-components/keys-page.test.tsx@@ -39,7 +39,9 @@ vi.mock('../-lib/api', async (importOriginal) => ({vi.mock('sonner', () => ({ toast: toastMocks }))vi.mock('react-i18next', () => ({useTranslation: () => ({- t: (key: string) => key,+ // Plural counts are appended so assertions can check them.+ t: (key: string, values?: { count?: number }) =>+ values?.count === undefined ? key : `${key} ${values.count}`,i18n: { resolvedLanguage: 'en' },}),}))@@ -125,6 +127,17 @@ const laptop: GatewayKey = {prefix: 'ovgw_Ab3dE9x',created_at: 1_700_000_000,}+const direct: GatewayKey = {+ ...laptop,+ id: 'k3',+ name: '',+ source: 'openviking',+ policy_id: '',+ upstream_ids: [],+ user_id: 'carol',+ prefix: '7f3a9c1e',+ created_at: 1_800_000_000,+}const ci: GatewayKey = {...laptop,id: 'k2',@@ -200,6 +213,56 @@ describe('KeysPage', () => {).toBe(gatewayDocsUrl('keys', 'en'))})+ it('marks an OpenViking API key and shows the defaults it uses', async () => {+ api.listKeys.mockResolvedValue([direct, laptop])+ renderPage()++ const rows = await screen.findAllByRole('row')+ expect(within(rows[1]).getByText('keys.openviking.name')).toBeTruthy()+ expect(within(rows[1]).getByText('7f3a9c1e…')).toBeTruthy()+ // Profile and upstreams: the account's defaults, not a missing profile.+ expect(+ within(rows[1]).getAllByText('keys.openviking.defaults'),+ ).toHaveLength(2)+ expect(within(rows[1]).queryByText('keys.missing')).toBeNull()+ expect(within(rows[1]).getByText('states.any')).toBeTruthy()+ // Only OpenViking can revoke it.+ expect(+ within(rows[1]).queryByRole('button', { name: 'keys.actions.revokeKey' }),+ ).toBeNull()+ expect(+ within(rows[2]).getByRole('button', { name: 'keys.actions.revokeKey' }),+ ).toBeTruthy()+ })++ it.each([+ [[direct], 0],+ [[direct, { ...laptop, user_id: 'carol' }], 1],+ ])(+ 'warns that deleting user data does not stop an OpenViking API key',+ async (keys, revoked) => {+ api.listKeys.mockResolvedValue(keys)+ renderPage()++ fireEvent.click(+ (+ await screen.findAllByRole('button', { name: 'keys.actions.more' })+ )[0],+ )+ fireEvent.click(+ await screen.findByRole('menuitem', {+ name: 'keys.actions.deleteUserData',+ }),+ )+ // Only gateway keys are counted as revoked.+ expect(+ screen.getByText(+ `keys.deleteUser.description ${revoked} keys.deleteUser.directKey`,+ ),+ ).toBeTruthy()+ },+ )+it('revokes a key after confirmation', async () => {api.revokeKey.mockResolvedValue({ deleted: true })renderPage()diff --git a/web-studio/src/routes/gateway/-components/keys-page.tsx b/web-studio/src/routes/gateway/-components/keys-page.tsxindex afbae8766..a209509ef 100644--- a/web-studio/src/routes/gateway/-components/keys-page.tsx+++ b/web-studio/src/routes/gateway/-components/keys-page.tsx@@ -36,7 +36,7 @@ import { cn } from '#/lib/utils'import { deleteUserData, revokeKey } from '../-lib/api'import type { GatewayKey, IssuedKey, Profile, Upstream } from '../-lib/api'import { formatDateTime, formatRelativeTime, shortenId } from '../-lib/format'-import { gatewayErrorMessage, protocolLabel } from '../-lib/localize'+import { gatewayErrorMessage, keyName, protocolLabel } from '../-lib/localize'import { requestManagementUnlock } from '../-lib/management-key'import { NEW_ID } from '../-lib/search'import {@@ -132,7 +132,11 @@ export function KeysPage() {keysQuery.isFetching ||profilesQuery.isFetching ||upstreamsQuery.isFetching- const userKeyCount = keys.filter((key) => key.user_id === userTarget).length+ const userKeys = keys.filter((key) => key.user_id === userTarget)+ // OpenViking API keys are listed too, but deleting the user revokes only gateway keys.+ const userGatewayKeyCount = userKeys.filter(+ (key) => key.source !== 'openviking',+ ).lengthfunction openIssue() {setIssueSession((session) => session + 1)@@ -290,7 +294,11 @@ export function KeysPage() {profiles={profilesQuery.isSuccess ? profiles : undefined}upstreams={upstreamsQuery.isSuccess ? upstreams : undefined}showUser={canIssueForOthers}- onRevoke={() => setRevokeTarget(key)}+ onRevoke={+ key.source === 'openviking'+ ? undefined+ : () => setRevokeTarget(key)+ }onDeleteUser={canIssueForOthers? () => setUserTarget(key.user_id)@@ -349,10 +357,16 @@ export function KeysPage() {if (!open) setUserTarget(null)}}title={t('keys.deleteUser.title', { user: userTarget ?? '' })}- description={t('keys.deleteUser.description', {- user: userTarget ?? '',- count: userKeyCount,- })}+ description={[+ t('keys.deleteUser.description', {+ user: userTarget ?? '',+ count: userGatewayKeyCount,+ }),+ // A client sending the OpenViking API key itself keeps working.+ ...(userKeys.some((key) => key.source === 'openviking')+ ? [t('keys.deleteUser.directKey')]+ : []),+ ].join(' ')}confirmLabel={t('keys.deleteUser.confirm')}icon={<UserXIcon />}onConfirm={() =>@@ -431,18 +445,26 @@ function KeyRow({upstreams?: Upstream[]/** Admins see whose identity each key acts as. */showUser: boolean- onRevoke: () => void+ /** Absent for an OpenViking API key: only OpenViking can revoke it. */+ onRevoke?: () => voidonDeleteUser?: () => void}) {const { t, i18n } = useTranslation('gateway')const locale = i18n.resolvedLanguage+ const direct = key.source === 'openviking'+ const name = keyName(t, key)const profile = profiles?.find((item) => item.id === key.policy_id)+ const defaults = (+ <span className="text-muted-foreground">+ {t('keys.openviking.defaults')}+ </span>+ )return (<TableRow><TableCell className="pl-4">- <span className="block max-w-48 truncate font-medium" title={key.name}>- {key.name}+ <span className="block max-w-48 truncate font-medium" title={name}>+ {name}</span><spanclassName="block max-w-56 truncate font-mono text-xs text-muted-foreground md:hidden"@@ -467,7 +489,9 @@ function KeyRow({</TableCell>) : null}<TableCell className={DESKTOP_ONLY}>- {profile ? (+ {direct ? (+ defaults+ ) : profile ? (<Linkto="/gateway/profiles/$profileId"params={{ profileId: profile.id }}@@ -487,47 +511,51 @@ function KeyRow({)}</TableCell><TableCell className={DESKTOP_ONLY}>- <ChipList- items={key.upstream_ids}- label={(id) =>- upstreams?.find((upstream) => upstream.id === id)?.name ?? id- }- render={(id) => {- const upstream = upstreams?.find((item) => item.id === id)- if (upstream) {- return (+ {direct ? (+ defaults+ ) : (+ <ChipList+ items={key.upstream_ids}+ label={(id) =>+ upstreams?.find((upstream) => upstream.id === id)?.name ?? id+ }+ render={(id) => {+ const upstream = upstreams?.find((item) => item.id === id)+ if (upstream) {+ return (+ <Badge+ key={id}+ variant="outline"+ className={cn(+ 'max-w-40 font-normal',+ protocolTint(upstream.protocol),+ )}+ title={protocolLabel(t, upstream.protocol)}+ >+ <span className="truncate">{upstream.name}</span>+ </Badge>+ )+ }+ return upstreams ? (+ <ToneBadge+ key={id}+ tone="warning"+ title={t('keys.missingUpstream')}+ >+ {t('keys.missing')}+ </ToneBadge>+ ) : (<Badgekey={id}variant="outline"- className={cn(- 'max-w-40 font-normal',- protocolTint(upstream.protocol),- )}- title={protocolLabel(t, upstream.protocol)}+ className="font-mono font-normal text-muted-foreground">- <span className="truncate">{upstream.name}</span>+ {shortenId(id)}</Badge>)- }- return upstreams ? (- <ToneBadge- key={id}- tone="warning"- title={t('keys.missingUpstream')}- >- {t('keys.missing')}- </ToneBadge>- ) : (- <Badge- key={id}- variant="outline"- className="font-mono font-normal text-muted-foreground"- >- {shortenId(id)}- </Badge>- )- }}- />+ }}+ />+ )}</TableCell><TableCell className={DESKTOP_ONLY}>{key.models.length ? (@@ -556,17 +584,19 @@ function KeyRow({</TableCell><TableCell className="pr-4"><div className="flex items-center justify-end gap-1">- <Button- type="button"- variant="ghost"- size="sm"- className="h-8 px-2 text-xs text-muted-foreground hover:bg-destructive/10 hover:text-destructive"- aria-label={t('keys.actions.revokeKey', { name: key.name })}- onClick={onRevoke}- >- <Trash2Icon />- {t('actions.revoke')}- </Button>+ {onRevoke ? (+ <Button+ type="button"+ variant="ghost"+ size="sm"+ className="h-8 px-2 text-xs text-muted-foreground hover:bg-destructive/10 hover:text-destructive"+ aria-label={t('keys.actions.revokeKey', { name })}+ onClick={onRevoke}+ >+ <Trash2Icon />+ {t('actions.revoke')}+ </Button>+ ) : null}{onDeleteUser ? (<DropdownMenu><DropdownMenuTrigger@@ -576,7 +606,7 @@ function KeyRow({variant="ghost"size="icon-sm"className="text-muted-foreground"- aria-label={t('keys.actions.more', { name: key.name })}+ aria-label={t('keys.actions.more', { name })}/>}>diff --git a/web-studio/src/routes/gateway/-components/profiles-editor.tsx b/web-studio/src/routes/gateway/-components/profiles-editor.tsxindex 297fd0491..c02a99aa4 100644--- a/web-studio/src/routes/gateway/-components/profiles-editor.tsx+++ b/web-studio/src/routes/gateway/-components/profiles-editor.tsx@@ -49,6 +49,7 @@ import {} from './profiles-settings'import { BackLink, SectionHeader } from './section-header'import { SettingField } from './setting-field'+import { ToggleRow } from './toggle-row'/** Key-order-independent copy, so reordered objects still compare equal. */function canonical(value: unknown): unknown {@@ -190,6 +191,7 @@ function ProfileEditorForm({...current,...PROFILE_DEFAULTS,name: current.name,+ client_overrides: current.client_overrides,}))toast.success(t('profiles.toast.reset'))}@@ -273,7 +275,7 @@ function ProfileEditorForm({<SectionNav settings={draft} errors={errors} /><div className="grid min-w-0 gap-4"><Card className="gap-0 py-0">- <CardContent className="py-5">+ <CardContent className="grid gap-4 py-5"><SettingFieldlabel={t('profiles.name.label')}htmlFor="profile-name"@@ -297,6 +299,16 @@ function ProfileEditorForm({}/></SettingField>+ <ToggleRow+ id="profile-client_overrides"+ label={t('profiles.clientOverrides.label')}+ description={t('profiles.clientOverrides.description')}+ docs="clientOverrides"+ checked={draft.client_overrides}+ onCheckedChange={(client_overrides) =>+ update({ client_overrides })+ }+ /></CardContent></Card><ProfileSettingsFormdiff --git a/web-studio/src/routes/gateway/-components/profiles-pages.test.tsx b/web-studio/src/routes/gateway/-components/profiles-pages.test.tsxindex 96806b780..562bf26fb 100644--- a/web-studio/src/routes/gateway/-components/profiles-pages.test.tsx+++ b/web-studio/src/routes/gateway/-components/profiles-pages.test.tsx@@ -322,6 +322,24 @@ describe('profile list', () => {)})+ it('does not count OpenViking API keys as users of the default profile', async () => {+ api.listProfiles.mockResolvedValue([{ ...coding, id: 'default' }])+ // As the server lists them: no binding of their own.+ api.listKeys.mockResolvedValue([+ { ...key('k3', ''), source: 'openviking', upstream_ids: [] },+ ])+ renderAt('/gateway/profiles')+ await screen.findByRole('link', { name: 'Coding' })++ const codingCard = within(card('Coding'))+ expect(codingCard.getByText('profiles.unused')).toBeTruthy()+ expect(+ codingCard.getByRole<HTMLButtonElement>('button', {+ name: 'actions.delete',+ }).disabled,+ ).toBe(false)+ })+it('creates a profile with the recommended settings in one click', async () => {api.listProfiles.mockResolvedValue([])renderAt('/gateway/profiles')@@ -385,11 +403,12 @@ describe('profile editor', () => {it('hides settings of switched-off sections and switches long-conversation features on their own', async () => {renderAt('/gateway/profiles/p2')await screen.findByDisplayValue('Chat')- // Every section links its docs, switched on or not, and so does the- // experimental agent-managed windows setting.+ // Every section links its docs, switched on or not, and so do the+ // client override and experimental agent-managed windows settings.expect(hrefsOf('docs.learnMore')).toEqual(([+ 'clientOverrides','recall','capture','longConversations',@@ -690,6 +709,30 @@ describe('profile editor', () => {})})+ it('lets clients override settings by default and keeps the switch on reset', async () => {+ // Profiles saved before the switch existed lack the field; the gateway treats it as on.+ const { client_overrides: _, ...legacy } = chat+ api.listProfiles.mockResolvedValue([legacy as Profile])+ renderAt('/gateway/profiles/p2')+ await screen.findByDisplayValue('Chat')+ const overrides = () =>+ screen.getByRole('switch', { name: 'profiles.clientOverrides.label' })+ expect(overrides().getAttribute('aria-checked')).toBe('true')++ fireEvent.click(overrides())+ fireEvent.click(screen.getByRole('button', { name: 'actions.more' }))+ fireEvent.click(+ await screen.findByRole('menuitem', { name: 'profiles.actions.reset' }),+ )+ expect(overrides().getAttribute('aria-checked')).toBe('false')+ fireEvent.click(saveButton())++ await waitFor(() => expect(api.saveProfile).toHaveBeenCalledTimes(1))+ expect(api.saveProfile.mock.calls[0][2]).toMatchObject({+ client_overrides: false,+ })+ })+it('starts category limits from the searched sources', async () => {renderAt('/gateway/profiles/p2')await screen.findByDisplayValue('Chat')diff --git a/web-studio/src/routes/gateway/-components/request-details.tsx b/web-studio/src/routes/gateway/-components/request-details.tsxindex df07e72ef..a6af1d6dc 100644--- a/web-studio/src/routes/gateway/-components/request-details.tsx+++ b/web-studio/src/routes/gateway/-components/request-details.tsx@@ -18,6 +18,7 @@ import {import {captureReasonLabel,degradationInfo,+ keyName,recallReasonLabel,toolSkipReasonLabel,toolStopReasonLabel,@@ -328,7 +329,9 @@ export function RequestDetails({<DetailItem label={t('requests.details.key')}>{gatewayKey ? (<span className="flex min-w-0 items-baseline gap-2">- <span className="truncate font-medium">{gatewayKey.name}</span>+ <span className="truncate font-medium">+ {keyName(t, gatewayKey)}+ </span><span className="font-mono text-xs text-muted-foreground">{gatewayKey.prefix}…</span>@@ -506,6 +509,13 @@ export function RequestDetails({) : null}</DetailItem>) : null}+ {record.context_override?.length ? (+ <DetailItem label={t('requests.details.contextOverride')}>+ <span className="font-mono text-xs">+ {record.context_override.join(', ')}+ </span>+ </DetailItem>+ ) : null}</dl>{degradation ? (<Calloutdiff --git a/web-studio/src/routes/gateway/-components/requests-page.tsx b/web-studio/src/routes/gateway/-components/requests-page.tsxindex 4b0152375..6cbd0d037 100644--- a/web-studio/src/routes/gateway/-components/requests-page.tsx+++ b/web-studio/src/routes/gateway/-components/requests-page.tsx@@ -39,7 +39,8 @@ import { cn } from '#/lib/utils'import { LOG_KINDS, resyncCapture } from '../-lib/api'import type { GatewayKey, LogKind, LogRecord, Upstream } from '../-lib/api'import { formatClockTime, formatNumber } from '../-lib/format'-import { gatewayErrorMessage, kindLabel } from '../-lib/localize'+import { gatewayErrorMessage, keyName, kindLabel } from '../-lib/localize'+import type { Translate } from '../-lib/localize'import type { RequestsFilter } from '../-lib/search'import { useGateway, useKeys, useLogs, useUpstreams } from '../-lib/use-gateway'import { ConfirmDialog } from './confirm-dialog'@@ -86,6 +87,7 @@ function inSegment(record: LogRecord, segment: Segment): boolean {/** Text a search term is matched against: model, conversation, key, upstream. */function searchableText(+ t: Translate,record: LogRecord,upstreams?: Map<string, Upstream>,keys?: Map<string, GatewayKey>,@@ -98,7 +100,7 @@ function searchableText(record.model,record.session,record.request_id,- key?.name,+ key && keyName(t, key),key?.prefix,upstream?.name,]@@ -210,7 +212,9 @@ export function RequestsPage() {(kind === 'all' || record.kind === kind) &&(!needle ||(session !== undefined && record.session === session) ||- searchableText(record, upstreamsById, keysById).includes(needle)),+ searchableText(t, record, upstreamsById, keysById).includes(+ needle,+ )),)}, [records,@@ -221,6 +225,7 @@ export function RequestsPage() {hashed,upstreamsById,keysById,+ t,])const pageCount = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE))diff --git a/web-studio/src/routes/gateway/-lib/api.ts b/web-studio/src/routes/gateway/-lib/api.tsindex a5c2cb3e9..775a9808f 100644--- a/web-studio/src/routes/gateway/-lib/api.ts+++ b/web-studio/src/routes/gateway/-lib/api.ts@@ -134,6 +134,8 @@ export type ProfileSettings = {tool_result_bytes: numbertool_total_seconds: number | nulltool_total_tokens: number | null+ /** Clients may override the other settings with `X-OpenViking-Context`. */+ client_overrides: boolean}export type Profile = ProfileSettings & { id: string; revision: number }@@ -143,11 +145,17 @@ export type GatewayKey = {id: stringrevision: numbername: string+ /**+ * An OpenViking API key used directly. It stores no binding, so name,+ * policy_id, upstream_ids and models are empty; the gateway applies the+ * account's defaults to each request.+ */+ source?: 'openviking'policy_id: stringupstream_ids: string[]models: string[]user_id: string- /** First 12 characters of the secret, e.g. `ovgw_Ab3dE9x`. */+ /** First characters of the secret: 12 of a gateway key (`ovgw_Ab3dE9x`), 8 of an OpenViking API key. */prefix: string/** Epoch seconds. */created_at: number@@ -314,6 +322,8 @@ export type LogRecord = {cache_min_tokens?: numbercache_eligible?: booleanduration_ms?: number+ /** Profile fields the client set with `X-OpenViking-Context`; values are not logged. */+ context_override?: string[]}/** Where clients reach the gateway. */diff --git a/web-studio/src/routes/gateway/-lib/client-guides.ts b/web-studio/src/routes/gateway/-lib/client-guides.tsindex cd2d6dc91..b846d08f2 100644--- a/web-studio/src/routes/gateway/-lib/client-guides.ts+++ b/web-studio/src/routes/gateway/-lib/client-guides.ts@@ -399,6 +399,7 @@ export const DOCS_SECTIONS = {},conversations: { page: 'clients', id: 'how-conversations-are-recognized' },providerKey: { page: 'clients', id: 'bring-your-own-provider-key' },+ contextHeader: { page: 'clients', id: 'override-profile-settings' },// OpenViking toolstools: { page: 'tools', id: 'choose-tools' },toolsNotOffered: { page: 'tools', id: 'when-tools-are-not-offered' },@@ -423,6 +424,7 @@ export const DOCS_SECTIONS = {profiles: { page: 'profiles', id: 'context-profiles' },recall: { page: 'profiles', id: 'recall-memory' },capture: { page: 'profiles', id: 'save-conversations' },+ clientOverrides: { page: 'profiles', id: 'client-overrides' },// Gateway keyskeys: { page: 'keys', id: 'gateway-keys' },// Overview and requestsdiff --git a/web-studio/src/routes/gateway/-lib/localize.ts b/web-studio/src/routes/gateway/-lib/localize.tsindex 454cc1474..56a0375d3 100644--- a/web-studio/src/routes/gateway/-lib/localize.ts+++ b/web-studio/src/routes/gateway/-lib/localize.ts@@ -1,6 +1,7 @@import type { TFunction } from 'i18next'import { toGatewayError } from './api'+import type { GatewayKey } from './api'/** `t` from `useTranslation('gateway')`. */export type Translate = TFunction<'gateway'>@@ -33,6 +34,10 @@ export const vendorLabel = (t: Translate, vendor: string) =>export const authModeLabel = (t: Translate, mode: string) =>label(t, 'authMode', mode)+/** OpenViking API keys used directly have no name of their own. */+export const keyName = (t: Translate, key: GatewayKey) =>+ key.source === 'openviking' ? t('keys.openviking.name') : key.name+/** Request type: new message, tool step, housekeeping, memory sync… */export const kindLabel = (t: Translate, kind: string) => label(t, 'kind', kind)diff --git a/web-studio/src/routes/gateway/-lib/profile-schema.ts b/web-studio/src/routes/gateway/-lib/profile-schema.tsindex 77fa251b4..cd94e8be9 100644--- a/web-studio/src/routes/gateway/-lib/profile-schema.ts+++ b/web-studio/src/routes/gateway/-lib/profile-schema.ts@@ -48,6 +48,7 @@ export const PROFILE_DEFAULTS: ProfileSettings = {tool_result_bytes: 65536,tool_total_seconds: null,tool_total_tokens: null,+ client_overrides: true,}type NumericField = {@@ -101,14 +102,20 @@ export const QUOTA_LIMIT: NumberRule = {unit: 'entries',}-/** Save body for `PUT policies/{id}`: known profile fields only. */+/**+ * Save body for `PUT policies/{id}`: known profile fields only. Fields a+ * profile saved by an older gateway lacks take the gateway's defaults, as on+ * the server (`null` is a real value, so no `??`).+ */export function toProfileSettings(profile: Profile | ProfileSettings,): ProfileSettings {return Object.fromEntries(Object.keys(PROFILE_DEFAULTS).map((field) => [field,- profile[field as keyof ProfileSettings],+ field in profile+ ? profile[field as keyof ProfileSettings]+ : PROFILE_DEFAULTS[field as keyof ProfileSettings],]),) as ProfileSettings}