AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
perf(backend): cut three top egress queries via aggregation + caps (#13033)
Zamil Majdye10f32e84414
diff --git a/autogpt_platform/backend/backend/copilot/db.py b/autogpt_platform/backend/backend/copilot/db.pyindex 56e99622f7..d4aa1a5007 100644--- a/autogpt_platform/backend/backend/copilot/db.py+++ b/autogpt_platform/backend/backend/copilot/db.py@@ -255,7 +255,7 @@ async def update_chat_session(total_prompt_tokens: int | None = None,total_completion_tokens: int | None = None,title: str | None = None,-) -> ChatSession | None:+) -> ChatSessionInfo | None:"""Update a chat session's mutable fields.Note: ``metadata`` (which includes ``dry_run``) is intentionally omitted —@@ -277,12 +277,14 @@ async def update_chat_session(if title is not None:data["title"] = title+ # Returns the bare session row (no eager Messages include): pulling the+ # full message history per update was a top-egress query, and the only+ # caller ignores the return value.session = await PrismaChatSession.prisma().update(where={"id": session_id},data=data,- include={"Messages": {"order_by": {"sequence": "asc"}}},)- return ChatSession.from_db(session) if session else None+ return ChatSessionInfo.from_db(session) if session else Noneasync def update_chat_session_title(diff --git a/autogpt_platform/backend/backend/data/execution.py b/autogpt_platform/backend/backend/data/execution.pyindex e89e467f45..88c762cdad 100644--- a/autogpt_platform/backend/backend/data/execution.py+++ b/autogpt_platform/backend/backend/data/execution.py@@ -60,6 +60,7 @@ from .includes import (EXECUTION_RESULT_INCLUDE,EXECUTION_RESULT_ORDER,GRAPH_EXECUTION_INCLUDE_WITH_NODES,+ MAX_NODE_INPUT_OUTPUT_FETCH,graph_execution_include,)from .model import (@@ -457,7 +458,14 @@ class NodeExecutionResult(BaseModel):input_data = type_utils.convert(_node_exec.executionData, BlockInput)else:input_data: BlockInput = defaultdict()- for data in _node_exec.Input or []:+ inputs = _node_exec.Input or []+ if len(inputs) >= MAX_NODE_INPUT_OUTPUT_FETCH:+ logger.warning(+ "NodeExecution %s Input rows hit MAX_NODE_INPUT_OUTPUT_FETCH "+ "cap; result may be truncated",+ _node_exec.id,+ )+ for data in inputs:input_data[data.name] = type_utils.convert(data.data, JsonValue)output_data: CompletedBlockOutput = defaultdict(list)@@ -466,7 +474,14 @@ class NodeExecutionResult(BaseModel):for name, messages in stats.cleared_outputs.items():output_data[name].extend(messages)else:- for data in _node_exec.Output or []:+ outputs = _node_exec.Output or []+ if len(outputs) >= MAX_NODE_INPUT_OUTPUT_FETCH:+ logger.warning(+ "NodeExecution %s Output rows hit MAX_NODE_INPUT_OUTPUT_FETCH "+ "cap; result may be truncated",+ _node_exec.id,+ )+ for data in outputs:output_data[data.name].append(type_utils.convert(data.data, JsonValue))graph_execution: AgentGraphExecution | None = _node_exec.GraphExecutiondiff --git a/autogpt_platform/backend/backend/data/execution_io_cap_test.py b/autogpt_platform/backend/backend/data/execution_io_cap_test.pynew file mode 100644index 0000000000..ef2b8ba877--- /dev/null+++ b/autogpt_platform/backend/backend/data/execution_io_cap_test.py@@ -0,0 +1,82 @@+"""Coverage for the cap-hit warning path on NodeExecutionResult.from_db."""++import logging+from datetime import datetime, timezone+from unittest.mock import MagicMock++from prisma.enums import AgentExecutionStatus++from backend.data.execution import NodeExecutionResult+from backend.data.includes import MAX_NODE_INPUT_OUTPUT_FETCH+++def _make_io_row(name: str, value: str) -> MagicMock:+ row = MagicMock()+ row.name = name+ row.data = value+ return row+++def _make_node_exec(*, inputs: list, outputs: list, exec_id: str = "ne-1") -> MagicMock:+ ne = MagicMock()+ ne.id = exec_id+ ne.stats = {}+ ne.executionData = None+ ne.Input = inputs+ ne.Output = outputs+ ne.agentGraphExecutionId = "ge-1"+ ne.agentNodeId = "n-1"+ ne.executionStatus = AgentExecutionStatus.COMPLETED+ ne.addedTime = datetime.now(timezone.utc)+ ne.queuedTime = None+ ne.startedTime = None+ ne.endedTime = None++ ne.Node = MagicMock()+ ne.Node.agentBlockId = "blk-1"++ ne.GraphExecution = MagicMock()+ ne.GraphExecution.userId = "u-1"+ ne.GraphExecution.agentGraphId = "g-1"+ ne.GraphExecution.agentGraphVersion = 1+ return ne+++def test_node_exec_input_cap_logs_warning(caplog):+ inputs = [+ _make_io_row(f"in_{i}", f"v{i}") for i in range(MAX_NODE_INPUT_OUTPUT_FETCH)+ ]+ ne = _make_node_exec(inputs=inputs, outputs=[])++ with caplog.at_level(logging.WARNING, logger="backend.data.execution"):+ result = NodeExecutionResult.from_db(ne)++ assert any(+ "Input rows hit MAX_NODE_INPUT_OUTPUT_FETCH" in m for m in caplog.messages+ )+ assert isinstance(result, NodeExecutionResult)+++def test_node_exec_output_cap_logs_warning(caplog):+ outputs = [_make_io_row("out", f"v{i}") for i in range(MAX_NODE_INPUT_OUTPUT_FETCH)]+ ne = _make_node_exec(inputs=[], outputs=outputs)++ with caplog.at_level(logging.WARNING, logger="backend.data.execution"):+ result = NodeExecutionResult.from_db(ne)++ assert any(+ "Output rows hit MAX_NODE_INPUT_OUTPUT_FETCH" in m for m in caplog.messages+ )+ assert isinstance(result, NodeExecutionResult)+++def test_node_exec_under_cap_does_not_warn(caplog):+ inputs = [_make_io_row(f"in_{i}", f"v{i}") for i in range(3)]+ outputs = [_make_io_row("out", f"v{i}") for i in range(3)]+ ne = _make_node_exec(inputs=inputs, outputs=outputs)++ with caplog.at_level(logging.WARNING, logger="backend.data.execution"):+ result = NodeExecutionResult.from_db(ne)++ assert not any("MAX_NODE_INPUT_OUTPUT_FETCH" in m for m in caplog.messages)+ assert isinstance(result, NodeExecutionResult)diff --git a/autogpt_platform/backend/backend/data/generate_data.py b/autogpt_platform/backend/backend/data/generate_data.pyindex 234b5d18d4..94f649ac1e 100644--- a/autogpt_platform/backend/backend/data/generate_data.py+++ b/autogpt_platform/backend/backend/data/generate_data.py@@ -1,10 +1,10 @@+import asyncioimport logging-from collections import defaultdictfrom datetime import datetime-from prisma.enums import AgentExecutionStatus+from pydantic import BaseModel, Field-from backend.data.execution import get_graph_executions+from backend.data.db import query_raw_with_schemafrom backend.data.graph import get_graph_metadatafrom backend.data.model import UserExecutionSummaryStatsfrom backend.util.exceptions import DatabaseError@@ -13,97 +13,125 @@ from backend.util.logging import TruncatedLoggerlogger = TruncatedLogger(logging.getLogger(__name__), prefix="[SummaryData]")+class _ExecutionAggregates(BaseModel):+ total_executions: int = 0+ successful_runs: int = 0+ failed_runs: int = 0+ total_cost_cents: float = 0.0+ total_walltime: float = 0.0+ walltime_count: int = 0+ cost_by_graph_id: dict[str, float] = Field(default_factory=dict)+ usage_by_graph_id: dict[str, int] = Field(default_factory=dict)++async def get_user_execution_summary_data(user_id: str, start_time: datetime, end_time: datetime) -> UserExecutionSummaryStats:- """Gather all summary data for a user in a time range.+ """Aggregate per-graph execution stats for a user via grouped SQL.- This function fetches graph executions once and aggregates all required- statistics in a single pass for efficiency.+ Pulls only one summary row per agentGraphId instead of every individual+ AgentGraphExecution: heavy users had thousands of executions per call,+ making this the dominant row-egress query in the prior implementation."""try:- # Fetch graph executions once- executions = await get_graph_executions(- user_id=user_id,- created_time_gte=start_time,- created_time_lte=end_time,- )-- # Initialize aggregation variables- total_credits_used = 0.0- total_executions = len(executions)- successful_runs = 0- failed_runs = 0- terminated_runs = 0- execution_times = []- agent_usage = defaultdict(int)- cost_by_graph_id = defaultdict(float)-- # Single pass through executions to aggregate all stats- for execution in executions:- # Count execution statuses (including TERMINATED as failed)- if execution.status == AgentExecutionStatus.COMPLETED:- successful_runs += 1- elif execution.status == AgentExecutionStatus.FAILED:- failed_runs += 1- elif execution.status == AgentExecutionStatus.TERMINATED:- terminated_runs += 1-- # Aggregate costs from stats- if execution.stats and hasattr(execution.stats, "cost"):- cost_in_dollars = execution.stats.cost / 100- total_credits_used += cost_in_dollars- cost_by_graph_id[execution.graph_id] += cost_in_dollars-- # Collect execution times- if execution.stats and hasattr(execution.stats, "duration"):- execution_times.append(execution.stats.duration)-- # Count agent usage- agent_usage[execution.graph_id] += 1-- # Calculate derived stats- total_execution_time = sum(execution_times)- average_execution_time = (- total_execution_time / len(execution_times) if execution_times else 0- )-- # Find most used agent- most_used_agent = "No agents used"- if agent_usage:- most_used_agent_id = max(agent_usage, key=lambda k: agent_usage[k])- try:- graph_meta = await get_graph_metadata(graph_id=most_used_agent_id)- most_used_agent = (- graph_meta.name if graph_meta else f"Agent {most_used_agent_id[:8]}"- )- except Exception:- logger.warning(f"Could not get metadata for graph {most_used_agent_id}")- most_used_agent = f"Agent {most_used_agent_id[:8]}"-- # Convert graph_ids to agent names for cost breakdown- cost_breakdown = {}- for graph_id, cost in cost_by_graph_id.items():- try:- graph_meta = await get_graph_metadata(graph_id=graph_id)- agent_name = graph_meta.name if graph_meta else f"Agent {graph_id[:8]}"- except Exception:- logger.warning(f"Could not get metadata for graph {graph_id}")- agent_name = f"Agent {graph_id[:8]}"- cost_breakdown[agent_name] = cost-- # Build the summary stats object (include terminated runs as failed)- return UserExecutionSummaryStats(- total_credits_used=total_credits_used,- total_executions=total_executions,- successful_runs=successful_runs,- failed_runs=failed_runs + terminated_runs,- most_used_agent=most_used_agent,- total_execution_time=total_execution_time,- average_execution_time=average_execution_time,- cost_breakdown=cost_breakdown,- )-+ rows = await _fetch_execution_aggregate_rows(user_id, start_time, end_time)+ agg = _reduce_execution_rows(rows)+ name_by_graph_id = await _resolve_agent_names(list(agg.cost_by_graph_id))+ return _assemble_summary(agg, name_by_graph_id)except Exception as e:logger.error(f"Failed to get user summary data: {e}")raise DatabaseError(f"Failed to get user summary data: {e}") from e+++async def _fetch_execution_aggregate_rows(+ user_id: str, start_time: datetime, end_time: datetime+) -> list[dict]:+ return await query_raw_with_schema(+ """+ SELECT+ "agentGraphId" AS graph_id,+ COUNT(*) AS total,+ COUNT(*) FILTER (WHERE "executionStatus" = 'COMPLETED') AS successful,+ COUNT(*) FILTER (WHERE "executionStatus" IN ('FAILED', 'TERMINATED')) AS failed,+ COALESCE(SUM(("stats"::jsonb->>'cost')::numeric), 0) AS total_cost_cents,+ COALESCE(SUM(("stats"::jsonb->>'walltime')::numeric), 0) AS total_walltime,+ COUNT(*) FILTER (WHERE ("stats"::jsonb->>'walltime') IS NOT NULL) AS walltime_count+ FROM {schema_prefix}"AgentGraphExecution"+ WHERE "userId" = $1+ AND "isDeleted" = false+ AND "createdAt" >= $2::timestamp+ AND "createdAt" <= $3::timestamp+ GROUP BY "agentGraphId"+ """,+ user_id,+ start_time,+ end_time,+ )+++def _reduce_execution_rows(rows: list[dict]) -> _ExecutionAggregates:+ agg = _ExecutionAggregates()+ for row in rows:+ graph_id = row["graph_id"]+ count = int(row["total"])+ cost_cents = float(row["total_cost_cents"])++ agg.total_executions += count+ agg.successful_runs += int(row["successful"])+ agg.failed_runs += int(row["failed"])+ agg.total_cost_cents += cost_cents+ agg.total_walltime += float(row["total_walltime"])+ agg.walltime_count += int(row["walltime_count"])+ agg.usage_by_graph_id[graph_id] = count+ agg.cost_by_graph_id[graph_id] = cost_cents / 100+ return agg+++async def _resolve_agent_names(graph_ids: list[str]) -> dict[str, str]:+ resolved = await asyncio.gather(*(_resolve_agent_name(gid) for gid in graph_ids))+ return dict(zip(graph_ids, resolved))+++def _assemble_summary(+ agg: _ExecutionAggregates, name_by_graph_id: dict[str, str]+) -> UserExecutionSummaryStats:+ most_used_agent = "No agents used"+ if agg.usage_by_graph_id:+ # Tuple key gives a deterministic tie-break by graph_id when execution+ # counts match, instead of relying on dict insertion order.+ most_used_agent_id = max(+ agg.usage_by_graph_id,+ key=lambda k: (agg.usage_by_graph_id[k], k),+ )+ most_used_agent = name_by_graph_id[most_used_agent_id]++ # Sum on name collisions (two distinct graphs can resolve to the same+ # display name); a plain assign would silently drop one bucket.+ cost_breakdown: dict[str, float] = {}+ for graph_id, cost in agg.cost_by_graph_id.items():+ name = name_by_graph_id[graph_id]+ cost_breakdown[name] = cost_breakdown.get(name, 0.0) + cost++ average_execution_time = (+ agg.total_walltime / agg.walltime_count if agg.walltime_count else 0+ )++ return UserExecutionSummaryStats(+ total_credits_used=agg.total_cost_cents / 100,+ total_executions=agg.total_executions,+ successful_runs=agg.successful_runs,+ failed_runs=agg.failed_runs,+ most_used_agent=most_used_agent,+ total_execution_time=agg.total_walltime,+ average_execution_time=average_execution_time,+ cost_breakdown=cost_breakdown,+ )+++async def _resolve_agent_name(graph_id: str) -> str:+ try:+ graph_meta = await get_graph_metadata(graph_id=graph_id)+ return graph_meta.name if graph_meta else f"Agent {graph_id[:8]}"+ except Exception:+ logger.warning(f"Could not get metadata for graph {graph_id}", exc_info=True)+ return f"Agent {graph_id[:8]}"diff --git a/autogpt_platform/backend/backend/data/generate_data_test.py b/autogpt_platform/backend/backend/data/generate_data_test.pynew file mode 100644index 0000000000..649b57bdda--- /dev/null+++ b/autogpt_platform/backend/backend/data/generate_data_test.py@@ -0,0 +1,291 @@+"""Tests for the SQL-aggregated user execution summary."""++import logging+from datetime import datetime, timedelta, timezone+from uuid import uuid4++import pytest+from prisma.enums import AgentExecutionStatus+from prisma.errors import UniqueViolationError+from prisma.models import AgentGraph, AgentGraphExecution, User++from backend.data import generate_data+from backend.data.generate_data import (+ _resolve_agent_name,+ get_user_execution_summary_data,+)+from backend.util.json import SafeJson+from backend.util.test import SpinTestServer++logger = logging.getLogger(__name__)+++async def _create_test_user(user_id: str) -> None:+ try:+ await User.prisma().create(+ data={+ "id": user_id,+ "email": f"test-{user_id}@example.com",+ "name": f"Test User {user_id[:8]}",+ }+ )+ except UniqueViolationError:+ pass+++async def _create_graph(graph_id: str, user_id: str, name: str) -> None:+ try:+ await AgentGraph.prisma().create(+ data={+ "id": graph_id,+ "version": 1,+ "name": name,+ "description": "test",+ "userId": user_id,+ "isActive": True,+ }+ )+ except UniqueViolationError:+ pass+++async def _create_exec(+ exec_id: str,+ user_id: str,+ graph_id: str,+ status: AgentExecutionStatus,+ cost_cents: int,+ walltime_s: float,+ created_at: datetime,+) -> None:+ await AgentGraphExecution.prisma().create(+ data={+ "id": exec_id,+ "agentGraphId": graph_id,+ "agentGraphVersion": 1,+ "executionStatus": status,+ "userId": user_id,+ "createdAt": created_at,+ "stats": SafeJson({"cost": cost_cents, "walltime": walltime_s}),+ }+ )+++async def _cleanup(user_id: str, graph_ids: list[str]) -> None:+ try:+ await AgentGraphExecution.prisma().delete_many(where={"userId": user_id})+ for gid in graph_ids:+ await AgentGraph.prisma().delete_many(where={"id": gid})+ await User.prisma().delete_many(where={"id": user_id})+ except Exception as exc:+ logger.warning("cleanup for %s failed: %s", user_id, exc)++[email protected](loop_scope="session")+async def test_summary_empty_returns_zero_stats(server: SpinTestServer):+ user_id = f"sum-empty-{uuid4()}"+ await _create_test_user(user_id)+ try:+ now = datetime.now(timezone.utc)+ stats = await get_user_execution_summary_data(+ user_id, now - timedelta(days=1), now+ )+ assert stats.total_executions == 0+ assert stats.successful_runs == 0+ assert stats.failed_runs == 0+ assert stats.total_credits_used == 0+ assert stats.total_execution_time == 0+ assert stats.average_execution_time == 0+ assert stats.cost_breakdown == {}+ assert stats.most_used_agent == "No agents used"+ finally:+ await _cleanup(user_id, [])++[email protected](loop_scope="session")+async def test_summary_aggregates_by_status_and_graph(server: SpinTestServer):+ user_id = f"sum-agg-{uuid4()}"+ graph_a = f"graph-a-{uuid4()}"+ graph_b = f"graph-b-{uuid4()}"+ await _create_test_user(user_id)+ await _create_graph(graph_a, user_id, "Alpha")+ await _create_graph(graph_b, user_id, "Beta")++ now = datetime.now(timezone.utc)+ in_window = now - timedelta(hours=1)++ try:+ # Graph A: 2 successful (50 + 75 cents), 1 failed (25 cents)+ await _create_exec(+ f"a1-{uuid4()}",+ user_id,+ graph_a,+ AgentExecutionStatus.COMPLETED,+ 50,+ 1.5,+ in_window,+ )+ await _create_exec(+ f"a2-{uuid4()}",+ user_id,+ graph_a,+ AgentExecutionStatus.COMPLETED,+ 75,+ 2.5,+ in_window,+ )+ await _create_exec(+ f"a3-{uuid4()}",+ user_id,+ graph_a,+ AgentExecutionStatus.FAILED,+ 25,+ 0.5,+ in_window,+ )+ # Graph B: 1 terminated (10 cents) — counted as failed+ await _create_exec(+ f"b1-{uuid4()}",+ user_id,+ graph_b,+ AgentExecutionStatus.TERMINATED,+ 10,+ 0.1,+ in_window,+ )++ stats = await get_user_execution_summary_data(+ user_id, now - timedelta(hours=2), now+ )++ assert stats.total_executions == 4+ assert stats.successful_runs == 2+ assert stats.failed_runs == 2 # 1 FAILED + 1 TERMINATED+ assert stats.total_credits_used == pytest.approx((50 + 75 + 25 + 10) / 100)+ assert stats.total_execution_time == pytest.approx(1.5 + 2.5 + 0.5 + 0.1)+ assert stats.average_execution_time == pytest.approx(+ (1.5 + 2.5 + 0.5 + 0.1) / 4+ )+ # Most-used agent is Graph A (3 executions vs Graph B's 1)+ assert stats.most_used_agent == "Alpha"+ # Cost breakdown keyed by agent name+ assert stats.cost_breakdown == {+ "Alpha": pytest.approx((50 + 75 + 25) / 100),+ "Beta": pytest.approx(10 / 100),+ }+ finally:+ await _cleanup(user_id, [graph_a, graph_b])++[email protected](loop_scope="session")+async def test_summary_sums_costs_on_agent_name_collision(server: SpinTestServer):+ # Two distinct agentGraphIds resolving to the same display name must sum+ # into the same cost_breakdown bucket, not overwrite each other.+ user_id = f"sum-collide-{uuid4()}"+ graph_a = f"graph-c1-{uuid4()}"+ graph_b = f"graph-c2-{uuid4()}"+ await _create_test_user(user_id)+ await _create_graph(graph_a, user_id, "Scraper")+ await _create_graph(graph_b, user_id, "Scraper")++ now = datetime.now(timezone.utc)+ in_window = now - timedelta(hours=1)++ try:+ await _create_exec(+ f"c1-{uuid4()}",+ user_id,+ graph_a,+ AgentExecutionStatus.COMPLETED,+ 30,+ 1.0,+ in_window,+ )+ await _create_exec(+ f"c2-{uuid4()}",+ user_id,+ graph_b,+ AgentExecutionStatus.COMPLETED,+ 70,+ 2.0,+ in_window,+ )++ stats = await get_user_execution_summary_data(+ user_id, now - timedelta(hours=2), now+ )++ assert stats.cost_breakdown == {+ "Scraper": pytest.approx((30 + 70) / 100),+ }+ assert stats.total_credits_used == pytest.approx(100 / 100)+ finally:+ await _cleanup(user_id, [graph_a, graph_b])++[email protected](loop_scope="session")+async def test_summary_excludes_out_of_window(server: SpinTestServer):+ user_id = f"sum-window-{uuid4()}"+ graph_a = f"graph-w-{uuid4()}"+ await _create_test_user(user_id)+ await _create_graph(graph_a, user_id, "InWindow")++ now = datetime.now(timezone.utc)+ in_window = now - timedelta(hours=1)+ out_of_window = now - timedelta(days=10)++ try:+ await _create_exec(+ f"in-{uuid4()}",+ user_id,+ graph_a,+ AgentExecutionStatus.COMPLETED,+ 100,+ 1.0,+ in_window,+ )+ await _create_exec(+ f"out-{uuid4()}",+ user_id,+ graph_a,+ AgentExecutionStatus.COMPLETED,+ 200,+ 2.0,+ out_of_window,+ )++ stats = await get_user_execution_summary_data(+ user_id, now - timedelta(hours=2), now+ )+ assert stats.total_executions == 1+ assert stats.total_credits_used == pytest.approx(100 / 100)+ finally:+ await _cleanup(user_id, [graph_a])+++async def test_resolve_agent_name_falls_back_on_exception(+ monkeypatch: pytest.MonkeyPatch,+):+ # Direct unit test: when get_graph_metadata raises, _resolve_agent_name+ # logs and returns the short-id fallback.+ async def boom(graph_id: str, version=None):+ raise RuntimeError("simulated DB blip")++ monkeypatch.setattr(generate_data, "get_graph_metadata", boom)+ name = await _resolve_agent_name("abcdef0123456789")+ assert name == "Agent abcdef01"+++async def test_resolve_agent_name_falls_back_when_metadata_missing(+ monkeypatch: pytest.MonkeyPatch,+):+ # When get_graph_metadata returns None (e.g. graph not found),+ # _resolve_agent_name must produce a short-id label.+ async def returns_none(graph_id: str, version=None):+ return None++ monkeypatch.setattr(generate_data, "get_graph_metadata", returns_none)+ name = await _resolve_agent_name("abcdef0123456789")+ assert name == "Agent abcdef01"diff --git a/autogpt_platform/backend/backend/data/includes.py b/autogpt_platform/backend/backend/data/includes.pyindex a8e79d55d2..cadee9550f 100644--- a/autogpt_platform/backend/backend/data/includes.py+++ b/autogpt_platform/backend/backend/data/includes.py@@ -21,9 +21,16 @@ EXECUTION_RESULT_ORDER: list[prisma.types.AgentNodeExecutionOrderByInput] = [{"addedTime": "desc"},]+# Defensive cap on per-execution Input/Output fanout. Set well above the+# realistic p99 (~tens of rows per node execution) so the cap only kicks in+# on pathological cases — `NodeExecutionResult.from_db` rebuilds input/output+# dicts from these rows, so silently truncating real data would corrupt the+# result. Matches `MAX_NODE_EXECUTIONS_FETCH` for symmetry.+MAX_NODE_INPUT_OUTPUT_FETCH = 1000+EXECUTION_RESULT_INCLUDE: prisma.types.AgentNodeExecutionInclude = {- "Input": {"order_by": {"time": "asc"}},- "Output": {"order_by": {"time": "asc"}},+ "Input": {"order_by": {"time": "asc"}, "take": MAX_NODE_INPUT_OUTPUT_FETCH},+ "Output": {"order_by": {"time": "asc"}, "take": MAX_NODE_INPUT_OUTPUT_FETCH},"Node": True,"GraphExecution": True,}