Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

fix(gateway): log the capture status a request ends with (#5981)

t0sakie05452ee8e0f
diff --git a/openviking_gateway/proxy.py b/openviking_gateway/proxy.py
index 709893bf7..a6b070663 100644
--- a/openviking_gateway/proxy.py
+++ b/openviking_gateway/proxy.py
@@ -7,6 +7,7 @@ import json
import logging
import time
import uuid
+from dataclasses import replace
import aiohttp
import orjson
@@ -14,6 +15,8 @@ from fastapi import HTTPException
from fastapi.responses import Response, StreamingResponse
from starlette.background import BackgroundTask
+from .capture import CapturePipeline
+from .models import Policy
from .protocols import SSEDecoder, parse_body
from .storage import digest
from .tool_executor import ToolExecutor
@@ -327,6 +330,20 @@ class ProxyRequest:
{"upstream_id": self.upstream["id"], "user_id": self.credential["user_id"]},
ttl=self.config.response_ttl_seconds,
)
+ if self.prepared:
+ # Delivery may have failed or recovered while this request was in flight.
+ # A worker row inserted between this read and the log below can still be
+ # older than this row; if the read fails, the prepare-time fields are kept.
+ try:
+ capture = await self.store.capture.get(
+ self.prepared.scope, self.prepared.session
+ )
+ CapturePipeline.metrics(
+ replace(self.prepared, capture=capture, metrics=self.metrics),
+ Policy.model_validate(self.prepared.root["policy"]),
+ )
+ except Exception:
+ logger.exception("OpenViking Gateway capture status refresh failed")
await self.management.log(
self.credential["account"], self.metrics, user_id=self.credential["user_id"]
)
diff --git a/tests/gateway/test_app.py b/tests/gateway/test_app.py
index b5e3539cb..b4782c2f4 100644
--- a/tests/gateway/test_app.py
+++ b/tests/gateway/test_app.py
@@ -1,5 +1,6 @@
import asyncio
import json
+import time
from pathlib import Path
import orjson
@@ -7,6 +8,7 @@ import pytest
from aiohttp import web
from conftest import MCP_TOOLS
+from openviking_gateway.capture import ready_at
from openviking_gateway.protocols import normalize
from openviking_gateway.tool_loop import REFUSED
@@ -1157,6 +1159,61 @@ async def test_overview_counts_model_requests_recalls_and_capture_issues(running
assert overview["log_retention_days"] == 30
+async def test_overview_counts_capture_recovered_during_a_request(running_gateway):
+ app, client, admin, key, _, _ = running_gateway
+ store = app.state.store
+ headers = {"Authorization": "Bearer " + key["key"], "X-OpenViking-Session": "recovering"}
+ history = [{"role": "user", "content": "Question"}]
+ response = await client.post(
+ "/v1/chat/completions", headers=headers, json={"model": "model", "messages": history}
+ )
+ assert response.status_code == 200, response.text
+ with store.connect() as c:
+ ((scope, session),) = list(c.execute("SELECT scope,session FROM capture"))
+ retry = {"attempts": 1, "reason": "openviking_http_503", "retry_at": time.time() + 3600}
+ old = await store.capture.get(scope, session)
+ value = {**old.value, "error": retry}
+ assert await store.capture.swap(scope, session, old, value, ready_at(value))
+
+ async def recover(request):
+ # The worker's retry succeeds while this request is still upstream.
+ if request.path == "/v1/chat/completions":
+ old = await store.capture.get(scope, session)
+ value = {**old.value, "error": {}}
+ assert await store.capture.swap(scope, session, old, value, ready_at(value))
+ await app.state.worker.log(
+ {"session": session}, old.value, "active", "delivery_recovered"
+ )
+
+ app.state.test_backend["handler"] = recover
+ history += [{"role": "assistant", "content": "hello"}, {"role": "user", "content": "Next"}]
+ response = await client.post(
+ "/v1/chat/completions", headers=headers, json={"model": "model", "messages": history}
+ )
+ assert response.status_code == 200, response.text
+ overview = (await client.get("/admin/overview", headers=admin)).json()
+ assert overview["capture_issues"] == {"retrying": 0, "paused": 0}
+
+
+async def test_capture_status_refresh_failure_still_logs_request(running_gateway, monkeypatch):
+ _, client, admin, key, _, _ = running_gateway
+
+ class Broken:
+ @staticmethod
+ def model_validate(_):
+ raise RuntimeError("refresh failed")
+
+ monkeypatch.setattr("openviking_gateway.proxy.Policy", Broken)
+ response = await client.post(
+ "/v1/chat/completions",
+ headers={"Authorization": "Bearer " + key["key"], "X-OpenViking-Session": "s"},
+ json={"model": "model", "messages": [{"role": "user", "content": "Question"}]},
+ )
+ assert response.status_code == 200, response.text
+ logs = (await client.get("/admin/logs", headers=admin)).json()
+ assert [log["capture_status"] for log in logs if log["kind"] == "user"] == ["active"]
+
+
async def test_overview_without_model_requests(running_gateway):
_, client, admin, _, _, _ = running_gateway
overview = (await client.get("/admin/overview", headers=admin)).json()