The owner fixed the map cap at 1920 px on the long side and 1080 px on the short side (either orientation). fff-vtt import now shrinks a larger source with ImageMagick Lanczos before tiling (alpha kept, proportions preserved, no upscaling), prints `scaled WxH -> WxH`, and records the shrunk w/h; a source at or below the cap is untouched, so the pixel-identity tests still hold. A scene row already above the cap is not rewritten: the server logs `map_above_cap` at startup and serve prints the re-import advice. Docs: ADR-0023, DESIGN 3.3/5.3/8/11.1/13/14, TESTING 5.3/13, README, HANDOFF-M4, client README. The M4 phone gate and the fogbench measurement now use the Full HD maximum; the 16384 px / 262144-cell bench and test rows stay as labelled server stress references. import-scale now proves a 16384² input is shrunk to 1080x1080 (289 tiles at 64 px) quickly and bounded. Part of #63, #85. #77 is blocked by this issue.
191 lines
7.9 KiB
JavaScript
191 lines
7.9 KiB
JavaScript
// #83/#85: the map import at the old 16384 px input scale, now under the Full HD cap: the source is
|
||
// shrunk to 1080x1080 before tiling (289 tiles at 64 px, not 65,536). 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: the huge input is shrunk quickly, memory and file
|
||
// descriptors stay bounded (it runs under a low `ulimit -n`), the streamed progress trail appears,
|
||
// and the output tile tree follows the shrunk scene.
|
||
//
|
||
// It is deliberately NOT part of `devbox run test`: generating the 16384 px source takes seconds,
|
||
// and the shrink is real ImageMagick work. `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 OUT = 1080
|
||
const TILE = 64
|
||
const TILE_COUNT = Math.ceil(OUT / 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: a 16384 px source is shrunk to Full HD and stays memory- and fd-bounded (#83, #85)',
|
||
{ 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, 'the shrunk 1080x1080 scene has all 289 tiles at 64 px')
|
||
assert.match(fs.readFileSync(`${dir}/0_0.png`).slice(0, 8).toString('latin1'), /^\x89PNG/,
|
||
'tiles are PNGs')
|
||
assert.deepEqual(pngSize(`${dir}/15_15.png`), { width: TILE, height: TILE })
|
||
assert.deepEqual(pngSize(`${dir}/15_0.png`), { width: TILE, height: TILE })
|
||
assert.deepEqual(pngSize(`${dir}/16_16.png`),
|
||
{ width: OUT - 16 * TILE, height: OUT - 16 * TILE }, 'the last edge tile is 56x56')
|
||
assert.equal(fs.existsSync(`${dir}/255_255.png`), false,
|
||
'the 16384 px grid is gone: the scene is the Full HD shrink')
|
||
|
||
// The shrink itself is reported, then the slice of the shrunk image.
|
||
assert.match(run.stdout, /scaled 16384×16384 → 1080×1080/)
|
||
assert.match(run.stdout, /1080x1080 px, tile 64 px, 17x17 tiles/)
|
||
assert.match(run.stderr, /slicing 1080x1080 into 289 tiles at 64 px/)
|
||
assert.match(run.stderr, /rows 17\/17, tiles 289\/289/)
|
||
|
||
// The numbers are the point of this gate: 4-8 GB and 1024 fds were the old failure, and a
|
||
// 16384 px input used to mean minutes and 65k tiles.
|
||
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 < 180_000, `the huge input must be shrunk and tiled 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 })
|
||
}
|
||
})
|