fix: stream map import so 16384 px at 64 px is memory- and fd-bounded (#83)

The one-shot `magick -crop 64x64 +adjoin` built an image list of all 65,536 tiles; ImageMagick's
memory/map limits are per image, so the attempt held 4.3 GB of source cache plus every tile cache and
died after minutes with "Too many open files" at 1023 fds, having published nothing.

Slice by streaming instead: one disk-cache-backed decode of the source to raw samples, the CLI reads
it one tile row at a time, and a pool of 8 magick children cuts one row band each. Live caches and
fds are bounded by the worker count, never by the tile count. Progress goes to stderr ("rows 37/256,
tiles 9472/65536") and failures quote the image, row band and magick's own message. Atomicity is
unchanged: temp dir then rename, scene row only on success, same lock and exit codes.

Measured on the owner's 16384x16384 map at 64 px: 19 s, 391 MB peak RSS, 10 fds, 65,536 tiles (was
~5 min then failure). The tile pixels are identical to the old crop (proven tile by tile in
tools/import.test.mjs); PNG bytes can differ because the encoder now sees raw samples.

New gate: devbox run import-scale (16384/64 under ulimit -n 256) writes results/import-scale.log;
devbox run test keeps the fast fixtures and skips it.
This commit is contained in:
2026-11-21 20:48:45 +01:00
parent b56d645b3a
commit c8b5289a3d
6 changed files with 477 additions and 23 deletions
+76
View File
@@ -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 `<x>_<y>.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()
+181
View File
@@ -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 })
}
})