Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix(gfs): make large GFS uploads work end-to-end (two stacked defects)

Alfredo Lopezaad726d5c043
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index c78677b12..25186a050 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.422",
+ "version": "0.1.423",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.422",
+ "version": "0.1.423",
"dependencies": {
"@clerum/image-policy": "file:../packages/image-policy",
"@clerum/llm-providers": "file:../packages/llm-providers",
diff --git a/control-api/package.json b/control-api/package.json
index 39923958d..42d242d1f 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.422",
+ "version": "0.1.423",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/config.ts b/control-api/src/config.ts
index 15dd35298..ecb1fc3eb 100644
--- a/control-api/src/config.ts
+++ b/control-api/src/config.ts
@@ -185,6 +185,10 @@ type Config = {
gfscBaseUrl: string
// In-cluster base URL of the writer-only gfsc Service for mutations.
gfscWriteBaseUrl: string
+ // Timeout (ms) for the control-api→gfsc proxied fetch. Homologous with the
+ // browser client (GFS_UPLOAD_TIMEOUT_MS) and the control-ui server proxy
+ // (CONTROL_API_PROXY_TIMEOUT_MS): all default 300000. Raise all three together.
+ gfscProxyTimeoutMs: number
// ClusterIP service URL template for the per-SFS wfc. {hash} is replaced
// with the 10-char sfsHash that HCC's sharedFileSystemReconciler computes.
// The template ends without a trailing slash; the proxy concatenates the
@@ -210,6 +214,14 @@ function assertNotPlaceholder(label: string, value: string): void {
}
}
+// Parse a millisecond timeout env: must be a positive integer within the
+// setTimeout/AbortSignal safe range (2^31-1); anything else falls back to the
+// default (never lets NaN/overflow reach AbortSignal.timeout).
+function parseTimeoutMs(raw: string | undefined, fallback: number): number {
+ const parsed = raw ? Number(raw) : Number.NaN
+ return Number.isInteger(parsed) && parsed > 0 && parsed <= 2_147_483_647 ? parsed : fallback
+}
+
function parseInternalTokens(input: string): string[] {
const tokens = input
.split(',')
@@ -798,6 +810,7 @@ export const config: Config = {
gfscBaseUrl: process.env.CONTROL_API_GFSC_BASE_URL || 'http://gfsc.gfs.svc.cluster.local:8087',
gfscWriteBaseUrl:
process.env.CONTROL_API_GFSC_WRITE_BASE_URL || 'http://gfsc-writer.gfs.svc.cluster.local:8087',
+ gfscProxyTimeoutMs: parseTimeoutMs(process.env.CONTROL_API_GFSC_PROXY_TIMEOUT_MS, 300_000),
// {hash} = first 10 chars of sha256(`${ns}/${name}`); see sharedFileSystemHash
// in host-context-controller/src/k8s/sharedFileSystemFactory.ts.
wfcServiceUrlTemplate:
diff --git a/control-api/src/routes/gfs/proxy.ts b/control-api/src/routes/gfs/proxy.ts
index 6456c924f..6486fcb56 100644
--- a/control-api/src/routes/gfs/proxy.ts
+++ b/control-api/src/routes/gfs/proxy.ts
@@ -59,14 +59,55 @@ export function registerGfsProxyRoute(router: Router): void {
headers['content-type'] = 'application/json'
}
- const upstreamRes = await fetch(target, {
- method: req.method,
- headers,
- body:
- req.method === 'GET' || req.method === 'HEAD'
- ? undefined
- : JSON.stringify(req.body ?? {}),
- })
+ let upstreamRes: Response
+ try {
+ upstreamRes = await fetch(target, {
+ method: req.method,
+ headers,
+ body:
+ req.method === 'GET' || req.method === 'HEAD'
+ ? undefined
+ : JSON.stringify(req.body ?? {}),
+ // Homologous with the browser client and control-ui proxy (all 300s by
+ // default). Without this the fetch had NO timeout: a slow/large upload or
+ // a hung gfsc would pin the connection indefinitely.
+ signal: AbortSignal.timeout(config.gfscProxyTimeoutMs),
+ })
+ } catch (err) {
+ // Never silent: a failed or timed-out gfsc fetch is logged with the target.
+ const timedOut = err instanceof Error && err.name === 'TimeoutError'
+ rootLogger.error(
+ { err, target, method: req.method, timeoutMs: config.gfscProxyTimeoutMs },
+ timedOut
+ ? 'gfs operator proxy: gfsc fetch timed out'
+ : 'gfs operator proxy: gfsc fetch failed'
+ )
+ res
+ .status(timedOut ? 504 : 502)
+ .json({ error: timedOut ? 'gfsc_timeout' : 'gfsc_unreachable' })
+ return
+ }
+
+ if (upstreamRes.status >= 400) {
+ // Error envelopes are small JSON: buffer, LOG (so a gfsc 5xx is never
+ // undiagnosable at this hop again — the base64 RangeError 500 was invisible
+ // here before), then forward the body verbatim.
+ const errorBody = await upstreamRes.text()
+ const logCtx = {
+ target,
+ method: req.method,
+ status: upstreamRes.status,
+ body: errorBody.slice(0, 2048),
+ }
+ if (upstreamRes.status >= 500)
+ rootLogger.error(logCtx, 'gfs operator proxy: gfsc upstream error')
+ else rootLogger.warn(logCtx, 'gfs operator proxy: gfsc upstream client error')
+ res.status(upstreamRes.status)
+ const contentType = upstreamRes.headers.get('content-type')
+ if (contentType) res.setHeader('content-type', contentType)
+ res.send(errorBody)
+ return
+ }
res.status(upstreamRes.status)
for (const header of PASSTHROUGH_RESPONSE_HEADERS) {
diff --git a/control-ui/next.config.js b/control-ui/next.config.js
index fd33c01b7..7b9bee733 100644
--- a/control-ui/next.config.js
+++ b/control-ui/next.config.js
@@ -12,7 +12,13 @@ const nextConfig = {
root: path.join(__dirname, '..'),
},
async rewrites() {
- const controlApiDestination = process.env.CONTROL_API_INTERNAL_URL || 'http://127.0.0.1:8090'
+ // NOTE: `/control-api/:path*` is intentionally NOT rewritten here. It is served by
+ // the app-router handler app/control-api/[...path]/route.ts, which streams the body
+ // (no 10MiB proxyClientMaxBodySize truncation) and honours the runtime-configurable
+ // CONTROL_API_PROXY_TIMEOUT_MS. Routing it through a rewrite sends it via Next's
+ // internal proxy, which silently truncates request bodies at 10MiB and hard-caps at
+ // a 30s proxyTimeout — the "Request timed out" / "request aborted" failure on large
+ // GFS uploads. The handler reads CONTROL_API_INTERNAL_URL for its upstream.
return [
{ source: '/agents', destination: '/hosts' },
{ source: '/agents/:path*', destination: '/hosts/:path*' },
@@ -39,10 +45,6 @@ const nextConfig = {
{ source: '/marketplace/:path*', destination: '/registry/:path*' },
{ source: '/cost-and-usage/:path*', destination: '/cost/:path*' },
{ source: '/settings/ui', destination: '/settings' },
- {
- source: '/control-api/:path*',
- destination: `${controlApiDestination}/:path*`,
- },
]
},
async redirects() {
diff --git a/control-ui/package-lock.json b/control-ui/package-lock.json
index 9368cfbce..dcca8f277 100644
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-ui",
- "version": "0.1.388",
+ "version": "0.1.389",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.388",
+ "version": "0.1.389",
"dependencies": {
"@clerum/llm-providers": "file:../packages/llm-providers",
"@clerum/workflow-recipe-capability-policy": "file:../packages/workflow-recipe-capability-policy",
diff --git a/control-ui/package.json b/control-ui/package.json
index 4397b10b0..d71b5a910 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-ui",
- "version": "0.1.388",
+ "version": "0.1.389",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",
diff --git a/deploy/base/control-plane/control-api.yaml b/deploy/base/control-plane/control-api.yaml
index ce429b99c..cea8ae8b4 100644
--- a/deploy/base/control-plane/control-api.yaml
+++ b/deploy/base/control-plane/control-api.yaml
@@ -79,6 +79,11 @@ spec:
value: "mcp-host,sandbox-recipes"
- name: CONTROL_API_REMOTE_MCP_EGRESS_PROXY_IMAGE
value: clerum/nginx-egress-proxy:0.1.0
+ # control-api→gfsc proxy fetch timeout (ms). Homologous with the browser
+ # client and the control-ui server proxy (all 300s). Raise all three
+ # together or none. Guards large GFS uploads from a premature cut.
+ - name: CONTROL_API_GFSC_PROXY_TIMEOUT_MS
+ value: "300000"
- name: CONTROL_API_PG_CONNECTION_STRING
valueFrom:
secretKeyRef:
diff --git a/gfs-controller/src/api/serve.test.ts b/gfs-controller/src/api/serve.test.ts
index c1579b0be..59c4b50d9 100644
--- a/gfs-controller/src/api/serve.test.ts
+++ b/gfs-controller/src/api/serve.test.ts
@@ -476,6 +476,27 @@ describe("GfsServingHandler — write routes (governed mutation)", () => {
expect((calls[0].input as { content: Buffer }).content.toString("utf8")).toBe("new");
});
+ it("200 replace accepts a large (>4.47MB) base64 body without a regex stack overflow", async () => {
+ // 5MiB raw -> ~6.99MB base64, well past the ~4.47MB-char threshold where the
+ // previous grouped-quantifier regex /(?:[A-Za-z0-9+/]{4})*.../ overflowed V8's
+ // regexp backtrack stack (RangeError -> bogus 500 `internal` on any large upload).
+ const rawBytes = 5 * 1024 * 1024;
+ const largeBase64 = Buffer.alloc(rawBytes, 0x41).toString("base64");
+ const res = new FakeRes();
+ const { d, calls } = writeDeps();
+ await run(
+ d,
+ reqBody(`/v1/resources/${RID}/content`, {
+ method: "PUT",
+ auth: "Bearer t",
+ body: { contentBase64: largeBase64, ifMatch: 2 },
+ }),
+ res
+ );
+ expect(res.statusCode).toBe(200);
+ expect((calls[0].input as { content: Buffer }).content.length).toBe(rawBytes);
+ });
+
it("400 path_invalid for invalid encoded file content", async () => {
const res = new FakeRes();
const { d, calls, authzOps } = writeDeps();
diff --git a/gfs-controller/src/api/serve.ts b/gfs-controller/src/api/serve.ts
index cadae859b..826fbd88c 100644
--- a/gfs-controller/src/api/serve.ts
+++ b/gfs-controller/src/api/serve.ts
@@ -71,8 +71,18 @@ export interface ServingDeps {
now?: () => number;
}
-/** Largest mutation body gfsc accepts before failing loud with payload_too_large. */
-const MAX_WRITE_BODY_BYTES = 16 * 1024 * 1024;
+/**
+ * Largest mutation body gfsc accepts before failing loud with payload_too_large.
+ * Configurable via GFS_MAX_WRITE_BODY_BYTES so ops can raise it beyond the 16MiB
+ * default (which already fits base64(10MB) ≈ 13.98MB). A non-integer or
+ * non-positive value falls back to the default (fail-safe; never NaN).
+ * NOTE: to take effect on the gfsc pod this env must be plumbed through the
+ * host-context-controller gfsc template (deferred — inert while the default holds).
+ */
+const MAX_WRITE_BODY_BYTES = ((): number => {
+ const raw = Number(process.env.GFS_MAX_WRITE_BODY_BYTES);
+ return Number.isInteger(raw) && raw > 0 ? raw : 16 * 1024 * 1024;
+})();
const MAX_NODE_TIMER_DELAY_MS = 2_147_483_647;
const NANOSECONDS_PER_MILLISECOND = 1_000_000n;
@@ -210,6 +220,16 @@ export class GfsServingHandler {
}
} catch (err) {
const { status, body } = toResponse(err);
+ if (status >= 500) {
+ // A 5xx must never be invisible: an unknown throw (e.g. the base64
+ // RangeError that produced a bogus `internal` 500) previously left no
+ // trace anywhere in the system. Log code + stack (never the body/content).
+ console.error(
+ `[gfsc] ${method} ${req.url ?? "?"} -> ${status} ${body.error.code}: ${
+ err instanceof Error ? (err.stack ?? err.message) : String(err)
+ }`
+ );
+ }
if (!res.headersSent) sendJson(res, status, body);
else res.end(); // a content stream already started; just terminate
} finally {
@@ -592,8 +612,13 @@ function readContentBuffer(body: Record<string, unknown>): Buffer {
function decodeBase64Content(encoded: string): Buffer {
if (encoded.length === 0) return Buffer.alloc(0);
- const standardBase64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
- if (!standardBase64.test(encoded)) {
+ // Canonical base64: length is a multiple of 4, only base64 chars, and padding
+ // ('=' x0-2) only at the very end. This uses a single character-class star,
+ // which V8 compiles to a linear loop. The previous `/(?:[A-Za-z0-9+/]{4})*.../`
+ // used a GROUPED quantifier that pushes an Irregexp backtrack frame per 4-char
+ // group and threw `RangeError: Maximum call stack size exceeded` above ~4.47M
+ // chars (~3.2MB raw) — surfacing as a bogus 500 `internal` on any large upload.
+ if (encoded.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(encoded)) {
throw new GfsError("path_invalid", "'contentBase64' must be valid base64");
}
return Buffer.from(encoded, "base64");