Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Read organization_pricing.ended_at in the staged pricing model so ended contracts stop accruing revenue (SKY-18295) (#8907)
Aaron Perezfa85868c775f
diff --git a/skyvern/forge/api_app.py b/skyvern/forge/api_app.pyindex f91e70b9a..3a203b079 100644--- a/skyvern/forge/api_app.py+++ b/skyvern/forge/api_app.py@@ -150,7 +150,9 @@ class SecurityHeadersMiddleware:def add_credentialed_cors_middleware(fastapi_app: FastAPI) -> None:fastapi_app.add_middleware(CORSMiddleware,- **cors_middleware_kwargs(settings.ALLOWED_ORIGINS, settings.ALLOWED_ORIGIN_REGEX),+ **cors_middleware_kwargs(+ settings.ALLOWED_ORIGINS, settings.ALLOWED_ORIGIN_REGEX, expose_headers=["X-Next-Cursor"]+ ),)diff --git a/skyvern/forge/request_logging.py b/skyvern/forge/request_logging.pyindex 060765807..6090aedb1 100644--- a/skyvern/forge/request_logging.py+++ b/skyvern/forge/request_logging.py@@ -81,7 +81,7 @@ _ROUTINE_CLIENT_ERROR_STATUSES = frozenset({404, 405})_MAX_RESPONSE_READ_BYTES = 1024 * 1024 # 1 MB — skip logging bodies larger than this_BINARY_PLACEHOLDER = "<binary>"_LOGGABLE_CONTENT_TYPES = {"text/", "application/json"}-_STREAMING_CONTENT_TYPE = "text/event-stream"+_STREAMING_CONTENT_TYPES = ("text/event-stream", "application/x-ndjson")_ACTION_LOG_ENDPOINT_RE = re.compile(r"^/v1/browser_sessions/[^/]+/action_logs/?$")_raw_request_exception_logger: ContextVar[typing.Callable[[int], None] | None] = ContextVar("raw_request_exception_logger", default=None@@ -414,7 +414,7 @@ async def log_raw_request_middleware(request: Request, call_next: Callable[[Requresponse = await call_next(request)resp_content_type = response.headers.get("content-type", "")- is_streaming_response = _STREAMING_CONTENT_TYPE in resp_content_type+ is_streaming_response = any(content_type in resp_content_type for content_type in _STREAMING_CONTENT_TYPES)# Skip successful reads before buffering the response body; 4xx/5xx and# mutating paths keep logging, and sensitive endpoints always keepdiff --git a/skyvern/forge/sdk/db/repositories/tasks.py b/skyvern/forge/sdk/db/repositories/tasks.pyindex 67033be08..0e373007d 100644--- a/skyvern/forge/sdk/db/repositories/tasks.py+++ b/skyvern/forge/sdk/db/repositories/tasks.py@@ -7,7 +7,7 @@ from decimal import Decimalfrom typing import Anyimport structlog-from sqlalchemy import and_, delete, func, or_, select, update+from sqlalchemy import and_, delete, func, or_, select, tuple_, updatefrom skyvern.forge.sdk.db._error_handling import db_operationfrom skyvern.forge.sdk.db.base_alchemy_db import read_retry@@ -921,16 +921,20 @@ class TasksRepository(BaseRepository):application: str | None = None,order_by_column: OrderBy = OrderBy.created_at,order: SortDirection = SortDirection.desc,+ keyset: bool = False,+ after: tuple[datetime, str] | None = None,) -> list[Task]:"""Get all tasks.- :param page: Starts at 1+ :param page: Starts at 1; ignored when keyset is set:param page_size::param task_status::param workflow_run_id::param only_standalone_tasks::param order_by_column::param order:+ :param keyset: order by (order_by_column, task_id) and return the rows strictly after `after`+ :param after: the (sort timestamp, task_id) of the last row already read, or None to start:return:"""if page < 1:@@ -952,11 +956,26 @@ class TasksRepository(BaseRepository):if application:query = query.filter(TaskModel.application == application)order_by_col = getattr(TaskModel, order_by_column)- query = (- query.order_by(order_by_col.desc() if order == SortDirection.desc else order_by_col.asc())- .limit(page_size)- .offset(db_page * page_size)- )+ descending = order == SortDirection.desc+ if keyset:+ if after is not None:+ after_ts, after_task_id = after+ row = tuple_(order_by_col, TaskModel.task_id)+ # The single-column bound lets the (organization_id, created_at) index range-scan;+ # the row comparison alone is not always used as an index condition.+ query = query.filter(+ order_by_col <= after_ts if descending else order_by_col >= after_ts,+ row < tuple_(after_ts, after_task_id) if descending else row > tuple_(after_ts, after_task_id),+ )+ query = query.order_by(+ *(col.desc() if descending else col.asc() for col in (order_by_col, TaskModel.task_id))+ ).limit(page_size)+ else:+ query = (+ query.order_by(order_by_col.desc() if descending else order_by_col.asc())+ .limit(page_size)+ .offset(db_page * page_size)+ )results = (await session.execute(query)).all()diff --git a/skyvern/forge/sdk/routes/agent_protocol.py b/skyvern/forge/sdk/routes/agent_protocol.pyindex 36f924301..349ed0773 100644--- a/skyvern/forge/sdk/routes/agent_protocol.py+++ b/skyvern/forge/sdk/routes/agent_protocol.py@@ -1,14 +1,19 @@import asyncio+import base64+import binasciiimport jsonimport random+import reimport timeimport unicodedata-from collections.abc import Sequence+from collections.abc import AsyncIterator, Sequence+from dataclasses import asdict, dataclassfrom datetime import UTC, datetimefrom enum import Enumfrom typing import Annotated, Anyfrom urllib.parse import parse_qs, quote, urlparse+import orjsonimport structlogimport yamlfrom fastapi import (@@ -25,7 +30,7 @@ from fastapi import (UploadFile,)from fastapi import status as http_status-from fastapi.responses import ORJSONResponse+from fastapi.responses import ORJSONResponse, StreamingResponsefrom opentelemetry import tracefrom pydantic import TypeAdapter, ValidationErrorfrom sqlalchemy.exc import IntegrityError, SQLAlchemyError@@ -3985,6 +3990,160 @@ async def run_task_v1(return CreateTaskResponse(task_id=created_task.task_id)+@dataclass(frozen=True)+class TaskListFilters:+ """The task filters shared by GET /tasks and GET /tasks/export, named as the repository's get_tasks takes them."""++ task_status: list[TaskStatus] | None+ workflow_run_id: str | None+ only_standalone_tasks: bool+ application: str | None+ order_by_column: OrderBy+ order: SortDirection+++def task_list_filters(+ task_status: Annotated[list[TaskStatus] | None, Query()] = None,+ workflow_run_id: Annotated[str | None, Query()] = None,+ only_standalone_tasks: bool = Query(False),+ application: Annotated[str | None, Query()] = None,+ sort: OrderBy = Query(OrderBy.created_at),+ order: SortDirection = Query(SortDirection.desc),+) -> TaskListFilters:+ if only_standalone_tasks and workflow_run_id:+ raise HTTPException(+ status_code=http_status.HTTP_400_BAD_REQUEST,+ detail="only_standalone_tasks and workflow_run_id cannot be used together",+ )+ return TaskListFilters(+ task_status=sorted(task_status) if task_status else None,+ workflow_run_id=workflow_run_id,+ only_standalone_tasks=only_standalone_tasks,+ application=application,+ order_by_column=sort,+ order=order,+ )+++_TASK_CURSOR_MAX_LENGTH = 1024+# A client can edit a decoded cursor, and a NUL or lone surrogate in the id would fail in the driver as a 500.+_CURSOR_TASK_ID_PATTERN = re.compile(r"tsk_[A-Za-z0-9_]+")+TASK_NEXT_CURSOR_HEADER = "X-Next-Cursor"+++def _task_cursor_scope(organization_id: str, filters: TaskListFilters) -> str:+ # The positional layout is the cursor wire format; changing it rejects every cursor already handed out.+ scope = [+ organization_id,+ filters.order_by_column,+ filters.order,+ filters.task_status or [],+ filters.workflow_run_id,+ filters.only_standalone_tasks,+ filters.application,+ ]+ return calculate_sha256(json.dumps(scope))[:16]+++def _task_keyset_position(task: Task, sort: OrderBy) -> tuple[datetime, str]:+ sort_value = task.created_at if sort == OrderBy.created_at else task.modified_at+ if sort_value.tzinfo is not None:+ sort_value = sort_value.astimezone(UTC).replace(tzinfo=None)+ return sort_value, task.task_id+++def _encode_task_cursor(scope: str, task: Task, sort: OrderBy) -> str:+ sort_value, task_id = _task_keyset_position(task, sort)+ payload = json.dumps({"scope": scope, "after": [sort_value.isoformat(), task_id]}, separators=(",", ":"))+ return base64.urlsafe_b64encode(payload.encode()).decode().rstrip("=")+++def _decode_task_cursor(cursor: str, scope: str) -> tuple[datetime, str] | None:+ if cursor == "":+ return None+ try:+ decoded = json.loads(base64.urlsafe_b64decode(cursor + "=" * (-len(cursor) % 4)))+ cursor_scope = decoded["scope"]+ sort_value_raw, task_id = decoded["after"]+ if not isinstance(sort_value_raw, str) or not isinstance(task_id, str):+ raise ValueError+ if not _CURSOR_TASK_ID_PATTERN.fullmatch(task_id):+ raise ValueError+ sort_value = datetime.fromisoformat(sort_value_raw)+ if sort_value.tzinfo is not None:+ raise ValueError+ except (binascii.Error, json.JSONDecodeError, UnicodeDecodeError, KeyError, ValueError, TypeError) as exc:+ raise HTTPException(status_code=http_status.HTTP_400_BAD_REQUEST, detail="Invalid cursor") from exc+ if cursor_scope != scope:+ raise HTTPException(+ status_code=http_status.HTTP_400_BAD_REQUEST,+ detail="cursor was issued for a different organization, sort, order or filters; restart with cursor=''",+ )+ return sort_value, task_id+++TASK_EXPORT_BATCH_SIZE = 500+++def _ndjson_line(content: Any) -> bytes:+ line = orjson.dumps(content, option=orjson.OPT_NON_STR_KEYS | orjson.OPT_SERIALIZE_NUMPY)+ # orjson leaves U+2028, U+2029 and U+0085 raw, and str.splitlines() splits on them. They can only occur inside+ # JSON strings, so escaping them keeps each record on one line for any line reader.+ return (+ line.replace(b"\xe2\x80\xa8", b"\\u2028").replace(b"\xe2\x80\xa9", b"\\u2029").replace(b"\xc2\x85", b"\\u0085")+ + b"\n"+ )+++def _serialize_task_export_batch(tasks: list[Task]) -> bytes:+ return b"".join(_ndjson_line(task.to_task_response().model_dump()) for task in tasks)+++# Registered before /tasks/{task_id}, which would otherwise match "export" as a task id.+@legacy_base_router.get("/tasks/export", tags=["agent"])+@legacy_base_router.get("/tasks/export/", include_in_schema=False)+async def export_tasks(+ filters: Annotated[TaskListFilters, Depends(task_list_filters)],+ current_org: Organization = Depends(org_auth_service.get_current_org),+ cursor: str | None = Query(None, max_length=_TASK_CURSOR_MAX_LENGTH),+) -> StreamingResponse:+ """+ Stream every task matching the GET /tasks filters as newline-delimited JSON, one task per line.++ After each full batch a {"cursor": "..."} line marks a checkpoint, and the stream ends with+ {"export_complete": true, "task_count": N}. A stream without that last line was cut off: drop the task lines after+ its last checkpoint and resume by passing that cursor back. Cursors from GET /tasks with the same filters also work.+ Each batch is a fresh query, so an export is not a snapshot: with sort=modified_at or a task_status filter, a task+ that changes during the export (or before a resume) can be skipped or written twice.+ """+ analytics.capture("skyvern-oss-agent-tasks-export")+ organization_id = current_org.organization_id+ scope = _task_cursor_scope(organization_id, filters)+ start_after = _decode_task_cursor(cursor or "", scope)++ async def batches() -> AsyncIterator[bytes]:+ after = start_after+ task_count = 0+ while True:+ tasks = await app.DATABASE.tasks.get_tasks(+ page_size=TASK_EXPORT_BATCH_SIZE,+ organization_id=organization_id,+ keyset=True,+ after=after,+ **asdict(filters),+ )+ if tasks:+ task_count += len(tasks)+ yield await asyncio.to_thread(_serialize_task_export_batch, tasks)+ if len(tasks) < TASK_EXPORT_BATCH_SIZE:+ yield _ndjson_line({"export_complete": True, "task_count": task_count})+ return+ after = _task_keyset_position(tasks[-1], filters.order_by_column)+ yield _ndjson_line({"cursor": _encode_task_cursor(scope, tasks[-1], filters.order_by_column)})++ return StreamingResponse(batches(), media_type="application/x-ndjson")++@legacy_base_router.get("/tasks/{task_id}",tags=["agent"],@@ -4393,18 +4552,19 @@ async def retry_webhook(include_in_schema=False,)async def get_tasks(+ filters: Annotated[TaskListFilters, Depends(task_list_filters)],page: int = Query(1, ge=1),page_size: int = Query(10, ge=1),- task_status: Annotated[list[TaskStatus] | None, Query()] = None,- workflow_run_id: Annotated[str | None, Query()] = None,current_org: Organization = Depends(org_auth_service.get_current_org),- only_standalone_tasks: bool = Query(False),- application: Annotated[str | None, Query()] = None,- sort: OrderBy = Query(OrderBy.created_at),- order: SortDirection = Query(SortDirection.desc),+ cursor: str | None = Query(None, max_length=_TASK_CURSOR_MAX_LENGTH),) -> Response:"""Get all tasks.+ :param cursor: Opt-in keyset pagination. Pass an empty cursor to start, then the X-Next-Cursor response header+ to continue; the header is absent on the last page. Rows are ordered by (sort, task_id) and page must stay 1.+ A cursor only works with the organization, sort, order and filters it was issued for. Each page is a fresh+ query, so a walk is not a snapshot: with sort=modified_at or a task_status filter, a task that changes during+ the walk can be skipped or returned twice.:param page: Starting page, defaults to 1:param page_size: Page size, defaults to 10:param task_status: Task status filter@@ -4416,25 +4576,34 @@ async def get_tasks(get_agent_task endpoint."""analytics.capture("skyvern-oss-agent-tasks-get")- if only_standalone_tasks and workflow_run_id:+ if cursor is None:+ tasks = await app.DATABASE.tasks.get_tasks(+ page, page_size, organization_id=current_org.organization_id, **asdict(filters)+ )+ # Without a last step, build_task_response is just to_task_response. Building and serializing a large page+ # in a thread keeps it from stalling every other request on the event loop.+ return await asyncio.to_thread(lambda: ORJSONResponse([task.to_task_response().model_dump() for task in tasks]))++ if page != 1:raise HTTPException(status_code=http_status.HTTP_400_BAD_REQUEST,- detail="only_standalone_tasks and workflow_run_id cannot be used together",+ detail="page cannot be combined with cursor",)+ scope = _task_cursor_scope(current_org.organization_id, filters)tasks = await app.DATABASE.tasks.get_tasks(- page,- page_size,- task_status=task_status,- workflow_run_id=workflow_run_id,+ page_size=page_size + 1,organization_id=current_org.organization_id,- only_standalone_tasks=only_standalone_tasks,- order=order,- order_by_column=sort,- application=application,+ keyset=True,+ after=_decode_task_cursor(cursor, scope),+ **asdict(filters),)- # Without a last step, build_task_response is just to_task_response. Building and serializing a large page- # in a thread keeps it from stalling every other request on the event loop.- return await asyncio.to_thread(lambda: ORJSONResponse([task.to_task_response().model_dump() for task in tasks]))+ page_tasks = tasks[:page_size]+ response = await asyncio.to_thread(+ lambda: ORJSONResponse([task.to_task_response().model_dump() for task in page_tasks])+ )+ if len(tasks) > page_size:+ response.headers[TASK_NEXT_CURSOR_HEADER] = _encode_task_cursor(scope, page_tasks[-1], filters.order_by_column)+ return response_RUN_IDENTIFIER_SEARCH_DESCRIPTION = (diff --git a/skyvern/forge/sdk/services/route_authorization.py b/skyvern/forge/sdk/services/route_authorization.pyindex 5de44d15b..a44e92eac 100644--- a/skyvern/forge/sdk/services/route_authorization.py+++ b/skyvern/forge/sdk/services/route_authorization.py@@ -60,6 +60,7 @@ ROUTE_ACTIONS: Mapping[str, str] = {"skyvern.forge.sdk.routes.agent_protocol.get_steps": "task.list","skyvern.forge.sdk.routes.agent_protocol.get_task_v1": "task.read","skyvern.forge.sdk.routes.agent_protocol.get_task_v2": "task.read",+ "skyvern.forge.sdk.routes.agent_protocol.export_tasks": "task.list","skyvern.forge.sdk.routes.agent_protocol.get_tasks": "task.list","skyvern.forge.sdk.routes.agent_protocol.get_version": "version.read","skyvern.forge.sdk.routes.agent_protocol.get_workflow": "workflow.read",diff --git a/tests/unit/forge/sdk/routes/test_agent_protocol_get_tasks.py b/tests/unit/forge/sdk/routes/test_agent_protocol_get_tasks.pyindex a58434719..199d9ec90 100644--- a/tests/unit/forge/sdk/routes/test_agent_protocol_get_tasks.py+++ b/tests/unit/forge/sdk/routes/test_agent_protocol_get_tasks.py@@ -1,4 +1,5 @@import asyncio+import base64import jsonimport threadingfrom collections.abc import Callable@@ -9,10 +10,12 @@ import httpximport pytestfrom fastapi import FastAPIfrom fastapi.responses import ORJSONResponse+from sqlalchemy import updatefrom sqlalchemy.ext.asyncio import AsyncEnginefrom skyvern.forge.agent import ForgeAgentfrom skyvern.forge.sdk.db.agent_db import AgentDB+from skyvern.forge.sdk.db.models import TaskModelfrom skyvern.forge.sdk.db.repositories import tasks as tasks_repositoryfrom skyvern.forge.sdk.routes import agent_protocolfrom skyvern.forge.sdk.routes.routers import base_router, legacy_base_router@@ -75,21 +78,206 @@ async def test_task_listing_builds_and_serializes_the_page_off_the_event_loop(monkeypatch.setattr(tasks_repository, "convert_to_task", probe.gate("convert", tasks_repository.convert_to_task))monkeypatch.setattr(Task, "to_task_response", probe.gate("serialize", Task.to_task_response))+ ticker = asyncio.create_task(probe.tick_forever())+ try:+ async with _client() as client:+ response = await client.get("/api/v1/tasks", params={"page_size": 1000, "only_standalone_tasks": False})+ finally:+ ticker.cancel()++ assert response.status_code == 200, response.text+ assert probe.loop_ran == {"convert": True, "serialize": True}+ assert response.json() == json.loads(expected_body)+ assert len(response.json()) == 3+ assert agent_protocol.TASK_NEXT_CURSOR_HEADER not in response.headers+++def _client(organization_id: str = ORG_ID) -> httpx.AsyncClient:now = datetime.now(UTC)- organization = Organization(organization_id=ORG_ID, organization_name="Listing", created_at=now, modified_at=now)+ organization = Organization(+ organization_id=organization_id, organization_name="Listing", created_at=now, modified_at=now+ )fastapi_app = FastAPI()fastapi_app.include_router(base_router, prefix="/v1")fastapi_app.include_router(legacy_base_router, prefix="/api/v1")fastapi_app.dependency_overrides[org_auth_service.get_current_org] = lambda: organization+ return httpx.AsyncClient(transport=httpx.ASGITransport(app=fastapi_app), base_url="http://test")+++async def _seed_tasks_with_timestamp_ties(+ monkeypatch: pytest.MonkeyPatch, sqlite_engine: AsyncEngine, count: int+) -> list[str]:+ db = AgentDB("sqlite+aiosqlite://", db_engine=sqlite_engine)+ task_ids = []+ for index in range(count):+ task = await db.tasks.create_task(+ url="https://example.com",+ # Characters str.splitlines() treats as line breaks; the export must keep each record on one line.+ title=f"Task {index} \u2028\u2029\x85",+ navigation_goal="Find the pricing page",+ data_extraction_goal=None,+ navigation_payload=None,+ organization_id=ORG_ID,+ )+ task_ids.append(task.task_id)+ # Each sort column gets a few shared values, in an order unlike creation, so page boundaries fall inside a tie.+ async with db.Session() as session:+ for index, task_id in enumerate(task_ids):+ await session.execute(+ update(TaskModel)+ .where(TaskModel.task_id == task_id)+ .values(+ created_at=datetime(2026, 10, 1 + index % 2, 12, 0, 0),+ modified_at=datetime(2026, 10, 5 + index % 3, 12, 0, 0),+ )+ )+ await session.commit()+ app_instance = object.__getattribute__(agent_protocol.app, "_inst")+ monkeypatch.setattr(app_instance, "DATABASE", db)+ monkeypatch.setattr(agent_protocol.analytics, "capture", lambda *args, **kwargs: None)+ return task_ids+++async def _walk_tasks(params: dict[str, Any]) -> tuple[list[int], list[dict[str, Any]]]:+ page_lengths: list[int] = []+ walked: list[dict[str, Any]] = []+ cursor = ""+ async with _client() as client:+ for _ in range(10):+ response = await client.get("/api/v1/tasks", params={**params, "cursor": cursor})+ assert response.status_code == 200, response.text+ page_lengths.append(len(response.json()))+ walked.extend(response.json())+ if agent_protocol.TASK_NEXT_CURSOR_HEADER not in response.headers:+ break+ cursor = response.headers[agent_protocol.TASK_NEXT_CURSOR_HEADER]+ return page_lengths, walked++[email protected]("order", ["desc", "asc"])+async def test_task_cursor_walk_returns_every_task_once_across_timestamp_ties(+ monkeypatch: pytest.MonkeyPatch, sqlite_engine: AsyncEngine, order: str+) -> None:+ task_ids = await _seed_tasks_with_timestamp_ties(monkeypatch, sqlite_engine, count=7)++ page_lengths, walked = await _walk_tasks({"page_size": 2, "order": order})++ assert page_lengths == [2, 2, 2, 1]+ keys = [(task["created_at"], task["task_id"]) for task in walked]+ assert keys == sorted(keys, reverse=order == "desc")+ assert len(keys) == len(set(keys)) == len(task_ids)+++async def test_task_cursor_walk_by_modified_at_ends_on_an_exactly_full_page(+ monkeypatch: pytest.MonkeyPatch, sqlite_engine: AsyncEngine+) -> None:+ task_ids = await _seed_tasks_with_timestamp_ties(monkeypatch, sqlite_engine, count=6)++ page_lengths, walked = await _walk_tasks({"page_size": 2, "sort": "modified_at"})++ assert page_lengths == [2, 2, 2]+ keys = [(task["modified_at"], task["task_id"]) for task in walked]+ assert keys == sorted(keys, reverse=True)+ assert len(set(keys)) == len(task_ids)+++async def test_task_cursor_reused_with_different_filters_is_rejected(+ monkeypatch: pytest.MonkeyPatch, sqlite_engine: AsyncEngine+) -> None:+ await _seed_tasks_with_timestamp_ties(monkeypatch, sqlite_engine, count=3)++ async with _client() as client:+ first = await client.get("/api/v1/tasks", params={"page_size": 1, "cursor": ""})+ cursor = first.headers[agent_protocol.TASK_NEXT_CURSOR_HEADER]+ reordered = await client.get("/api/v1/tasks", params={"page_size": 1, "cursor": cursor, "order": "asc"})+ refiltered = await client.get(+ "/api/v1/tasks", params={"page_size": 1, "cursor": cursor, "only_standalone_tasks": True}+ )+ resorted = await client.get("/api/v1/tasks", params={"page_size": 1, "cursor": cursor, "sort": "modified_at"})+ status_filtered = await client.get(+ "/api/v1/tasks", params={"page_size": 1, "cursor": cursor, "task_status": "created"}+ )+ paged = await client.get("/api/v1/tasks", params={"page_size": 1, "cursor": cursor, "page": 2})+ garbage = await client.get("/api/v1/tasks", params={"page_size": 1, "cursor": "not-a-cursor"})+ payload = json.loads(base64.urlsafe_b64decode(cursor + "=" * (-len(cursor) % 4)))+ payload["after"][1] = "tsk_1\u0000"+ forged_cursor = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode().rstrip("=")+ forged = await client.get("/api/v1/tasks", params={"page_size": 1, "cursor": forged_cursor})+ async with _client("o_other_org") as other_org_client:+ other_org = await other_org_client.get("/api/v1/tasks", params={"page_size": 1, "cursor": cursor})++ responses = [reordered, refiltered, resorted, status_filtered, paged, garbage, forged, other_org]+ assert [response.status_code for response in responses] == [400] * len(responses)++[email protected]("count", [6, 7])+async def test_task_export_streams_every_task_once_across_batch_boundaries(+ monkeypatch: pytest.MonkeyPatch, sqlite_engine: AsyncEngine, count: int+) -> None:+ task_ids = await _seed_tasks_with_timestamp_ties(monkeypatch, sqlite_engine, count=count)+ monkeypatch.setattr(agent_protocol, "TASK_EXPORT_BATCH_SIZE", 2)++ async with _client() as client:+ response = await client.get("/api/v1/tasks/export")++ assert response.status_code == 200, response.text+ assert response.headers["content-type"] == "application/x-ndjson"+ *lines, trailer = (json.loads(line) for line in response.text.splitlines())+ assert trailer == {"export_complete": True, "task_count": count}+ exported = [line for line in lines if "task_id" in line]+ assert len(lines) - len(exported) == count // 2+ keys = [(task["created_at"], task["task_id"]) for task in exported]+ assert keys == sorted(keys, reverse=True)+ assert sorted(task["task_id"] for task in exported) == sorted(task_ids)+++async def test_task_export_resumes_from_its_last_checkpoint(+ monkeypatch: pytest.MonkeyPatch, sqlite_engine: AsyncEngine+) -> None:+ task_ids = await _seed_tasks_with_timestamp_ties(monkeypatch, sqlite_engine, count=7)+ monkeypatch.setattr(agent_protocol, "TASK_EXPORT_BATCH_SIZE", 2)++ async with _client() as client:+ full = [json.loads(line) for line in (await client.get("/api/v1/tasks/export")).text.splitlines()]+ # Simulate a drop after the second checkpoint: keep tasks up to it, resume from its cursor.+ checkpoints = [index for index, line in enumerate(full) if "cursor" in line]+ kept = full[: checkpoints[1]]+ resumed_response = await client.get("/api/v1/tasks/export", params={"cursor": full[checkpoints[1]]["cursor"]})+ resumed = [json.loads(line) for line in resumed_response.text.splitlines()]++ exported_ids = [line["task_id"] for line in kept + resumed if "task_id" in line]+ assert sorted(exported_ids) == sorted(task_ids)+ assert len(exported_ids) == len(set(exported_ids))+ assert resumed[-1] == {"export_complete": True, "task_count": 3}+++async def test_task_export_applies_filters_and_builds_batches_off_the_event_loop(+ monkeypatch: pytest.MonkeyPatch, sqlite_engine: AsyncEngine+) -> None:+ task_ids = await _seed_tasks_with_timestamp_ties(monkeypatch, sqlite_engine, count=3)+ db = object.__getattribute__(agent_protocol.app, "_inst").DATABASE+ async with db.Session() as session:+ await session.execute(update(TaskModel).where(TaskModel.task_id == task_ids[0]).values(status="completed"))+ await session.commit()+ probe = _LoopProbe()+ monkeypatch.setattr(tasks_repository, "convert_to_task", probe.gate("convert", tasks_repository.convert_to_task))+ monkeypatch.setattr(Task, "to_task_response", probe.gate("serialize", Task.to_task_response))ticker = asyncio.create_task(probe.tick_forever())try:- async with httpx.AsyncClient(transport=httpx.ASGITransport(app=fastapi_app), base_url="http://test") as client:- response = await client.get("/api/v1/tasks", params={"page_size": 1000, "only_standalone_tasks": False})+ async with _client() as client:+ response = await client.get("/api/v1/tasks/export", params={"task_status": "created"})finally:ticker.cancel()assert response.status_code == 200, response.textassert probe.loop_ran == {"convert": True, "serialize": True}- assert response.json() == json.loads(expected_body)- assert len(response.json()) == 3+ *exported, trailer = (json.loads(line) for line in response.text.splitlines())+ assert sorted(task["task_id"] for task in exported) == sorted(task_ids[1:])+ assert trailer == {"export_complete": True, "task_count": 2}diff --git a/tests/unit/test_request_logging.py b/tests/unit/test_request_logging.pyindex 85cf695e0..0a6fb81e7 100644--- a/tests/unit/test_request_logging.py+++ b/tests/unit/test_request_logging.py@@ -694,6 +694,13 @@ def _make_app(unhandled_exception_status: int = 500) -> FastAPI:log_raw_request_exception(response.status_code)return response+ @app.get("/ndjson-stream")+ async def ndjson_stream() -> StreamingResponse:+ async def lines() -> typing.AsyncIterator[bytes]:+ yield b'{"task_id":"tsk_1"}\n'++ return StreamingResponse(lines(), media_type="application/x-ndjson")+@app.get("/heartbeat")async def heartbeat() -> dict:return {"ok": True}@@ -836,6 +843,20 @@ class TestMiddlewareLogVolume:assert "SYNTHETIC_SECRET" not in repr(call)assert "sk-test-" not in repr(call)+ def test_ndjson_stream_logs_once_without_reading_body(+ self, log_mock: MagicMock, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ monkeypatch.setattr(request_logging.settings, "LOG_RAW_API_REQUESTS_SUCCESSFUL_READS", True)+ read_body = AsyncMock(side_effect=AssertionError("NDJSON must not be buffered for logging"))+ monkeypatch.setattr(request_logging, "_get_response_body_str", read_body)++ response = TestClient(_make_app()).get("/ndjson-stream")++ assert response.status_code == 200+ assert response.content == b'{"task_id":"tsk_1"}\n'+ read_body.assert_not_awaited()+ assert log_mock.info.call_args.kwargs["response_body"] == "<streaming>"+@pytest.mark.parametrize("method", ["POST", "GET"])def test_mcp_stream_logs_once_without_reading_body(self, log_mock: MagicMock, method: str, monkeypatch: pytest.MonkeyPatch