diff --git a/README.md b/README.md index 4f70992..052dd94 100644 --- a/README.md +++ b/README.md @@ -118,11 +118,18 @@ cleanup. Any problem exits non-zero and writes no tiles: a missing/unreadable so unsupported or multi-frame image, a scene other than 1, a tile size that is not a multiple of the cell, a malformed state DB, or a server still holding the state-dir lock (exit 3). +Slicing streams: one ImageMagick decode of the source supplies raw row bands, and a small pool of +`magick` children cuts one tile row each (live caches and file descriptors are bounded by the worker +count, never by the tile count). A long import reports where it is on stderr, e.g. +`rows 128/256, tiles 32768/65536`; a failure prints the image, the row band and ImageMagick's own +message. + **A 16384 px scene with 50 tokens (the phone-playtest target).** 1. Prepare a 16384×16384 PNG or WebP. `--tile-size=64` is the designed fallback and gives 256×256 = - 65,536 tiles (32 px would give 262,144 files); ImageMagick keeps the source in a disk-backed - pixel cache, so allow temp space and a few minutes rather than gigabytes of RAM. + 65,536 tiles (32 px would give 262,144 files). On this 16-core box such an import takes about + 20 s and peaks near 400 MB RSS (the old one-shot crop died at 4-8 GB and 65k fds, #83); the + decode still uses ImageMagick's disk-backed pixel cache, so allow a few GB of temp space. 2. Start with the import in one step: `devbox run serve -- --image=run/map16384.png --tile-size=64` (or stop the server, run `fff-vtt import` as above, then restart it). 3. Create the 50 tokens with the seeding tool, not 50 panel submits (a rerun does not double up): @@ -318,6 +325,7 @@ panel); it needs USB debugging, the overlay does not. | `devbox run mutation` | mutation suite on a temp copy of `server/`, `tests/`, `tools/`: every seeded mutation must fail at least one test | | `devbox run bench` | release-build bench of the vision and egress paths, writing `results/bench.log` | | `devbox run fogbench` | the 50-token / 16384 px server measurement, writing `results/m4-fog-bench.log`; the numbers live in `results/m4-fog-bench.md` | +| `devbox run import-scale` | the map import at target scale: 16384×16384 at 64 px (65,536 tiles) under a 256-fd limit, asserting bounded RSS/fds and progress, writing `results/import-scale.log`; ~25 s, too slow for the pre-push gate (`test` skips it) | | `devbox run -- nimble install -d -y` | install/refresh the pinned Nim dependencies | | `devbox run -- bash -c 'cd client && npm ci && npm run dev'` | Vite dev server on :5173 — the UI only, no server API behind it | diff --git a/devbox.json b/devbox.json index 3416205..6d0ac60 100644 --- a/devbox.json +++ b/devbox.json @@ -44,6 +44,9 @@ "bench": [ "mkdir -p results; nim c -d:release --hints:off -r tools/bench.nim > results/bench.log 2>&1; rc=$?; cat results/bench.log; exit $rc" ], + "import-scale": [ + "mkdir -p results; IMPORT_SCALE=1 node --test --test-concurrency=1 --test-reporter=spec tools/importscale.test.mjs > results/import-scale.log 2>&1; rc=$?; cat results/import-scale.log; exit $rc" + ], "fogbench": [ "mkdir -p results; nim c -d:release --hints:off -o:run/test/fogbench tools/fogbench.nim > results/m4-fog-bench.log 2>&1 && ./run/test/fogbench >> results/m4-fog-bench.log 2>&1; rc=$?; cat results/m4-fog-bench.log; exit $rc" ] diff --git a/results/import-scale.log b/results/import-scale.log new file mode 100644 index 0000000..283cd72 --- /dev/null +++ b/results/import-scale.log @@ -0,0 +1,10 @@ +# scale: gen=2515ms import=15259ms peakRSS=486MiB peakFds=71 peakProcs=10 tiles=65536 +✔ map import CLI: 16384 px source at 64 px stays memory- and fd-bounded (#83) (21279.293203ms) +ℹ tests 1 +ℹ suites 0 +ℹ pass 1 +ℹ fail 0 +ℹ cancelled 0 +ℹ skipped 0 +ℹ todo 0 +ℹ duration_ms 21545.730115 diff --git a/server/importer.nim b/server/importer.nim index 19bc71f..9c3786a 100644 --- a/server/importer.nim +++ b/server/importer.nim @@ -10,11 +10,16 @@ ## ## Decoding is delegated to ImageMagick (`magick` from the root devbox, `imagemagick`), the one ## reviewed source of PNG/WebP codecs here: a 16384 px source is far too large for a whole-image -## decoder in this process (Q16-HDRI stores it in ImageMagick's *disk-backed* pixel cache under the -## explicit `-limit memory/-limit map` below, so RSS stays bounded). No Nim or npm image dependency -## is added; the FIXED stack of DESIGN 2 is unchanged, and `tools/` keeps its built-ins-only rule -## (TESTING 10.4). The tile layout the gate parses is produced here, not by the prototype's -## deterministic fixture generator. +## decoder in this process. A single `-crop 64x64 +adjoin` over the source materialises all 65,536 +## tiles in one image list, and `-limit memory/-limit map` are *per image*, so that attempt needed +## 4.3 GB RSS and 65k file descriptors and died with "Too many open files" (#83). Slicing therefore +## streams: one `magick` decodes the source to raw samples (its own pixel cache is disk-backed under +## the `-limit` flags below, so RSS stays ~50 MB), this process reads it one tile row at a time and +## hands that band to a small pool of `magick` children, each of which only ever holds a single row +## band. Live caches and fds are bounded by the worker count, never by the tile count. No Nim or npm +## image dependency is added; the FIXED stack of DESIGN 2 is unchanged, and `tools/` keeps its +## built-ins-only rule (TESTING 10.4). The tile layout the gate parses is produced here, not by the +## prototype's deterministic fixture generator. import std/[math, options, os, osproc, streams, strutils, times] import db_connector/db_sqlite import config, db, instancelock, world @@ -22,6 +27,14 @@ import config, db, instancelock, world const ImportedFormats* = ["PNG", "WEBP"] ## Source formats accepted by the CLI. Output tiles are always PNG (the gate's URL suffix). + SliceCacheLimit = "32MiB" + ## Per-image pixel-cache RAM cap for every `magick` of the slice. Large images spill to + ## ImageMagick's disk cache instead of growing RSS (#83). + MaxSliceWorkers = 8 + ## Child `magick` count of the slice: half a 16-core box, and never more than the band count. + MaxBandBytes = 32 * 1024 * 1024 + ## Largest tile row handed to one child. A row band above this (a very large `--tile-size` on a + ## wide source) falls back to the one-shot crop, whose image list is then small by construction. ImportUsage* = """fff-vtt import --image= [options] Slice a map image into the scene's tile tree and register the scene dimensions. @@ -117,6 +130,157 @@ proc lastLine(s: string): string = var lines = s.strip.splitLines if lines.len == 0: "" else: lines[^1] +type + SlicePlan = object + ## How the decoded source is handed to the children as raw samples: the channel set follows + ## the source's own type, so a plain RGB image still produces plain RGB tiles and an image with + ## alpha keeps its alpha channel (pixel-identical tiles to the one-shot crop; PNG bytes can + ## differ because the encoder sees raw samples instead of a decoded image's properties). + rawSpec: string + channels: int + sampleDepth: int + +proc slicePlan(imgType: string, srcDepth: int): SlicePlan = + let t = imgType.toLowerAscii + let alpha = t.endsWith("alpha") + let gray = t.startsWith("gray") or t.startsWith("bilevel") + result.sampleDepth = if srcDepth > 8: 16 else: 8 + result.channels = (if gray: 1 else: 3) + (if alpha: 1 else: 0) + result.rawSpec = + if gray: (if alpha: "graya:" else: "gray:") + else: (if alpha: "rgba:" else: "rgb:") + +proc removeBands(dir: string) = + ## Row bands are one-shot scratch files next to the tile temp dir: files first, then the dir. + if not dirExists(dir): return + for kind, path in walkDir(dir): + if kind in {pcFile, pcLinkToFile}: + try: removeFile(path) + except OSError: discard + try: removeDir(dir) + except OSError: discard + +proc sliceRows(imagePath, tempDir: string, imgW, imgH, tileSize, cols, rows: int, + plan: SlicePlan): tuple[rc: int, message: string] = + ## Stream the source once and cut one tile row (a band) per child `magick`, so live pixel caches + ## stay bounded by the worker count and the fd count does not follow the tile count (#83). The + ## decoder's own cache is disk-backed (`SliceCacheLimit`), a band file is a few MB, and every + ## child only ever holds one band. Tiles are written as `tile_.png`; the caller + ## renames them to the `_.png` gate grammar. + let sampleBytes = plan.sampleDepth div 8 + let bandStride = imgW * plan.channels * sampleBytes + let workers = max(1, min(MaxSliceWorkers, min(countProcessors() div 2, rows))) + let total = cols * rows + let progressStep = max(1, rows div 20) + let bandDir = tempDir & "-bands" + + stderr.writeLine "fff-vtt import: slicing " & $imgW & "x" & $imgH & " into " & $total & + " tiles at " & $tileSize & " px (" & $workers & " workers)" + removeBands(bandDir) + try: createDir(bandDir) + except OSError as e: + return (1, "cannot create scratch directory " & bandDir & ": " & e.msg) + + let decode = try: + startProcess("magick", options = {poUsePath}, args = @[ + "-limit", "memory", SliceCacheLimit, "-limit", "map", SliceCacheLimit, + imagePath, "-depth", $plan.sampleDepth, plan.rawSpec & "-"]) + except OSError as e: + removeBands(bandDir) + return (1, "cannot run ImageMagick (magick): " & e.msg & "; run inside devbox") + + var buf = newString(bandStride * tileSize) + var busy: seq[tuple[p: Process, row: int]] + + proc reap(w: var tuple[p: Process, row: int]): int = + ## Reap one child (its stderr already went straight to ours) and drop its band file. + result = try: w.p.waitForExit() except CatchableError: -1 + w.p.close() + try: removeFile(bandDir / ("band_" & $w.row & ".raw")) + except OSError: discard + + proc abortChildren() = + for i in 0 ..< busy.len: + try: busy[i].p.terminate() + except CatchableError: discard + discard reap(busy[i]) + busy.setLen(0) + + var row = 0 + var handed = 0 + var failure = "" + var gotShort = false + while row < rows and failure.len == 0: + let bandH = min(tileSize, imgH - row * tileSize) + let want = bandStride * bandH + var got = 0 + while got < want: + var n = 0 + try: + n = decode.outputStream.readData(addr buf[got], want - got) + except CatchableError: + n = 0 + if n <= 0: break + got += n + if got < want: + gotShort = true + failure = "the decoder stopped after " & $got & " of " & $want & " bytes of row band " & + $row & " (source " & $imgW & "x" & $imgH & ")" + break + + if busy.len >= workers: + var w = busy[0] + busy.delete(0) + if reap(w) != 0: + failure = "magick failed on the tiles of row " & $w.row & " (its message is above)" + break + + let bandFile = bandDir / ("band_" & $row & ".raw") + try: + writeFile(bandFile, buf[0 ..< want]) + except IOError as e: + failure = "cannot write row band " & $row & ": " & e.msg + break + let child = try: + # poParentStreams: the child needs no pipes at all (it reads the band file and writes tiles), + # so every magick's stderr lands on ours and no descriptors are inherited per child. + startProcess("magick", options = {poUsePath, poParentStreams}, args = @[ + "-size", $imgW & "x" & $bandH, "-depth", $plan.sampleDepth, plan.rawSpec & bandFile, + "-crop", $tileSize & "x" & $tileSize, "+repage", "+adjoin", + "-scene", $(row * cols), tempDir / "tile_%d.png"]) + except OSError as e: + failure = "cannot run ImageMagick (magick): " & e.msg & "; run inside devbox" + break + busy.add((child, row)) + handed += cols + if (row + 1) mod progressStep == 0 or row + 1 == rows: + stderr.writeLine "fff-vtt import: rows " & $(row + 1) & "/" & $rows & ", tiles " & + $min(handed, total) & "/" & $total + inc row + + # Every child must be reaped (and its status checked) before the tile tree is trusted. + while busy.len > 0 and failure.len == 0: + var w = busy[0] + busy.delete(0) + if reap(w) != 0: + failure = "magick failed on the tiles of row " & $w.row & " (its message is above)" + if failure.len > 0: + abortChildren() + + # The decoder's own exit status matters even when every band arrived: a corrupt tail is exactly + # the case where the band loop stops short, and the error text lives on its stderr. + let decodeErr = try: decode.errorStream.readAll() except CatchableError: "" + let decodeRc = try: decode.waitForExit() except CatchableError: -1 + decode.close() + removeBands(bandDir) + if failure.len == 0 and decodeRc != 0: + failure = "magick failed to decode \"" & imagePath & "\": " & lastLine(decodeErr) + elif failure.len > 0 and gotShort and decodeErr.len > 0: + # A short read is the decoder's failure: quote its own last line, not just our byte count. + failure.add ": " & lastLine(decodeErr) + if failure.len > 0: return (1, failure) + (0, "") + proc removeTemp(dir: string) = ## The slice temp dir holds only files (ImageMagick `+adjoin`); no recursive delete is needed. if not dirExists(dir): return @@ -150,26 +314,29 @@ proc runImport*(rawArgs: seq[string]): int = return failImport("source image \"" & a.image & "\" does not exist", 1) let imagePath = expandFilename(a.image) - # Identify: dimensions and one format only. Multi-frame input (animated PNG/WebP) would break the - # one-tile-per-coordinate tree, so it is refused rather than silently importing frame zero. - let ident = runMagick(@["identify", "-ping", "-format", "%w %h %m", imagePath]) + # Identify: dimensions, one format, and the sample layout the streaming slice feeds raw to + # `magick` (type/depth). Multi-frame input (animated PNG/WebP) would break the one-tile-per- + # coordinate tree, so it is refused rather than silently importing frame zero. + let ident = runMagick(@["identify", "-ping", "-format", "%w %h %m %[type] %z", imagePath]) if ident.status != 0: return failImport("cannot read image \"" & a.image & "\": " & lastLine(ident.output), 1) let parts = ident.output.splitWhitespace - if parts.len != 3: + if parts.len != 5: return failImport("multi-frame image \"" & a.image & "\" is not supported; import a single-frame PNG or WebP", 2) if parts[2].toUpperAscii notin ImportedFormats: return failImport("unsupported format " & parts[2] & ": the source must be PNG or WebP (tiles are always PNG)", 2) - var imgW, imgH: int + var imgW, imgH, srcDepth: int try: imgW = parseInt(parts[0]) imgH = parseInt(parts[1]) + srcDepth = parseInt(parts[4]) except ValueError: return failImport("cannot read image dimensions from \"" & a.image & "\"", 1) if imgW <= 0 or imgH <= 0: return failImport("image \"" & a.image & "\" has no pixels", 1) + let plan = slicePlan(parts[3], srcDepth) # A fresh or empty state dir is the normal case (#82): create and migrate through the same # startup path as the server, under the same state-dir lock. The lock is taken before the DB is @@ -238,17 +405,26 @@ proc runImport*(rawArgs: seq[string]): int = except OSError as e: return failImport("cannot create temporary tile directory " & tempDir & ": " & e.msg, 1) - # Memory-sane slicing (DESIGN 11.1): 256 MiB heap and a 512 MiB map cap push ImageMagick's pixel - # cache to disk, so a 16384 px source never needs a whole-image buffer in RAM. `-crop` with - # `+repage` emits tiles in row-major order; `tile_%d.png` is renamed below to the gate's exact - # `_.png` spelling (no leading zeros). - let crop = $tileSize & "x" & $tileSize - let sliced = runMagick(@["-limit", "memory", "256MiB", "-limit", "map", "512MiB", - imagePath, "-crop", crop, "+repage", "+adjoin", "tile_%d.png"], - tempDir) - if sliced.status != 0: - removeTemp(tempDir) - return failImport("magick failed to slice \"" & a.image & "\": " & lastLine(sliced.output), 1) + # Memory-sane slicing (DESIGN 11.1, #83). A single `-crop tile +adjoin` over a 16384 px source + # builds one image list of every tile and dies on fds/memory, so the normal path streams: one + # decode to raw samples, then one row band per child `magick` (bounded caches, bounded fds, and + # progress on stderr). Only a source whose single tile row is itself huge falls back to the + # one-shot crop, where the tile list is small by construction. `tile_%d.png` names use the global + # scene index, so the rename below to `_.png` is the same for both paths. + let bandBytes = imgW * plan.channels * (plan.sampleDepth div 8) * tileSize + if bandBytes <= MaxBandBytes: + let streamed = sliceRows(imagePath, tempDir, imgW, imgH, tileSize, cols, rows, plan) + if streamed.rc != 0: + removeTemp(tempDir) + return failImport(streamed.message, 1) + else: + let crop = $tileSize & "x" & $tileSize + let sliced = runMagick(@["-limit", "memory", "256MiB", "-limit", "map", "512MiB", + imagePath, "-crop", crop, "+repage", "+adjoin", "tile_%d.png"], + tempDir) + if sliced.status != 0: + removeTemp(tempDir) + return failImport("magick failed to slice \"" & a.image & "\": " & lastLine(sliced.output), 1) for i in 0 ..< cols * rows: let src = tempDir / ("tile_" & $i & ".png") diff --git a/tools/import.test.mjs b/tools/import.test.mjs index c4b4246..a3c5449 100644 --- a/tools/import.test.mjs +++ b/tools/import.test.mjs @@ -78,6 +78,11 @@ test('map import CLI: a fixture slices into v1 tiles, the scene row and a 200 th const first = runImport(stateDir, [`--image=${img}`, '--tile-size=64']) assert.equal(first.status, 0, first.stderr) assert.match(first.stdout, /256x192 px, tile 64 px, 4x3 tiles/) + // #83: a long import must say where it is, and the streamed slice reports one line per row + // band (the old one-shot crop printed nothing for minutes and looked hung). + assert.match(first.stderr, /slicing 256x192 into 12 tiles at 64 px/) + assert.match(first.stderr, /rows 1\/3, tiles 4\/12/) + assert.match(first.stderr, /rows 3\/3, tiles 12\/12/) const dir1 = path.join(stateDir, 'tiles', '1', 'v1') const names = tileNames(dir1) assert.deepEqual(names, [ @@ -136,6 +141,77 @@ test('map import CLI: a fixture slices into v1 tiles, the scene row and a 200 th } }) +test('map import CLI: the streamed slice matches the one-shot crop pixel for pixel (#83)', () => { + // The #83 fix replaces one `-crop` over the whole source with one raw row band per child + // `magick`. The tile tree must be unchanged: same pixels in the same `_.png` files, for + // every source shape the CLI accepts. The reference is the old one-shot command itself. + const stateDir = makeStateDir() + try { + const magickRun = args => spawnSync('magick', args, { encoding: 'utf8' }) + const cases = [ + ['rgb8-exact', 256, 192, f => fs.writeFileSync( + f, pngBytesWH(256, 192, (x, y) => [x & 0xff, y & 0xff, (x * y) & 0xff]))], + ['rgb8-partial-edges', 250, 190, f => fs.writeFileSync( + f, pngBytesWH(250, 190, (x, y) => [x & 0xff, y & 0xff, 128]))], + ['rgb16', null, null, f => magickRun(['-size', '130x300', 'gradient:blue-yellow', + '-depth', '16', f])], + ['rgba8', null, null, f => magickRun(['-size', '100x100', 'plasma:fractal', + '-alpha', 'set', '-channel', 'A', '-evaluate', + 'set', '60%', '+channel', 'PNG32:' + f])], + ['gray8', null, null, f => magickRun(['-size', '64x96', 'gradient:', + '-colorspace', 'gray', '-depth', '8', f])], + ] + for (const [name, w, h, make] of cases) { + const img = path.join(stateDir, `${name}.png`) + make(img) + const dims = w && h ? { width: w, height: h } : pngSize(img) + const state = path.join(stateDir, name) + const imported = runImport(state, [`--image=${img}`, '--tile-size=64']) + assert.equal(imported.status, 0, `${name}: ${imported.stderr}`) + const ref = fs.mkdtempSync(path.join(stateDir, 'ref-')) + const oneShot = magickRun([img, '-crop', '64x64', '+repage', '+adjoin', + path.join(ref, 'tile_%d.png')]) + assert.equal(oneShot.status, 0, oneShot.stderr) + const cols = Math.ceil(dims.width / 64) + const rows = Math.ceil(dims.height / 64) + for (let i = 0; i < cols * rows; i++) { + const x = i % cols + const y = (i / cols) | 0 + const got = path.join(state, 'tiles', '1', 'v1', `${x}_${y}.png`) + const want = path.join(ref, `tile_${i}.png`) + assert.equal(fs.existsSync(got), true, `${name}: tile ${x}_${y} exists`) + const same = magickRun(['compare', '-metric', 'AE', got, want, 'null:']) + assert.equal(same.status, 0, + `${name}: tile ${x}_${y} must be pixel-identical to the one-shot crop: ${same.stderr}`) + } + assert.equal(fs.readdirSync(path.join(state, 'tiles', '1', 'v1')).filter(n => n.endsWith('.png')).length, + cols * rows, `${name}: exactly the grid's tiles`) + } + } finally { + fs.rmSync(stateDir, { recursive: true, force: true }) + } +}) + +test('map import CLI: a truncated source fails loudly and publishes nothing (#83)', () => { + // The streaming path reads the decoder's stdout band by band; a decode that dies mid-stream must + // surface magick's own message, not an empty tile tree or a byte-count mystery. + const stateDir = makeStateDir() + try { + const img = path.join(stateDir, 'truncated.png') + const full = pngBytesWH(256, 192, (x, y) => [x & 0xff, y & 0xff, 0]) + fs.writeFileSync(img, full.subarray(0, full.length - 40)) + const r = runImport(stateDir, [`--image=${img}`, '--tile-size=64']) + assert.notEqual(r.status, 0, 'a truncated source must not import') + assert.match(r.stderr, /cannot read image|decoder stopped|magick failed to decode/) + assert.equal(fs.existsSync(path.join(stateDir, 'tiles', '1', 'v1')), false, + 'nothing is published') + assert.equal(fs.readdirSync(path.join(stateDir, 'tiles', '1')) + .some(n => n.startsWith('.import-')), false, 'no temp or band directory is left behind') + } finally { + fs.rmSync(stateDir, { recursive: true, force: true }) + } +}) + test('map import CLI: a fresh/empty state dir is created, migrated and servable (#82)', async () => { const root = makeStateDir() diff --git a/tools/importscale.test.mjs b/tools/importscale.test.mjs new file mode 100644 index 0000000..61fdfd2 --- /dev/null +++ b/tools/importscale.test.mjs @@ -0,0 +1,181 @@ +// #83: the map import at the real target scale — a 16384x16384 source at tile size 64, i.e. 65,536 +// tiles. The one-shot `-crop ... +adjoin` this replaces died here with "Too many open files" after +// minutes at 4-8 GB RSS, so this gate is the regression proof: bounded memory, bounded file +// descriptors (it runs under a low `ulimit -n`), a streamed progress trail, and the full tile tree. +// +// It is deliberately NOT part of `devbox run test`: generating the source and writing 65,536 PNGs +// takes ~40 s on a 16-core box. `devbox run import-scale` runs it and leaves results/import-scale.log. +import test from 'node:test' +import assert from 'node:assert/strict' +import fs from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import zlib from 'node:zlib' +import { spawn, spawnSync } from 'node:child_process' +import { buildServer, gmKeyOf, makeStateDir } from './withserver.mjs' +import { pngSize } from './tilefixture.mjs' + +const enabled = process.env.IMPORT_SCALE === '1' +const SIDE = 16384 +const TILE = 64 +const TILE_COUNT = (SIDE / TILE) ** 2 + +const CRC_TABLE = (() => { + const table = new Int32Array(256) + for (let n = 0; n < 256; n++) { + let c = n + for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1 + table[n] = c + } + return table +})() + +function crc32(buf) { + let c = 0xffffffff + for (let i = 0; i < buf.length; i++) c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8) + return (c ^ 0xffffffff) >>> 0 +} + +// A real SIDE x SIDE 8-bit RGB PNG, written streaming so generating it costs seconds and a few MB +// of RSS (the coordinate colours make every tile distinct without making the file huge). +function writeScaleImage(file) { + const fd = fs.openSync(file, 'w') + const chunk = (type, data) => { + const head = Buffer.alloc(8) + head.writeUInt32BE(data.length) + head.write(type, 4, 'latin1') + const crc = Buffer.alloc(4) + crc.writeUInt32BE(crc32(Buffer.concat([Buffer.from(type, 'latin1'), data]))) + fs.writeSync(fd, Buffer.concat([head, data, crc])) + } + fs.writeSync(fd, Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) + const ihdr = Buffer.alloc(13) + ihdr.writeUInt32BE(SIDE, 0) + ihdr.writeUInt32BE(SIDE, 4) + ihdr[8] = 8 + ihdr[9] = 2 // truecolour RGB + chunk('IHDR', ihdr) + const deflate = zlib.createDeflate({ level: 1 }) + let pending = [] + deflate.on('data', d => pending.push(d)) + let y = 0 + while (y < SIDE) { + // A batch of rows per drain keeps the event loop out of the per-row path. + for (let n = 0; n < 64 && y < SIDE; n++, y++) { + const row = Buffer.alloc(1 + SIDE * 3) + for (let x = 0; x < SIDE; x++) { + row[1 + x * 3] = x & 0xff + row[2 + x * 3] = y & 0xff + row[3 + x * 3] = 128 + } + deflate.write(row) + } + if (pending.reduce((a, b) => a + b.length, 0) > 8 * 1024 * 1024) { + chunk('IDAT', Buffer.concat(pending)) + pending = [] + } + } + deflate.end() + return new Promise(resolve => deflate.on('end', () => { + if (pending.length) chunk('IDAT', Buffer.concat(pending)) + chunk('IEND', Buffer.alloc(0)) + fs.closeSync(fd) + resolve(file) + })) +} + +function childrenOf(pid) { + try { + return fs.readFileSync(`/proc/${pid}/task/${pid}/children`, 'utf8').trim().split(/\s+/) + .filter(Boolean).map(Number) + } catch { + return [] + } +} + +function treeOf(pid) { + const out = [pid] + for (const child of childrenOf(pid)) out.push(...treeOf(child)) + return out +} + +// Sample the process tree's total RSS and open descriptors while the import runs. The import is +// spawned under a deliberately small `ulimit -n`, so the old design could not even get this far. +async function runMeasured(args, ulimitN) { + const started = Date.now() + const child = spawn('bash', ['-c', `ulimit -n ${ulimitN}; exec "$@"`, 'bash', ...args], + { stdio: ['ignore', 'pipe', 'pipe'] }) + let stdout = '' + let stderr = '' + child.stdout.on('data', d => { stdout += d }) + child.stderr.on('data', d => { stderr += d }) + let peakRssKiB = 0 + let peakFds = 0 + let peakProcs = 0 + const timer = setInterval(() => { + let rss = 0 + let fds = 0 + const tree = treeOf(child.pid) + for (const pid of tree) { + try { + const status = fs.readFileSync(`/proc/${pid}/status`, 'utf8') + const m = status.match(/VmRSS:\s+(\d+) kB/) + if (m) rss += Number(m[1]) + fds += fs.readdirSync(`/proc/${pid}/fd`).length + } catch { /* the process exited between listing and reading */ } + } + peakRssKiB = Math.max(peakRssKiB, rss) + peakFds = Math.max(peakFds, fds) + peakProcs = Math.max(peakProcs, tree.length) + }, 100) + const status = await new Promise(resolve => child.on('close', resolve)) + clearInterval(timer) + return { status, stdout, stderr, ms: Date.now() - started, peakRssMiB: peakRssKiB / 1024, + peakFds, peakProcs } +} + +test('map import CLI: 16384 px source at 64 px stays memory- and fd-bounded (#83)', + { skip: enabled ? false : 'scale test: run `devbox run import-scale`' }, async () => { + const stateDir = makeStateDir() + const img = path.join(stateDir, 'map16384.png') + try { + const genStart = Date.now() + await writeScaleImage(img) + const genMs = Date.now() - genStart + assert.deepEqual(pngSize(img), { width: SIDE, height: SIDE }) + + const run = await runMeasured( + [buildServer(), 'import', `--state-dir=${stateDir}`, `--image=${img}`, `--tile-size=${TILE}`], + 256) + const dir = path.join(stateDir, 'tiles', '1', 'v1') + const tiles = fs.existsSync(dir) ? fs.readdirSync(dir).filter(n => n.endsWith('.png')) : [] + // One diagnostic line so `devbox run import-scale` leaves usable evidence in results/. + console.log(`# scale: gen=${genMs}ms import=${run.ms}ms peakRSS=${run.peakRssMiB.toFixed(0)}MiB ` + + `peakFds=${run.peakFds} peakProcs=${run.peakProcs} tiles=${tiles.length}`) + + assert.equal(run.status, 0, run.stderr) + assert.equal(tiles.length, TILE_COUNT, 'every tile of the 256x256 grid exists') + assert.match(fs.readFileSync(`${dir}/0_0.png`).slice(0, 8).toString('latin1'), /^\x89PNG/, + 'tiles are PNGs') + assert.deepEqual(pngSize(`${dir}/255_255.png`), { width: TILE, height: TILE }) + assert.deepEqual(pngSize(`${dir}/255_0.png`), { width: TILE, height: TILE }) + + // Progress must be visible while it runs, not only at the end. + assert.match(run.stderr, /slicing 16384x16384 into 65536 tiles at 64 px/) + assert.match(run.stderr, /rows 12\/256, tiles 3072\/65536/) + assert.match(run.stderr, /rows 256\/256, tiles 65536\/65536/) + assert.match(run.stdout, /16384x16384 px, tile 64 px, 256x256 tiles/) + + // The numbers are the point of this gate: 4-8 GB and 1024 fds were the old failure. + assert.ok(run.peakRssMiB < 1024, `peak RSS ${run.peakRssMiB.toFixed(0)} MiB must stay under 1 GiB`) + assert.ok(run.peakFds < 256, `peak fds ${run.peakFds} must stay far under the 256 ulimit`) + assert.ok(run.peakProcs <= 12, `only the importer, one decoder and <=8 children may run (saw ${run.peakProcs})`) + assert.ok(run.ms < 600_000, `a 16384/64 import must finish in minutes, took ${run.ms} ms`) + + assert.equal(fs.readdirSync(path.join(stateDir, 'tiles', '1')) + .some(n => n.startsWith('.import-')), false, 'no temporary directory is left behind') + gmKeyOf(stateDir) // the state dir is a valid, migrated server state dir + } finally { + fs.rmSync(stateDir, { recursive: true, force: true }) + } + })