Skip to content

fix(hub): stream large artifacts to R2 so the whole-package zip publishes; cut email 0.2.2 - #1849

Merged
itomek-amd merged 5 commits into
mainfrom
tmi/hub-stream-publish
Jun 24, 2026
Merged

itomek-amd merged 5 commits into
mainfrom
tmi/hub-stream-publish

Conversation

@itomek

@itomek itomek commented Jun 24, 2026

Copy link
Copy Markdown
Collaborator

Closes #1848

The email-agent release currently dies at the "publish the whole-package zip" step with a Cloudflare 502, which also skips the npm publish and website redeploy that run after it — so every release is stuck half-done (binaries on the Hub, no npm package, no catalog update). The cause isn't auth: the Hub worker buffers the entire upload in memory (request.formData() → arrayBuffer()), and the new 177 MB whole-package zip needs ~350 MB+, far over Cloudflare's hard 128 MB per-Worker memory limit → the isolate is OOM-killed → 502. The ~40 MB per-platform binaries stay under the ceiling, which is why they publish fine with the same token.

This streams large artifacts straight to R2 instead of buffering them: the whole-package zip is sent as a raw application/octet-stream body with metadata in X-Gaia-* headers, and stored via env.BUCKET.put(key, request.body, { sha256 }) — the body is never materialized, so worker memory is independent of artifact size, and R2 verifies the client-supplied SHA-256 as it streams (mismatch → 400, fail-loud). The proven multipart path for the smaller per-platform binaries (which carry README/CHANGELOG) is left byte-for-byte unchanged; routing is purely by Content-Type.

Test plan

  • cd workers/agent-hub && npm run typecheck && npm test — 76 pass (12 new streaming tests, incl. integrity-mismatch rejection)
  • python -m pytest tests/unit/test_publish_to_r2_stream.py — 11 pass (asserts the zip goes octet-stream with X-Gaia-* headers, binaries stay multipart)
  • Definitive prod gate: re-run the email-agent release workflow (CI holds the publish token) → confirm the zip step, npm publish, and website redeploy all complete

Evidence

Worker suite (independently re-run on this branch):

$ npm run typecheck   # tsc --noEmit → exit 0, no output
$ npm test
 ✓ test/manifest.test.ts (20 tests)
 ✓ test/routes.test.ts (7 tests)
 ✓ test/publish.test.ts (49 tests)
 Test Files  3 passed (3)
      Tests  76 passed (76)

The decisive worker tests: a wrong X-Gaia-Sha256 makes R2 reject the streamed bytes → worker returns 400 integrity_check_failed (proves server-side integrity with no worker-side checksum over the body); an oversized Content-Length → 413 without buffering.

Python client (independently re-run):

$ python -m pytest tests/unit/test_publish_to_r2_stream.py -q
11 passed

Honest scope note: local wrangler dev runs workerd without the production 128 MB isolate cap, so it can't reproduce the OOM — the unit tests prove the streaming protocol + integrity, the diff proves the no-buffering behavior (request.body passed straight to R2), and the CI release re-run is the definitive proof the 502 is gone.

Follow-ups (out of scope here)
  • _download_sha256 (the 409 idempotency re-check) still buffers the response; switch to chunked iter_content (rare path).
  • Presigned direct-to-R2 upload as the durable escape hatch for any future artifact exceeding Cloudflare's edge body limit.
  • Migrate the per-platform binary path to streaming too (~40 MB × buffered copies sits close to the 128 MB ceiling).

Tomasz Iniewicz added 4 commits June 24, 2026 15:25
TDD red state: 11 new tests for the streaming POST /publish path
(application/octet-stream + X-Gaia-* headers). All 11 fail with 415
because the handler has not been updated yet. Existing 65 multipart
tests remain green.
…artifacts

The existing multipart path buffers the entire artifact in memory, hitting
Cloudflare's ~128 MB per-Worker limit for the 177 MB whole-package zip.

New second path: when Content-Type is application/octet-stream, the raw body
is passed directly to R2.put() without buffering. Metadata travels in
X-Gaia-* headers (Manifest, Filename, Sha256, Package-Files). R2-side sha256
integrity enforces upload correctness. The multipart path (per-platform
binaries, README, CHANGELOG) is unchanged.

Shared tail extracted (finishPublish) so both paths write ancillary objects
and rebuild the index identically. validatePackageFilesJson() refactored into
a shared helper used by both paths.
publish_to_r2.py: add publish_streaming() for platform_key=="package"
(the whole-package zip). Sends application/octet-stream with X-Gaia-*
headers and data=<file-handle> — requests streams chunk-by-chunk, never
loading the full ~177 MB into memory. Per-platform binaries keep using
the existing multipart publish_one() unchanged. _sha256_file() now hashes
in 1 MiB chunks instead of read_bytes().

tests/unit/test_publish_to_r2_stream.py: 11 new tests asserting call
validity (octet-stream + X-Gaia-* for zip; multipart for binary), 201/409
idempotency, integrity mismatch → SystemExit, and main() routing.

workers/agent-hub/README.md: document the new streaming protocol alongside
the existing multipart contract (required/optional headers, curl examples,
shared 201 body shape).
R2.put() can return null on success in some binding implementations. Guard
against it with an explicit null check + 500, rather than silently falling
back to the client-supplied Content-Length (unverified, could corrupt the
catalog's size_bytes field).
@github-actions github-actions Bot added the tests Test changes label Jun 24, 2026
@itomek
itomek marked this pull request as ready for review June 24, 2026 19:40
@itomek
itomek requested a review from kovtcharov-amd as a code owner June 24, 2026 19:40
@itomek itomek self-assigned this Jun 24, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Verdict: Approve with suggestions — no blocking issues.

This fixes the release-killing 502 by streaming the ~177 MB whole-package zip straight to R2 instead of buffering it in the Worker (which blew past Cloudflare's 128 MB isolate cap). The proven multipart path for the smaller per-platform binaries is left untouched, routing is purely by Content-Type, and integrity is enforced server-side by R2's own SHA-256 check — a clean, fail-loud design with strong test coverage on both the client and Worker sides.

One thing worth tightening before/after merge: the PR introduces a shared "finish publish" helper but only wires the new streaming path through it — the existing multipart path still carries its own byte-for-byte copy of that same tail logic, and the helper's docstring claims both paths use it. That's a drift risk (two copies of the per-version-record + index-rebuild logic must now stay in sync) plus an inaccurate comment. Non-blocking, but cheap to fix now.

🔍 Technical details

🟡 Important

finishPublish is documented as shared but the multipart path doesn't use it (workers/agent-hub/src/publish.ts:858-913 vs 494-546)
The new finishPublish docstring says "Called by both the multipart and streaming paths once the artifact is stored", but handlePublish's multipart branch still inlines the identical tail — per-version raw-manifest write, the packageFilesKey head-gated write, makeVersionEntry → upsertVersion → writeAgentManifest → rebuildIndex → 201. So there are now two copies of the same logic, which is exactly the duplication the helper was meant to remove (and CLAUDE.md's reuse guidance pushes against). Best fix: route multipart through finishPublish too — but note the multipart branch also writes optional README/CHANGELOG inside its !versionExists block, which finishPublish doesn't handle, so they aren't drop-in identical yet. At minimum, correct the docstring so it doesn't claim a caller that doesn't exist:

 * Shared publish tail: write ancillary objects → update catalog → rebuild index → 201.
 *
 * Currently called only by the streaming path; the multipart path inlines an
 * equivalent tail (which also writes the optional README/CHANGELOG parts).
 * Keep the two in sync until the multipart path is migrated here.

🟢 Minor

  • README documents X-Gaia-Content-Type but the client never sends it (workers/agent-hub/README.md:683, publish_to_r2.py:71-78). The zip is therefore stored as application/octet-stream, not application/zip. Harmless for download, but the documented optional header is currently dead on the publish side — either set it in publish_streaming or note it's server/manual-only.

  • _b64 imports base64 inside the function body (publish_to_r2.py:33-37). hashlib/requests are already top-level imports; move import base64 up to match.

def _b64(data: bytes) -> str:
    """Base64-encode bytes to ASCII string."""
    return base64.b64encode(data).decode("ascii")

(add import base64 to the top-level imports)

  • Streaming size guard trusts Content-Length only (publish.ts:984-997). The actual streamed body isn't bounded against maxBytes on the Worker side — a client could under-declare Content-Length and stream more. Low risk since /publish is authenticated and R2 has its own object cap, but worth a one-line comment that the guard is advisory and R2 is the real ceiling.

Strengths

  • Genuinely thorough tests: Worker side covers the integrity-mismatch rejection (proving server-side SHA verification with no Worker-side checksum), 413 on oversized Content-Length, each missing required header, per-filename 409 idempotency, and a regression guard that the multipart path is unchanged; the Python side asserts the outgoing call shape (octet-stream + X-Gaia-* via data=, binaries stay files=) rather than just "we called it" — exactly the call-validity bar CLAUDE.md asks for.
  • Fail-loud throughout: R2 SHA mismatch → 400 integrity_check_failed, client re-verifies the server-returned SHA on 201 and SystemExits on drift, 409 re-checks remote bytes for true idempotency.
  • Honest scope note in the PR that wrangler dev can't reproduce the prod 128 MB cap, with the CI release re-run flagged as the definitive gate — and the buffered _download_sha256/multipart paths explicitly deferred rather than silently left.

- drop unused unittest.mock.call import (flake8 F401 — the CI Code Quality blocker)
- move base64 import to module top-level in publish_to_r2.py
- send X-Gaia-Content-Type: application/zip so the stored package object has
  the right content-type and the documented header is actually exercised
- correct finishPublish docstring (the multipart path still inlines its own
  tail) and note the Content-Length size guard is advisory — R2 is the real
  ceiling and the body is never buffered
@itomek

itomek commented Jun 24, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks for the review — addressed the suggestions in b0c08c2, and CI Code Quality is green again.

  • finishPublish docstring: corrected to state only the streaming path uses it today; the multipart path still inlines an equivalent tail. Left the full multipart→finishPublish migration as a noted follow-up rather than refactoring the proven release path in this PR.
  • X-Gaia-Content-Type: the client now sends application/zip, so the stored package object gets the right content-type and the documented header is actually exercised.
  • base64 import: moved to the module top-level in publish_to_r2.py.
  • Size guard: added a comment that the Content-Length check is advisory — R2's object-size limit is the real ceiling and the body is never buffered regardless.

The Code Quality failure itself was a flake8 F401 (an unused unittest.mock.call import in the new test) — also removed.

@itomek-amd
itomek-amd added this pull request to the merge queue Jun 24, 2026
Merged via the queue into main with commit a268d1b Jun 24, 2026
33 of 34 checks passed
@itomek-amd
itomek-amd deleted the tmi/hub-stream-publish branch June 24, 2026 20:23
@itomek itomek changed the title fix(hub): stream large artifacts to R2 so the whole-package zip publish stops OOMing (502) fix(hub): stream large artifacts to R2 so the whole-package zip publishes; cut email 0.2.2 Jun 24, 2026
pull Bot pushed a commit to bhardwajRahul/gaia that referenced this pull request Jun 25, 2026
…ature set) (amd#1851)

Bumps the email agent to **0.2.2** so the release can be re-cut now that
the Hub publish 502 is fixed on main
([amd#1849](amd#1849), the streaming fix).
0.2.1 published its per-platform binaries to the Hub but its npm publish
never completed (the worker OOM'd on the ~177 MB whole-package zip), so
0.2.2 is the first *complete* publish of the same feature set. No agent
wire-contract change — `SCHEMA_VERSION` stays 2.0.

Keeps all four version sources in sync (the release workflow's
version-resolve step asserts this): `gaia-agent.yaml`, `pyproject.toml`,
`version.py`, npm `package.json` → 0.2.2, plus the CHANGELOG entry.

> ⚠️ **Prerequisite before tagging `agent-pkg-email-v0.2.2`:** the live
Agent Hub **worker must be redeployed** with the streaming fix. Merging
amd#1849 updated the worker *source* on main but no CI deploys the worker —
it's a manual `wrangler deploy` (Cloudflare account that owns
`agent-hub`). Tagging before that redeploy would 502 again.

## Test plan
- [x] All four version sources read 0.2.2 (sync gate)
- [x] `cd hub/agents/npm/agent-email && npm run build && npm test` — 46
pass; `npm pack` ships README/CHANGELOG/SKILL/SPEC

---------

Co-authored-by: Tomasz Iniewicz <[email protected]>
pull Bot pushed a commit to bhardwajRahul/gaia that referenced this pull request Jun 25, 2026
…loy) (amd#1854)

Re-cuts the email agent at **0.2.3** now that the Agent Hub worker has
been redeployed with the streaming fix
([amd#1849](amd#1849)). 0.2.2 published its
per-platform binaries but its whole-package zip + npm publish never
completed because the live worker hadn't yet picked up the fix — so
0.2.3 is the first fully-published release of this feature set. No agent
wire-contract change (`SCHEMA_VERSION` stays 2.0).

All seven version targets synced via `stamp_version.py` (the sync gate):
`version.py` (source), `gaia-agent.yaml`, `pyproject.toml`, npm
`package.json`, `binaries.lock.json` (agentVersion + baseUrl), and the
`architecture.html` badge → 0.2.3, plus the CHANGELOG entry.

## Test plan
- [x] `stamp_version.py --check` passes on all targets
- [x] `cd hub/agents/npm/agent-email && npm run build && npm test`
- [ ] Tag `agent-pkg-email-v0.2.3` → release run publishes binaries +
zip + npm @0.2.3 (the real test that the worker redeploy resolved the
502)

Co-authored-by: Tomasz Iniewicz <[email protected]>
pull Bot pushed a commit to bhardwajRahul/gaia that referenced this pull request Jun 25, 2026
…ail 0.2.4 (amd#1855)

Gets the email-agent release unblocked. The ~177 MB all-platforms
whole-package zip (amd#1843) exceeds **Cloudflare's edge upload limit** —
`POST /publish` returns `413 Payload Too Large` before the request even
reaches the worker, which blocked the release on 0.2.1–0.2.3 (each
published its binaries but never the zip/npm). That edge limit is
plan-based and not fixable in worker code, so the worker-side streaming
attempt ([amd#1849](amd#1849)) couldn't have
solved it.

This reverts that streaming change and disables the whole-package zip
publish (`if: false`, with a note to revive it via presigned-to-R2 or
per-platform zips). **0.2.4 ships the per-platform binaries + npm client
+ website with no combined zip** — the binaries stay individually
downloadable from the Hub. No agent wire-contract change
(`SCHEMA_VERSION` stays 2.0).

<details>
<summary>What's in here</summary>

- **Revert amd#1849** — restores the worker + `publish_to_r2.py` to the
multipart-only path; worker suite back to 64 tests passing.
- **Disable the zip steps** — "Assemble + publish the whole-package zip"
and its edge-verify step are `if: false`; the binary fetch-verify, npm
publish, and website redeploy are untouched.
- **0.2.4 bump** — all six version targets synced via `stamp_version.py`
+ CHANGELOG.
</details>

## Test plan
- [x] `stamp_version.py --check` passes (all targets 0.2.4)
- [x] worker `npm run typecheck && npm test` — 64 pass (revert clean)
- [x] `cd hub/agents/npm/agent-email && npm run build && npm test` — 46
pass
- [ ] Tag `agent-pkg-email-v0.2.4` → release publishes binaries + npm
@0.2.4 + website (no zip step)

---------

Co-authored-by: Tomasz Iniewicz <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(hub): Agent Hub worker OOMs (502) publishing the 177 MB whole-package zip

2 participants