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
+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 })
}
})