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()