Skip to content

Commit ed3f05a

Browse files
jrusso1020claude
andauthored
fix(aws-lambda): pin the shell ZIP route, gate ZIP headroom, match arm64 fonts to x86 (#8170)
- build-zip --source=chrome-headless-shell stages only the repo's pinned build (managedChromeVersion) and only when its folder matches the pinned digest (isPinnedHeadlessShell), instead of the newest folder in the cache. The folder cannot fit a ZIP function, so lambda deploy refuses --chrome-source chrome-headless-shell up front on either arch, and the docs say the arm64 video image is where the shell runs. - build-zip prints the headroom under the unzipped gate, and a new "Lambda handler ZIP" workflow builds the ZIP on PRs that touch the code it bundles, so growth fails before merge rather than in the release job. - The arm64 image keeps @sparticuz/chromium's fonts and fonts.conf from the handler ZIP (FONTCONFIG_PATH=/var/task/fonts) instead of liberation-fonts, so text falls back to the same fonts as on x86. The image workflow renders a mixed-script page on both arches and fails when any line resolves to different platform fonts. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent b525686 commit ed3f05a

20 files changed

Lines changed: 318 additions & 110 deletions

‎.github/workflows/lambda-arm64-image.yml‎

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -129,8 +129,14 @@ jobs:
129129
reply=$(curl -sS --retry 30 --retry-all-errors --retry-delay 1 \
130130
-d '{}' http://localhost:9001/2015-03-31/functions/function/invocations)
131131
docker logs hf-smoke
132-
echo "$reply"
132+
jq 'del(.textPng)' <<<"$reply"
133133
jq -e '.arch == "arm64" and .screenshotBytes > 0 and (.ffmpeg | startswith("ffmpeg version 7.0.2"))' <<<"$reply"
134+
mkdir text && jq -S .fonts <<<"$reply" >text/fonts.json && jq -r .textPng <<<"$reply" | base64 -d >text/text.png
135+
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
136+
with:
137+
name: text-arm64
138+
path: text/
139+
retention-days: 7
134140
- name: The Lambda runtime loads the handler
135141
run: |
136142
docker run -d --name hf-video -p 9000:8080 hf-video:ci
@@ -139,3 +145,46 @@ jobs:
139145
docker logs hf-video
140146
echo "$reply"
141147
grep -q 'no recognised Action' <<<"$reply"
148+
149+
# The x86 function: the handler ZIP on the same base, running its @sparticuz/chromium.
150+
x86-text:
151+
name: x86 text render
152+
needs: handler-zip
153+
runs-on: ubuntu-latest
154+
timeout-minutes: 15
155+
steps:
156+
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
157+
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
158+
with:
159+
name: handler-zip
160+
path: artifacts
161+
- name: The handler ZIP renders the text page under the Lambda runtime
162+
run: |
163+
unzip -q artifacts/handler.zip -d task
164+
cp packages/aws-lambda/image/smoke-video.mjs task/
165+
base=$(sed -n 's/^ARG BASE=//p' packages/aws-lambda/image/Dockerfile)
166+
docker run -d --name hf-x86 --platform linux/amd64 -p 9002:8080 -v "$PWD/task:/var/task:ro" \
167+
"$base" smoke-video.handler
168+
reply=$(curl -sS --retry 30 --retry-all-errors --retry-delay 1 \
169+
-d '{}' http://localhost:9002/2015-03-31/functions/function/invocations)
170+
docker logs hf-x86
171+
jq 'del(.textPng)' <<<"$reply"
172+
jq -e '.arch == "x64" and .screenshotBytes > 0' <<<"$reply"
173+
mkdir text && jq -S .fonts <<<"$reply" >text/fonts.json && jq -r .textPng <<<"$reply" | base64 -d >text/text.png
174+
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
175+
with:
176+
name: text-x86
177+
path: text/
178+
retention-days: 7
179+
180+
# --video-arch picks which of the two renders a stack's frames, so each line must resolve to the same fonts on both.
181+
text-compare:
182+
name: Text fonts match across arches
183+
needs: [image, x86-text]
184+
runs-on: ubuntu-latest
185+
timeout-minutes: 5
186+
steps:
187+
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
188+
with:
189+
pattern: text-*
190+
- run: cat text-arm64/fonts.json && diff text-x86/fonts.json text-arm64/fonts.json
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
name: Lambda handler ZIP
2+
3+
permissions:
4+
contents: read
5+
6+
# The x86 handler ZIP sits close to its unzipped-size gate, and the handler bundles the producer, engine and core,
7+
# so a change there can push it over. Build it on those PRs, so that fails before merge, not in the release job.
8+
on:
9+
pull_request:
10+
paths:
11+
- "packages/aws-lambda/**"
12+
- "packages/producer/src/**"
13+
- "packages/engine/src/**"
14+
- "packages/core/src/**"
15+
- "packages/parsers/src/**"
16+
- "bun.lock"
17+
- ".github/workflows/lambda-handler-zip.yml"
18+
19+
concurrency:
20+
group: lambda-handler-zip-${{ github.ref }}
21+
cancel-in-progress: true
22+
23+
jobs:
24+
changes:
25+
name: Detect changes
26+
runs-on: ubuntu-latest
27+
timeout-minutes: 4
28+
outputs:
29+
release_only: ${{ steps.release.outputs.release_only }}
30+
steps:
31+
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
32+
with:
33+
fetch-depth: 0
34+
- name: Find a release-only diff
35+
id: release
36+
uses: ./.github/actions/release-only-diff
37+
38+
handler-zip:
39+
name: Handler ZIP size
40+
needs: changes
41+
# A release PR changes versions and notes only; a failed change detection must not skip the build.
42+
if: ${{ !cancelled() && needs.changes.outputs.release_only != 'true' }}
43+
runs-on: ubuntu-latest
44+
timeout-minutes: 30
45+
steps:
46+
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
47+
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2
48+
- run: bun install --frozen-lockfile
49+
- run: bun run build
50+
- run: bun run --cwd packages/aws-lambda build:zip

‎bun.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎docs/packages/aws-lambda.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ The Lambda adapter wraps the distributed producer primitives behind one dispatch
5656

5757
All three phases must fit the configured per-invocation Lambda timeout, at most 15 minutes, and the function's temporary storage. Smaller chunks can reduce each worker's extraction and rendering work, but do not divide video extraction that still happens in Plan. See [long-video planning limits](/deploy/aws-lambda#long-video-planning-times-out) for FFmpeg frame-stall timeouts and how to split jobs that cannot fit.
5858

59-
The x86 handler ZIP uses `@sparticuz/chromium` by default, with a build-time fallback for bundling `chrome-headless-shell` directly when needed. The arm64 video image runs Chrome for Testing's linux-arm64 `chrome-headless-shell`.
59+
The x86 handler ZIP uses `@sparticuz/chromium`; a `chrome-headless-shell` ZIP is over Lambda's 250 MiB unzipped limit. The arm64 video image runs Chrome for Testing's linux-arm64 `chrome-headless-shell`, with `@sparticuz/chromium`'s fonts so text resolves as on x86.
6060

6161
### Page network restriction
6262

‎docs/packages/cli.mdx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3070,8 +3070,8 @@ deploy:
30703070
| `--profile` | `AWS_PROFILE` | AWS profile name |
30713071
| `--concurrency` | none | Lambda reserved concurrency. Without it, a new stack reserves none and each render runs up to 90% of the account's unreserved concurrency; a redeploy keeps the stack's current reservation; `none` removes it |
30723072
| `--memory` | `10240` | Lambda memory in MB |
3073-
| `--chrome-source` | `sparticuz` | `sparticuz` or `chrome-headless-shell` |
3074-
| `--video-arch` | `arm64` | `arm64` runs the plan and the chunks on an arm64 container-image function, pushed to an ECR repository named `<stack>-video`; audio and assemble stay on x86. The image runs its own `chrome-headless-shell`; the handler ZIP it is built from needs `sparticuz`. `x86_64` runs everything on the x86 function |
3073+
| `--chrome-source` | `sparticuz` | `sparticuz`. `chrome-headless-shell` is refused: it does not fit a ZIP function, and the arm64 video image already runs it |
3074+
| `--video-arch` | `arm64` | `arm64` runs the plan and the chunks on an arm64 container-image function, pushed to an ECR repository named `<stack>-video`; audio and assemble stay on x86. The image runs its own `chrome-headless-shell`. `x86_64` runs everything on the x86 function |
30753075
| `--skip-build` | off | Reuse the existing `handler.zip` |
30763076
| `--no-warm` | warm | Skip the one warm-up call to the video function after deploy, which loads its container image so the first render is not the one that waits for it |
30773077

‎examples/aws-lambda/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -200,7 +200,7 @@ with `--profile <name>` or `AWS_PROFILE=<name>`.
200200
| `LambdaMemoryMb` | `10240` | Lambda memory; Lambda allocates CPU proportionally. 10 GB recommended for 1080p. |
201201
| `LambdaTimeoutSec` | `900` | Per-invocation timeout. 15 min is Lambda's hard ceiling. |
202202
| `ReservedConcurrency` | `-1` | Hard cap on simultaneous Lambda invocations. `-1` = unreserved. Set to e.g. `50` to bound cost. |
203-
| `ChromeSource` | `sparticuz` | Must match the `--source=` flag passed to `build-zip.ts`. |
203+
| `ChromeSource` | `sparticuz` | Must match the `--source=` flag passed to `build-zip.ts`; a shell ZIP is over Lambda's limit. |
204204
| `ChunkInvocationAlarmThreshold` | `1000` | CloudWatch alarm threshold (RenderChunk invocations per hour). |
205205

206206
## Cleanup

‎examples/aws-lambda/template.yaml‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,8 +53,9 @@ Parameters:
5353
Description: >-
5454
Which Chrome runtime the bundled ZIP was built with. Must match the
5555
`--source=` flag passed to `build-zip.ts`. The handler reads this
56-
via the HYPERFRAMES_LAMBDA_CHROME_SOURCE env var at boot. The arm64
57-
video image always runs its own chrome-headless-shell.
56+
via the HYPERFRAMES_LAMBDA_CHROME_SOURCE env var at boot. A
57+
chrome-headless-shell ZIP is over Lambda's unzipped limit today; the
58+
arm64 video image always runs its own chrome-headless-shell.
5859
5960
ChunkInvocationAlarmThreshold:
6061
Type: Number

‎packages/aws-lambda/README.md‎

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -90,10 +90,10 @@ when `sites/<id>/files.json` is missing, the render uses that site's
9090

9191
The package supports two Chromium sources:
9292

93-
| Source | Default | Size | When to pick it |
94-
| ------------------------------- | ------- | ------------------ | --------------------------------------------------------------------------------------------------------------------- |
95-
| `@sparticuz/chromium` | yes | ~70 MiB compressed | Lambda. Decompresses into `/tmp` at runtime; the rest of the ecosystem already uses it for headless-Chrome-in-Lambda. |
96-
| Bundled `chrome-headless-shell` | no | ~296 MB | Fallback. Used if `@sparticuz/chromium` ever drops `HeadlessExperimental.beginFrame` support. |
93+
| Source | Default | Size | When to pick it |
94+
| ------------------------------- | ------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------- |
95+
| `@sparticuz/chromium` | yes | ~70 MiB compressed | Lambda. Decompresses into `/tmp` at runtime; the rest of the ecosystem already uses it for headless-Chrome-in-Lambda. |
96+
| Bundled `chrome-headless-shell` | no | ~296 MB | Does not fit a ZIP function today. Kept for the case where `@sparticuz/chromium` drops `HeadlessExperimental.beginFrame`. |
9797

9898
Pick the source at build time:
9999

@@ -105,14 +105,19 @@ bun run --cwd packages/aws-lambda build:zip -- --source=chrome-headless-shell
105105
The handler reads `HYPERFRAMES_LAMBDA_CHROME_SOURCE` at boot, and for
106106
`chrome-headless-shell` the executable from `HYPERFRAMES_LAMBDA_CHROME_PATH`.
107107
`examples/aws-lambda/template.yaml` and the CDK construct set both from the
108-
Chrome source. The build stages the whole shell folder (the executable needs
109-
its ICU data and `.pak` files beside it), which is over Lambda's 250 MiB
110-
unzipped limit for a ZIP function, so the x86 ZIP ships `@sparticuz/chromium`.
108+
Chrome source. The build stages the repo's pinned shell build, and only when
109+
its folder matches the pinned digest. It stages the whole folder (the
110+
executable needs its ICU data and `.pak` files beside it), which is over
111+
Lambda's 250 MiB unzipped limit for a ZIP function, so the build fails its
112+
size gate and the x86 ZIP ships `@sparticuz/chromium`. `hyperframes lambda
113+
deploy` refuses `--chrome-source chrome-headless-shell` for the same reason.
111114

112115
The arm64 video image (`image/Dockerfile`, `video` target) does not use
113116
`@sparticuz/chromium`: it installs Chrome for Testing's linux-arm64
114117
`chrome-headless-shell` folder, pinned by version and sha256, with the shared
115-
libraries and fonts it needs, and sets both env vars itself.
118+
libraries it needs, and sets both env vars itself. It keeps `@sparticuz/chromium`'s
119+
fonts and `fonts.conf` from the handler ZIP, so text resolves to the same fonts as
120+
on the x86 function; CI compares the two on a mixed-script page.
116121

117122
## BeginFrame regression guard
118123

@@ -130,7 +135,9 @@ bun run --cwd packages/aws-lambda probe:beginframe:docker
130135
The probe boots `@sparticuz/chromium` inside
131136
`public.ecr.aws/lambda/nodejs:22` and asserts CDP `beginFrame` with
132137
`screenshot: true` returns a PNG buffer. Exit code 0 = green; non-zero =
133-
fall back to bundling chrome-headless-shell directly via `--source=chrome-headless-shell`.
138+
`@sparticuz/chromium` lost BeginFrame. `--source=chrome-headless-shell` does
139+
not fit a ZIP function, so that function would move to a container image like
140+
the arm64 video function.
134141

135142
## Building the ZIP
136143

@@ -150,7 +157,9 @@ designed to extract cleanly into Lambda's `/var/task/`.
150157
- Unzipped ≤ 248 MiB (in-house budget; Lambda hard ceiling is 250 MiB unzipped — AWS docs label this "250 MB" but use binary mebibytes)
151158
- Zipped ≤ 150 MiB (in-house budget; Lambda has no hard zipped cap for S3-deployed functions)
152159

153-
CI fails the PR if either is exceeded.
160+
The sparticuz ZIP is about 1.5 MiB under the unzipped budget, and the handler
161+
bundles the producer, engine and core. So the `Lambda handler ZIP` workflow
162+
builds it on every PR that touches them, and fails the PR if either is exceeded.
154163

155164
## Running tests
156165

‎packages/aws-lambda/image/Dockerfile‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,16 +38,17 @@ COPY --from=check /check.txt /hf-media-check.txt
3838
# The video function. /var/task comes from scripts/stage-arm64-image.ts as the `task` build context:
3939
# docker buildx build --platform linux/arm64 --target video --build-context task=<out>/task packages/aws-lambda/image
4040
# Its Chrome is Chrome for Testing's linux-arm64 chrome-headless-shell, the whole folder: the executable
41-
# alone finds no ICU data or .pak resources. The base has none of the shared libraries the shell links
42-
# and no fonts, so they come from the base's own repository; this RUN needs an arm64 host or emulation.
41+
# alone finds no ICU data or .pak resources. The base has none of the shared libraries the shell links, so
42+
# they come from the base's own repository; this RUN needs an arm64 host or emulation. Its fonts are the
43+
# x86 function's: stage-arm64-image.ts unpacks @sparticuz/chromium's fonts and fonts.conf into /var/task/fonts.
4344
# Bump the version and the archive's sha256 together, with the rest of the repo's pins.
4445
FROM ${BASE} AS video
4546
ARG CHROME_HEADLESS_SHELL_VERSION=158.0.8127.36
4647
ARG CHROME_HEADLESS_SHELL_SHA256=176ee5c55486c22de43128871189061365ea28e881fc96016fd18e7cb59437c8
4748
COPY fetch.sh /fetch.sh
4849
RUN . /fetch.sh && retry microdnf install -y --nodocs --setopt=install_weak_deps=0 --releasever=2023.12.20260914 \
4950
alsa-lib at-spi2-atk at-spi2-core atk dbus-libs expat fontconfig libX11 libXcomposite libXdamage \
50-
libXext libXfixes libXrandr libxcb libxkbcommon liberation-fonts mesa-libgbm nspr nss nss-util \
51+
libXext libXfixes libXrandr libxcb libxkbcommon mesa-libgbm nspr nss nss-util \
5152
systemd-libs unzip && \
5253
curl -fsSL --retry 5 --retry-all-errors --retry-delay 3 --connect-timeout 20 --max-time 600 -o /tmp/chs.zip \
5354
"https://storage.googleapis.com/chrome-for-testing-public/${CHROME_HEADLESS_SHELL_VERSION}/linux-arm64/chrome-headless-shell-linux-arm64.zip" && \
@@ -57,6 +58,7 @@ RUN . /fetch.sh && retry microdnf install -y --nodocs --setopt=install_weak_deps
5758
/opt/chrome-headless-shell-linux-arm64/chrome-headless-shell --version | grep -F "${CHROME_HEADLESS_SHELL_VERSION}"
5859
# src/chromium.ts launches this executable.
5960
ENV HYPERFRAMES_LAMBDA_CHROME_SOURCE=chrome-headless-shell \
60-
HYPERFRAMES_LAMBDA_CHROME_PATH=/opt/chrome-headless-shell-linux-arm64/chrome-headless-shell
61+
HYPERFRAMES_LAMBDA_CHROME_PATH=/opt/chrome-headless-shell-linux-arm64/chrome-headless-shell \
62+
FONTCONFIG_PATH=/var/task/fonts
6163
COPY --from=task / /var/task/
6264
CMD ["handler.handler"]

‎packages/aws-lambda/image/smoke-video.mjs‎

Lines changed: 54 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,74 @@
1-
// A handler mounted into the video image and invoked through its own Lambda bootstrap, which sets
2-
// AWS_EXECUTION_ENV as Lambda does: the bundled ffmpeg answers and the image's chrome-headless-shell
3-
// renders, found where src/chromium.ts finds it and launched with the engine's Lambda flags.
1+
// A handler mounted into a Lambda Node 22 image and invoked through its own Lambda bootstrap, which sets
2+
// AWS_EXECUTION_ENV as Lambda does. In the arm64 video image it runs the image's chrome-headless-shell, found
3+
// where src/chromium.ts finds it; in the x86 base over the unzipped handler ZIP, @sparticuz/chromium.
4+
// It reports the platform fonts each line of a mixed-script page renders with, so the two can be compared.
45
import { execFileSync } from "node:child_process";
56
import puppeteer from "puppeteer-core";
67

8+
const LINES = {
9+
latin: "sans-serif|Quick brown fox ÀÉÎÕÜ ß œ",
10+
serif: "serif|Quick brown fox ÀÉÎÕÜ ß œ",
11+
mono: "monospace|Quick brown fox 0123456789",
12+
greekCyrillic: "sans-serif|Ελληνικά Кириллица",
13+
cjk: "sans-serif|漢字 かな カナ 한국어",
14+
arabic: "sans-serif|العربية",
15+
emoji: "sans-serif|😀 🎬 ✅",
16+
};
17+
18+
const textPage = Object.entries(LINES)
19+
.map(([id, line]) => {
20+
const [family, text] = line.split("|");
21+
return `<p id="${id}" style="font:24px ${family};margin:4px">${text}</p>`;
22+
})
23+
.join("");
24+
25+
async function launch() {
26+
if (process.env.HYPERFRAMES_LAMBDA_CHROME_PATH) {
27+
return puppeteer.launch({
28+
executablePath: process.env.HYPERFRAMES_LAMBDA_CHROME_PATH,
29+
args: ["--no-sandbox", "--disable-setuid-sandbox", "--no-zygote", "--disable-dev-shm-usage"],
30+
});
31+
}
32+
const { default: chromium } = await import("@sparticuz/chromium");
33+
return puppeteer.launch({ executablePath: await chromium.executablePath(), args: chromium.args });
34+
}
35+
36+
async function platformFonts(page) {
37+
const cdp = await page.createCDPSession();
38+
await cdp.send("DOM.enable");
39+
await cdp.send("CSS.enable");
40+
const { root } = await cdp.send("DOM.getDocument", { depth: -1 });
41+
const fonts = {};
42+
for (const id of Object.keys(LINES)) {
43+
const { nodeId } = await cdp.send("DOM.querySelector", {
44+
nodeId: root.nodeId,
45+
selector: `#${id}`,
46+
});
47+
const { fonts: used } = await cdp.send("CSS.getPlatformFontsForNode", { nodeId });
48+
fonts[id] = used.map((font) => `${font.familyName}:${font.glyphCount}`).sort();
49+
}
50+
return fonts;
51+
}
52+
753
export const handler = async () => {
854
const ffmpeg = execFileSync("/var/task/bin/ffmpeg", ["-hide_banner", "-version"], {
955
encoding: "utf-8",
1056
}).split("\n")[0];
11-
const browser = await puppeteer.launch({
12-
executablePath: process.env.HYPERFRAMES_LAMBDA_CHROME_PATH,
13-
args: ["--no-sandbox", "--disable-setuid-sandbox", "--no-zygote", "--disable-dev-shm-usage"],
14-
});
57+
const browser = await launch();
1558
try {
1659
const page = await browser.newPage();
1760
await page.setContent("<div style='width:64px;height:64px;background:#0a0'></div>");
1861
const shot = await page.screenshot({ clip: { x: 0, y: 0, width: 64, height: 64 } });
62+
await page.setViewport({ width: 640, height: 360 });
63+
await page.setContent(textPage);
1964
return {
2065
executionEnv: process.env.AWS_EXECUTION_ENV,
2166
arch: process.arch,
2267
ffmpeg,
2368
chrome: await browser.version(),
2469
screenshotBytes: shot.length,
70+
fonts: await platformFonts(page),
71+
textPng: Buffer.from(await page.screenshot()).toString("base64"),
2572
};
2673
} finally {
2774
await browser.close();

0 commit comments

Comments
 (0)