Skip to content

Commit e42af5e

Browse files
authored
fix(proxy): slim oversized response.create history (#560)
* fix(proxy): slim oversized response.create history * fix(proxy): drop omission notice when recent input fits * fix(proxy): slim core websocket response history * fix(proxy): bound response history omission search * fix(proxy): keep tool outputs paired while trimming history * test(proxy): type websocket slimmed payload assertions
1 parent 9581fe7 commit e42af5e

6 files changed

Lines changed: 482 additions & 13 deletions

File tree

‎app/core/clients/proxy.py‎

Lines changed: 116 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,9 @@
9595
"[codex-lb omitted historical tool output ({bytes} bytes) to fit upstream websocket budget]"
9696
)
9797
_RESPONSE_CREATE_IMAGE_OMISSION_NOTICE = "[codex-lb omitted historical inline image to fit upstream websocket budget]"
98+
_RESPONSE_CREATE_HISTORY_OMISSION_NOTICE = (
99+
"[codex-lb omitted {count} historical input items to fit upstream websocket budget]"
100+
)
98101
_UPSTREAM_TRACE_HEADER_ALLOWLIST = frozenset(
99102
{
100103
"accept",
@@ -1328,13 +1331,14 @@ def _prepare_websocket_response_create_payload(payload_dict: JsonObject) -> Json
13281331
(
13291332
"Slimmed response.create before upstream websocket connect request_id=%s "
13301333
"original_bytes=%s slimmed_bytes=%s historical_tool_outputs_slimmed=%s "
1331-
"historical_images_slimmed=%s"
1334+
"historical_images_slimmed=%s historical_items_omitted=%s"
13321335
),
13331336
get_request_id(),
13341337
payload_size,
13351338
len(slimmed_text.encode("utf-8")),
13361339
slim_summary["historical_tool_outputs_slimmed"],
13371340
slim_summary["historical_images_slimmed"],
1341+
slim_summary["historical_items_omitted"],
13381342
)
13391343
payload_text = slimmed_text
13401344
payload_size = len(payload_text.encode("utf-8"))
@@ -1375,7 +1379,6 @@ def _slim_response_create_payload_for_upstream(
13751379
*,
13761380
max_bytes: int,
13771381
) -> tuple[JsonObject, dict[str, int] | None]:
1378-
del max_bytes
13791382
input_value = payload.get("input")
13801383
if not isinstance(input_value, list) or not input_value:
13811384
return payload, None
@@ -1395,17 +1398,113 @@ def _slim_response_create_payload_for_upstream(
13951398
images_slimmed += item_images_slimmed
13961399
slimmed_historical.append(slimmed_item)
13971400

1398-
if tool_outputs_slimmed == 0 and images_slimmed == 0:
1399-
return payload, None
1400-
14011401
candidate_payload = dict(payload)
14021402
candidate_payload["input"] = slimmed_historical + recent
1403+
1404+
items_omitted = 0
1405+
if _serialized_json_size(candidate_payload) > max_bytes:
1406+
candidate_payload, items_omitted = _omit_historical_response_input_items_to_fit(
1407+
candidate_payload,
1408+
slimmed_historical=slimmed_historical,
1409+
recent=recent,
1410+
max_bytes=max_bytes,
1411+
)
1412+
1413+
if tool_outputs_slimmed == 0 and images_slimmed == 0 and items_omitted == 0:
1414+
return payload, None
1415+
14031416
return candidate_payload, {
14041417
"historical_tool_outputs_slimmed": tool_outputs_slimmed,
14051418
"historical_images_slimmed": images_slimmed,
1419+
"historical_items_omitted": items_omitted,
14061420
}
14071421

14081422

1423+
def _omit_historical_response_input_items_to_fit(
1424+
payload: JsonObject,
1425+
*,
1426+
slimmed_historical: list[JsonValue],
1427+
recent: list[JsonValue],
1428+
max_bytes: int,
1429+
) -> tuple[JsonObject, int]:
1430+
if not slimmed_historical:
1431+
return payload, 0
1432+
1433+
def candidate_with_omitted_count(prefix_omitted_count: int) -> tuple[JsonObject, int]:
1434+
remaining_historical, orphaned_outputs = _drop_orphaned_function_call_outputs(
1435+
slimmed_historical[prefix_omitted_count:],
1436+
recent,
1437+
)
1438+
omitted_count = prefix_omitted_count + orphaned_outputs
1439+
candidate_payload = dict(payload)
1440+
candidate_payload["input"] = [
1441+
_response_create_history_omission_notice_item(omitted_count),
1442+
*remaining_historical,
1443+
*recent,
1444+
]
1445+
return candidate_payload, omitted_count
1446+
1447+
low = 1
1448+
high = len(slimmed_historical)
1449+
best: tuple[JsonObject, int] | None = None
1450+
while low <= high:
1451+
prefix_omitted_count = (low + high) // 2
1452+
candidate_payload, omitted_count = candidate_with_omitted_count(prefix_omitted_count)
1453+
if _serialized_json_size(candidate_payload) <= max_bytes:
1454+
best = (candidate_payload, omitted_count)
1455+
high = prefix_omitted_count - 1
1456+
else:
1457+
low = prefix_omitted_count + 1
1458+
1459+
if best is not None:
1460+
return best
1461+
1462+
recent_only_payload = dict(payload)
1463+
recent_only_payload["input"] = list(recent)
1464+
if _serialized_json_size(recent_only_payload) <= max_bytes:
1465+
return recent_only_payload, len(slimmed_historical)
1466+
1467+
return candidate_with_omitted_count(len(slimmed_historical))
1468+
1469+
1470+
def _drop_orphaned_function_call_outputs(
1471+
historical: list[JsonValue],
1472+
recent: list[JsonValue],
1473+
) -> tuple[list[JsonValue], int]:
1474+
kept_call_ids = {
1475+
item.get("call_id")
1476+
for item in [*historical, *recent]
1477+
if is_json_mapping(item) and item.get("type") == "function_call" and isinstance(item.get("call_id"), str)
1478+
}
1479+
if not kept_call_ids:
1480+
filtered = [
1481+
item
1482+
for item in historical
1483+
if not (
1484+
is_json_mapping(item)
1485+
and item.get("type") == "function_call_output"
1486+
and isinstance(item.get("call_id"), str)
1487+
)
1488+
]
1489+
return filtered, len(historical) - len(filtered)
1490+
1491+
filtered = [
1492+
item
1493+
for item in historical
1494+
if not (
1495+
is_json_mapping(item)
1496+
and item.get("type") == "function_call_output"
1497+
and isinstance(item.get("call_id"), str)
1498+
and item.get("call_id") not in kept_call_ids
1499+
)
1500+
]
1501+
return filtered, len(historical) - len(filtered)
1502+
1503+
1504+
def _serialized_json_size(payload: JsonObject) -> int:
1505+
return len(json.dumps(payload, ensure_ascii=True, separators=(",", ":")).encode("utf-8"))
1506+
1507+
14091508
def _response_create_recent_suffix_start(input_items: list[JsonValue]) -> int:
14101509
last_user_index: int | None = None
14111510
for index, item in enumerate(input_items):
@@ -1491,6 +1590,18 @@ def _response_create_inline_image_notice_item() -> JsonObject:
14911590
return {"role": "user", "content": [_response_create_inline_image_notice_part()]}
14921591

14931592

1593+
def _response_create_history_omission_notice_item(count: int) -> JsonObject:
1594+
return {
1595+
"role": "assistant",
1596+
"content": [
1597+
{
1598+
"type": "output_text",
1599+
"text": _RESPONSE_CREATE_HISTORY_OMISSION_NOTICE.format(count=count),
1600+
}
1601+
],
1602+
}
1603+
1604+
14941605
def _is_inline_image_reference(value: JsonValue) -> bool:
14951606
return isinstance(value, str) and value.startswith("data:image/")
14961607

‎app/modules/proxy/service.py‎

Lines changed: 98 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@
1414
from datetime import datetime, timezone
1515
from hashlib import sha256
1616
from ipaddress import ip_address
17-
from pathlib import Path
1817
from typing import Any, AsyncIterator, Literal, Mapping, NoReturn, TypeVar, cast, overload
1918
from urllib.parse import urlparse
2019
from uuid import uuid4
@@ -60,7 +59,7 @@
6059
connect_responses_websocket,
6160
filter_inbound_websocket_headers,
6261
)
63-
from app.core.config.settings import Settings, get_settings
62+
from app.core.config.settings import DEFAULT_HOME_DIR, Settings, get_settings
6463
from app.core.config.settings_cache import get_settings_cache
6564
from app.core.crypto import TokenEncryptor
6665
from app.core.errors import (
@@ -171,7 +170,7 @@
171170

172171
_UPSTREAM_RESPONSE_CREATE_MAX_BYTES = get_settings().upstream_response_create_max_bytes
173172
_UPSTREAM_RESPONSE_CREATE_WARN_BYTES = int(_UPSTREAM_RESPONSE_CREATE_MAX_BYTES * 0.8)
174-
_OVERSIZED_RESPONSE_CREATE_DUMP_DIR = Path("/var/lib/codex-lb/debug/response-create-dumps")
173+
_OVERSIZED_RESPONSE_CREATE_DUMP_DIR = DEFAULT_HOME_DIR / "debug" / "response-create-dumps"
175174
_OVERSIZED_RESPONSE_CREATE_LARGEST_ITEMS = 10
176175
_RESPONSE_CREATE_HISTORY_OMISSION_NOTICE = (
177176
"[codex-lb omitted {count} historical input items to fit upstream websocket budget]"
@@ -9115,13 +9114,108 @@ def _slim_response_create_payload_for_upstream(
91159114
candidate_payload = dict(payload)
91169115
candidate_payload["input"] = slimmed_historical + recent
91179116

9118-
if tool_outputs_slimmed == 0 and images_slimmed == 0:
9117+
items_omitted = 0
9118+
if _serialized_json_size(candidate_payload) > max_bytes:
9119+
candidate_payload, items_omitted = _omit_historical_response_input_items_to_fit(
9120+
candidate_payload,
9121+
slimmed_historical=slimmed_historical,
9122+
recent=recent,
9123+
max_bytes=max_bytes,
9124+
)
9125+
9126+
if tool_outputs_slimmed == 0 and images_slimmed == 0 and items_omitted == 0:
91199127
return payload, None
91209128

91219129
return candidate_payload, {
91229130
"historical_tool_outputs_slimmed": tool_outputs_slimmed,
91239131
"historical_images_slimmed": images_slimmed,
9132+
"historical_items_omitted": items_omitted,
9133+
}
9134+
9135+
9136+
def _omit_historical_response_input_items_to_fit(
9137+
payload: dict[str, JsonValue],
9138+
*,
9139+
slimmed_historical: list[JsonValue],
9140+
recent: list[JsonValue],
9141+
max_bytes: int,
9142+
) -> tuple[dict[str, JsonValue], int]:
9143+
if not slimmed_historical:
9144+
return payload, 0
9145+
9146+
def candidate_with_omitted_count(prefix_omitted_count: int) -> tuple[dict[str, JsonValue], int]:
9147+
remaining_historical, orphaned_outputs = _drop_orphaned_function_call_outputs(
9148+
slimmed_historical[prefix_omitted_count:],
9149+
recent,
9150+
)
9151+
omitted_count = prefix_omitted_count + orphaned_outputs
9152+
candidate_payload = dict(payload)
9153+
candidate_payload["input"] = [
9154+
_response_create_history_omission_notice_item(omitted_count),
9155+
*remaining_historical,
9156+
*recent,
9157+
]
9158+
return candidate_payload, omitted_count
9159+
9160+
low = 1
9161+
high = len(slimmed_historical)
9162+
best: tuple[dict[str, JsonValue], int] | None = None
9163+
while low <= high:
9164+
prefix_omitted_count = (low + high) // 2
9165+
candidate_payload, omitted_count = candidate_with_omitted_count(prefix_omitted_count)
9166+
if _serialized_json_size(candidate_payload) <= max_bytes:
9167+
best = (candidate_payload, omitted_count)
9168+
high = prefix_omitted_count - 1
9169+
else:
9170+
low = prefix_omitted_count + 1
9171+
9172+
if best is not None:
9173+
return best
9174+
9175+
recent_only_payload = dict(payload)
9176+
recent_only_payload["input"] = list(recent)
9177+
if _serialized_json_size(recent_only_payload) <= max_bytes:
9178+
return recent_only_payload, len(slimmed_historical)
9179+
9180+
return candidate_with_omitted_count(len(slimmed_historical))
9181+
9182+
9183+
def _drop_orphaned_function_call_outputs(
9184+
historical: list[JsonValue],
9185+
recent: list[JsonValue],
9186+
) -> tuple[list[JsonValue], int]:
9187+
kept_call_ids = {
9188+
item.get("call_id")
9189+
for item in [*historical, *recent]
9190+
if is_json_mapping(item) and item.get("type") == "function_call" and isinstance(item.get("call_id"), str)
91249191
}
9192+
if not kept_call_ids:
9193+
filtered = [
9194+
item
9195+
for item in historical
9196+
if not (
9197+
is_json_mapping(item)
9198+
and item.get("type") == "function_call_output"
9199+
and isinstance(item.get("call_id"), str)
9200+
)
9201+
]
9202+
return filtered, len(historical) - len(filtered)
9203+
9204+
filtered = [
9205+
item
9206+
for item in historical
9207+
if not (
9208+
is_json_mapping(item)
9209+
and item.get("type") == "function_call_output"
9210+
and isinstance(item.get("call_id"), str)
9211+
and item.get("call_id") not in kept_call_ids
9212+
)
9213+
]
9214+
return filtered, len(historical) - len(filtered)
9215+
9216+
9217+
def _serialized_json_size(payload: dict[str, JsonValue]) -> int:
9218+
return len(json.dumps(payload, ensure_ascii=True, separators=(",", ":")).encode("utf-8"))
91259219

91269220

91279221
def _response_create_recent_suffix_start(input_items: list[JsonValue]) -> int:
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Proposal: slim-oversized-response-create-history
2+
3+
## Why
4+
5+
Large Codex `response.create` requests can still exceed the upstream websocket
6+
budget after the existing inline-image and tool-output slimming pass. In that
7+
case the proxy returns `413 payload_too_large` even when the oversized content is
8+
old conversation history and the current user turn could be preserved.
9+
10+
The oversized debug dump path also used a Docker-only data directory. Local
11+
`uv tool` or LaunchAgent installs may not be allowed to create `/var/lib/codex-lb`,
12+
so the diagnostic dump can fail exactly when it is needed.
13+
14+
## What Changes
15+
16+
- After existing historical image/tool-output slimming, omit the oldest
17+
historical input items until the serialized `response.create` fits the
18+
upstream websocket budget.
19+
- Preserve the recent user-turn suffix and insert a single assistant notice that
20+
says how many historical input items were omitted.
21+
- Use the configured default app home directory for oversized response-create
22+
dumps, preserving `/var/lib/codex-lb` in containers while using
23+
`~/.codex-lb` for local installs.
24+
25+
## Impact
26+
27+
- Fewer oversized Codex websocket requests fail with `413` when old history can
28+
be safely summarized away.
29+
- Debug dumps remain writable in both Docker and local user installs.
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
## MODIFIED Requirements
2+
3+
### Requirement: Upstream Responses request size budget
4+
The service SHALL enforce the configured upstream `response.create` websocket
5+
request size budget before sending a request upstream. When a request exceeds
6+
the budget, the service SHALL first slim historical inline images and historical
7+
tool outputs. If the request is still too large and contains historical input
8+
items before the recent user-turn suffix, the service SHALL omit the oldest
9+
historical input items until the serialized request fits the budget or no
10+
historical items remain. The service SHALL preserve the recent user-turn suffix
11+
and SHALL include an assistant notice describing the number of omitted
12+
historical input items.
13+
14+
#### Scenario: oversized historical text can be omitted
15+
- **WHEN** a Codex `response.create` request remains over the websocket request
16+
size budget after image and tool-output slimming
17+
- **AND** the request has historical input items before the recent user-turn
18+
suffix
19+
- **THEN** the proxy omits the oldest historical input items until the request
20+
fits the budget
21+
- **AND** the recent user-turn suffix remains in the upstream request
22+
- **AND** the upstream request includes an assistant notice with the omitted
23+
item count
24+
25+
### Requirement: Oversized Responses request diagnostics
26+
The service SHALL write oversized `response.create` debug dumps under the
27+
configured app home directory by default. Container installs SHALL keep using
28+
the container data directory, while local user installs SHALL use the user app
29+
data directory.
30+
31+
#### Scenario: local install dump directory is writable by the user
32+
- **WHEN** codex-lb runs outside a container
33+
- **THEN** oversized `response.create` debug dumps default under the user's
34+
app data directory instead of `/var/lib/codex-lb`
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
## 1. Implementation
2+
3+
- [x] 1.1 Add a second slimming pass that omits oldest historical input items
4+
after image/tool-output slimming if the request is still over budget.
5+
- [x] 1.2 Preserve the recent user-turn suffix and insert an omission notice.
6+
- [x] 1.3 Move oversized response-create dumps under the default app home
7+
directory.
8+
9+
## 2. Verification
10+
11+
- [x] 2.1 Add unit coverage for historical item omission.
12+
- [x] 2.2 Add unit coverage for the portable dump directory default.
13+
- [x] 2.3 Run targeted pytest, ruff, ty, and OpenSpec validation.

0 commit comments

Comments
 (0)