Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(storage): upload large originals from disk with bounded memory
garrytana1323193af4b
diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.mdindex 2b81eaa96a..84c86bb79b 100644--- a/docs/architecture/key-files/core-utilities-2.md+++ b/docs/architecture/key-files/core-utilities-2.md@@ -39,7 +39,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/storage-config.ts` — Storage tiering: `loadStorageConfig` reads `gbrain.yml` (warning once per process for each unknown key under `storage:`; an optional `keep_db` prefix list, present only when declared, is normalized like the tiers and matched by `isKeepDbSlug`, consumed by `repair/keep-db-policy.ts`), normalizes deprecated keys (`git_tracked`/`supabase_only`) to canonical (`db_tracked`/`db_only`) with once-per-process deprecation warning, and runs `normalizeAndValidateStorageConfig` (auto-fixes missing trailing `/`, throws `StorageConfigError` on tier overlap). Path-segment matcher: `media/x/` does NOT match `media/xerox/foo`. `isDeclaredDbOnlySlug` matches a lowercase page slug against the declared db_only dirs case-insensitively; managed persistence uses it to publish those pages database-only. `hasUnresolvedDbOnlyDeclaration` detects a db_only key line that resolved no directory (unsupported syntax such as flow-style lists; an intentionally empty `db_only: []` is an accepted false positive); the sync baseline-commit guard refuses on it, and managed persistence turns a missing-file refusal into `storage_error`. Uses a dedicated parser for the `gbrain.yml` shape rather than gray-matter (broken on delimiter-less YAML). Also carries `DERIVE_PHASE_DB_ONLY_DEFAULTS` (`life/events/`, `atoms/`, `extracts/`, `dream-cycle-summaries/`) + `effectiveDbOnlyDirs` — the engine's derive-phase output prefixes treated as implicitly-declared db_only by the `undeclared_db_only_pages` doctor check but deliberately NOT merged into `loadStorageConfig` (a global merge would auto-gitignore those dirs and silently kill ingestion for brains that file-back them) — and `findDbOnlyCollisions` (pure collector-output vs db_only overlap detector shared by the `db_only_collector_collision` doctor check and sync's `manageGitignore` warning). Pinned by `test/storage-config.test.ts` + `test/doctor-silent-death-checks.test.ts`.-- `src/core/storage.ts` — Pluggable storage interface (S3, Supabase Storage, local).+- `src/core/storage.ts` — Pluggable storage interface (S3, Supabase Storage, local). `uploadFile` streams from disk in bounded memory (#7427).- `src/core/stored-embedding-identity.ts` — reads the existing primary vector column's database type and width plus its recorded model before either engine initializes the schema or runs bootstrap DDL. Its fixed-name store inventory covers primary-space vectors in chunks, facts, query cache and takes; re-init refuses a model change when any is populated. Existing stores retain their identity instead of inheriting a fresh-install default; unknown column identity or missing model metadata refuses schema initialization with explicit migration guidance. This does not merge database model rows into the runtime gateway or rewrite stored vectors. Configless runtime access remains keyword-only until an embedding identity is explicitly configured. Approved model migrations invalidate companion vectors and clear the query cache atomically with their checkpoint and DB identity; same-target resume preserves already-regenerated companion vectors.diff --git a/src/commands/files.ts b/src/commands/files.tsindex f9cf230d6e..559f6a24bb 100644--- a/src/commands/files.ts+++ b/src/commands/files.ts@@ -3,7 +3,7 @@ import { readFileSync, readdirSync, statSync, lstatSync, existsSync, writeFileSyimport { join, relative, extname, basename, dirname, resolve } from 'path';import { createHash } from 'crypto';import type { BrainEngine } from '../core/engine.ts';-import type { StorageBackend, StorageConfig } from '../core/storage.ts';+import { hashStorageFile, type StorageBackend, type StorageConfig } from '../core/storage.ts';import { sqlQueryForEngine, executeRawJsonb, FILES_METADATA_MERGE_SQL } from '../core/sql-query.ts';import { humanSize } from '../core/file-resolver.ts';import { createProgress } from '../core/progress.ts';@@ -42,8 +42,7 @@ export function getMimeType(filePath: string): string | null {}function fileHash(filePath: string): string {- const content = readFileSync(filePath);- return createHash('sha256').update(content).digest('hex');+ return hashStorageFile(filePath);}export function formatFileSizeKb(rawSizeBytes: number | bigint | string | null): string {@@ -201,10 +200,9 @@ async function uploadFile(engine: BrainEngine, args: string[]) {return;}- const content = readFileSync(filePath);- const method = content.length >= SIZE_THRESHOLD ? 'TUS resumable' : 'standard';+ const method = stat.size >= SIZE_THRESHOLD ? 'TUS resumable' : 'standard';console.log(`Uploading ${humanSize(stat.size)} via ${method}...`);- await storage.upload(storagePath, content, mimeType || undefined);+ await storage.uploadFile(storagePath, filePath, mimeType || undefined);// files.metadata is JSONB — bind a real object via executeRawJsonb instead// of casting a string into ::jsonb (the #2339 double-encode class).@@ -343,14 +341,13 @@ async function uploadRaw(engine: BrainEngine, args: string[]) {const { createStorage } = await import('../core/storage.ts');const storage = await createStorage(config.storage as any);- const content = readFileSync(filePath);- const hash = createHash('sha256').update(content).digest('hex');+ const hash = fileHash(filePath);const storagePath = pageSlug ? `${pageSlug}/${filename}` : `unsorted/${hash.slice(0, 8)}-${filename}`;const bucket = (config.storage as any).bucket || 'brain-files';- const method = content.length >= SIZE_THRESHOLD ? 'TUS resumable' : 'standard';+ const method = stat.size >= SIZE_THRESHOLD ? 'TUS resumable' : 'standard';console.error(`Uploading ${humanSize(stat.size)} via ${method}...`);- await storage.upload(storagePath, content, mimeType || undefined);+ await storage.uploadFile(storagePath, filePath, mimeType || undefined);// Create .redirect.yaml pointer in the brain repolet pointerPath: string | null = null;@@ -470,7 +467,7 @@ async function syncFiles(engine: BrainEngine, dir?: string) {const pageSlug = pathParts.length > 1 ? pathParts.slice(0, -1).join('/') : null;// Actually put the bytes in storage before recording them as stored.- await storage.upload(storagePath, readFileSync(filePath), mimeType || undefined);+ await storage.uploadFile(storagePath, filePath, mimeType || undefined);// files.metadata is JSONB — bind a real object via executeRawJsonb instead// of casting a string into ::jsonb (the #2339 double-encode class).@@ -642,9 +639,8 @@ async function mirrorFiles(args: string[]) {let uploaded = 0;for (const filePath of files) {const relPath = relative(dir, filePath);- const data = readFileSync(filePath);const mime = getMimeType(filePath);- await storage.upload(relPath, data, mime || undefined);+ await storage.uploadFile(relPath, filePath, mime || undefined);uploaded++;}diff --git a/src/core/ops/files.ts b/src/core/ops/files.tsindex 9700bb2963..632605f326 100644--- a/src/core/ops/files.ts+++ b/src/core/ops/files.ts@@ -60,9 +60,9 @@ const file_upload: Operation = {handler: async (ctx, p) => {if (ctx.dryRun) return { dry_run: true, action: 'file_upload', path: p.path };- const { readFileSync, statSync } = await import('fs');+ const { statSync } = await import('fs');const { basename, extname } = await import('path');- const { createHash } = await import('crypto');+ const { hashStorageFile } = await import('../storage.ts');const filePath = p.path as string;const pageSlug = (p.page_slug as string) || null;@@ -78,8 +78,7 @@ const file_upload: Operation = {validateFilename(filename);const stat = statSync(filePath);- const content = readFileSync(filePath);- const hash = createHash('sha256').update(content).digest('hex');+ const hash = hashStorageFile(filePath);const storagePath = pageSlug ? `${pageSlug}/${filename}` : `unsorted/${hash.slice(0, 8)}-${filename}`;const MIME_TYPES: Record<string, string> = {@@ -128,7 +127,7 @@ const file_upload: Operation = {}try {- await storage.upload(storagePath, content, mimeType || undefined);+ await storage.uploadFile(storagePath, filePath, mimeType || undefined);} catch (uploadErr) {throw opError('storage_error', `Upload failed: ${uploadErr instanceof Error ? uploadErr.message : String(uploadErr)}`,'Nothing was recorded. Check the storage backend (credentials, bucket, disk) with `gbrain doctor --json`, then upload again; the upload is keyed by content hash, so repeating it is safe.');diff --git a/src/core/storage.ts b/src/core/storage.tsindex 4e35cb3555..22afcf9706 100644--- a/src/core/storage.ts+++ b/src/core/storage.ts@@ -1,3 +1,7 @@+import { closeSync, openSync, readSync } from 'fs';+import type { FileHandle } from 'fs/promises';+import { createHash } from 'crypto';+/*** StorageBackend — pluggable interface for binary file storage.*@@ -7,6 +11,8 @@export interface StorageBackend {upload(path: string, data: Buffer, mime?: string): Promise<void>;+ /** Upload a file from disk with memory bounded independently of its size (#7427). */+ uploadFile(path: string, filePath: string, mime?: string): Promise<void>;download(path: string): Promise<Buffer>;delete(path: string): Promise<void>;exists(path: string): Promise<boolean>;@@ -50,3 +56,29 @@ export async function createStorage(config: StorageConfig): Promise<StorageBackethrow new Error(`Unknown storage backend: ${config.backend}`);}}++/** SHA-256 of a file read in fixed-size chunks, so large originals are never held in memory. */+export function hashStorageFile(filePath: string): string {+ const fd = openSync(filePath, 'r');+ try {+ const hash = createHash('sha256');+ const chunk = Buffer.allocUnsafe(1024 * 1024);+ let length: number;+ while ((length = readSync(fd, chunk, 0, chunk.length, null)) > 0) {+ hash.update(chunk.subarray(0, length));+ }+ return hash.digest('hex');+ } finally {+ closeSync(fd);+ }+}++/** Read exactly `length` bytes at `position` into the start of `buffer`. */+export async function readFileRange(file: FileHandle, buffer: Buffer, length: number, position: number): Promise<Buffer> {+ for (let filled = 0; filled < length;) {+ const { bytesRead } = await file.read(buffer, filled, length - filled, position + filled);+ if (!bytesRead) throw new Error('File shrank during upload');+ filled += bytesRead;+ }+ return buffer.subarray(0, length);+}diff --git a/src/core/storage/local.ts b/src/core/storage/local.tsindex be42599a7d..378f89e0fe 100644--- a/src/core/storage/local.ts+++ b/src/core/storage/local.ts@@ -1,4 +1,4 @@-import { readFileSync, writeFileSync, unlinkSync, existsSync, mkdirSync, readdirSync, realpathSync } from 'fs';+import { copyFileSync, readFileSync, writeFileSync, unlinkSync, existsSync, mkdirSync, readdirSync, realpathSync } from 'fs';import { join, dirname, resolve } from 'path';import type { StorageBackend } from '../storage.ts';@@ -28,6 +28,12 @@ export class LocalStorage implements StorageBackend {writeFileSync(full, data);}+ async uploadFile(path: string, filePath: string, _mime?: string): Promise<void> {+ const full = this.contained(path);+ mkdirSync(dirname(full), { recursive: true });+ copyFileSync(filePath, full);+ }+async download(path: string): Promise<Buffer> {const full = this.contained(path);if (!existsSync(full)) throw new Error(`File not found in storage: ${path}`);diff --git a/src/core/storage/s3.ts b/src/core/storage/s3.tsindex 2f535c5df0..6d4e2c2212 100644--- a/src/core/storage/s3.ts+++ b/src/core/storage/s3.ts@@ -1,12 +1,28 @@+import { open } from 'fs/promises';import {S3Client,+ CreateMultipartUploadCommand,+ UploadPartCommand,+ CompleteMultipartUploadCommand,+ AbortMultipartUploadCommand,PutObjectCommand,GetObjectCommand,DeleteObjectCommand,HeadObjectCommand,ListObjectsV2Command,} from '@aws-sdk/client-s3';-import type { StorageBackend, StorageConfig } from '../storage.ts';+import { readFileRange, type StorageBackend, type StorageConfig } from '../storage.ts';++const MIN_PART_SIZE = 16 * 1024 * 1024;+const MAX_PART_SIZE = 5 * 1024 * 1024 * 1024;+const MAX_PARTS = 10_000;++/** Multipart part size for `size` bytes within S3's limits: 5 MiB..5 GiB per part, at most 10,000 parts. */+export function multipartPartSize(size: number): number {+ const partSize = Math.max(MIN_PART_SIZE, Math.ceil(size / MAX_PARTS));+ if (partSize > MAX_PART_SIZE) throw new Error(`File too large for an S3 multipart upload: ${size} bytes`);+ return partSize;+}/*** S3-compatible storage — works with AWS S3, Cloudflare R2, MinIO, etc.@@ -54,6 +70,54 @@ export class S3Storage implements StorageBackend {}));}+ /**+ * Sequential multipart upload from one reused part buffer, so memory is+ * bounded by the part size, not the file size (#7427). A file that fits in+ * one part is a single PutObject.+ */+ async uploadFile(path: string, filePath: string, mime?: string): Promise<void> {+ const file = await open(filePath, 'r');+ const target = { Bucket: this.bucket, Key: path };+ let uploadId: string | undefined;+ try {+ const { size } = await file.stat();+ const partSize = multipartPartSize(size);+ const buffer = Buffer.allocUnsafe(Math.min(size, partSize));+ if (size <= partSize) {+ await this.upload(path, await readFileRange(file, buffer, size, 0), mime);+ return;+ }+ const created = await this.client.send(new CreateMultipartUploadCommand({+ ...target, ContentType: mime || 'application/octet-stream',+ }));+ uploadId = created.UploadId;+ if (!uploadId) throw new Error('S3 multipart upload returned no upload ID');+ const parts: { PartNumber: number; ETag: string }[] = [];+ for (let offset = 0; offset < size;) {+ const length = Math.min(partSize, size - offset);+ const PartNumber = parts.length + 1;+ const result = await this.client.send(new UploadPartCommand({+ ...target, UploadId: uploadId, PartNumber,+ Body: await readFileRange(file, buffer, length, offset), ContentLength: length,+ }));+ if (!result.ETag) throw new Error(`S3 multipart part ${PartNumber} returned no ETag`);+ parts.push({ PartNumber, ETag: result.ETag });+ offset += length;+ }+ await this.client.send(new CompleteMultipartUploadCommand({+ ...target, UploadId: uploadId, MultipartUpload: { Parts: parts },+ }));+ } catch (error) {+ if (uploadId) {+ // Best effort: the original failure is the one to surface.+ await this.client.send(new AbortMultipartUploadCommand({ ...target, UploadId: uploadId })).catch(() => {});+ }+ throw error;+ } finally {+ await file.close();+ }+ }+async download(path: string): Promise<Buffer> {const res = await this.client.send(new GetObjectCommand({Bucket: this.bucket,diff --git a/src/core/storage/supabase.ts b/src/core/storage/supabase.tsindex d386636c5a..6051444bfc 100644--- a/src/core/storage/supabase.ts+++ b/src/core/storage/supabase.ts@@ -1,4 +1,5 @@-import type { StorageBackend, StorageConfig } from '../storage.ts';+import { open } from 'fs/promises';+import { readFileRange, type StorageBackend, type StorageConfig } from '../storage.ts';/** Size thresholds for upload method selection */const TUS_THRESHOLD = 100 * 1024 * 1024; // 100 MB — use TUS resumable above this@@ -45,12 +46,28 @@ export class SupabaseStorage implements StorageBackend {async upload(path: string, data: Buffer, mime?: string): Promise<void> {if (data.length >= TUS_THRESHOLD) {- await this.uploadTus(path, data, mime);+ await this.uploadTus(path, data.length, async (offset, length) => data.subarray(offset, offset + length), mime);} else {await this.uploadStandard(path, data, mime);}}+ /** Upload from disk: TUS reads each chunk from the file, so memory is bounded by the chunk size (#7427). */+ async uploadFile(path: string, filePath: string, mime?: string): Promise<void> {+ const file = await open(filePath, 'r');+ try {+ const { size } = await file.stat();+ if (size < TUS_THRESHOLD) {+ await this.uploadStandard(path, await readFileRange(file, Buffer.allocUnsafe(size), size, 0), mime);+ return;+ }+ const chunk = Buffer.allocUnsafe(TUS_CHUNK_SIZE);+ await this.uploadTus(path, size, (offset, length) => readFileRange(file, chunk, length, offset), mime);+ } finally {+ await file.close();+ }+ }+/** Standard single-request upload for files < 100 MB */private async uploadStandard(path: string, data: Buffer, mime?: string): Promise<void> {const res = await this.fetchImpl(this.url(path), {@@ -70,9 +87,15 @@ export class SupabaseStorage implements StorageBackend {/*** TUS resumable upload for files >= 100 MB.- * Sends in 6 MB chunks with retry + exponential backoff.+ * Sends in 6 MB chunks with retry + exponential backoff; `readChunk` supplies+ * each chunk's bytes, from memory or from disk.*/- private async uploadTus(path: string, data: Buffer, mime?: string): Promise<void> {+ private async uploadTus(+ path: string,+ size: number,+ readChunk: (offset: number, length: number) => Promise<Buffer>,+ mime?: string,+ ): Promise<void> {const tusUrl = `${this.projectUrl}/storage/v1/upload/resumable`;const objectName = `${this.bucket}/${path}`;@@ -82,7 +105,7 @@ export class SupabaseStorage implements StorageBackend {headers: {...this.headers(),'Tus-Resumable': '1.0.0',- 'Upload-Length': String(data.length),+ 'Upload-Length': String(size),'Upload-Metadata': [`bucketName ${btoa(this.bucket)}`,`objectName ${btoa(path)}`,@@ -102,7 +125,7 @@ export class SupabaseStorage implements StorageBackend {// Step 2: Upload chunkslet offset = 0;- while (offset < data.length) {+ while (offset < size) {let attempt = 0;const maxAttempts = 3;while (attempt < maxAttempts) {@@ -119,8 +142,8 @@ export class SupabaseStorage implements StorageBackend {}}- const end = Math.min(offset + TUS_CHUNK_SIZE, data.length);- const chunk = data.subarray(offset, end);+ const end = Math.min(offset + TUS_CHUNK_SIZE, size);+ const chunk = await readChunk(offset, end - offset);const patchRes = await this.fetchImpl(uploadUrl, {method: 'PATCH',diff --git a/test/e2e/multi-source.test.ts b/test/e2e/multi-source.test.tsindex 5c45c6b7ac..4580a707ee 100644--- a/test/e2e/multi-source.test.ts+++ b/test/e2e/multi-source.test.ts@@ -547,6 +547,7 @@ describeE2E('v0.18.0 multi-source — storage backfill against file_migration_leconst uploaded = new Set<string>();const stub: StorageBackend = {upload: async (p: string) => { uploaded.add(p); },+ uploadFile: async (p: string) => { uploaded.add(p); },download: async (p: string) => Buffer.from('bytes-for:' + p),delete: async (p: string) => { uploaded.delete(p); },exists: async (p: string) => uploaded.has(p),diff --git a/test/storage-backfill.test.ts b/test/storage-backfill.test.tsindex 415c82d09b..e0ff5a736d 100644--- a/test/storage-backfill.test.ts+++ b/test/storage-backfill.test.ts@@ -71,6 +71,7 @@ function makeStorage(): { storage: StorageBackend; calls: string[] } {const uploaded = new Set<string>();const storage: StorageBackend = {upload: async (path: string) => { calls.push(`upload:${path}`); uploaded.add(path); },+ uploadFile: async (path: string) => { calls.push(`uploadFile:${path}`); uploaded.add(path); },download: async (path: string) => { calls.push(`download:${path}`); return Buffer.from('content-for:' + path); },delete: async (path: string) => { calls.push(`delete:${path}`); uploaded.delete(path); },exists: async (path: string) => { calls.push(`exists:${path}`); return uploaded.has(path); },diff --git a/test/storage-upload-file.test.ts b/test/storage-upload-file.test.tsnew file mode 100644index 0000000000..1d8fbdafe5--- /dev/null+++ b/test/storage-upload-file.test.ts@@ -0,0 +1,323 @@+/**+ * #7427 — uploading a large original must not read the whole file into memory.+ *+ * Every backend uploads straight from disk (StorageBackend.uploadFile):+ * - S3 streams fixed-size multipart parts from one reused part buffer and+ * aborts the multipart upload when a part fails;+ * - Supabase TUS reads each 6 MiB chunk from disk;+ * - local copies the file.+ * The callers (file_upload, gbrain files upload | upload-raw | sync | mirror)+ * hash and upload from the path, never via a whole-file read.+ *+ * The memory bound is asserted without allocating gigabytes: no request body+ * is larger than one part, and no body is a view into a larger allocation+ * (body.buffer.byteLength), which a whole-file buffer sliced into parts+ * would be.+ */++import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';+import * as fs from 'fs';+import * as fsp from 'fs/promises';+import { closeSync, existsSync, mkdirSync, mkdtempSync, openSync, readSync, rmSync, truncateSync, writeFileSync, writeSync } from 'fs';+import { tmpdir } from 'os';+import { join, resolve } from 'path';+import { createHash } from 'crypto';+import type { S3Client } from '@aws-sdk/client-s3';+import {+ AbortMultipartUploadCommand,+ CompleteMultipartUploadCommand,+ CreateMultipartUploadCommand,+ PutObjectCommand,+ UploadPartCommand,+} from '@aws-sdk/client-s3';+import { S3Storage, multipartPartSize } from '../src/core/storage/s3.ts';+import { SupabaseStorage } from '../src/core/storage/supabase.ts';+import { LocalStorage } from '../src/core/storage/local.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { operationsByName } from '../src/core/operations.ts';+import { runFiles } from '../src/commands/files.ts';+import { withEnv } from './helpers/with-env.ts';++const MiB = 1024 * 1024;+const GiB = 1024 * MiB;+const S3_PART = 16 * MiB;+const TUS_CHUNK = 6 * MiB;++let engine: PGLiteEngine;+let workDir: string;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ workDir = mkdtempSync(join(tmpdir(), 'gb-7427-'));+});++afterAll(async () => {+ await engine.disconnect();+ rmSync(workDir, { recursive: true, force: true });+});++function writePatterned(path: string, size: number): void {+ const fd = openSync(path, 'w');+ const block = Buffer.alloc(MiB);+ try {+ for (let offset = 0, i = 0; offset < size; offset += block.length, i++) {+ block.fill(i % 251);+ writeSync(fd, block, 0, Math.min(block.length, size - offset), offset);+ }+ } finally {+ closeSync(fd);+ }+}++function sha256Of(path: string): string {+ const fd = openSync(path, 'r');+ const hash = createHash('sha256');+ const block = Buffer.alloc(MiB);+ try {+ let n: number;+ while ((n = readSync(fd, block, 0, block.length, null)) > 0) hash.update(block.subarray(0, n));+ } finally {+ closeSync(fd);+ }+ return hash.digest('hex');+}++/** Records whole-file read APIs called on the given paths. */+function watchWholeFileReads(paths: string[]) {+ const targets = new Set(paths.map(p => resolve(p)));+ const spies = [spyOn(fs, 'readFileSync'), spyOn(fsp, 'readFile'), spyOn(Bun, 'file')];+ return {+ reads: () => spies.flatMap(s => s.mock.calls.map(c => c[0]))+ .filter(p => typeof p === 'string' && targets.has(resolve(p))),+ restore: () => spies.forEach(s => s.mockRestore()),+ };+}++function s3Stub(onSend: (command: any) => any): { client: S3Client; sent: any[] } {+ const sent: any[] = [];+ const client = {+ send: async (command: any) => {+ sent.push(command);+ return onSend(command);+ },+ } as unknown as S3Client;+ return { client, sent };+}++describe('S3 uploadFile (#7427)', () => {+ test('a file larger than one part streams bounded multipart parts and completes in order', async () => {+ const src = join(workDir, 's3-large.bin');+ const size = 2 * S3_PART + MiB + 19;+ writePatterned(src, size);+ const received = createHash('sha256');+ const bodies: { length: number; allocation: number; contentLength: number }[] = [];+ const { client, sent } = s3Stub((command) => {+ if (command instanceof CreateMultipartUploadCommand) return { UploadId: 'upload-a' };+ if (command instanceof UploadPartCommand) {+ const body = command.input.Body as Uint8Array;+ bodies.push({ length: body.byteLength, allocation: body.buffer.byteLength, contentLength: command.input.ContentLength! });+ received.update(body);+ return { ETag: '"etag-' + command.input.PartNumber + '"' };+ }+ return {};+ });+ const watch = watchWholeFileReads([src]);+ try {+ await new S3Storage({ backend: 's3', bucket: 'originals' }, client).uploadFile('media/s3-large.bin', src, 'video/mp4');+ expect(watch.reads()).toEqual([]);+ } finally {+ watch.restore();+ }++ expect(sent.some(c => c instanceof PutObjectCommand)).toBe(false);+ expect(sent[0]).toBeInstanceOf(CreateMultipartUploadCommand);+ expect(sent[0].input).toEqual({ Bucket: 'originals', Key: 'media/s3-large.bin', ContentType: 'video/mp4' });+ expect(bodies.map(b => b.length)).toEqual([S3_PART, S3_PART, MiB + 19]);+ for (const b of bodies) {+ expect(b.allocation).toBeLessThanOrEqual(S3_PART);+ expect(b.contentLength).toBe(b.length);+ }+ expect(received.digest('hex')).toBe(sha256Of(src));+ const complete = sent.at(-1);+ expect(complete).toBeInstanceOf(CompleteMultipartUploadCommand);+ expect(complete.input.UploadId).toBe('upload-a');+ expect(complete.input.MultipartUpload.Parts).toEqual([+ { PartNumber: 1, ETag: '"etag-1"' },+ { PartNumber: 2, ETag: '"etag-2"' },+ { PartNumber: 3, ETag: '"etag-3"' },+ ]);+ });++ test('a failed part aborts the multipart upload and surfaces the part error', async () => {+ const src = join(workDir, 's3-abort.bin');+ writePatterned(src, 2 * S3_PART + 7);+ const { client, sent } = s3Stub((command) => {+ if (command instanceof CreateMultipartUploadCommand) return { UploadId: 'upload-b' };+ if (command instanceof UploadPartCommand && command.input.PartNumber === 2) throw new Error('part 2 rejected');+ if (command instanceof UploadPartCommand) return { ETag: '"e"' };+ if (command instanceof AbortMultipartUploadCommand) throw new Error('abort also failed');+ return {};+ });+ await expect(new S3Storage({ backend: 's3', bucket: 'originals' }, client).uploadFile('media/s3-abort.bin', src))+ .rejects.toThrow('part 2 rejected');+ const abort = sent.at(-1);+ expect(abort).toBeInstanceOf(AbortMultipartUploadCommand);+ expect(abort.input).toEqual({ Bucket: 'originals', Key: 'media/s3-abort.bin', UploadId: 'upload-b' });+ expect(sent.some(c => c instanceof CompleteMultipartUploadCommand)).toBe(false);+ expect(sent.filter(c => c instanceof UploadPartCommand).length).toBe(2);+ });++ test('a file within one part is a single PutObject with the exact bytes', async () => {+ const src = join(workDir, 's3-small.txt');+ writeFileSync(src, 'small original');+ const { client, sent } = s3Stub(() => ({}));+ await new S3Storage({ backend: 's3', bucket: 'originals' }, client).uploadFile('notes/s3-small.txt', src, 'text/plain');+ expect(sent.length).toBe(1);+ expect(sent[0]).toBeInstanceOf(PutObjectCommand);+ expect(Buffer.from(sent[0].input.Body).toString()).toBe('small original');+ expect(sent[0].input.ContentType).toBe('text/plain');+ });++ test('part size stays within S3 limits: >= 5 MiB, <= 5 GiB, at most 10,000 parts', () => {+ expect(multipartPartSize(33 * MiB)).toBe(S3_PART);+ for (const size of [22 * GiB, 1024 * GiB, 5 * 1024 * GiB, 10_000 * 5 * GiB]) {+ const part = multipartPartSize(size);+ expect(part).toBeGreaterThanOrEqual(5 * MiB);+ expect(part).toBeLessThanOrEqual(5 * GiB);+ expect(Math.ceil(size / part)).toBeLessThanOrEqual(10_000);+ }+ expect(() => multipartPartSize(10_000 * 5 * GiB + 1)).toThrow();+ });+});++describe('Supabase uploadFile (#7427)', () => {+ test('a TUS-sized file is sent in bounded chunks read from disk', async () => {+ const src = join(workDir, 'supabase-large.bin');+ const size = 100 * MiB + 3 * MiB + 5;+ writeFileSync(src, '');+ truncateSync(src, size);+ const fd = openSync(src, 'r+');+ for (let offset = 0, i = 1; offset < size; offset += 7 * MiB, i++) writeSync(fd, Buffer.alloc(4096, i), 0, 4096, offset);+ closeSync(fd);++ const received = createHash('sha256');+ const patches: { length: number; allocation: number }[] = [];+ let uploadLength = '';+ const fetchImpl = async (_url: string, init: RequestInit) => {+ const headers = init.headers as Record<string, string>;+ if (init.method === 'POST') {+ uploadLength = headers['Upload-Length'];+ return new Response(null, { status: 201, headers: { Location: 'https://example.test/tus/1' } });+ }+ const body = init.body as Uint8Array;+ patches.push({ length: body.byteLength, allocation: body.buffer.byteLength });+ received.update(body);+ return new Response(null, { status: 204, headers: { 'Upload-Offset': String(Number(headers['Upload-Offset']) + body.byteLength) } });+ };+ const watch = watchWholeFileReads([src]);+ try {+ const storage = new SupabaseStorage({ backend: 'supabase', bucket: 'b', projectUrl: 'https://example.test', serviceRoleKey: 'k' }, fetchImpl);+ await storage.uploadFile('media/supabase-large.bin', src, 'video/mp4');+ expect(watch.reads()).toEqual([]);+ } finally {+ watch.restore();+ }+ expect(uploadLength).toBe(String(size));+ expect(patches.reduce((n, p) => n + p.length, 0)).toBe(size);+ for (const p of patches) {+ expect(p.length).toBeLessThanOrEqual(TUS_CHUNK);+ expect(p.allocation).toBeLessThanOrEqual(TUS_CHUNK);+ }+ expect(received.digest('hex')).toBe(sha256Of(src));+ });+});++describe('local uploadFile (#7427)', () => {+ test('copies the original without a whole-file read', async () => {+ const src = join(workDir, 'local-src.bin');+ writePatterned(src, 3 * MiB + 1);+ const storageDir = mkdtempSync(join(tmpdir(), 'gb-7427-local-'));+ const watch = watchWholeFileReads([src]);+ try {+ await new LocalStorage(storageDir).uploadFile('media/local-src.bin', src);+ expect(watch.reads()).toEqual([]);+ } finally {+ watch.restore();+ }+ expect(sha256Of(join(storageDir, 'media/local-src.bin'))).toBe(sha256Of(src));+ rmSync(storageDir, { recursive: true, force: true });+ });+});++describe('upload callers hash and upload from disk (#7427)', () => {+ test('file_upload never reads the whole original', async () => {+ const storageDir = mkdtempSync(join(tmpdir(), 'gb-7427-op-'));+ const src = join(workDir, 'op-original.mp4');+ writePatterned(src, 2 * MiB + 3);+ const ctx = {+ engine,+ config: { engine: 'pglite', storage: { backend: 'local', bucket: 'b', localPath: storageDir } },+ logger: { info() {}, warn() {}, error() {} },+ dryRun: false,+ remote: false,+ sourceId: 'default',+ } as never;+ const watch = watchWholeFileReads([src]);+ let out: { status: string; storage_path: string };+ try {+ out = await operationsByName['file_upload'].handler(ctx, { path: src, page_slug: 'media/op-example' }) as typeof out;+ expect(watch.reads()).toEqual([]);+ } finally {+ watch.restore();+ }+ expect(out.status).toBe('uploaded');+ expect(sha256Of(join(storageDir, out.storage_path))).toBe(sha256Of(src));+ const rows = await engine.executeRaw<{ content_hash: string }>(+ 'SELECT content_hash FROM files WHERE storage_path = $1', [out.storage_path],+ );+ expect(rows[0].content_hash).toBe(sha256Of(src));+ rmSync(storageDir, { recursive: true, force: true });+ });++ test('gbrain files upload, upload-raw, sync and mirror never read the whole original', async () => {+ const home = mkdtempSync(join(tmpdir(), 'gb-7427-home-'));+ const storageDir = mkdtempSync(join(tmpdir(), 'gb-7427-cli-'));+ mkdirSync(join(home, '.gbrain'), { recursive: true });+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({+ engine: 'pglite',+ storage: { backend: 'local', bucket: 'b', localPath: storageDir },+ }));+ const single = join(workDir, 'cli-single.mp4');+ writePatterned(single, MiB + 11);+ const syncDir = join(workDir, 'cli-sync');+ const mirrorDir = join(workDir, 'cli-mirror');+ mkdirSync(join(syncDir, 'media'), { recursive: true });+ mkdirSync(mirrorDir, { recursive: true });+ const synced = join(syncDir, 'media', 'clip.mp4');+ const mirrored = join(mirrorDir, 'clip.mp4');+ writePatterned(synced, MiB + 13);+ writePatterned(mirrored, MiB + 17);++ const watch = watchWholeFileReads([single, synced, mirrored]);+ try {+ await withEnv({ GBRAIN_HOME: home }, async () => {+ await runFiles(engine, ['upload', single, '--page', 'media/cli-example']);+ await runFiles(engine, ['upload-raw', single, '--page', 'media/raw-example', '--no-pointer']);+ await runFiles(engine, ['sync', syncDir]);+ await runFiles(engine, ['mirror', mirrorDir]);+ });+ expect(watch.reads()).toEqual([]);+ } finally {+ watch.restore();+ }+ expect(sha256Of(join(storageDir, 'media/cli-example/cli-single.mp4'))).toBe(sha256Of(single));+ expect(sha256Of(join(storageDir, 'media/raw-example/cli-single.mp4'))).toBe(sha256Of(single));+ expect(sha256Of(join(storageDir, 'media/clip.mp4'))).toBe(sha256Of(synced));+ expect(existsSync(join(storageDir, 'clip.mp4'))).toBe(true);+ expect(sha256Of(join(storageDir, 'clip.mp4'))).toBe(sha256Of(mirrored));+ rmSync(home, { recursive: true, force: true });+ rmSync(storageDir, { recursive: true, force: true });+ });+});