Skip to content

Commit f9e8534

Browse files
fix: check requests against both of the service's size limits before sending
The service refuses a request on two sizes: what is sent (4.3 MB of xz, the Function URL's limit) and what it decompresses to (256 MiB of JSON for a feature, 32 MiB for a briefing). The Action checked only the first, so a briefing of 32-43 MiB of JSON, which xz takes under 4.3 MB, went out whole, was refused, and went out again on every sync. _encode now enforces both in one step: it measures the JSON, which is cheap, then compresses once. The limits sit together and name the service's constants they follow. The briefing leaves findings out against the JSON limit first, largest first, counted per entry, and only recompresses when the compressed size is still over, aimed by the ratio it just measured, at most 3 compressions in all. It used to recompress once per dropped finding. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent f83141b commit f9e8534

4 files changed

Lines changed: 127 additions & 56 deletions

File tree

‎scripts/problem_history.py‎

Lines changed: 26 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -32,13 +32,13 @@
3232

3333
sys.path.insert(0, str(Path(__file__).resolve().parent))
3434
from remote_features import (
35-
MAX_BUNDLE_BYTES,
35+
MAX_BRIEFING_JSON_BYTES,
3636
Skip,
37+
TooLarge,
3738
_bearer,
38-
_check_size,
39+
_encode,
3940
_error_message,
4041
_github,
41-
_compress,
4242
_post,
4343
) # noqa: E402
4444

@@ -71,6 +71,8 @@
7171
# The review artifact's retention-days in action.yml; an unread merge older than this has nothing left to find.
7272
REVIEW_RETENTION_DAYS = 14
7373
MAX_BODY_CHARS = 2000
74+
# Compressions of one request at most: the first, and retries aimed by the ratio the one before measured.
75+
MAX_COMPRESSIONS = 3
7476
SERVICE_TIMEOUT = 300
7577
# A composite action's step cannot set timeout-minutes, so the script stops itself at the step's budget.
7678
STEP_LIMIT_SECONDS = 600
@@ -685,17 +687,27 @@ def build_request(env: dict, ledger: dict | None, facts: dict) -> dict:
685687

686688

687689
def pack(body: dict) -> tuple[bytes, list[str]]:
688-
"""The compressed request and the pull requests whose findings were left out of it: the largest
689-
envelopes go first while it is over the service's limit, and their merges stay unread for a later run."""
690-
findings, dropped = dict(body.get("findings") or {}), []
691-
while True:
692-
data = _compress({**body, "findings": findings})
693-
if len(data) <= MAX_BUNDLE_BYTES or not findings:
694-
_check_size(data, "request")
695-
return data, dropped
696-
largest = max(findings, key=lambda pr: len(json.dumps(findings[pr])))
697-
del findings[largest]
698-
dropped.append(largest)
690+
"""The compressed request and the pull requests whose findings were left out of it, largest first;
691+
their merges stay unread for a later run. Findings are left out until the JSON is under the service's
692+
limit, counted per entry rather than serialised again, and then it is compressed once. Only when that
693+
is over the limit on what is sent is it compressed again, down to a little under what the ratio just
694+
measured says fits, at most MAX_COMPRESSIONS times in all."""
695+
findings = body.get("findings") or {}
696+
# An entry's bytes in the request: `"pr": {...}` and its separator, exact while one entry is left.
697+
cost = {pr: len(json.dumps({pr: envelope})) for pr, envelope in findings.items()}
698+
kept, dropped = sorted(findings, key=cost.get), []
699+
size, budget = len(json.dumps({**body, "findings": findings})), MAX_BRIEFING_JSON_BYTES
700+
for compressions in range(1, MAX_COMPRESSIONS + 1):
701+
while kept and size > budget:
702+
dropped.append(kept.pop())
703+
size -= cost[dropped[-1]]
704+
request = {**body, "findings": {pr: findings[pr] for pr in findings if pr not in dropped}}
705+
try:
706+
return _encode(request, MAX_BRIEFING_JSON_BYTES, "request"), dropped
707+
except TooLarge as e:
708+
if not kept or e.fits is None or compressions == MAX_COMPRESSIONS:
709+
raise
710+
budget = e.fits * 9 // 10
699711

700712

701713
def _newest_pr(*lists) -> int | None:

‎scripts/remote_features.py‎

Lines changed: 39 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,10 @@
3333
3434
Size limits
3535
-----------
36-
- MAX_BUNDLE_BYTES (4.3 MB compressed): the most a request may carry. Past it the request is skipped,
37-
after first dropping source.json if architecture carried it.
36+
- The service sets two limits on every request, and _encode checks both before anything is sent: the
37+
JSON, measured first because that is cheap, against MAX_FEATURE_JSON_BYTES (MAX_BRIEFING_JSON_BYTES
38+
for the problem history), then the xz once against MAX_COMPRESSED_BYTES. Past either a feature request
39+
is skipped, after first dropping source.json if architecture carried it.
3840
- MAX_FILES: how many changed files have their contents sent; past it a feature reads diffs only.
3941
- MAX_FILE_BYTES: a larger file is sent neither in files.json nor in source.json.
4042
- MAX_SOURCE_BYTES: the most source.json holds; past it source is not sent.
@@ -73,9 +75,14 @@
7375

7476
from analysis_reader import Method, component_members, method_edges, method_spans
7577

76-
# A Function URL takes 6 MB, measured after base64, and a compressed body goes through base64 on the
77-
# way in: 4.5 MB of bundle arrives, and 5 MB is refused with a 413.
78-
MAX_BUNDLE_BYTES = 4_300_000
78+
# The service's limits on a request, which move with it. A Function URL takes 6 MB, measured after
79+
# base64, and a compressed body goes through base64 on the way in: 4.5 MB of it arrives, and 5 MB is
80+
# refused with a 413. Decompressed, the service refuses a feature request over 256 MiB and a problem
81+
# history request over 32 MiB: MAX_BUNDLE_BYTES and MAX_BRIEFING_BYTES in licensing-aws
82+
# closed_functions/handler.py.
83+
MAX_COMPRESSED_BYTES = 4_300_000
84+
MAX_FEATURE_JSON_BYTES = 256 * 1024 * 1024
85+
MAX_BRIEFING_JSON_BYTES = 32 * 1024 * 1024
7986
# Changed files whose contents are sent at both commits; past this a feature reads diffs only.
8087
MAX_FILES = 300
8188
# A file larger than this is sent neither as a changed file's contents nor as source.
@@ -106,6 +113,15 @@ class Skip(Exception):
106113
"""A step that did not happen, for a reason worth one line in the log."""
107114

108115

116+
class TooLarge(Skip):
117+
"""A request over one of the service's limits. Over the compressed one, `fits` is how much JSON the
118+
compression ratio just measured would bring under it."""
119+
120+
def __init__(self, message: str, fits: int | None = None):
121+
super().__init__(message)
122+
self.fits = fits
123+
124+
109125
# --- GitHub ---------------------------------------------------------------------------------------
110126

111127

@@ -578,21 +594,25 @@ def _post(url: str, body: bytes, headers: dict[str, str], timeout: int = 600) ->
578594
raise RuntimeError(reason) from error
579595

580596

581-
def _compress(body: dict) -> bytes:
582-
return lzma.compress(json.dumps(body).encode(), preset=9 | lzma.PRESET_EXTREME)
597+
def _encode(body: dict, max_json_bytes: int, what: str = "bundle") -> bytes:
598+
"""The request as sent, xz-compressed JSON, or TooLarge when it is over either of the service's
599+
limits. The JSON is measured before compressing it, which is the slow part, and it is compressed once."""
600+
text = json.dumps(body).encode()
601+
if len(text) > max_json_bytes:
602+
raise TooLarge(f"its {what} is {len(text) / 1e6:.0f} MB of JSON, over the service's limit")
603+
data = lzma.compress(text, preset=9 | lzma.PRESET_EXTREME)
604+
if len(data) > MAX_COMPRESSED_BYTES:
605+
message = f"its {what} is {len(data) / 1e6:.1f} MB compressed, over the service's limit"
606+
raise TooLarge(message, fits=len(text) * MAX_COMPRESSED_BYTES // len(data))
607+
return data
583608

584609

585610
def _pack(ctx: dict, files: dict[str, str], omitted: dict[str, str]) -> bytes:
586-
"""A request body: the named files, and why any optional one is missing."""
611+
"""A feature request: the named files, and why any optional one is missing."""
587612
body = {"version": 1, "repo": ctx["repo"], "pr": ctx["pr"], "files": files}
588613
if omitted:
589614
body["omitted"] = omitted
590-
return _compress(body)
591-
592-
593-
def _check_size(data: bytes, what: str = "bundle") -> None:
594-
if len(data) > MAX_BUNDLE_BYTES:
595-
raise Skip(f"its {what} is {len(data) / 1e6:.1f} MB, over the service's limit")
615+
return _encode(body, MAX_FEATURE_JSON_BYTES)
596616

597617

598618
def _no_architecture(ctx: dict, status: str, reason: str) -> dict:
@@ -616,7 +636,6 @@ def run_review_guide(service_url: str, ctx: dict, inputs: dict, headers: dict, a
616636
if "x-llm-provider" in headers and "x-llm-api-key" not in headers:
617637
raise Skip("the service cannot call this run's provider")
618638
data = _pack(ctx, inputs, {})
619-
_check_size(data)
620639
answer = _post(f"{service_url.rstrip('/')}/v1/review-guide", data, headers)
621640
guide = answer.get("guide")
622641
if not isinstance(guide, dict):
@@ -637,12 +656,14 @@ def run_architecture(service_url: str, ctx: dict, inputs: dict, headers: dict, e
637656
omitted["source.json"] = why or "the source was not collected"
638657
else:
639658
files["source.json"] = source
640-
data = _pack(ctx, files, omitted)
641-
if "source.json" in files and len(data) > MAX_BUNDLE_BYTES:
659+
try:
660+
data = _pack(ctx, files, omitted)
661+
except TooLarge:
662+
if "source.json" not in files:
663+
raise
642664
del files["source.json"]
643665
omitted["source.json"] = "the repository is too large to send"
644666
data = _pack(ctx, files, omitted)
645-
_check_size(data)
646667
answer = _post(f"{service_url.rstrip('/')}/v1/architecture", data, headers)
647668
envelope = answer.get("envelope")
648669
if not isinstance(envelope, dict) or envelope.get("status") not in ("ok", "partial", "skipped", "failed"):

‎tests/test_problem_history.py‎

Lines changed: 41 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -391,8 +391,11 @@ def test_every_body_is_cut_to_2000_characters_and_an_oversized_request_is_refuse
391391
gh.issue_pages[(("OPEN",), "DESC")] = [[issue_node(1, body="x" * 5000), issue_node(2)]]
392392
self.run_update(gh)
393393
self.assertEqual([i["body"] for i in self.body["issues"]], ["x" * 2000, "It breaks when saving."])
394-
with mock.patch.dict(ph._check_size.__globals__, {"MAX_BUNDLE_BYTES": 10}):
395-
with self.assertRaisesRegex(problem_history.Skip, "its request is"):
394+
with mock.patch.dict(ph._encode.__globals__, {"MAX_COMPRESSED_BYTES": 10}):
395+
with self.assertRaisesRegex(problem_history.Skip, "its request is .* compressed"):
396+
problem_history.pack({"issues": []})
397+
with mock.patch.object(ph, "MAX_BRIEFING_JSON_BYTES", 10):
398+
with self.assertRaisesRegex(problem_history.Skip, "its request is .* of JSON"):
396399
problem_history.pack({"issues": []})
397400

398401
def test_a_cut_counts_utf16_units_and_never_splits_a_surrogate_pair(self):
@@ -784,22 +787,49 @@ def test_an_unread_merge_older_than_the_review_artifacts_is_not_asked_again(self
784787
retention = re.search(r"retention-days: (\d+)", upload).group(1)
785788
self.assertEqual(int(retention), ph.REVIEW_RETENTION_DAYS)
786789

787-
def test_findings_that_would_overflow_the_request_are_left_out(self):
790+
def pack_counting(self, body, **limits):
791+
"""pack(body) under `limits` (MAX_BRIEFING_JSON_BYTES, MAX_COMPRESSED_BYTES), and how often it compressed."""
792+
compress = mock.Mock(wraps=lzma.compress)
793+
with (
794+
mock.patch.object(
795+
ph, "MAX_BRIEFING_JSON_BYTES", limits.get("MAX_BRIEFING_JSON_BYTES", ph.MAX_BRIEFING_JSON_BYTES)
796+
),
797+
mock.patch.dict(ph._encode.__globals__, limits),
798+
mock.patch.object(lzma, "compress", compress),
799+
):
800+
data, dropped = ph.pack(body)
801+
return json.loads(lzma.decompress(data))["findings"], dropped, compress.call_count
802+
803+
def test_findings_over_the_services_json_limit_are_left_out_before_compressing(self):
804+
# xz takes these to almost nothing, so only their JSON is over the service's limit.
805+
small, big = {**ENVELOPE, "data": {"findings": ["a"]}}, {**ENVELOPE, "data": {"findings": ["b" * 3000]}}
806+
body = {"issues": [], "findings": {"41": small, "42": big, "43": small}}
807+
limit = len(json.dumps({**body, "findings": {"41": small, "43": small}}))
808+
kept, dropped, compressions = self.pack_counting(body, MAX_BRIEFING_JSON_BYTES=limit)
809+
self.assertEqual((kept, dropped, compressions), ({"41": small, "43": small}, ["42"], 1))
810+
811+
def test_findings_over_the_compressed_limit_are_left_out_in_a_few_compressions(self):
812+
rnd = random.Random(1)
813+
findings = {
814+
str(pr): {**ENVELOPE, "data": {"findings": [rnd.randbytes(100 + 20 * pr).hex()]}} for pr in range(60)
815+
}
816+
kept, dropped, compressions = self.pack_counting(
817+
{"issues": [], "findings": findings}, MAX_COMPRESSED_BYTES=20_000
818+
)
819+
self.assertLessEqual(compressions, ph.MAX_COMPRESSIONS)
820+
self.assertTrue(dropped and kept)
821+
self.assertEqual(list(kept), [pr for pr in findings if pr not in dropped])
822+
self.assertLess(max(map(int, kept)), min(map(int, dropped)))
823+
788824
small, big = {**ENVELOPE, "data": {"findings": ["a"]}}, {
789825
**ENVELOPE,
790826
"data": {"findings": [random.Random(1).randbytes(3000).hex()]},
791827
}
792-
body = {"issues": [], "findings": {"41": small, "42": big}}
793-
with mock.patch.dict(ph._check_size.__globals__, {"MAX_BUNDLE_BYTES": 1000}):
794-
with mock.patch.object(ph, "MAX_BUNDLE_BYTES", 1000):
795-
data, dropped = ph.pack(body)
796-
self.assertEqual((json.loads(lzma.decompress(data))["findings"], dropped), ({"41": small}, ["42"]))
797-
798828
gh = FakeGitHub()
799829
gh.merged_pages = [[pr_node(41, "2026-11-06T00:00:00Z"), pr_node(42, "2026-11-05T00:00:00Z")]]
800830
gh.add_review(41, 41, small)
801831
gh.add_review(42, 42, big)
802-
with mock.patch.object(ph, "MAX_BUNDLE_BYTES", 1200):
832+
with mock.patch.dict(ph._encode.__globals__, {"MAX_COMPRESSED_BYTES": 1200}):
803833
notice = self.run_update(gh)
804834
self.assertEqual(list(self.body["findings"]), ["41"])
805835
self.assertIn("left out the findings of #42 to stay under the request limit", notice)
@@ -1008,7 +1038,7 @@ def test_the_step_uses_only_keys_a_composite_run_step_accepts(self):
10081038
self.assertIn("continue-on-error", keys)
10091039

10101040
def test_shares_the_remote_features_transport(self):
1011-
for shared in (ph._bearer, ph._post, ph._github, ph._compress, ph._check_size, ph._error_message):
1041+
for shared in (ph._bearer, ph._post, ph._github, ph._encode, ph._error_message):
10121042
self.assertEqual(shared.__module__, "remote_features")
10131043

10141044

‎tests/test_remote_features.py‎

Lines changed: 21 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ def test_analysed_commits_and_both_sides(self):
128128
self.assertEqual(set(bundle), INPUTS)
129129
self.assertEqual(json.loads(bundle["head.json"])["version"], 1)
130130

131-
def test_a_changed_file_over_the_size_limit_is_sent_at_neither_commit(self):
131+
def test_a_changed_file_over_the_size_limit_is_left_out_only_at_that_commit(self):
132132
with tempfile.TemporaryDirectory() as tmp:
133133
env = _workspace(Path(tmp))
134134
with (
@@ -521,19 +521,27 @@ def test_source_toggle_and_read_failure_only_omit_architecture_source(self):
521521
self.assertNotIn("source.json", body["files"])
522522
self.assertEqual("omitted" in body, request["path"] == "/v1/architecture")
523523

524-
def test_bundle_limit_omits_source_then_skips_if_required_inputs_too_large(self):
525-
with (
526-
mock.patch.object(remote_features, "MAX_BUNDLE_BYTES", 1000),
527-
mock.patch.object(remote_features, "collect_source", return_value=(os.urandom(2000).hex(), None)),
524+
def test_either_limit_omits_source_then_skips_if_required_inputs_too_large(self):
525+
with mock.patch.object(remote_features, "collect_source", return_value=(None, "off")):
526+
without_source = max(len(lzma.decompress(r["body"])) for r in self.run_service().requests)
527+
# Random source is over the compressed limit; repeated source compresses to almost nothing and is
528+
# over the JSON limit only.
529+
for limit, room, source in (
530+
("MAX_COMPRESSED_BYTES", 1000, os.urandom(2000).hex()),
531+
("MAX_FEATURE_JSON_BYTES", without_source + 1000, "x" * 100_000),
528532
):
529-
service = self.run_service()
530-
arch = next(r for r in service.requests if r["path"] == "/v1/architecture")
531-
body = json.loads(lzma.decompress(arch["body"]))
532-
self.assertNotIn("source.json", body["files"])
533-
self.assertIn("too large", body["omitted"]["source.json"])
534-
with mock.patch.object(remote_features, "MAX_BUNDLE_BYTES", 1):
535-
self.assertEqual(self.run_service().requests, [])
536-
self.assertEqual(_read(self.env, "closed/architecture.json")["status"], "skipped")
533+
with (
534+
mock.patch.object(remote_features, limit, room),
535+
mock.patch.object(remote_features, "collect_source", return_value=(source, None)),
536+
):
537+
service = self.run_service()
538+
arch = next(r for r in service.requests if r["path"] == "/v1/architecture")
539+
body = json.loads(lzma.decompress(arch["body"]))
540+
self.assertNotIn("source.json", body["files"])
541+
self.assertIn("too large", body["omitted"]["source.json"])
542+
with mock.patch.object(remote_features, limit, 1):
543+
self.assertEqual(self.run_service().requests, [])
544+
self.assertEqual(_read(self.env, "closed/architecture.json")["status"], "skipped")
537545

538546

539547
class SourceTests(unittest.TestCase):

0 commit comments

Comments
 (0)