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:
+197
-21
@@ -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=<path> [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_<global index>.png`; the caller
|
||||
## renames them to the `<x>_<y>.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
|
||||
# `<x>_<y>.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 `<x>_<y>.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")
|
||||
|
||||
Reference in New Issue
Block a user