Skip to content

Commit 96ff064

Browse files
perf: compress each feature request once, one at a time
The guide and architecture each compressed their own body in parallel, nearly the same bytes twice, and architecture compressed again after dropping source.json. At preset 9 | EXTREME each compressor takes about 700 MB. Both features can send the body without source, so it is compressed once and carries why source is missing, which only architecture reads. Architecture's body with source is compressed only when there is source; when it does not fit, the shared bytes stand in. A run compresses once without source and at most twice with it, and never two at a time. The JSON check needs no ratio guess: the 256 MiB limit is 62 times the 4.3 MB one, so it already turns away whatever could only fit at better than 62:1, and no tighter cut-off holds for every request. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 14d2db9 commit 96ff064

2 files changed

Lines changed: 60 additions & 51 deletions

File tree

‎scripts/remote_features.py‎

Lines changed: 34 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@
88
99
What a request sends
1010
--------------------
11-
One JSON object of named files, compressed with xz. Both requests send the same files:
11+
One JSON object of named files, compressed with xz. Both requests send the same files, and the same
12+
bytes unless architecture's carries source:
1213
1314
- head.json and base.json: one side document per commit (see side_document). It holds what the
1415
service reads from that commit's analysis.json and call graph (static_analysis.pkl), each fact once:
@@ -35,8 +36,12 @@
3536
-----------
3637
- The service sets two limits on every request, and _encode checks both before anything is sent: the
3738
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.
39+
for the problem history), then the xz once against MAX_COMPRESSED_BYTES. The JSON limit is 62 times
40+
the compressed one, so the cheap check already turns away whatever could only fit at better than 62:1.
41+
These bundles compress about 10:1, but no tighter cut-off holds for every request.
42+
- xz at this preset takes about 700 MB and seconds per 10 MB, so a run compresses one body at a time and
43+
each at most once: the body without source, which both features send, and architecture's with source
44+
when there is source. When that one does not fit, architecture sends the shared one.
4045
- MAX_FILES: how many changed files have their contents sent; past it a feature reads diffs only.
4146
- MAX_FILE_BYTES: a larger file is sent neither in files.json nor in source.json.
4247
- MAX_SOURCE_BYTES: the most source.json holds; past it source is not sent.
@@ -607,12 +612,24 @@ def _encode(body: dict, max_json_bytes: int, what: str = "bundle") -> bytes:
607612
return data
608613

609614

610-
def _pack(ctx: dict, files: dict[str, str], omitted: dict[str, str]) -> bytes:
611-
"""A feature request: the named files, and why any optional one is missing."""
612-
body = {"version": 1, "repo": ctx["repo"], "pr": ctx["pr"], "files": files}
613-
if omitted:
614-
body["omitted"] = omitted
615-
return _encode(body, MAX_FEATURE_JSON_BYTES)
615+
def _requests(ctx: dict, inputs: dict[str, str], env: dict) -> tuple[bytes, bytes]:
616+
"""The review guide's request and architecture's, compressed one after the other. Both can send the
617+
body without source, so it is compressed once; it says why source is missing, which only architecture
618+
reads. Architecture's body with source is compressed only when there is source, and the shared one
619+
stands in when it does not fit. TooLarge when not even the shared one fits."""
620+
try:
621+
source, why = collect_source(env)
622+
except Exception as error:
623+
source, why = None, f"reading it failed: {type(error).__name__}"
624+
body = {"version": 1, "repo": ctx["repo"], "pr": ctx["pr"], "files": inputs}
625+
missing = (why or "the source was not collected") if source is None else "the repository is too large to send"
626+
shared = _encode({**body, "omitted": {"source.json": missing}}, MAX_FEATURE_JSON_BYTES)
627+
if source is None:
628+
return shared, shared
629+
try:
630+
return shared, _encode({**body, "files": {**inputs, "source.json": source}}, MAX_FEATURE_JSON_BYTES)
631+
except TooLarge:
632+
return shared, shared
616633

617634

618635
def _no_architecture(ctx: dict, status: str, reason: str) -> dict:
@@ -631,11 +648,10 @@ def _no_architecture(ctx: dict, status: str, reason: str) -> dict:
631648
}
632649

633650

634-
def run_review_guide(service_url: str, ctx: dict, inputs: dict, headers: dict, artifact: Path) -> None:
651+
def run_review_guide(service_url: str, data: bytes, headers: dict, artifact: Path) -> None:
635652
try:
636653
if "x-llm-provider" in headers and "x-llm-api-key" not in headers:
637654
raise Skip("the service cannot call this run's provider")
638-
data = _pack(ctx, inputs, {})
639655
answer = _post(f"{service_url.rstrip('/')}/v1/review-guide", data, headers)
640656
guide = answer.get("guide")
641657
if not isinstance(guide, dict):
@@ -645,25 +661,8 @@ def run_review_guide(service_url: str, ctx: dict, inputs: dict, headers: dict, a
645661
print(f"::notice::review-guide {'skipped' if isinstance(error, Skip) else 'failed'}: {error}")
646662

647663

648-
def run_architecture(service_url: str, ctx: dict, inputs: dict, headers: dict, env: dict) -> dict:
664+
def run_architecture(service_url: str, ctx: dict, data: bytes, headers: dict) -> dict:
649665
try:
650-
try:
651-
source, why = collect_source(env)
652-
except Exception as error:
653-
source, why = None, f"reading it failed: {type(error).__name__}"
654-
files, omitted = dict(inputs), {}
655-
if source is None:
656-
omitted["source.json"] = why or "the source was not collected"
657-
else:
658-
files["source.json"] = source
659-
try:
660-
data = _pack(ctx, files, omitted)
661-
except TooLarge:
662-
if "source.json" not in files:
663-
raise
664-
del files["source.json"]
665-
omitted["source.json"] = "the repository is too large to send"
666-
data = _pack(ctx, files, omitted)
667666
answer = _post(f"{service_url.rstrip('/')}/v1/architecture", data, headers)
668667
envelope = answer.get("envelope")
669668
if not isinstance(envelope, dict) or envelope.get("status") not in ("ok", "partial", "skipped", "failed"):
@@ -684,15 +683,18 @@ def main(env: dict | None = None) -> int:
684683
return 0
685684
try:
686685
headers = {**_bearer(env), **model_headers(env)}
687-
inputs = collect(env)
686+
guide_request, architecture_request = _requests(ctx, collect(env), env)
687+
except TooLarge as error:
688+
print(f"::notice::review-guide skipped: {error}")
689+
architecture = _no_architecture(ctx, "skipped", str(error))
688690
except Exception as error:
689691
reason = f"collecting inputs or credentials failed: {type(error).__name__}: {error}"
690692
print(f"::notice::review-guide failed: {reason}")
691693
architecture = _no_architecture(ctx, "failed", reason)
692694
else:
693695
with ThreadPoolExecutor(max_workers=2) as pool:
694-
guide = pool.submit(run_review_guide, service_url, ctx, inputs, headers, artifact)
695-
result = pool.submit(run_architecture, service_url, ctx, inputs, headers, env)
696+
guide = pool.submit(run_review_guide, service_url, guide_request, headers, artifact)
697+
result = pool.submit(run_architecture, service_url, ctx, architecture_request, headers)
696698
architecture = result.result()
697699
guide.result()
698700
path = artifact / "closed" / "architecture.json"

‎tests/test_remote_features.py‎

Lines changed: 26 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99
import tempfile
1010
import threading
1111
import unittest
12-
from contextlib import nullcontext
1312
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
1413
from pathlib import Path
1514
from unittest import mock
@@ -480,19 +479,27 @@ def test_empty_url_disables_both(self):
480479
post.assert_not_called()
481480
self.assertFalse((Path(self.env["ARTIFACT_DIR"]) / "closed").exists())
482481

483-
def test_source_toggle_and_read_failure_only_omit_architecture_source(self):
482+
def run_counting(self, **patches):
483+
"""run_service with `patches` on remote_features, and how often it compressed."""
484+
compress = mock.Mock(wraps=lzma.compress)
485+
with mock.patch.object(lzma, "compress", compress), mock.patch.dict(remote_features.__dict__, patches):
486+
service = self.run_service()
487+
return {r["path"]: r["body"] for r in service.requests}, compress.call_count
488+
489+
def test_without_source_both_send_one_body_compressed_once(self):
484490
for failure in (False, True):
485491
self.env["CLOSED_FEATURES_SOURCE"] = "false"
486-
with (
487-
mock.patch.object(remote_features, "collect_source", side_effect=OSError())
488-
if failure
489-
else nullcontext()
490-
):
491-
service = self.run_service()
492-
for request in service.requests:
493-
body = json.loads(lzma.decompress(request["body"]))
494-
self.assertNotIn("source.json", body["files"])
495-
self.assertEqual("omitted" in body, request["path"] == "/v1/architecture")
492+
patches = {"collect_source": mock.Mock(side_effect=OSError())} if failure else {}
493+
bodies, compressions = self.run_counting(**patches)
494+
self.assertEqual((compressions, len(set(bodies.values()))), (1, 1))
495+
body = json.loads(lzma.decompress(bodies["/v1/architecture"]))
496+
self.assertNotIn("source.json", body["files"])
497+
self.assertIn("reading it failed" if failure else "turned off", body["omitted"]["source.json"])
498+
499+
def test_source_is_compressed_once_more_and_only_for_architecture(self):
500+
bodies, compressions = self.run_counting(collect_source=mock.Mock(return_value=("{}", None)))
501+
self.assertEqual(compressions, 2)
502+
self.assertNotEqual(bodies["/v1/architecture"], bodies["/v1/review-guide"])
496503

497504
def test_either_limit_omits_source_then_skips_if_required_inputs_too_large(self):
498505
with mock.patch.object(remote_features, "collect_source", return_value=(None, "off")):
@@ -503,13 +510,13 @@ def test_either_limit_omits_source_then_skips_if_required_inputs_too_large(self)
503510
("MAX_COMPRESSED_BYTES", 1000, os.urandom(2000).hex()),
504511
("MAX_FEATURE_JSON_BYTES", without_source + 1000, "x" * 100_000),
505512
):
506-
with (
507-
mock.patch.object(remote_features, limit, room),
508-
mock.patch.object(remote_features, "collect_source", return_value=(source, None)),
509-
):
510-
service = self.run_service()
511-
arch = next(r for r in service.requests if r["path"] == "/v1/architecture")
512-
body = json.loads(lzma.decompress(arch["body"]))
513+
bodies, compressions = self.run_counting(
514+
**{limit: room, "collect_source": mock.Mock(return_value=(source, None))}
515+
)
516+
# Architecture sends the guide's body, which already says why source is missing.
517+
self.assertEqual(bodies["/v1/architecture"], bodies["/v1/review-guide"])
518+
self.assertEqual(compressions, 2 if limit == "MAX_COMPRESSED_BYTES" else 1)
519+
body = json.loads(lzma.decompress(bodies["/v1/architecture"]))
513520
self.assertNotIn("source.json", body["files"])
514521
self.assertIn("too large", body["omitted"]["source.json"])
515522
with mock.patch.object(remote_features, limit, 1):

0 commit comments

Comments
 (0)