pbfhogg CLI Reference
Every command, flag and output contract of the pbfhogg binary, as it stands on the main branch (unreleased changes included; CHANGELOG.md says which release brought what). This page is written by hand, not generated: pbfhogg <command> --help gives the short form of each flag, and a test (crates/cli/src/lib.rs, doc_coverage_tests) fails when a visible command, flag or enumerated value of the CLI has no place here.
Older links to the former CLI reference must use this page. The former site fragments #index-verifying-blob-level-metadata and #locations-verifying-inline-way-locations are now #index-verification and #inline-location-verification; the former LocationsOnWays maintenance section is the --locations-on-ways section. Old fragments are not forwarded.
Every enumerated flag value (--compression, --type, --index-type, --clean, inspect tags --sort, the bench-* modes) is parsed once at the argument boundary, so a malformed one is a usage error before any input is opened. --help lists the accepted values of the fixed sets (such as --index-type, --clean, --sort and the bench-* modes); the --compression and --type grammars are spelled out below.
--type is one comma-list grammar (node,way,relation, any subset) with a single parser on every command that takes it. A command that acts on one kind (inspect tags) refuses a list of more than one, and export refuses relation (it accepts node, way or node,way); each refusal names what the command accepts.
Global flags
| Flag | Description |
|---|---|
-h, --help | Print help, for pbfhogg or for the command it follows |
-V, --version | Print the version (pbfhogg only) |
-q, --quiet | The exit code is the answer (see Quiet). Accepted before or after the subcommand: pbfhogg -q diff a b and pbfhogg diff a b -q are the same |
Quiet
-q, --quiet means one thing on every command: the exit code is the answer.
- Dropped: every
Note:, every progress line, the command's closing summary (single- or multi-line,apply-changes' block, each region's line ofextract --configand its openingMulti-extract:line,inspect tags'K key rows and P key/value rows counted, ...line), and the developer lines some backends print ([altw external] ..., the geocode builder's hotpath counters). - Kept: every
Warning:and the finalError:line, which explain the exit code, and clap's usage errors. - Never touched: what a command writes to
-o(a quiet run writes the same bytes), and a report a command prints on stdout (inspect,inspect tags,digest,exportwithout-o), with three exceptions:diff,checkandinspect --indexed, whose answer is their exit code, print nothing at all. A quiet textdiffdiscards its diff text, so-o,-c,-vand-s, which only shape that text or its summary, are refused with-q; a quietdiff --format oscwrites its-olike any other command. A quietcheckrefuses--json,--show-idsand--max-errors, and a quietinspect --indexedrefuses--json, for the same reason.getid -vis refused with-q: the ID lists are all it adds.
diff -q and check --quiet used to be flags of those two commands alone; they are this flag now, with the same effect there (and diff --format osc now accepts it).
Exit codes
Every command uses the same contract. 1 is reserved for a command that ran to completion and whose answer is negative; a command that could not run, or could not deliver its output or diagnostics, exits 2, so a script can branch on the answer without swallowing failures. 3 is the one failure split out of 2: a requested platform I/O feature is unavailable, so the same invocation without that flag can succeed. 64 (EX_USAGE) is a command line refused before the command executed, so a mistyped or malformed invocation is never mistaken for a command that ran and refused. 101 is a panic, a defect in pbfhogg, kept apart from 2 so it is never mistaken for a refusal. 130 and 143 are interruptions, following the shell's 128 + signal convention.
| Code | Meaning |
|---|---|
0 | Success. |
1 | The command ran and its answer is negative. Only four commands can produce it: diff (differences found), inspect --indexed (the first data blob lacks indexdata; a header-only file is indexed), inspect --show (element not in the file), and check (integrity violations). Nothing is printed to stderr for it beyond the command's normal output. |
2 | The command failed or refused: missing or unreadable input, an existing output without --overwrite, an output that aliases an input, unsorted or unindexed input it will not take, a malformed PBF (a zero-byte file, or one whose first blob is not the OSMHeader, is PBF file does not start with an OsmHeader blob naming the file, from every command including inspect --indexed), an I/O error (a failed stderr write included, below, after a run that otherwise completed), and a value the command itself refuses once the command line was accepted (the build-geocode-index S2 level bounds, a renumber --start-id from which the input's IDs would run past the 64-bit range, an -i/-I ID source holding no ID). Error: ... goes to stderr, unless stderr itself is what failed. A command line clap or the CLI refuses is 64, not 2. |
3 | The command failed because the host refused a requested I/O feature at setup: --direct-io on a filesystem that rejects O_DIRECT at open (tmpfs, some overlay and network filesystems) or on a file whose reported direct I/O alignment (statx STATX_DIOALIGN) is not a power of two or exceeds the direct I/O transfer buffer, or --io-uring where the kernel lacks io_uring or WriteFixed, a sandbox denies io_uring_setup, or the kernel refuses the writer's registered buffer pool while RLIMIT_MEMLOCK is below it. On kernels before 5.12, which also charge the ring itself to RLIMIT_MEMLOCK, a low limit can instead fail ring creation with a generic ENOMEM that pbfhogg cannot tell apart from kernel resource exhaustion; that case exits 2. stderr carries Error: platform feature <feature> unavailable: ... with <feature> direct-io or io-uring (an --io-uring output also opens with O_DIRECT, so it can report either). A refused --direct-io input reads Error: platform feature direct-io unavailable: failed to open <path>: Invalid argument (os error 22). Failures after setup, including an EINVAL or ENOSPC mid-run, stay 2. The code follows the typed error chain, not the message text: it survives added context, io::Error carriers, and the thread joins of multi-stage commands, so it holds when the refusal is raised by a worker stage, such as the output writer of the external add-locations-to-ways backend (which previously exited 2 for the same refusal). |
64 | Usage error (EX_USAGE): the command line was refused before command execution, during argument parsing (an unknown flag, a missing, malformed or conflicting argument, a retired short flag, --direct-io or --io-uring in a build without the feature, a missing subcommand) or during the CLI's own option validation (the Flag rules, malformed expressions whether given on the command line or in an -e file, tags-filter with an -e file holding no expression, malformed positional IDs, an unknown inspect --get key, an OSC output name). Printed by clap on stderr, as an error: ... diagnostic with a usage line, or as help when a subcommand or argument is missing; never as Error: .... No output is reserved or opened and no scratch directory is created. A missing or unreadable -e file is a 2. --help and --version exit 0 (2 if their text cannot be written, below). Before this status existed, usage errors exited 2. |
101 | The command panicked or reported a caught panic: a panic on the main thread, which the Rust runtime reports on stderr, or a panic on a worker, writer or decode thread that pbfhogg caught at its join and returned, printed as Error: ... <who> panicked: <payload>. Either is a defect in pbfhogg, never a refusal of the input. The code follows the typed error chain, like 3, and outranks every other status, including an interruption that arrived during the same run. Before this status, a caught worker panic exited 2. |
130 | Interrupted by SIGINT (Ctrl-C). See Interruption. |
143 | Interrupted by SIGTERM. See Interruption. |
A stdout whose reader has gone away (pbfhogg ... | head) is not a failure. The status is taken from the error the command returned, not from whether any stdout write failed. When the command stopped because a stdout write met the closed pipe, the run ends with 0 and no Error: line. A verdict decided before that write keeps its status: check, inspect --indexed, and a diff whose whole report was buffered until the final flush. A streaming diff that meets the closed pipe mid-comparison has no verdict yet and ends with 0. Any other returned error keeps its status, even if stdout also failed while the command cleaned up. For example, an export that finds a truncated input exits 2. Usage errors, platform refusals and interruptions keep their own statuses.
A command that re-encodes elements can build an output block too large for one blob (the 32 MiB payload limit, or an encoded body past the 32 MiB blob size) although every input blob fits: a rebuilt string table, or a codec change, can make it larger. cat, extract, multi-extract, tags-filter, getid, getparents and time-filter cut such a block as sort does (see sort), with the same remaining refusals (exit 2). repack and degrade refuse it instead (their layouts are count rules), and a repaired payload cat --repair frames under its input header is refused rather than cut.
A stderr whose reader has gone away (pbfhogg ... 2>&1 | head) is not a failure either: the diagnostics stop and the status is the command's own. Any other stderr write failure (2>/dev/full, a full disk behind 2>file) is an I/O error. The diagnostics stop, the command runs to its end, and a run that would have exited 0 or 1 exits 2 instead, with no Error: line since stderr cannot take one; anything it published stays. This holds for the stdout reader-gone 0 above too. A run that already has a failure status (2, 3, 64, 101, 130, 143) keeps it. A run that writes nothing to stderr, such as a -q run with no warning, is unaffected. --help and --version follow the stdout rule: 0 into a closed pipe, 2 for any other write failure. One write is counted only if its failure is recorded before the status is chosen: the signal "stopping" notice, which a separate thread prints so the exit never waits on a stuck stderr. A run that writes no stderr line of its own after it (--help, or a run ended by stdout's reader leaving) can exit 0 although that notice failed.
Interruption
Every command handles SIGINT and SIGTERM the same way. The first one prints Note: SIGINT received; stopping and removing this run's staging and scratch files. ... (not under -q, which drops notes), and the run stops at its next checkpoint: its workers wind down, its output staging and scratch directory are removed, and nothing is published - an existing output stays byte-identical. It then prints Error: interrupted by SIGINT: the run stopped before completing, removed its staging and scratch files and published nothing and exits 130 (143 for SIGTERM). A run that was already publishing when the signal arrived finishes publishing, and a run that had already completed keeps its normal outcome and exit code with a Note: that the signal arrived too late to matter. A report printed to stdout once a command has decided its result is not cut short by a signal; output streamed while the command runs (diff text to stdout) stops where the run stopped.
The run stops at the next block it reads, dispatches or writes, the next result a worker pool hands back, or the next stage boundary - normally well under a second. A few phases have no such point inside them and finish first: the geocode builder's in-memory admin assembly and interpolation passes and its writes of the index's own data files, merge-changes --simplify's in-memory dedupe, renumber's rank-table builds, one external-join bucket or add-locations-to-ways node blob in flight per worker, a single copy_file_range call of a raw blob copy, and the removal of a large scratch directory during cleanup.
A second SIGINT or SIGTERM while that cleanup is under way exits at once with 128 + that signal's number, leaving whatever staging and scratch the first had not yet removed; the next run in that directory reports it (see Scratch files). SIGKILL is never handled.
Before 0.6.0 every one of these outcomes exited 1, so "the files differ" and "the file does not exist" were indistinguishable. Callers that branch on 1 for the semantic answer are unaffected; callers that treat any non-zero as failure are unaffected. Only a caller that read 1 as "the command failed" needs to widen to != 0.
Sidecar marker FIFO
When BROKKR_MARKER_FIFO names a FIFO, pbfhogg opens it write-only and non-blocking and writes brokkr's sidecar stream to it: the phase markers (<timestamp_us> <name>) and counters (<timestamp_us> @<name>=<value>) its commands emit, timestamps in microseconds since process start. A FIFO that cannot be opened is a Warning: and the run continues without it. Every line is written whole or dropped, never partly, so the stream is best effort. The variable unset, nothing is written.
The CLI adds one pair of its own, its command interval:
CLI_COMMAND_START, once the command line has been parsed and accepted (flag rules, the input/output alias refusal and the leftover scan of Names pbfhogg leaves behind), immediately before the subcommand is dispatched;CLI_COMMAND_END, when the subcommand returns, whether it succeeded, answered negatively, failed (an existing output without--overwriteincluded) or was interrupted, and before the end-of-run counters (writer_*,pipeline_*and their kin), which follow it.
Between them lie the subcommand's own option handling, the opening of its outputs and scratch, every library pass it makes with all of its markers, its publication and the summary or report it prints. Process policy (the raised descriptor limit, input page-cache eviction) is applied inside the interval, where the command needs it.
A process writes at most one pair. A command line refused before dispatch (by the argument parser, a flag rule or the alias refusal), --help and --version write neither marker. A usage error found while the subcommand resolves its options (an invalid expression for inspect tags or export, malformed positional IDs, an unknown inspect --get key, cat --reindex with several inputs) lies inside the interval like any other refusal, so exit 64 does not by itself mean no interval was written. A run that panics, or exits at once on a second signal, writes no CLI_COMMAND_END. The names are reserved: no library phase uses them.
Indexdata is believed
Commands that act on blob-level indexdata or tagdata, or on the header's Sort.Type_then_ID flag, believe them; a few checks happen in passing where a command decodes anyway, but none is a guarantee. A file whose claims are false can get a wrong answer that reports success. check --index --ids verifies a file of unknown provenance, except for the header's feature flags. Which command believes which claim, and what a false one costs, is in the indexdata trust model.
Common flags
These flags appear on most commands that produce PBF output:
| Flag | Description |
|---|---|
-o, --output <FILE> | Output file path |
-O, --overwrite | Replace the output if it already exists. Without it an existing output is refused before any work is done; a symlink is refused either way |
--staging-dir <DIR> | Stage the output in DIR instead of beside it (see Staging directory) |
--compression <COMPRESSION> | Compression of the blobs the command encodes: none, zlib (level 6), zstd (level 3), or with a level, zlib:0 to zlib:9, or zstd:LEVEL for any level the linked zstd library supports (up to zstd:22, and negative levels down to its minimum; a level outside that range is refused, not clamped). The default is zlib everywhere except renumber, which defaults to zlib:1. Blobs a command passes through (plain cat, the blobs apply-changes leaves alone) keep the compression they had; repack re-encodes every blob |
--direct-io | Use O_DIRECT on the paths listed in the I/O capability matrix (requires linux-direct-io) |
--force | On a command that would refuse unindexed input: proceed with the slower fallback (see Proceeding without indexdata) |
--generator <GENERATOR> | Override the writing program name in the output header |
--output-header <KEY=VALUE> | Set output header fields (repeatable). Keys: osmosis_replication_timestamp (UNIX seconds or YYYY-MM-DDTHH:MM:SSZ), osmosis_replication_sequence_number, osmosis_replication_base_url. An empty value (KEY=) omits the field |
Short flags
Every short flag has one meaning across all subcommands. A command offers a short only where it has the long flag the short stands for.
| Short | Long | Commands |
|---|---|---|
-b | --bbox | extract, export |
-c | --suppress-common | diff |
-d | --directory | extract |
-e | --expressions | tags-filter, export, inspect tags |
-g | --get | inspect |
-h | --help | every command |
-i | --id-file | getid, getparents |
-I | --id-osm-file | getid, getparents |
-j | --jobs | tags-filter, inspect, inspect tags, diff, apply-changes, merge-changes |
-M | --max-count | inspect tags |
-o | --output, --output-dir | every command that writes an output (--output-dir on build-geocode-index) |
-O | --overwrite | every command that writes an output |
-p | --polygon | extract |
-q | --quiet | every command (global) |
-r | --add-referenced | getid |
-R | --omit-referenced | tags-filter |
-s | --osmium-summary | diff |
-t | --type | cat, diff, check, export, inspect tags |
-v | --verbose | diff, getid |
-V | --version | pbfhogg |
Where a letter used to mean something else on a command, it now refuses on that command, naming the long flag to spell instead, so an old command line never silently means something new:
| Command | Short | Spell instead |
|---|---|---|
| cat | -c | --clean |
| extract | -c | --config |
| extract | -s | --simple |
| renumber | -s | --start-id |
| getparents | -s | --add-self |
| inspect | -e | --extended |
| inspect tags | -s | --sort |
| tags-filter | -t | --remove-tags |
| tags-filter | -i | --invert-match |
| getid | -t | --remove-tags |
Flag rules
- A flag the command line makes ineffective is refused, as a usage error (exit
64, in clap's format), never warned about or ignored:-Owithout-o,--forcewhere nothing would refuse,--tmp-diron a path that writes no scratch,-jon a path with no worker pool, a PBF-only flag on OSC input, and so on. The refusal names the flags involved. - A fallback the host or the input selects at run time is not grounds for refusal: an unindexed input taking diff's fallback path,
-j 0resolving to one worker on a one-core host. The same command line must not be valid on one machine or file and invalid on another. Whether a fallback prints aNote:depends on the command and the path it takes. - Every flag is parsed and checked before any input is opened: malformed values (
--bbox,--start-id, the time-filter timestamp,--drop-ids,--output-header,--compression,-j), flag combinations, and--direct-io/--io-uringin a build without the feature. Positional IDs (which depend on--default-type) and expressions are checked right after, still before the output is reserved; an-eexpressions file, anextract --polygonfile and anextract --configfile are read at that point too. Two checks ride a read that happens anyway: tags-filter's input kind, when not given by--input-kind, comes from a four-byte sniff of the input, so its OSC-mode refusals follow that sniff; and an ID file (-i,-I) is read after the output is checked, so an existing output is refused before a full pass over an-IPBF. Refusals that depend on the input's contents (unsorted, unindexed, lackingLocationsOnWays) come from the first read of the input that can tell.
Worker threads
-j, --jobs <N> has one rule on every command that has it: 0 (the default) sizes the worker pools automatically, 1 runs one worker (the command's sequential path where it has one), N caps the worker pools at N threads. The worker count does not include a command's own reader, scanner or drain threads, which run beside the workers at any -j. "Automatically" is each command's own sizing (a reserve of cores for its scanner, drain or writer threads, a minimum, a fallback when the host cannot say how many cores it has); -j 0 and an omitted -j are the same. An explicit -j (any value, 0 included) is refused where it can have no effect: tags-filter -R, inspect outside --nodes. Diff uses the worker budget according to the inputs it finds.
- diff (text and
--format osc): with both inputs indexed,Nworkers merge the work units both inputs are streamed into, at anyN. When the initial probe finds an unindexed input, up to eight workers decode ahead on a shared pool. WithN > 1, selected nodes compare in parallel over validated ID ranges within the same worker budget. Ways, relations and any node suffix the planner cannot safely cut use the element stream. The unindexed-route note retains its spelling,Note: Using sequential comparison: missing indexdata, and is printed when the resolved worker count exceeds one. Automatic sizing uses the host's reported parallelism, or one worker if the host reports none.
apply-changes -j 1 runs one worker beside the scanner and drain threads; its automatic sizing still starts at two. Its single worker decodes, rewrites and compresses every blob that needs rewriting, and new elements are encoded on the drain thread, so the run has little parallelism: it can take far longer, while the memory concurrent workers would hold is saved. merge-changes -j 1 and OSC-mode tags-filter -j 1 run one worker beside the reader thread that frames each input.
The other commands that run worker pools (sort, cat, repack, degrade, renumber, extract, add-locations-to-ways, getid, getparents, time-filter, check, export, digest, build-geocode-index) size them themselves and have no -j.
Proceeding without indexdata
With --force, a command that would refuse unindexed input proceeds with the slower fallback. Only commands that refuse unindexed input have the flag, and each refuses through the same gate: a typed missing-indexdata error naming the input, which the CLI follows with Generate an indexed PBF first ... and check --index to diagnose missing or contradictory blob metadata (the library's text names no command or flag). The CLI then adds Or pass --force to proceed anyway. only where --force is accepted: modes that need indexdata whatever --force says get no such line, and build-geocode-index names --allow-unindexed instead.
A command refuses only on paths where indexdata buys the run something, and the refusal says what: skipping blobs by element type, ID range or node bounding box, or copying a blob whole. A forced run loses only that. Every filter the command applies still applies to every element it decodes, so inspect tags --type node --force counts node tags only, and tag-key skipping, which reads tagdata rather than indexdata, still skips blobs. The forced run prints one Note:, Input contains blobs without indexdata; proceeding without its optimizations. Where a path skips nothing on indexdata it takes an unindexed input as it is, and --force there is refused as ineffective (see Flag rules); for inspect tags and tags-filter -R the expressions decide which, so that refusal follows the expressions check rather than clap's.
| Command | Refuses unindexed input on | --force refused with |
|---|---|---|
| cat | --type (with or without --clean), --dedupe | plain cat, which adds the indexdata, --reindex, which rescans every blob whatever it carries, and --clean without --type, which decodes every blob exactly once either way. --type node,way,relation --clean is the clean pass and does not refuse; --force alongside it is accepted and does nothing |
sort, repack, getid (with or without --invert) | every path | - |
| inspect tags | --type, or expressions that together leave some element type out (w/highway, not highway or w/highway highway) | any other run, which schedules every blob either way |
| degrade | the decode path (--unsort, --unsort-intra, --strip-locations, --drop-ids) | only header-only flags |
| tags-filter | PBF input, except -R with expressions that name every element type | --invert-match, --distrust-metadata (neither refuses), -R whose expressions name every element type, OSC input |
| extract | complete-ways and --smart | --simple |
| inspect | --nodes | anything but --nodes |
| add-locations-to-ways | sparse, and --index-type auto routing to it | --index-type external and --inject-prepass, which need indexdata whatever --force says |
| apply-changes | every path | --locations-on-ways, which needs an indexed base whatever --force says |
renumber has no --force: its schedule needs indexdata on every blob and has no fallback, so an unindexed blob is a hard error. export --resolve-way-locations also requires indexdata on every data blob. Ordinary export, getparents, time-filter, diff, digest and check accept wholly unindexed input. These commands have no --force. See Worker threads for when diff prints its unindexed-route note.
build-geocode-index is the exception: its indexdata switch is --allow-unindexed, and its --force is a legacy shorthand for both --overwrite and --allow-unindexed. It keeps working, and warns every time that it also grants overwrite, naming the two flags to spell instead.
This section is about absent indexdata. What commands believe when it is present, and what a partially indexed file meets, is in indexdata-trust.md.
Output header
Every PBF-writing command derives its OSMHeader from one rule (crates/lib/src/commands/output_header.rs): a header never claims more than the output contains. Each command states facts about its output - its order, what it did to way payloads and way blob headers, its bbox and replication state - and the header follows from them.
Sort.Type_then_ID: declared when the command emits type-then-ID order by construction (sort, renumber, apply-changes,cat --dedupe), or when it keeps the input's order and its one input declares it. A concatenation of several inputs, anddegrade --unsort*, are never declared sorted.LocationsOnWays,pbfhogg.WayMembers-v1,pbfhogg.SharedNodePins-v1: declared only when every way blob written carries them, with a meaning that still holds for the output. A command that copies every way blob whole (payload andBlobHeader) keeps each one its input declares; one that copies payloads but rebuilds some blob headers (to add indexdata) keepsLocationsOnWaysandSharedNodePins-v1and dropsWayMembers-v1(field 5 lives in theBlobHeader); one that re-encodes ways with their coordinates keepsLocationsOnWaysonly; one that re-encodes ways otherwise keeps none.sortandcat --dedupere-encode a rewritten way with its coordinates when every input declaresLocationsOnWays, and refuse a rewritten way that has refs but no coordinates there, since the kept declaration would misdescribe it; a way blob they copy is not decoded, so its arrays are believed. The filters that write each selected way whole (extract,tags-filter,getid,getparents) re-encode it with its coordinates when the input declaresLocationsOnWays, and refuse a way they re-encode that has refs but no coordinates there, for the same reason; every ref keeps the coordinate the input recorded beside it, including a ref to a node the output does not hold. A way blobgetid --invertcopies whole is not decoded, so its arrays are believed, as insort. time-filter keeps no coordinates: they record node positions as of when the input was written, not as of the cutoff. The two prepass features are facts about the whole file (relation membership, nodes shared between way positions), so they are kept only from a single input whose ways and relations reach the output with their content unchanged, all of them or a subset; a subset only over-approximates them, which their contract allows. With several inputsLocationsOnWaysstill means each way carries the coordinates its own input recorded, not that they agree with another input's nodes. The prepass fields are authoritative only in a file that declares them. When the input declares a feature the output does not, the command warns (header.way_metadata_loss); the warning means the declaration is gone, not necessarily the bytes.- bbox: the input's, or the union of every input's when all declare one (an input without a box makes the extent unknown, and the box is omitted), widened onto the decimicrodegree grid so a re-encoded node on its edge stays inside. Omitted by apply-changes, whose OSC can place a node outside the base's box, and by
degrade --strip-bbox.extract --set-boundsdeclares the region's envelope instead, which complete_ways and smart exceed by design with the out-of-region nodes of selected ways (osmium does the same). - Replication state: the base URL names the feed, and the timestamp and sequence number the position in it, that the output's content was drawn from: every object is in that feed's ID space, and a snapshot's objects are at their version as of that position. They do not promise that applying the feed's later diffs maintains a selection (an extract or a filter grows under them), and they are only as true as the input headers they come from. The base URL is kept when every input names the same one; the timestamp and sequence number only when every input carries the same timestamp, sequence number and base URL. time-filter writes
min(input timestamp, cutoff)and keeps the sequence number only when the input's timestamp is known and not after the cutoff. apply-changes keeps the base URL only: its output is past the base's position, at one it cannot name (an OSC has no sequence number, nor proof that it follows the base without a gap); a caller that knows the new position sets it with--output-header. renumber keeps none of the three: its new IDs are not the feed's, so the feed's diffs would address other objects. sourceis kept when every input agrees;HistoricalInformationwhen any input declares it, except from time-filter, whose output holds one version of each object and never declares it.- Writing program:
pbfhogg/<version>, the library's package version. - Optional features pbfhogg does not know are not carried: nothing can vouch for them after a rewrite. A required feature pbfhogg does not know never reaches a rewrite: every command that reads elements refuses such an input when it decodes the header (
inspectincluded, asosmium fileinfodoes), naming the feature. --generator/--output-headerapply last, and each replaces only the field it names; a later--output-headerfor the same key replaces an earlier one. An empty--output-headervalue omits the field, whatever the policy would have written (--output-header osmosis_replication_base_url=writes no base URL), as in osmium.--generator ""writes a present, empty writing program (osmium writes the writing program unconditionally too). An emptysourceor base URL carried from an input header stays a present, empty field.
The exception is degrade's header-only passthrough (--strip-indexdata, --strip-tagdata, --strip-bbox, --corrupt-*), which copies every blob payload and every other blob-header field, and so forwards the input header field for field - writing program, custom features, unknown required features and unknown fields included - with the bbox removed under --strip-bbox and each override replacing only its own field.
A command that copies blobs raw decides its header from the first data blob's indexdata (cat, cat --type, getid --invert); sort and cat --dedupe decide from their complete blob index. If a later way blob without indexdata would have to go through a branch that drops a declared enrichment, the run fails with an error rather than write a header that lies.
| Command | Order | Way enrichment kept |
|---|---|---|
cat (one input) | input's | all |
cat (several inputs) | not sorted | LocationsOnWays when every input declares it |
cat --type | input's | all, none when the first data blob carries no indexdata |
cat --clean | input's | none |
cat --dedupe | sorted | as copied; when a way blob is rewritten, LocationsOnWays only, when every input declares it |
sort | sorted | all; when a way blob is rewritten, LocationsOnWays only |
repack | input's | LocationsOnWays |
degrade (header-only flags) | input header, verbatim | input header, verbatim |
degrade (re-encoding flags) | input's, not sorted under --unsort* | none |
renumber | sorted (requires sorted input) | LocationsOnWays |
time-filter | sorted (requires sorted input) | none |
tags-filter, getid, getparents, extract | input's | LocationsOnWays |
getid --invert | input's | all when no way ID is requested on indexed input, else LocationsOnWays (even when no requested way exists) |
add-locations-to-ways | input's | LocationsOnWays, plus the prepass features with --inject-prepass |
apply-changes | sorted | LocationsOnWays with --locations-on-ways, else none |
PBF rebuild precision
A blob a command copies keeps its bytes, and so its block framing (granularity, lat_offset, lon_offset, date_granularity) and every value exactly as stored. A block a command rebuilds element by element (cat's re-encodes, sort and cat --dedupe overlap runs, repack, degrade's re-encoding flags, tags-filter, time-filter, getid, getparents, extract, add-locations-to-ways retained-node rewrites, apply-changes rewritten blobs) is written in the default framing, which holds the OSM data model's precision: coordinates in decimicrodegrees (1e-7 degrees) and timestamps in whole seconds. A source block already in the default framing loses nothing. A source block in another framing is converted:
- coordinates are truncated toward zero to decimicrodegrees, as libosmium reads them and as
diffandcheck --locationscompare them; - timestamps are scaled exactly to milliseconds and rounded down to the whole second holding the instant, as
time-filterand the OSC writer round them (libosmium truncates toward zero, which differs for negative sub-second values); - a timestamp whose scaling by
date_granularityoverflows, or whose rounded second no longer fits 64-bit milliseconds, is refused with an error naming the element, rather than written as a different, valid timestamp (cat --clean timestampdoes not convert the timestamp it drops, so it does not refuse it); - a dense node whose claimed timestamp rounds to 0 s and which is written without a version (it had none, or
--clean versiondropped it) is written as a plain node with an explicit 0, since a versionless dense slot holding 0 reads back as no timestamp.
In any framing, cat --clean version and extract --clean version on a dense node that carried a version keep the fields they do not clean as claims, except visible=true, which a node without a version does not claim (visible=false is kept). A node whose kept timestamp is 0 (the epoch), kept changeset or uid is 0 or below, or kept user is empty is written as a plain node carrying those values explicitly, since a versionless dense slot would read them back as absent. A field the command cleans claims nothing: a dense node holds it as the 0 osmium writes, a plain node omits it.
Under the default date_granularity the stored timestamp is copied as it is, an overflowing one included, so it reads back as the same refused claim. add-locations-to-ways splices locations into way blocks rather than rebuilding them: a way block keeps its own date_granularity and stored timestamps, while its coordinate framing is converted to the default (the way coordinates it writes are decimicrodegrees, and any it carried are replaced). A way block in a non-default coordinate framing that also holds nodes (a Node or a non-empty DenseNodes beside its ways) is refused, exit 2, since the splice copies those nodes verbatim and the default framing would misread them; repack, which rebuilds every block one kind per block, separates the kinds (plain cat copies an indexed blob whole and does not). An invalid date_granularity (outside int32) in a way block is refused rather than copied. Because the conversion of retained values applies only to rebuilt blocks, two outputs of the same input can differ below the model precision where one command route copies a non-default-framed blob and another rebuilds it (sort passthrough against an overlap rewrite, say). pbfhogg diff and the content digest forms compare coordinates at decimicrodegrees and ignore metadata, so they see no difference; digest --form full compares exact nanodegrees and millisecond timestamp claims, so it does.
Output files
Every output a command writes - PBF, OSC, diff text, GeoJSON, every file of extract --config, the build-geocode-index directory - follows one contract:
- An existing output is refused before any work is done, unless
-O, --overwriteis given.Error: output <path> already exists and replacing it was not requested; pass --overwrite (-O) to replace it, exit2. Forextract --configevery output the config names is checked up front, and--overwriteon the command line covers all of them. - An output may not be any file the command reads, refused before any work with
output <path> aliases input <path>, exit2, even with--overwrite. That covers every input, not only the positional ones:getidandgetparents-iand-I, the-eexpressions file oftags-filterandexport,extract --polygon, theextract --configfile and thepolygon_fileentries it names. A directory output may not hold one either:build-geocode-indexrefuses an--output-dirthat contains its input, or the entry naming it (a symlink or hard link inside), withoutput <dir> contains input <path>, because replacing the index directory deletes everything in it. Directories are compared by identity, so a bind mount aliasing the directory does not hide the input. A path that merely passes through the directory (a symlinked directory inside it) is not refused; only that link would be lost. The check is repeated immediately before publication, so an input moved into the index during the build is refused then (exit2), with nothing replaced. After a successful replacement, a backup that holds any link to the input is kept and the command prints a warning. - A symlink is never an output, even with
--overwrite: replacing it would turn the link into a regular file. The error names the link and its target. An existing directory (or device, FIFO) where a file output is named, or a non-directory where a directory output is named, is refused the same way. - An OSC output is framed by its name, the same way for every command (
merge-changes,tags-filter --input-kind osc,diff --format osc). A name ending.oscis written as plain XML, a name ending.osc.gzis gzipped, and any other name is refused before any work with a usage error naming both suffixes, exit64. The match is case-sensitive (.OSCis refused). Every OSC reader here sniffs the gzip magic, so either form is read back. - An OSC input must be XML 1.0 in its characters.
apply-changes,merge-changesandtags-filter --input-kind oscrefuse (exit2) a document holding a C0 control character other than tab, newline and carriage return, or U+FFFE / U+FFFF, anywhere in it - written literally or as a character reference in an attribute or text, including attributes no command reads and changes a filter would drop - as osmium does.&#1;and a reference inside a comment or CDATA are ordinary text and pass. A<!DOCTYPE>with an internal subset is refused; an external identifier is never loaded. - An OSC input must follow XML's lexical rules that osmium's Expat enforces. The same commands refuse (exit
2) a reference to any entity other than<,>,&,'and"(an external DTD does not excuse it), a bare&or a literal<in any attribute value, attributes with no whitespace between them (k="a"v="b"), an attribute or unrecognised element name that is not an XML name, a DOCTYPE after the root, repeated, misspelled (<!doctype) or with a malformed external identifier, an XML declaration that is not first, text, CDATA or a reference outside the root,--inside a comment,]]>in text, and a processing instruction targetingxml. - An OSC input may be a stream (a FIFO,
/dev/stdin) forapply-changes,merge-changesandtags-filter --input-kind osc: each is read front to back once, and the gzip sniff replays the bytes it took rather than seeking back. The open and every read wait for the stream's writer, and cancellation cannot interrupt a wait the writer never ends. Inmerge-changes, an error in one input can therefore wait for a stream input whose writer has neither written nor closed. Each argument is opened on its own, so naming the same FIFO twice splits its bytes between the two.tags-filterwithout--input-kindroutes a stream by its name (the extension rule) without reading it, since its content sniff reads regular files only, and only on Linux with/procmounted (elsewhere the kind comes from the name alone); use--input-kind oscfor a stream with another name. - Nothing appears under the output name until the run has succeeded. The command writes a hidden staging file beside the output (
.pbfhogg-tmp-<pid>-<n>.<name>), or in--staging-dirwhen given (see Staging directory), syncs it and renames it into place after its final flush; a run that fails before that removes it, so it leaves no file at the output path and leaves an existing output untouched. So does a run interrupted by SIGINT or SIGTERM (see Interruption). A run killed outright (SIGKILL, the OOM killer, power loss, a second interrupt) can leave the hidden staging file behind, never a partial file under the output name. Killed during publication, it can also leave.pbfhogg-backup-*entries beside the outputs (see Names pbfhogg leaves behind), and an output that was being replaced through a backup (a geocode index, anextract --configoutput) may be missing, its previous version in the backup. The rename itself is the last step, and the few failures possible after it are reported as such: a directory sync that fails after the output was put in place is an error that says the output was published (naming any backup of a replaced output, which is then kept), and a group whose rollback cannot complete names what is left where. A single file output that replaced an existing file keeps no copy of the previous version, so its rename is never undone: a failure after it leaves the new output in place and says so. The output's directory must exist and be writable, which is checked before any work. On Linux, replacing a directory output also requires write and search permission on the existing output directory itself: moving it into its backup container changes its parent. Effective-user access (including ACLs and privileges) is checked before any work and again before publication; a read-only index is refused up front, even with--overwriteand any staging placement. Permissions can still change after a check. - Without
--overwritepublication is exclusive: an output that appears while the command runs is not replaced either. On a filesystem with neither an exclusive rename nor hard links, such a run fails at the end and says so;--overwritepublishes there. - Several outputs (
extract --config) are published together: if one cannot be put in place, the ones already published are rolled back. If a rollback step itself fails, the previous output is kept in a.pbfhogg-backup-*directory beside it and the error names it.
-o /dev/null is not an output: it is refused as not a regular file.
Staging directory
--staging-dir <DIR>, on every command that writes an output, puts each output's staging entry (the staging file, or the geocode index's staging directory) in DIR instead of beside the output, under the same .pbfhogg-tmp-<pid>-<n>.<name> name. Publication still renames it into place, so DIR is checked before any work and refused unless:
- it exists and is a directory;
- it is on the same mount as every output's directory: the same device, and a mount the kernel does not refuse a rename across. A bind mount of the same device is a different mount, across which a rename fails, and is refused on every Linux kernel whose answer settles it (see below), including those that report no
statxmount id (before 5.8); - it is not, and does not contain, any output's directory (a directory below an output's directory is fine): a caller removes its staging directory whole, and a backup of a replaced output lands beside the output;
- for
build-geocode-index, it does not lie inside--output-dir, which publication replaces.
For extract --config it is checked against every output the config names before any output is reserved. A refusal names the staging directory and the output, exit 2. The mount check detects a refusal rather than promising the rename. It asks the kernel with a rename that cannot move anything, and an answer that settles nothing (a lookup error such as EACCES, or a sandbox such as a seccomp filter refusing the call) lets the run go ahead rather than refusing a directory that may be fine. A refusal it cannot foresee, or that went unanswered (a filesystem that refuses the rename itself, a mount table changed while the run worked), is met at the final rename, and is reported as the same staging-directory refusal with the kernel's error appended, after the run's outputs were rolled back as for any failed publication. --staging-dir needs an output: with export or a text diff writing to stdout it is refused as a usage error, exit 64. Publication syncs both directories a rename changes, the staging side as well as the output's directory. Library callers get the same placement and checks from Output::with_staging, OutputDir::with_staging, OutputSet::files_with_staging and geocode_index::builder::index_output_with_staging with Staging::Dir, whose refusals are OutputError::StagingDir with a StagingProblem. A library caller may also pass Staging::DirWithBackups, which the CLI never uses: backups of replaced outputs then go in the staging directory too, so nothing but the outputs appears beside them, and removing that directory removes any previous output a publication kept there. The same checks apply, and a move into such a backup refused across mounts is the same staging-directory refusal.
Scratch files
add-locations-to-ways, export --resolve-way-locations, diff --format osc, merge-changes (several inputs, without --simplify, not at -j 1) and build-geocode-index write scratch: disposable files that can be very large (hundreds of GB for add-locations-to-ways --index-type external at planet scale). Each run makes one hidden directory, .pbfhogg-run-<pid>-<random>, holds everything it writes in there and removes it when it ends, whether it succeeded, failed or was interrupted. If the directory cannot be removed the run says where the leftover is. The directory is made at startup, before any input is opened, by every run that may need scratch. A run whose command line guarantees it writes none (a text diff, at any -j, whose text goes straight to its output; a merge-changes of one input, with --simplify, or at -j 1, which reads its inputs one at a time) makes no directory, needs no writable location and refuses --tmp-dir. For a merge-changes of several inputs without --simplify, -j 0 is not such a guarantee even where it resolves to one worker: that is the host's choice, so it keeps the directory and the flag.
sort and cat --dedupe can create scratch after planning a qualifying large overlap component. They put one temporary directory at a time beside the staging file, including under --staging-dir when supplied, and remove it after that component. If scratch fills, sort fails and cat --dedupe can fall back to its serial sweep. See sort for space requirements and cat for the dedupe spill budget.
--tmp-dir <DIR>chooses the directory the run directory is made in. It must exist and be writable, and it is checked before any input is opened, so a bad value fails at once. Without it the scratch goes in the output's directory (the current directory for an output name with no directory part).build-geocode-indexrefuses a--tmp-dirinside the index directory it replaces.--tmp-dirnever moves an output's staging entry (.pbfhogg-tmp-*), which stays beside the output unless--staging-dirmoves it, nor a replaced output's backup (.pbfhogg-backup-*), which always stays beside the output: publication is a rename, which needs the same mount.
Leftovers of runs that never finished (SIGKILL, power loss, the OOM killer, a second SIGINT or SIGTERM) are reported, never removed. Before it starts, a command that writes an output scans the output's directory (and --tmp-dir and --staging-dir, when given) and prints one Warning: per entry it finds: an unfinished run directory, scratch left by older pbfhogg versions (.pbfhogg-external-join-*, .pbfhogg-sparse-index-*, diff-par-*, derive-* files), and an output's hidden staging file. Each line gives the size and why the entry is believed stale. That is a belief, not a proof: a run directory is judged by whether its flock is still held, other entries by whether the pid in the name exists, and a pid can be reused or belong to another container sharing the volume. Check before you delete. A run directory whose lock cannot be probed at all (another user's, an unexpected file type, a lock the filesystem refuses) is not reported as stale but as a Note: saying whether it is in use is unknown: do not delete it. On an NFS mount that keeps flock local to each client (local_lock=flock or local_lock=all, or NFSv3 with nolock) the lock cannot see a live run on another host, so such a run's directory may be reported while it is in use, as it may after a client lost its lock to an expired NFSv4 lease; keep --tmp-dir on a local filesystem when hosts share a directory.
Each command also looks where older versions of the same command left their scratch: extract --config scans the directory of every output the config names (each directory once), diff also scans the old input's directory (diff-par-*; --format osc fragments of older versions sat beside the output, which is scanned anyway), and build-geocode-index also scans everything inside the existing index directory it is about to replace, at any depth, including .buckets-level* trees (and the parent for .geocode-build-* staging of earlier versions). A .buckets-level* tree inside an index is deleted when successful publication removes the old index; the report says so. What is inside such a tree is checked like the rest of the index, so a backup or run directory that ended up in one blocks the replacement. That is the only reported entry that publication removes: an index that holds anything else pbfhogg leaves behind (a backup, a staging entry, a run directory, live or not, an older version's scratch) is not replaced at all. --overwrite then fails before any work, naming the entries; move or remove them first. An output named like one of these names, or inside one, is refused the same way.
A .pbfhogg-backup-* entry is reported with its own wording. It can be the only copy of a previous output, so pbfhogg never deletes one and you should look at it before removing it. If a backup cannot be removed after a successful replacement, the run still succeeds and prints a Warning: naming it. If a directory the replacement's publication changed cannot be synced, the backup is kept rather than removed, and the error names it. Library callers get the same scan as typed values from pbfhogg::scratch::find_stale and pbfhogg::scratch::find_stale_in_index.
Names pbfhogg leaves behind
A caller that kills pbfhogg children should not match these names at all. The supported way to own cleanup is to give each run directories of its own. When both --staging-dir and --tmp-dir are given, pbfhogg creates every staging entry under --staging-dir and all run scratch under --tmp-dir. They may be one directory: staging entries and run directories have distinct names, and a directory named by both is scanned once. --tmp-dir exists only on the commands that make run scratch (add-locations-to-ways, export, diff, merge-changes, build-geocode-index), and is accepted only on their command lines that do (see Scratch files); every other command line makes none, and --staging-dir alone holds everything disposable it leaves. After every process using those directories has stopped, the caller may remove them, provided they are private to the run, dedicated to its disposable state, and hold no outputs or other data it means to keep (pbfhogg refuses a --staging-dir that is or contains an output's directory; --tmp-dir is not checked that way). Publication may also leave backup entries (.pbfhogg-backup-*) beside the outputs. They are excluded from automatic cleanup: one can hold the only copy of a replaced output, though one left by an interrupted publication may also be empty, or hold only part of the previous output when the run was killed while removing it after the new one was in place. The run's diagnostics name them when they get to, and every later scan of that directory reports them. Published outputs stay at the paths that were asked for, including ones a killed group publication left installed: publishing several outputs is not all-or-nothing across a process death. Stale staging therefore never reaches the next run's directories, so no run has to decide whether to overwrite or refuse it.
"Every process using those directories" is the pbfhogg process alone. The pbfhogg CLI starts no other process; its threads end when it exits, so once it has exited no process or thread it started can still use its staging or scratch directories. It never closes or replaces a descriptor it inherited, nor changes that descriptor's descriptor or file-status flags, so an extra descriptor the caller passes it (for example one on which the caller holds a lock as a lease for those directories) stays open until the pbfhogg process exits. This is about processes and descriptors, not kernel I/O: the kernel may finish asynchronous cleanup after the process is gone. The CLI test suite runs every pbfhogg child it starts under a seccomp filter that kills it on any breach of this, for the whole run (reference/testing.md says what that filter does and does not see).
The spellings below are the contract for an external tool that cannot do that (a cleanup job sweeping directories it did not hand out). <pid> is the pid of the pbfhogg process, <seq> a counter within it, <dest name> the last component of the output path (the last 200 bytes of it, when longer).
| Name | What it is | An external tool may delete it |
|---|---|---|
.pbfhogg-tmp-<pid>-<seq>.<dest name> | Staging for an output, beside the destination or in --staging-dir: a file for file outputs, a directory (holding new/) for the geocode index. Never a file under the output name. | When no pbfhogg process is live that could own it (check <pid>; it is a hint only) |
.pbfhogg-backup-<pid>-<seq>.<dest name> | A directory holding the previous output, kept while a replacement is published, and kept for good when a rollback could not restore it, when syncing a directory the replacement's publication changed failed (the error names it), when removing it after a successful replacement failed, or when something pbfhogg never deletes turned up inside it (a warning names it in the last two cases). | Never without a human. It can hold the only copy of the previous output |
.pbfhogg-run-<pid>-<random> | One run's scratch directory, in the output's directory or --tmp-dir. | When its lock is not held (below), and nothing is using it |
A run directory holds a LOCK file, on which the owning process keeps an exclusive flock(2) for its whole life, and a READY file created after the lock was taken. The kernel drops the lock when the process dies. To test liveness, open LOCK read-write without creating it (O_RDWR, no O_CREAT; on NFS an exclusive flock is a POSIX write lock and fails with EBADF on a read-only descriptor) and try flock(LOCK_EX | LOCK_NB): failure with EWOULDBLOCK means a live run; success means the owner is gone (release the lock at once). Any other error, from the open or the lock, means liveness is unknown: do not delete. A directory without READY, or without LOCK, is a run that is starting or one that died while starting or finishing; there is no lock to take, so treat it as live while any pbfhogg process could still be using that location. Never create LOCK. The lock is advisory: on an NFS mount that keeps flock local to each client (local_lock=flock or local_lock=all, NFSv3 nolock) it says nothing about a run on another host, and a client whose NFSv4 lease expired has lost it.
Names older versions used, which the scan still recognises and which are disposable once no pbfhogg process runs there: .pbfhogg-external-join-<pid>*, .pbfhogg-sparse-index-<pid>* (directories and files), diff-par-<pid>*.tmp, derive-creates-<pid>*.tmp, derive-modifies-<pid>*.tmp, derive-deletes-<pid>*.tmp, derive-par-creates-<pid>*.tmp, derive-par-modifies-<pid>*.tmp, derive-par-deletes-<pid>*.tmp, and, inside an index directory, .buckets-level<N>. The geocode staging of the previous version, .geocode-build-<n> (<n> a counter, not a pid), is disposable only when it has no old/ inside: old/ was the previous index during a swap and may be the only copy, so the scan reports it as a backup.
Commands
inspect
Inspect PBF file: metadata, block breakdown, ordering analysis.
inspect describes a file: what it is and what it claims. By default it reports counts, ID ranges and per-block stats from the blobs' own indexdata (--distrust-metadata decodes instead). What it finds is not a verdict: a readable file exits 0 (--indexed answers yes or no in its exit code). Whether the file's contents match its claims, or meet the format's invariants, is check's question.
The scanning report's full-decode modes (--extended, --distrust-metadata, --locations, and the fallback taken when a data blob carries no indexdata) require every OSMData block to pass the strict block reader's construction checks: element and packed-array framing, the parallel-array length checks and stringtable UTF-8. They require this even where the faulty field feeds no reported statistic, such as a malformed way refs array under --extended. A failure aborts the report as a read error (exit 2, with the blob's byte offset); inspect does not present the blocks it did read as whole-file totals. A successful report is not an integrity verdict either: the construction checks do not resolve string indices, for one. The default index-only report decodes no payload and reports the stored claims, so it can succeed on the same file.
On indexed PBFs, uses an index-only fast path that reads blob headers without decompression. On Denmark (487 MB indexed), this took 111 ms at commit 53360af4 on bygg (2026-11-09, median of three cold-input runs); see reference/performance/cross-command.md, README campaign.
pbfhogg inspect [OPTIONS] <FILE>
pbfhogg inspect tags [OPTIONS] <FILE> [EXPRESSIONS]...| Flag | Description |
|---|---|
--indexed | Check if PBF has blob-level indexdata (exit code 0 = yes, 1 = no). Reads the first data blob only; later blobs are not checked (to verify every blob's indexdata against its payload, use check --index). A header-only file (no data blobs) is indexed; a file without a leading OSMHeader is an error (exit 2), not a "no", and so is a header the readers refuse, such as one requiring a feature pbfhogg does not implement. A verdict of its own: not combinable with any report flag (--nodes, --blocks, --id-ranges, --locations, --anomalies, --extended, --get, --distrust-metadata); --json and --direct-io remain. The report's own Indexed: line (and --get indexed) answers across every data blob instead. A combined run used to print the probe's verdict line before the report, under -q too, and overwrite the JSON report's indexed with the first-blob answer |
--nodes | Analyze node coordinate statistics for FOR compression sizing. A FOR block is up to 128 consecutive coordinates of one blob in element order; blocks never span blobs, so each blob's last block is partial unless its node count is a multiple of 128, and the report is the same at any -j. The size estimate packs each block's offsets at its bit width for the values it holds, rounded up to a byte, plus a 4-byte base per block and axis; bit-width and framing metadata are not counted |
-j, --jobs <N> | Worker threads for --nodes (see Worker threads). Requires --nodes: passing it elsewhere is an error rather than a no-op. The full-decode modes (--extended, --locations, --distrust-metadata, a report on an unindexed file) decode on the read pipeline's own pool, sized from the machine, which -j does not set. |
--blocks [N] | Show per-block distribution stats and optional block listing (N limits to first/last N blocks) |
--id-ranges | Show the numeric min/max element IDs per type, and whether each type's IDs strictly ascend numerically (monotonic: yes, no or unknown; true, false or null in --json). A decoding report judges the decoded elements. The index-only report says only what the blobs' claimed [min, max, count] prove, since a claim cannot say in what order a blob holds its IDs: no when a blob's minimum does not exceed the previous blob's maximum or a blob claims more elements than its range holds IDs, yes only when every blob of that type claims a single element, unknown otherwise (--distrust-metadata decodes and answers). Numeric ascent is not canonical OSM order once a file holds negative IDs; check --ids and --extended's data.objects_ordered judge canonical order |
--locations | Show locations-on-ways diagnostics |
--anomalies | Show blocks outside inspect's per-type median thresholds, plus mixed blocks |
--extended | Extended scan: timestamp range, data bbox, metadata coverage, ordering. Coverage counts objects whose field carries an available value, as osmium fileinfo -e: version 1 or more, non-zero timestamp, positive changeset and uid, a user name resolving to a non-empty string; each field is judged on its own value whatever the version, so a present uid 0 or empty user is no uid or user, and a user index past the string table counts as no user. The timestamp range covers non-zero timestamps only, and prints as YYYY-MM-DDTHH:MM:SSZ, with the exact .SSS milliseconds after the second holding the instant only when an extreme is not a whole second; a year outside 0000 to 9999 prints with more digits or a sign rather than refusing the file. A timestamp whose millisecond scaling by the block's date_granularity overflows refuses the blob as invalid data. With no objects, "All objects have" and "Some objects have" are both (none). It also reports whether any decoded element ID is negative (Negative IDs:, data.has_negative_ids in --json and as a --get key), a property of the input, not a fault. Ordered: (data.objects_ordered) says whether the decoded elements strictly ascend by type (nodes, ways, relations) and then by ID in canonical OSM order (0, then negative IDs by magnitude, then positive IDs), the order sort writes and check --ids judges; a repeated ID within a type is not ordered. It reads the element stream, not the block layout, so a block holding a node group followed by a way group is ordered although the ordering analysis counts it as a mixed segment. CORRECTNESS.md "Metadata coverage in inspect --extended" lists the boundaries against fileinfo. (-e used to be its short; -e now refuses here, naming --extended.) |
-g, --get <KEY> | Get a single value by key path (e.g. header.bbox, data.timestamp.first). Data and metadata paths enable extended stats automatically. The output is that one value and nothing else, so it is not combinable with --json, --indexed, --nodes, --blocks, --anomalies or --id-ranges (the last three only shape the full report). --extended, --locations and --distrust-metadata are accepted: each makes the scan decode payloads, so an elements.* count is counted rather than read from indexdata. A file.* or header.* key refuses --distrust-metadata whatever else is given, since no blob metadata can change its value. An unknown key is refused before the input is opened. |
--json | Machine-readable JSON output (schema_version 5; 4 made id_ranges.<type>.monotonic nullable, 5 made header.replication.timestamp a UTC timestamp string instead of an integer of seconds). Not combinable with --nodes (node stats have no JSON form) or --get. elements.tagged_nodes is null when the scan did not measure it: indexdata carries no tag count, so the index-only fast path leaves it unmeasured (--distrust-metadata or any decoding flag measures it); a number is always a decoded count. The text report prints (N tagged) only for a measured positive count. |
--show <TYPE_ID> | Display a single element by ID (e.g. n123 or node/123). Also accepts w456 / way/456 and r789 / relation/789, including signed IDs. Uses indexdata to skip non-matching blobs without reading them; stops at the element, so a miss walks the whole file (the header's sort claim is not trusted to end it early). A mode of its own: mutually exclusive with every other inspect flag (--indexed, --nodes, -j, --blocks, --id-ranges, --locations, --anomalies, --extended, --get, --json, --force, --distrust-metadata). |
--distrust-metadata | Decode every blob instead of reporting counts, ID ranges and per-block stats out of the blobs' own indexdata. Nothing validates indexdata against the payload it describes, so on a file you are inspecting because you suspect it, the default fast path reports the file's claims rather than its contents. Applies to the scanning report only: rejected alongside --indexed, --nodes on its own, and a file.* or header.* --get key (even when --extended or --locations sends that key through the full scan), none of which consult indexdata contents. Beside --nodes with a report flag such as --id-ranges it is accepted and applies to that report. |
--direct-io | Use O_DIRECT on the paths listed in the I/O capability matrix |
--force | Proceed on unindexed input with the slower fallback. Requires --nodes: only the node-stats scan refuses unindexed input, so passing it to another mode is an error rather than a no-op. |
The ordering analysis splits the data blobs into segments, runs of consecutive blobs of one kind (nodes, ways, relations, or mixed for a decoded blob holding more than one kind). The order is standard when there is at most one segment of each kind, in that order, and none mixed. The report counts every segment but lists only the first 64 with their block ranges (ordering.segment_count and ordering.segments_head in --json), so a file whose kind changes every blob costs no per-blob memory; the segment where a file first leaves standard order is always among those listed.
Text taken from the file prints as a quoted literal, escaped exactly as diff -v escapes keys, values and roles (a complete double-quoted string that is also a valid JSON string), so a newline, tab or quote in the text can never split a line or forge another one. In the report that is the file name (File: "name" (size)), the writing program (Program: "..."), each header feature (Features: "a", "b") and the replication URL on the Repl: line. The header's replication timestamp prints in every output (the Repl: line, JSON header.replication.timestamp, --get header.replication.timestamp) as YYYY-MM-DDTHH:MM:SSZ UTC, which --output-header osmosis_replication_timestamp= reads back; a year outside 0000 to 9999 prints expanded (five digits, or a sign), which that override refuses, so pass such a value as seconds. --show prints tags as "key"="value", the user as user: "name", and each member as type/id "role" (an unknown member type as unknown(raw)/id); a user or role whose string index is invalid prints a bare <invalid>, which a real string, always quoted, cannot be confused with. --get is the exception: it prints the raw value followed by one newline, unescaped, so a value holding a newline spans lines; use --json to read such a value losslessly. The file name is the path's last component as UTF-8, with invalid bytes replaced, in every form.
--show prints each metadata field the element claims on its own line (version, timestamp in whole epoch seconds, changeset, uid, user, visible), zeros and an empty user (user: "") included, and no line for a field it does not claim. A timestamp whose scaling by the block's date_granularity overflows 64-bit milliseconds prints timestamp: <invalid>. A dense node's claims follow CORRECTNESS.md "Version 0 is not a version claim either".
inspect --json and export use serde_json's JSON escaping for every destination, including a terminal. Quotes, backslashes and C0 controls are escaped; DEL, C1 controls, U+2028/U+2029 and Unicode bidi controls remain literal. This deliberately differs from human text quoting: the data format has the same bytes whether displayed, piped or saved, and JSON readers recover the original strings. Raw JSON is therefore not a terminal-safe display of untrusted strings; use a viewer that escapes display controls when reading it interactively.
inspect tags
Count tag keys, or key=value pairs for expressions with = (subcommand of inspect).
pbfhogg inspect tags [OPTIONS] <FILE> [EXPRESSIONS]...| Flag | Description |
|---|---|
--min-count <N> | Only show rows with at least this many occurrences [default: 1] |
-M, --max-count <N> | Only show rows with at most this many occurrences |
--sort <ORDER> | Sort order: count-desc (default), count-asc, name-asc, name-desc. count and name are accepted as aliases for count-desc and name-asc. (-s used to be its short; -s now refuses here, naming --sort.) |
-e, --expressions <FILE> | Read tag expressions from file (one per line, # comments) |
-t, --type <TYPE> | Count one element type: exactly one of node, way, or relation (a list is refused) |
-j, --jobs <N> | Worker threads (see Worker threads) |
--direct-io | Use O_DIRECT on the paths listed in the I/O capability matrix |
--force | Proceed on unindexed input with the slower fallback (see Proceeding without indexdata). Only with --type or expressions that together leave some element type out: any other run schedules every blob whether or not it is indexed, does not refuse unindexed input, and refuses --force as ineffective |
What is counted follows osmium tags-count. With no expression, every key is counted: one row per key, with the number of its occurrences, whatever their values. An expression without = (highway, addr:*) counts the keys it matches the same way. An expression with = (highway=*, highway=primary, highway!=primary) counts the key=value pairs it matches, one row per pair. A tag matched by both kinds of expression is counted in its key row and in its pair row (highway highway=* prints the highway total beside its breakdown by value). -e expressions join the positional ones in one list, and every key is counted only when that list is empty; osmium also counts every key when -e is given with no positional expression (see DEVIATIONS.md).
Each output row on stdout is tab-separated: the count, then the key, then for a pair row the value, each text field a double-quoted literal escaped as in diff -v (a valid JSON string). A key row is two fields, for example 120, TAB, "highway"; a pair row is three, for example 80, TAB, "highway", TAB, "primary". A pair whose value is the empty string is a three-field row ending in "", a different row from its key's. A tab or newline inside a key or value prints escaped, so splitting a row on tabs always yields two or three fields and each quoted field JSON-decodes to the original text.
--min-count and --max-count apply to every row, key and pair alike. --sort count-desc and count-asc break ties by name ascending; the name orders compare the key, then the value, a key row before its own pair rows in name-asc (after them in name-desc), which is osmium's order for every key without a NUL byte.
After the rows, one summary line on stderr gives three figures: K key rows and P key/value rows counted, R passed the count thresholds. K and P are the distinct key rows and pair rows the run selected (after --type and the expressions), before --min-count and --max-count; R is how many rows of both kinds those thresholds kept, which is the number of rows printed. None counts occurrences, and K is 0 for a run whose expressions all carry =, whatever keys its pairs have. -q drops the line (see Quiet).
inspect tags expressions use the same syntax as tags-filter, including element-type prefixes. For example, w/highway=primary counts that match only on ways; --type adds an overall element-type restriction.
Expressions select individual tags for counting. If a way has both highway=primary and name=Main Street, the expression w/highway counts only its highway tag, in the highway key row. In tags-filter the same expression selects the whole way; export also selects whole elements and accepts an omitted expression filter as unrestricted.
Counts are exact. Memory grows with the number of distinct selected rows (keys and key/value pairs) and their string bytes, with no fixed byte cap or spill to disk. One table, split into shards that the workers fill concurrently, stores each distinct pair's value bytes and counter, each key row's counter, and each distinct key's bytes once per shard holding a pair or the row of it, plus hash-table capacity overhead. A run that counts only keys (no expression, or none with =) holds no pairs, so it stays small; one with *=* holds every distinct pair of the file. The blob schedule, decoded blobs and each worker's per-blob scratch add transient storage; input blobs are not limited to the writer's default element count. Every distinct row stays in the table until the scan ends, whatever --min-count or --max-count say; only the rows those thresholds keep are then copied out, shard by shard, to be sorted and printed. Consequently count thresholds do not bound memory, even when few rows are printed. Restrict element types and tag expressions to reduce the selected cardinality; neither a higher minimum count nor fewer workers bounds the table. No approximate counts or silent truncation are used.
check
Validate PBF file integrity (IDs + referential integrity; opt-in blob metadata and inline way locations).
check verifies a file: its contents against its claims and against the format's invariants, exiting 1 on a violation. Describing a file - what it claims, cheaply - is inspect's job.
Validate PBF integrity along four independent axes, selected by flag. With no flag, the ID and referential integrity checks both run. Together they read the file once, indexed or not: each blob is decompressed and validated once for both checks, and each check still reports, stops or fails on its own, exactly as when run alone. On an unindexed file the referential check reads again only the blobs it re-reads when run alone.
--index and --locations are selectors like the other two but are deliberately not in the default set: each decompresses every blob in the file (--locations the way blobs once per pass), and folding that into a bare check would multiply the cost of the command everyone already runs; --locations also applies only to LocationsOnWays files. Passing either suppresses the default pair; combine selectors to run more than one.
pbfhogg check [OPTIONS] <FILE>| Flag | Description |
|---|---|
--ids | Check ID uniqueness and ordering only |
--refs | Check referential integrity only |
--index | Verify blob-level metadata against the blobs. Decompresses every blob |
--locations | Verify a LocationsOnWays file's inline way-node coordinates against its node records |
--agreement | Also require every inline coordinate of a node the file does not contain to agree across the ways referencing it. Requires --locations |
--full | Full duplicate detection (applies to ID check). A kind whose IDs are in strict canonical order holds no duplicate, so on an ordered file --full costs what the plain ID check does. On a kind found out of order, only the blobs that could hold a duplicate are read a second time with an ID bitmap (gigabytes at planet scale when they are many): a blob out of order inside itself, and blobs whose ID ranges overlap. A blob in order whose range meets no other is skipped wherever it sits in the file |
-t, --type <TYPE> | Filter by element type (comma-separated: node, way, relation; applies to ID check). Limits the kinds whose IDs are judged; type order is judged over every kind |
--max-errors <N> | Retain at most N violation details per check (0 = unlimited); scanning and total counts continue. The ref check retains details only under --show-ids [default: 100] |
--check-relations | Also check relation member references (applies to ref check) |
--show-ids | Show IDs of missing objects, format: n123 in w456 (applies to ref check) |
--json | Machine-readable JSON output |
--direct-io | Use O_DIRECT to bypass page cache where the check supports it: the ID check's front read and --index. --refs and --locations read buffered, through parallel unaligned blob preads; beside the ID or index check (the default pair included) they read that way without saying so, and without either it the flag is refused |
With the global -q, --quiet check prints no report: the exit code is the answer. --json, --show-ids and --max-errors, which only shape the report, are refused with it.
--full and -t/--type apply to the ID check and are rejected under --refs alone; --check-relations and --show-ids apply to the ref check and are rejected under --ids alone; --agreement is rejected without --locations. An explicit --max-errors is rejected under --refs alone without --show-ids, where no selected check retains details; the default is not. --direct-io is rejected under --refs, --locations or the two together, where no selected check reads it. Violations exit 1, not 2 - see Exit codes.
A false kind claim stops the check (exit 1). --refs, --ids and --locations read each blob in the pass of the kind its indexdata claims (--locations only for blobs claiming ways), so a blob holding an element of another kind is one the pass that needs it never reads. When a pass that does decode such a blob meets the foreign element, that check stops: its report is the one line <Check> stopped: blob N at byte offset M claims X but holds Y elements; its claimed-kind partition is invalid, with no counts and no other findings (they may already be false: a node hidden in a blob claiming relations makes a way's reference to it look missing before the relation pass finds the lie), its JSON section is {"complete": false, "passed": false, "kind_contradiction": {"claimed", "found", "blob", "offset"}}, and check exits 1, the same verdict --index gives the file. Other selected checks still run and print. A Note: names check --index and cat --reindex, the repair. The test is for a foreign kind only, decided on the decoded elements (an empty dense-node message is no node): an empty blob under any claim passes it. What no pass decodes is not seen: without --check-relations the ref check never reads a blob claiming relations, and --ids -t reads only the selected kinds' blobs; --index verifies every claim. When a file has two lying blobs, which one is named can vary from run to run.
A partially indexed file stops the check (exit 1). --refs, --ids and --locations do not run over a file with indexdata on some data blobs and not others, which the other commands refuse; instead the check stops, its report the one line <Check> stopped: blob N at byte offset M has no indexdata, but other data blobs carry it; the file is partially indexed, which this check does not accept (blob N is the first data blob without indexdata), its JSON section {"complete": false, "passed": false, "partially_indexed": {"blob", "offset"}}. Other selected checks still run and print, so check --ids --index reports the index check beside it. A Note: names cat, which indexes every blob that lacks indexdata. The judgement is made on blob headers only: a data blob no index can describe (empty, or mixed kinds) carrying no indexdata among indexed ones stops these checks too, while --index, which decodes it, passes the file.
A wholly unindexed input is checked, not refused. With no claims to read blobs by, --ids and --refs read each blob once and judge every kind it holds in that one read; --refs reads a blob again, once per kind at most, only where a way's reference or a relation's node or way member missed in that read: its target not yet read, an ID above the range the check sized from the file or a negative one (no sized range covers a negative), or a reference missing in fact. A sorted, referentially complete file costs about one read of each blob; no file costs more than one read per kind. The type-order check of --ids judges the decoded elements in the order pbfhogg reads them: blobs and their groups in turn, and within a group its nodes, then its ways, then its relations, whatever its field order (a group holding several kinds breaks the PBF format; it is read, not refused). A blob holding several kinds in order passes it; one whose way group comes before a node group fails it (type order: node after way). A Note: says the input has blobs without indexdata.
For missing node refs in ways and missing relation-to-relation members, reports unique missing IDs with the occurrence count when they differ: Missing node refs in ways: 1 (2 references), Missing relation members: 706 (777 references). JSON carries both counts (missing_node_refs and missing_node_ref_occurrences, missing_relation_members and missing_relation_member_occurrences). The FAILED (N missing references) total sums the unique counts.
The ID check judges monotonicity by canonical OSM order - 0, then the negative IDs by ascending absolute value, then the positives - which is the order sort produces. On a positive-only file (every production PBF) that is plain i64 order; on a file carrying negative IDs the two differ, and the canonical one is the definition. --full judges duplicates by the same signed IDs: n-7 repeated is a duplicate, and n-7 beside n7 is not.
The ID check lists its details in a fixed order, the same on every run and for a file with or without indexdata: kind-order findings first, then each kind in turn (nodes, ways, relations), its order violations in file order followed by its duplicates in canonical ID order, one per extra copy. --max-errors keeps the first N of that list.
Index verification
check --index is the metadata trust boundary. BlobHeader.indexdata (element kind, ID range, element count, spatial bbox) and BlobHeader.tagdata (the blob's tag key set) are claims every fast path in this crate believes without opening the blob; who believes which, and what a false one costs, is in indexdata-trust.md. Nothing in the format signs any of it, and degrade --corrupt-indexdata / --corrupt-indexdata-kind / --corrupt-tagdata exist precisely to manufacture files whose hints are well-formed and false.
check --index does not verify order: a file whose header claims Sort.Type_then_ID with a blob internally out of order passes it. Combine it with --ids, which checks ID and type order.
The CLI names check --index alongside the repair for missing indexdata (whole or partial) and contradictory indexdata. For an unsorted refusal it names check --index --ids alongside sort --distrust-metadata: diagnosing order requires --ids. These checks report defects; they do not repair them.
check --index is the other side of that boundary. It decompresses every OSMData blob, re-derives the metadata from the payload with try_scan_block_ids_checked (and, where the blob carries tagdata, the key set from the same walk), and reports each disagreement with the blob's ordinal and byte offset.
The input is read front to back through one open, so with --index alone <FILE> may be a stream (a FIFO, /dev/stdin). Blobs are decompressed and scanned on a worker pool while the read runs a little ahead of the report, so a failure partway through a stream can wait for the stream's writer to write again or close it before the command exits.
Those are the same two scanners the writer's passthrough path uses, so on a re-framed blob the check cannot catch a bug in the scanner itself - it can only catch metadata that has since diverged from its payload. Against the ordinary write path it is genuinely independent: BlockBuilder derives its index incrementally as elements are added and never rescans the bytes it emitted, so a disagreement between the two is a real finding either way.
There is no --distrust-metadata flag on it, by design. A verifier that consulted the thing it is verifying in order to decide what to look at would be worthless, so the command installs no blob filter, never calls require_indexdata, and decompresses every blob unconditionally - including blobs whose stored index claims a kind nobody asked about. Distrust is the only mode it has.
Absence is not a claim. A blob with no indexdata, or no tagdata, is not reported; that is the ordinary state of any third-party PBF, and of every v1 (26-byte) index, which has no bbox field at all.
Unreadable is not the same as absent. Indexdata whose length, version byte or element-kind byte the reader does not recognise is reported as a violation even though every reader collapses it to "no index" and decodes the blob. The safe reading is right for a reader and wrong for a verifier: a file that claims something it cannot back up is not a file that claims nothing. Malformed tagdata is reported the same way - including a key list that is out of order, repeats a key, or is followed by stray bytes, which readers also treat as no tagdata - and so is a well-formed tagdata attached to a blob this crate refuses to index at all - a group mixing element kinds, where any key set is necessarily incomplete because the scanner sees only the first element field, and tags-filter would skip the blob on the strength of it.
Two checks are containment rather than equality:
| Field | Test | Why |
|---|---|---|
| kind, count, min_id, max_id | exact equality | every consumer treats them as exact |
| bbox | stored must contain the blob's coordinates | the scan rounds outward through granularity/lat_offset/lon_offset, so a stored box narrower than the scan is the only shape that can make a spatial filter skip a blob it should have read. A wider box is sound; an absent box is no claim. A node coordinate outside the i32 decimicrodegree range lies outside every box, so a stored box over it is reported |
| tag key set | stored must contain every key the blob carries | an omitted key makes tags-filter skip a blob holding matches. A key listed but not present is sound - it only costs a decode - and is reported as a separate, distinct violation |
Exit 1 means mismatches were found, exit 2 that the check could not run.
Inline location verification
A LocationsOnWays header claims every way carries, per node reference, that node's location. check --locations compares each inline coordinate with the same file's record of that node. It exists because nothing else answers whether such a file is right - inspect --locations only counts ways with and without coordinates - and because it is an oracle independent of osmium for any producer of such files, add-locations-to-ways and apply-changes --locations-on-ways included.
Violations (exit 1). A reference whose inline coordinate differs from its node's record; a way with references but no coordinate arrays; an inline coordinate outside the geographic domain, judged on the exact nanodegree value (osmium's undefined location, 2147483647 on both axes, is one); a node whose valid records disagree with each other; a node record outside the domain (each record counted once). References to a node with conflicting or out-of-domain records are counted and not compared, since the node already carries its own violation. With --agreement, an absent node whose references carry two or more different coordinates.
Counted, not failed. A reference to a node the file has no record of. add-locations-to-ways keeps a node only if it is tagged, a relation member, or --keep-untagged-nodes is given, so on its default output most references have no record. Nothing in LocationsOnWays requires the record, so its absence is not a violation; the report counts such references, and those of them at exactly 0,0, the placeholder --ignore-missing-nodes writes. The count is of references, not distinct nodes: a distinct count would need another ID set that grows after the store is sized. --agreement checks the one thing the file can still show about those nodes, that all their inline copies agree, and reports the distinct number of absent nodes. That is consistency, not freshness.
Every reference is counted once, in one of: verified, mismatched, not compared (a node with one valid record, referenced by a way without coordinates or with an out-of-domain one, each reported as such), to a node with conflicting records, to a node with an out-of-domain record, and without a node record. The six sum to the reference count.
Refused (exit 2). A header without LocationsOnWays (no claim to check); a header declaring HistoricalInformation (several versions of a node legitimately disagree); any data blob the reader refuses to build a block from - every blob is validated once with the reader's own construction, which checks group and element framing, tag arrays and every tag key and value string-table index against the table, Info and DenseInfo arrays, way geometry and relation member arrays and string table UTF-8, but not what the reader only finds when it resolves other strings (a role or user string-table index past the end of the table passes). A blob whose indexdata claims ways while it holds elements of another kind is not a refusal: the check reads such a blob only in its way passes, so it stops there and fails the file (exit 1), as described under check above. The reader's verdict on such a blob comes first, with or without --agreement: one the reader also refuses is refused (exit 2). A partially indexed file stops it the same way (a blob whose indexdata cannot be read, a reversed range included, counts as unindexed, so among indexed blobs it makes the file partially indexed).
Comparison. Each coordinate is offset + granularity * raw nanodegrees, computed in 128-bit arithmetic (a product that overflows i64 can be brought back into range by the offset), judged against the domain exactly, then truncated toward zero to decimicrodegrees as the reader's decimicro_lat does. Inline and node values are compared there: values equal to the decimicrodegree are equal, which only blocks with a granularity below 100 or an offset that is not a multiple of 100 can distinguish further.
Mechanism and scale. An up-front pass decodes every blob that does not claim ways (node, relation and unindexed blobs) once, while the header walk is still discovering the file's blobs: it validates it, counts node records and invalid ones, inserts their IDs into the key set (the node IDs that get a slot; with --agreement, a further pass over the way blobs adds every referenced ID), and records which element kinds and which node-ID range the blob actually holds. Later passes route those blobs on what this pass saw, never on their indexdata, so after it an unindexed file costs the same passes as an indexed one; the up-front pass itself reads an unindexed file's way blobs too, which an indexed file's it skips. The key set is built by the workers directly, sharded by IdSet chunk, so no per-blob ID vector waits in a queue. It is then ranked and its rank space cut into partitions whose store fits the budget; partition k owns the node IDs of a contiguous ID interval, the intervals cover all of i64, and each ID belongs to exactly one. The store is built in bounded windows of slots: for each window, the records of every blob holding nodes in its ID interval are joined into it (a join over empty < coordinate < conflicting < out of domain, so the result is independent of worker order), taken from the blob's projection where the up-front pass kept one and by decoding the blob again otherwise. A projection is the blob's node IDs and the values they join with, in record order, kept while the bytes were already decoded; whether a blob has one changes the cost figures, never the answer. Once a partition's store is full, every blob holding ways is decoded and each reference the partition owns is compared, streaming one reference at a time; later partitions scale a coordinate only for an owned reference, while the first scales every one for its structural checks. The first partition also makes the partition-independent checks (missing arrays, out-of-domain inline values) and validates the blobs claiming ways, which the up-front pass did not read, in the same walk that scans their ways (with --agreement, the reference pass validates them instead, being the first to read them). Counts come from a scan of the final slot states, never from which worker won a race, and the retained details are the smallest by file position or node ID, so neither depends on timing or on the number of partitions. The check streams observations without scratch. Each way blob can reference nodes across the file, which limits how much whole-blob skipping could save. See the partition measurements for the measured mask trial and estimated spill traffic.
Memory. The store packs the coordinates of each block of 32 slots as offsets from the block's per-axis minima, at the widths the block needs. It adds a 16-byte block header and one mismatch bit per slot. A block holding a conflicting or unusable node keeps exact 8-byte words. Absent slots take no coordinate space, but under --agreement each one takes an 8-byte slot. Partitions are cut by encoded bytes, so how many a file needs depends on how closely neighbouring IDs' coordinates pack. Node records are joined into the store in bounded windows of slots. The budget is 60 % of the memory the host reported available before the run read any blob, less 2 GiB of headroom and an upper bound on the key set and its rank index (IdSet::ranked_bytes_upper_bound: 4 MiB and its block prefixes per allocated chunk, plus the chunk directory and its rank vectors); 4 GiB when the host reports none; never below 64 MiB (CHECK_LOCATIONS_* in crates/lib/src/tunables.rs). It is read before the passes because a host that charges page cache to the process (a cgroup v2 limit) reports far less available once the file has streamed through; for the same reason check runs --locations before any other selected check (the report order is unchanged). More than 16 planned partitions draw a warning naming the count and the budget. The budget bounds the store only: the key set (about 1.7 GB over a planet's node ID range) follows the number of distinct IDs; each worker holds its decompressed blob, validated where it lies, and a fixed ID batch; and retained violation details: with a non-zero --max-errors, at most that many per finished blob and in the report, and up to twice that (at least 64) in a list still collecting before it trims back; unbounded with --max-errors 0. No scratch disk is used.
Node projections take about 9 bytes per node record on sorted input. While the up-front pass (and the --agreement reference pass) build the key set, projections and the key set's chunks share 40 % of the memory available before the run less the headroom; each key chunk is charged at its full 4 MiB before its first ID goes in, and a charge that crosses that line drops retained projections at once, so the key set always takes precedence. Once the store budget is known, projections are cut, latest first, to what the headroom, the key set, the store budget and one window's raw words leave, and each is dropped after the last window its node range meets. A host that reports no available memory projects nothing. A blob with more than 1 Mi node records is never projected.
A planet that keeps every node has about 10 billion slots, tens of GB of store even packed: on a host with 28 GB free that is several partitions, so the way blobs are read several times. A node blob without a projection is decoded again for each window its node range meets: in a sorted planet once, or twice where it straddles a window's boundary; in an unsorted file, a node blob whose IDs are spread out can meet every window. A default add-locations-to-ways planet keeps a few percent of its nodes and fits one partition; with --agreement it needs as many as a complete one. The partitions and blob_decodes fields of the JSON report are these cost figures; they follow the host, not the file.
Negative IDs are checked like any other by every check: --refs resolves a reference to n-7 against n-7 only, never its positive twin, and reports it missing under its signed ID; --locations gives a negative node a slot, so its records, its references and (with --agreement) the inline copies of an absent one are compared; --ids --full orders and deduplicates them canonically, so an ordered file holding negatives passes. The ID check reports whether any element ID of a selected kind is negative (has_negative_ids in its JSON, Negative IDs: in its text); it is a property of the input, not a violation. Under --check-relations the ref check refuses (exit 2) a relation member of an unknown type, which no set can resolve. An ID outside the range the ref and full ID checks sized from the file's own indexdata (above it, or negative) is still tracked, inserted from each phase's merge. Missing references are counted into one ID set per category, so their memory follows the range of the missing IDs rather than the number of references. Retained --show-ids details (all of them under --max-errors 0) and the deferred relation-to-relation members still cost memory per occurrence.
cat
Concatenate PBF files with optional type filtering. Embeds blob-level indexdata and tagdata automatically.
With --dedupe, merges multiple sorted PBF files with blob-level passthrough and exact-duplicate deduplication.
The data blobs of every input are ordered by kind, then by first ID, ties in argument then file order. An overlap run starts at a blob whose range the next blob of its kind starts within, and grows while the next blob of its kind starts at or below the highest ID the run reaches so far, so overlap is followed transitively. A blob in no run is passed through with its serialized Blob payload unchanged (an unindexed one under a rebuilt blob header, below); a run's blobs are merged, deduplicated and re-encoded in its place. Exceptions: a blob holding no element is omitted, and an unindexed blob that is internally out of order or that no single index describes is rewritten even where it overlaps nothing.
With two distinct indexed inputs, a node or way overlap run of at least one million input records can merge independent ID ranges in parallel. The IDs must be positive and each input's blob ranges in the run must be disjoint within that input. The path can spill up to 4 GiB per run to scratch. If the spill exceeds that budget or runs out of writable space, the streaming sweep handles the run. Ranges cut between IDs, so every version and copy of an ID is judged together. Way range cuts also align with the sweep's output block boundaries.
A blob that already carries indexdata is passed through with it, unchecked, so plain cat cannot repair false indexdata; --reindex (below) does. --type copies a blob raw on its indexdata kind and --dedupe passes blobs through on their kind and range, both believed without a decode. See indexdata-trust.md.
--reindex: the repair for false indexdata and tagdata. Every data blob is decompressed and scanned, and its BlobHeader is rewritten with every indexdata (field 2) and tagdata (field 4) occurrence replaced by one derived from the payload; the compressed payload and every other header field (the WayMembers-v1 field 5 and unknown fields included) are copied byte for byte, the file header's HeaderBlock is carried through unchanged (its frame is written afresh under --compression, so a field of the header blob's own BlobHeader or Blob envelope is not kept), and any other blob is copied as it is. The input is read front to back through one open while blobs are scanned on a worker pool, so it may be a stream, read a window of blobs ahead of the output; a failure partway through a stream can wait for the stream's writer to write again or close it. The summary, Reindexed N blobs; indexdata changed in I, tagdata changed in T, counts the data blobs written and, independently (a blob can be in both), those whose indexdata changed (absent, unreadable or a different index; compared as values, so an older index version describing the same block does not count) and those whose tagdata as written differs from the input's (gained, dropped by the header-size rule below, a different key set, or repeated occurrences collapsed). The counts describe the rewrite, not a verdict on the input: blobs that gain tagdata the input never had were not wrong, and check --index is the verdict. A block no single index can describe (no elements, a group carrying more than one element field, or kinds mixed across groups) is refused (exit 2, nothing published) rather than left unindexed, which would make the output partially indexed, or re-encoded, which is not lossless; such a file is repaired only by a re-encoding mode. A rebuilt header that would reach the 64 KiB BlobHeader limit is written without its tag index, as the writer does, and refused if it still would. It takes exactly one input and is refused with --type, --clean, --dedupe, --force, --generator and --output-header. It accepts an unindexed and a partially indexed input.
--repair: rewrite what every reader refuses. Every data blob is decompressed and validated as a reader decodes it, and a blob refused for a shape with a defined meaning is rewritten into it instead of failing the run. The one such shape today is a repeated data-bearing Info or DenseInfo (Node.info appears twice with data and its kin), merged as protobuf merges a repeated message field: a field set in a later occurrence overrides an earlier one, and DenseInfo columns concatenate (see DEVIATIONS.md). Each occurrence must frame cleanly on its own, and the merged block is validated like any other, so merged columns longer than their group are refused, as is every other refusal. Accepted blobs are written as plain cat writes them, so an indexed blob is copied whole with its indexdata unchecked (--reindex checks that); a repaired blob's payload is recompressed under --compression and keeps every BlobHeader field except indexdata, tagdata and datasize, which are replaced. A Note: line counts the merged elements, dense groups and input blobs, and the summary adds Repaired N input blobs. Without --repair, plain cat copies an indexed blob unread, so such a blob passes through it, and --clean and --type refuse it. With --clean, the clean pass repairs as it decodes; --type needs --clean alongside, since the type passthrough copies selected blobs unread. Refused with --dedupe and --reindex. A well-formed file costs a full validating decode under this flag and nothing without it.
pbfhogg cat [OPTIONS] --output <OUTPUT> <FILES>...| Flag | Description |
|---|---|
-o, --output <FILE> | Output file |
-O, --overwrite | Replace the output if it already exists. Without it an existing output is refused before any work is done; a symlink is refused either way |
--staging-dir <DIR> | Stage the output in DIR instead of beside it (see Staging directory) |
-t, --type <TYPE> | Filter by element type (comma-separated: node, way, relation). Not valid with --dedupe. |
--clean <ATTR> | Strip metadata attribute (repeatable: version, timestamp, changeset, uid, user). Not valid with --dedupe. (-c used to be its short; -c now refuses here, naming --clean.) |
--dedupe | K-way sorted merge with dedup (all inputs must be sorted). Rejects --type and --clean: the dedupe path is blob-level passthrough and implements neither. |
--reindex | Rewrite every data blob's indexdata and tagdata from its payload, losslessly; one input. See above |
--repair | Validate every data blob and rewrite one refused for a repeated Info or DenseInfo into the merged message. With --type it needs --clean; not valid with --dedupe or --reindex. See above |
--compression | Blob compression [default: zlib] |
--direct-io | Use O_DIRECT on the paths listed in the I/O capability matrix |
--io-uring | Use io_uring for output I/O. Supported for plain passthrough and --dedupe. Combine with --direct-io to use direct input reads. |
--force | Proceed on unindexed input with the slower fallback. Requires --type or --dedupe: plain cat adds the indexdata and --clean without --type decodes every blob once either way, so neither refuses and --force with only those is an error. --type node,way,relation --clean is the clean pass, which does not refuse; --force there is accepted and does nothing. |
--generator | Override writing program name |
--output-header <K=V> | Set output header fields (repeatable) |
Blocks no single index describes. Plain cat copies an indexed blob whole and an unindexed blob's payload unchanged, rebuilding only its blob header to add indexdata (which drops any field 5 the header carried). The exception is an unindexed blob whose block no single index can describe (no elements, a group carrying more than one element field, kinds changing across groups); an indexed blob is never scanned, so it passes through whatever its block holds. Such an unindexed block is rebuilt into single-kind blocks by the same rules --type and --clean re-encode with: nodes written dense, coordinates and timestamps converted as PBF rebuild precision describes, metadata with an absent or sentinel version discarded, missing fields of retained metadata written as defaults, unknown fields discarded. Elements keep their input order, except inside a group carrying several element fields, which is written dense nodes, then plain nodes, ways and relations, whatever its field order (libosmium follows the field order; see DEVIATIONS.md). One that yields no elements is omitted, with any unknown fields it carried. A Note: line says how many blobs were rebuilt and how many omitted; the summary counts both as decoded. A way in such a block is refused under a declared WayMembers-v1, and a way carrying pins under a declared SharedNodePins-v1, since the rebuild cannot write either.
--dedupe (and sort, which shares its engine) treats an unindexed blob the same way where it can: a blob one index describes passes through under indexdata and tag keys scanned from its payload, and one holding no element is omitted. A block no single index describes is not split in input order but merged: each kind's elements join that kind's merge, are re-encoded as the overlap runs are (the way blobs among them losing the prepass enrichments, and their inline coordinates unless every input declares LocationsOnWays), and come out in type-then-ID order, with exact duplicates dropped under --dedupe. A Note: line says how many blobs were restructured and how many omitted, and the summary counts a restructured blob once, as rewritten, and an omitted one as omitted.
Output header. Follows Output header. Plain cat copies way payloads whole and --type copies indexed way blobs whole, so the way enrichments the input declares are kept (a rebuilt block keeps inline locations and refuses the rest, as above; --clean re-encodes, and drops them); --dedupe re-encodes the way blobs in its overlap runs, keeping their coordinates when every input declares LocationsOnWays. With several inputs the header is reconciled across all of them, the output is not declared sorted (--dedupe excepted), and the prepass features are never declared. osmium writes a wholly blank header for multiple inputs - the same honesty rule, applied bluntly - so keeping the agreed fields is a deliberate deviation (DEVIATIONS.md).
sort
Sort PBF into standard order (nodes, ways, relations, each by ascending ID; records of one ID, as in a history file, by ascending version, and records of one ID and version in input order). Every record is kept. For already-sorted inputs with indexdata, blobs pass through as raw bytes; under a header claiming Sort.Type_then_ID that includes trusting each blob's versions of one ID to ascend, which --distrust-metadata checks.
pbfhogg sort [OPTIONS] --output <OUTPUT> <FILE>| Flag | Description |
|---|---|
-o, --output <FILE> | Output file |
-O, --overwrite | Replace the output if it already exists. Without it an existing output is refused before any work is done; a symlink is refused either way |
--staging-dir <DIR> | Stage the output in DIR instead of beside it (see Staging directory) |
--compression | Blob compression [default: zlib] |
--direct-io | Use O_DIRECT on the paths listed in the I/O capability matrix |
--io-uring | Use io_uring for output I/O |
--force | Proceed on unindexed input with the slower fallback (see Proceeding without indexdata) |
--distrust-metadata | Believe no claim the input makes about itself: decode every blob in pass 1 as for a header without Sort.Type_then_ID (below), and also scan each blob's tag keys, so a blob whose indexdata or tagdata (compared as a key set) its payload contradicts is reframed under scanned ones. Needs no indexdata (--force is not needed alongside it) and accepts a partially indexed input. The repair every Unsorted refusal names: under a sorted header the default fast path copies an internally unsorted blob unchanged, because it believes the claim and the blob's indexdata |
--generator | Override writing program name |
--output-header <K=V> | Set output header fields (repeatable) |
An input whose header does not claim Sort.Type_then_ID (or any input, under --distrust-metadata) has every blob decoded in pass 1 to check its order; a blob whose IDs descend, or whose versions of one ID descend, is rewritten. An indexed blob whose indexdata that scan contradicts is copied under indexdata and tag keys scanned from its payload rather than with the false claim, and a Note: line counts them; the rebuilt BlobHeader keeps every other field, the way-members field 5 included, as cat --reindex keeps it, so the output keeps declaring WayMembers-v1. Unindexed blobs, and blocks no single index describes, are handled as cat --dedupe handles them (see cat, "Blocks no single index describes").
Blobs whose ID ranges overlap are merged into new blocks of up to 8000 elements each, the same for sort and cat --dedupe. In sort, a connected overlap component of at least one million records can use parallel key ranges. It spills a 16-byte index key per record, the encoded records and their string tables to scratch beside the staging file, then maps the spill for the range workers. Allow free space for the largest qualifying component's full spill (16 bytes per record plus the encoded record bodies and per-frame string tables), alongside the staged output. This can exceed the size of the compressed input. The measured Denmark wide-overlap fixture spilled 2,090,116,081 bytes (about 1.95 GiB). Sort fails if scratch fills. See Scratch files.
Records gathered from several input blobs can make such a block too large for one blob (the 32 MiB payload limit, or, compressed, a body past the 32 MiB blob size) although every input blob fits. That block is cut between elements into blobs that fit, each indexed from its own content: first with every piece keeping the block's whole string table, and where that cannot fit, with a dense node group cut between nodes and each piece's string table holding only the strings it uses. Nothing an element carries changes, and the order is kept. What is still refused (exit 2): a single element that does not fit even with only its own strings, and a cut that needs the last few bytes below the limit.
repack
Re-encode a PBF with a configurable per-blob element cap. Element semantics, tags, refs, members, metadata, and DenseNodes encoding all round-trip at the OSM data model's precision (a source block in a non-default framing is converted as PBF rebuild precision describes); output is type-sorted and propagates Sort.Type_then_ID from the input header.
Primary use case: producing same-corpus-different-encoding pairs for blob-density measurement (Geofabrik's ~8 k/blob convention vs planet.openstreetmap.org's ~228 k/blob), so commands with implicit blob-count scaling (HeaderWalker-based paths in particular) can be measured at controlled densities.
pbfhogg repack [OPTIONS] --output <OUTPUT> <FILE>| Flag | Description |
|---|---|
-o, --output <FILE> | Output file |
-O, --overwrite | Replace the output if it already exists. Without it an existing output is refused before any work is done; a symlink is refused either way |
--staging-dir <DIR> | Stage the output in DIR instead of beside it (see Staging directory) |
--elements-per-blob <N> | Per-blob element cap [default: 8000]. 8000 matches the osmium / Geofabrik convention; pass a larger value to approximate planet.openstreetmap.org-style packing. Must be > 0. |
--compression | Blob compression [default: zlib] |
--direct-io | Use O_DIRECT on the paths listed in the I/O capability matrix |
--io-uring | Use io_uring for output I/O |
--force | Proceed on unindexed input with the slower fallback (see Proceeding without indexdata) |
--generator | Override writing program name |
--output-header <K=V> | Set output header fields (repeatable) |
Input blobs with fewer elements of a kind than the cap coalesce across input-blob boundaries (growing, e.g. europe 8 k -> 64 k), so caps larger than the input blob size fire correctly. An input blob with at least the cap's worth is encoded on its own: full blocks of the cap, then the rest as its own possibly-under-cap block, which never coalesces with the blobs after it. So on a shrink the output blob count is not the general ceil(elements / cap), and repacking the output again at the same cap can merge such a remainder with the small blobs that follow it. When the input header declares LocationsOnWays, the output re-advertises it and every inline way-node coordinate round-trips at decimicrodegree precision (exactly, from a default-framed block); the two pbfhogg.* prepass features (WayMembers-v1, SharedNodePins-v1) are dropped with a warning.
degrade
Produce a valid-but-adversarial PBF by stripping properties or perturbing structure. Each flag composes; at least one is required. Used to produce inputs for benchmarking non-optimal code paths (sort overlap-rewrite, add-locations-to-ways, --force fallbacks).
pbfhogg degrade [OPTIONS] --output <OUTPUT> <FILE>| Flag | Description |
|---|---|
-o, --output <FILE> | Output file |
-O, --overwrite | Replace the output if it already exists. Without it an existing output is refused before any work is done; a symlink is refused either way |
--staging-dir <DIR> | Stage the output in DIR instead of beside it (see Staging directory) |
--unsort | Clear Sort.Type_then_ID; perturb the element stream so at least one adjacent same-kind blob pair has overlapping IDs (one per kind that has more elements than --elements-per-blob). Triggers sort's overlap-rewrite path. Needs --elements-per-blob of at least 2: single-element blobs of distinct IDs never overlap, so at a cap of 1 the swap would only permute blobs. On a history input the record at the cap moves together with its ID's later versions, past the first record of the next ID, so a swap always changes the ID order; with no next ID in the kind, nothing moves. |
--unsort-intra | Clear Sort.Type_then_ID; leave one same-kind blob per kind with an internal ID-order inversion but non-overlapping blob ranges - the intra-blob shape sort's overlap detector cannot see. On a history input the first two IDs swap with all their versions, in one blob; a kind whose first two IDs hold more records than --elements-per-blob is left unperturbed. Mutually exclusive with --unsort. |
--strip-locations | Drop the LocationsOnWays header feature. Inline way-node coordinates are not preserved; downstream add-locations-to-ways runs see a redundancy-free starting point. |
--strip-indexdata | Clear BlobHeader.indexdata on every OsmData blob. Forces commands into their --force / non-indexed fallback paths (sort, getid, tags-filter). Blob payloads are not decompressed. |
--strip-tagdata | Clear BlobHeader.tagdata (the per-blob tag key index) on every OsmData blob, forcing tags-filter's no-hint fallback path. Leaves indexdata intact - a tagdata-stripped file is still indexed. |
--corrupt-tagdata | Replace BlobHeader.tagdata on every OsmData blob with a well-formed tag key index naming one key (pbfhogg:degrade:no-such-key) the blob does not carry. The result parses cleanly and lies, so tags-filter skips blobs whose elements match and emits a short answer. This is the adversarial case --strip-tagdata cannot produce: a missing index is decoded rather than trusted, so stripping only exercises the slow path. Mutually exclusive with --strip-tagdata, and with every blob-re-encoding flag (which would rebuild the index correctly). tags-filter --distrust-metadata is what reads such a file correctly. |
--corrupt-indexdata | Replace BlobHeader.indexdata on every OsmData blob with a well-formed index that overstates the blob: same element kind, count and max_id inflated by 1,000,000. The kind is preserved deliberately, so per-kind classify schedules still route correctly and the lie is confined to the counts. Produces the file inspect reports from without decoding anything - see inspect --distrust-metadata. Mutually exclusive with --strip-indexdata and with every blob-re-encoding flag. |
--corrupt-indexdata-kind | Rotate the element kind declared by BlobHeader.indexdata on every OsmData blob - node to way to relation to node - leaving min_id, max_id, count and the bbox honest. The kind is what per-kind blob schedules (build_classify_schedule) select on, so unlike --corrupt-indexdata this is the corruption that makes a consumer skip a blob outright rather than misreport it, which is why the two are separate flags. It is what makes tags-filter --distrust-metadata testable through relation closure and way-dependency collection rather than only through the direct-match pass. Mutually exclusive with --strip-indexdata, combinable with --corrupt-indexdata, and rejected alongside every blob-re-encoding flag. |
--strip-bbox | Clear HeaderBlock.bbox (field 1). Header-only change; no OsmData blob is touched. Exercises inspect's bbox handling (extract_header_metadata, the inspect --get header.bbox fast path) and downstream/external-consumer tolerance of a file with no declared extent. Does not affect extract --bbox, which derives its region from the CLI argument and prunes via per-blob indexdata bboxes rather than reading the header. |
--drop-ids <N:SEED> | Deterministically remove exactly N distinct IDs selected globally by kind, ID, and seed, every record of each: on unique-ID input that is N elements, on input repeating an ID (one record per version) more. The summary's dropped M elements is the measured number of records removed. N above the input's distinct-ID count is refused before any output is written. Surviving references to removed elements intentionally dangle. |
--elements-per-blob <N> | Most elements in any output data blob on the decode path [default: 8000]. Output blobs follow the input's blob boundaries, except under --unsort, which packs each kind continuously to the cap, so the cap also places the --unsort swap. Must be > 0, and at least 2 with --unsort or --unsort-intra. Requires --unsort, --unsort-intra, --strip-locations or --drop-ids; the header-only flags encode no data blob (a usage error otherwise, exit 64). |
--force | Proceed on unindexed input on the decode path (--unsort, --unsort-intra, --strip-locations, --drop-ids), which falls back to scanning every blob for every kind; slower. The header-only flags never refuse, so --force without a decode-path flag is an error. |
--compression | Compression of the blobs the run encodes [default: zlib]. The header-only flags encode only the OSMHeader blob; every data blob is copied with the compression it has |
--direct-io | Use O_DIRECT on the paths listed in the I/O capability matrix |
--io-uring | Use io_uring for output I/O |
--generator | Override writing program name |
--output-header <K=V> | Set output header fields (repeatable) |
Implementation paths: the header-only flags (--strip-indexdata, --strip-tagdata, --strip-bbox, --corrupt-*), with no --unsort/--unsort-intra/--strip-locations/--drop-ids, run as a header-and-blob-level passthrough: the input HeaderBlock payload is forwarded field-for-field via a surgical wire-level field stripper, with only the bbox (field 1) removed under --strip-bbox and each --generator/--output-header override replacing only the field it names, and raw OsmData frames are reframed by copying the original BlobHeader through byte-for-byte with only indexdata (field 2) and/or tagdata (field 4) cleared or replaced as targeted; a --corrupt-* replacement that would grow a header to or above the 64 KiB BlobHeader limit is refused rather than written or dropped. This preserves every other header and blob-header field byte-for-byte - source, custom optional features, a non-default writingprogram, replication metadata, WayMembers-v1, and unknown/extension fields all survive, with or without an override. Any combination involving --unsort, --unsort-intra, --strip-locations, or --drop-ids decodes elements, re-encodes via BlockBuilder, and frames with indexdata=None when --strip-indexdata composes; --strip-bbox on this path clears the bbox from the rebuilt output header. --drop-ids requires N:SEED, rejects zero N, and is reproducible for a given input and seed.
A blob too large for the format on the decode path is refused with advice to lower --elements-per-blob, as on repack, unless the cap is already at its smallest or the oversized blob is the OSMHeader, whose size its header fields set.
getparents --full-scan-min-blobs is a hidden (hide = true) test instrument: it overrides an internal threshold so the suite can fire a code path without building a full-scale fixture. It is not part of the supported surface, and it exists only in builds compiled with the pbfhogg_test_hooks compiler cfg (--cfg in rustflags), which no Cargo feature enables, so no feature selection or cargo install without that cfg produces it; elsewhere the flag is unknown and refused as a usage error. In hook builds it is range-checked at the CLI boundary (1 to 1,000,000,000): the library entry point behind it takes the value raw, and 0 is not a threshold - it pins the FullScan arm unconditionally.
--recompress from the design doc remains deferred. The --unsort perturbation is the minimum-viable swap that triggers sort's overlap detector; configurable chaos modes (rotate / shuffle / reverse) are deferred. The --unsort and --unsort-intra shapes are stated for input already in canonical order with IDs of one sign: input that is itself unordered or has overlapping blobs keeps its own disorder on top of the swap, sort's range keys treat a mixed-sign blob conservatively, and on a history input blobs that share an ID only at their ends (including ones the cap packing creates) come on top of the stated overlap.
renumber
Renumber all element IDs sequentially, remapping cross-references (way node refs, relation member refs).
Each kind is numbered in canonical order (0, then -1, -2, ..., then 1, 2, ...), which the input must already follow; negative IDs are renumbered like any other, as osmium does. A positive --start-id counts up, a negative one counts down (-1, -2, ...), and 0 means 1.
A way ref or relation member whose element is absent from the input (an orphan) gets an ID outside its kind's renumbered range: one ID per distinct absent ID, the same for every ref to it, never the ID of an output element, below the range or above it. On positive input from start 1, an orphan X becomes X plus the number of input elements of its kind above X. osmium numbers orphans on past the range in the order it meets them instead (see DEVIATIONS.md, "renumber: orphan-reference handling"). The run reports their count as a warning.
Each input blob is written as one output blob unless the new IDs grow it past what a blob can hold: the 32 MiB payload limit, or, compressed, a body that expands past the 32 MiB blob size (a far or negative start widens every ID; refs alternating between live and orphan targets widen their deltas). Such a blob is cut between elements into blobs that fit, each with its own index: first with every piece keeping the input blob's string table and elements as they are, and where that cannot fit, with a dense node group cut between nodes and each piece's string table holding only the strings it uses. Nothing an element carries changes. What is still refused (exit 2): a single element that does not fit even with only its own strings, a block whose content renumber cannot read in full (an element or dense group with fields outside the format, which keep the whole table, and a dense group of such shape is not cut), and a cut that needs the last few bytes below the limit.
Block and group fields renumber does not interpret are dropped from every blob, nodes, ways and relations alike: a group's obsolete changesets and any unknown PrimitiveBlock or PrimitiveGroup field. Only the string table, the elements and the block's granularity, date granularity and offsets are written. A node, way or relation field of the blob's kind that is not a length-delimited message is refused (exit 2).
The output header carries no replication state: the new IDs are not the feed's, so its diffs would address other objects (see Output header).
A way keeps its inline coordinates: renumber rewrites only a way's ID and refs, one new ref in place of each old one, so the coordinates stay paired with their refs, and an input declaring LocationsOnWays yields an output declaring it. osmium renumber drops both the coordinates and the declaration. The prepass features (pbfhogg.WayMembers-v1, pbfhogg.SharedNodePins-v1) are not declared and are warned (header.way_metadata_loss); a way's field-20 bytes are carried, but without the declaration nothing vouches for them.
pbfhogg renumber [OPTIONS] --output <OUTPUT> <FILE>| Flag | Description |
|---|---|
-o, --output <FILE> | Output file |
-O, --overwrite | Replace the output if it already exists. Without it an existing output is refused before any work is done; a symlink is refused either way |
--staging-dir <DIR> | Stage the output in DIR instead of beside it (see Staging directory) |
--start-id <ID> | Starting ID(s): single value or comma-separated node,way,relation [default: 1]. Positive counts up, negative counts down, 0 means 1; --start-id -5 and --start-id=-5 both parse. A start from which the last ID would leave the 64-bit range is refused (exit 2). (-s used to be its short; -s now refuses here, naming --start-id.) |
--compression | Blob compression [default for renumber: zlib:1; other commands: zlib]. Level 1 is the measured external-renumber write path (see reference/performance/renumber.md). An explicit --compression zlib or --compression zlib:6 selects level 6. |
--direct-io | Use O_DIRECT on the paths listed in the I/O capability matrix |
--generator | Override writing program name |
--output-header <K=V> | Set output header fields (repeatable) |
extract
Extract elements within a geographic region (bounding box or polygon).
Three strategies: --simple (single pass, fast, may have dangling refs), complete-ways (default, two passes, all way nodes included), --smart (three passes, completes multipolygon/boundary relations).
Which elements each strategy writes:
- Inside the region. A node is inside a bbox when its stored decimicrodegree coordinates lie within the four edges, inclusive. A node the extract classifies or writes whose block framing (granularity, offsets) puts a coordinate beyond what an
i32decimicrodegree holds fails the extract, under every strategy, rather than being placed at a wrapped coordinate. (A node blob skipped on its bbox claim is not decoded.) Each edge is the decimal it was typed as, rounded half away from zero to a decimicrodegree, from its own text in both-band--config(so12.4is exactly column124000000, and a node on it is inside). A polygon region is decided in decimicrodegrees by osmium's rule: each vertex is rounded as libosmium rounds it,round(v * 1e7); outer rings are oriented counterclockwise and holes clockwise; a node on any vertex is inside; any other node is decided by an integer crossing test in which every ring of one Polygon or MultiPolygon shares one parity (a hole is a second crossing, overlapping members cancel). A node on an edge between vertices is therefore decided exactly as in osmium: on a simple ring it is inside unless the edge is horizontal with the region only below it. The features of a FeatureCollection are unioned, an open ring is closed, and a polygon crossing the antimeridian is supported; see DEVIATIONS.md. - Matched. A way is matched when at least one of its nodes is inside. A relation is matched when it has a member node inside or a member way matched; relation-type members do not match it.
--simple: the nodes inside, the matched ways (their other nodes are not added) and the matched relations. Nothing else.- complete-ways: as simple, plus every node of every matched way, plus every relation that has an included relation as a member, recursively to any depth. A relation included as such a parent adds nothing else.
--smart: as complete-ways, plus, for every matched relation whose firsttypetag ismultipolygonorboundary, its member nodes and member ways wherever they lie, and every node of those ways. Its relation-type members, and the parents complete-ways adds, are included as relations but not completed.
Negative IDs are IDs like any other in every strategy and in --config: a way referencing n-7 is matched only when n-7 itself is inside, and completion pulls in n-7, never its positive twin (osmium matches by absolute value).
These are osmium extract's simple, complete_ways and smart, element for element on a bbox and on a polygon osmium reads the same way, except that osmium's simple decides a relation on its first node or way member only and osmium's smart completes multipolygon alone unless given -S types=multipolygon,boundary, and that on input with negative IDs osmium folds IDs onto their magnitude as above. pbfhogg has no -S options. See DEVIATIONS.md. --set-bounds writes the region's envelope with each edge at the decimicrodegree it selects.
Node blobs whose indexdata bbox misses the region are skipped unread, and the sorted-input schedules split blobs on their indexdata kind; both claims are believed. Through --config a node blob is read when its bbox meets any region, and its nodes are selected for, and written to, only the regions its bbox meets, so a node ID repeated in several blobs (history-shaped input) reaches each region from the blobs its single-region extract reads. Complete-ways and --smart on sorted input write from only the node blobs whose indexdata ID range may hold a selected node (that claim is believed too), and from only the way and relation blobs that the classification found to hold an ID in range of a selected way or relation; smart reads a relation-pulled way's nodes from only the way blobs that may hold it. A node blob copied raw is first decoded to prove every node lies in the region, but keeps its input BlobHeader. --simple on sorted input, single region or through --config, decodes each blob of a kind once when every blob of the kind carries indexdata, and then refuses a blob whose ID range or count is not exact for what it holds (nothing is published). Blobs whose ID ranges overlap, as where a history file's versions of one ID straddle a blob boundary, are read together, so each is still decoded once. A kind with an unindexed blob, an overlap that skips a blob, or a run of more than 8 overlapping blobs is read twice, a classify pass and a write pass, and its ranges are not consulted. Through --config that choice is made per kind over the blobs any region reads, so an inexact node ID range or count that a single-region extract would refuse can pass unchecked; check --index verifies the claims. See indexdata-trust.md.
Supports multi-extract via --config with a JSON config file specifying multiple regions. On sorted input every strategy takes a shared route: --simple (cleaned or not) selects and writes every region in one read of a kind with disjoint ID ranges, and otherwise classifies the kind once for all regions and writes them in a second pass; complete-ways and --smart classify nodes, ways and relations once for all regions, resolve way completion, relation parents and (smart) relation completion per region in shared membership tables, and write every region in one pass over the input. Each region's output and summary line are those of a single-region extract with the same strategy and flags (on claims that are exact; see the indexdata paragraph above). The shared route writes every output through a buffered writer, --direct-io or not (see the I/O matrix), and asks for one descriptor per region up front. Unsorted input takes one full extract per region, announced by a Note: Multi-extract single-pass probe declined the input line. Relative directory and polygon_file values resolve from the config file's directory. Relative output paths resolve from directory, or from the config file's directory when it is omitted. -d rebases configured outputs under its directory, preserving paths below the configured output directory; an absolute output outside that root keeps only its filename. Under -d an output whose kept path contains .. or names no file (an empty output, ., or the configured directory itself) is refused with exit 2 before any work. The containment is lexical; a symlinked directory inside the override is followed. These rules intentionally differ from osmium extract: relative directory values use the config file's location here, and -d rebases absolute outputs under the override instead of concatenating the two path strings.
A selected way keeps its inline coordinates when the input declares LocationsOnWays, so the output declares it too and stays ready for export: every ref keeps the coordinate the input recorded beside it, including a ref to a node the region leaves out. A selected way with refs but no coordinates in such an input is refused. osmium extract keeps them only when asked with -f pbf,locations_on_ways=true.
pbfhogg extract [OPTIONS] <FILE>| Flag | Description |
|---|---|
-o, --output <FILE> | Output file (required for single extract, omit with --config) |
-O, --overwrite | Replace the output if it already exists. Without it an existing output is refused before any work is done; a symlink is refused either way |
--staging-dir <DIR> | Stage the output, or every output a --config names, in DIR instead of beside it; checked against every output's directory before any is reserved (see Staging directory) |
-b, --bbox <BBOX> | Bounding box: minlon,minlat,maxlon,maxlat |
-p, --polygon <FILE> | Polygon GeoJSON file |
--config <FILE> | Multi-extract JSON config file. (-c used to be its short; -c now refuses here, naming --config.) |
-d, --directory <DIR> | Rebase config outputs under this directory (only with --config) |
--simple | Simple strategy (single pass). (-s used to be its short; -s now refuses here, naming --simple.) |
--smart | Smart strategy (three passes, completes multipolygon and boundary relations) |
--set-bounds | Write the extract region bounding box, each edge at the decimicrodegree it selects, to the output header instead of the input's. complete_ways and smart exceed it by design with the out-of-region nodes of selected ways |
--clean <ATTR> | Strip metadata attribute (repeatable: version, timestamp, changeset, uid, user) |
--compression | Blob compression [default: zlib] |
--direct-io | Use O_DIRECT on the paths listed in the I/O capability matrix |
--force | Proceed on unindexed input with the slower fallback (complete-ways and --smart; not with --simple, which never refuses) |
--generator | Override writing program name |
--output-header <K=V> | Set output header fields (repeatable) |
tags-filter
Filter elements by tag expressions. Default mode resolves relation members transitively (matched relations pull in member ways, nodes, and nested relations). With -R, only directly matched elements are emitted.
Default mode selects objects by ID: a matched ID includes every record of it, and references are collected from the matching records. It therefore refuses (exit 2, no output published) a PBF whose header declares HistoricalInformation, before the first pass, and a PBF that repeats an ID whose records disagree about the expressions, after the second pass. Repeats that agree (every record of the ID matches, or none does) are accepted and every record is written. -R decides per record and accepts history files; osmium documents the same restriction (-R only on history) without enforcing it.
A written way keeps its inline coordinates when the input declares LocationsOnWays (--remove-tags strips only tags), and a written way with refs but no coordinates in such an input is refused; see Output header.
Negative IDs are IDs like any other in every mode: a matched w-7 pulls in exactly the nodes it references, a relation member n-7 brings n-7, and neither brings its positive twin (osmium folds both onto |id| when it adds references).
With --input-kind osc (or autodetected from .osc/.osc.gz extension), filters an OSC change file instead, always preserving deletes: every delete is kept whatever its tags, with the body its input gave (tags, refs, members, a deleted node's location), and kept elements are written in merge-changes' normal form under the same rules for delete locations and empty metadata attributes (see merge-changes). Every flag that only means something for a PBF is refused in OSC mode: -R, --invert-match, --remove-tags, --distrust-metadata, --generator, --output-header, an explicit --compression (OSC output is not a PBF; its framing comes from the output name, see "Output files"), --direct-io and --force. With --input-kind osc the refusal comes before the input is opened; an autodetected kind comes from the four-byte sniff that decides it (of a regular file; a stream is routed by its name, see "Output files"). One reader thread frames the OSC document and cuts it into batches; -j sizes the workers that filter the batches, and the output is the same at any -j.
The kept changes are written in input order, each under its input action. Every batch becomes its own gzip member (or plain fragment) with its own <create>/<modify>/<delete> sections, so a section can be split into adjacent sections of the same action, as in merge-changes without --simplify; the changes and their order are unchanged. Order is part of the answer: apply-changes lets the later of two equal-version changes win, so a delete followed by a re-create of the same object at the same version must stay in that order to leave the object alive. Selection is per change, not per object: a matching v2 followed by a non-matching v3 keeps the v2 and drops the v3, so applying a filtered stream can leave an object at an older matching state, and a kept way or relation can refer to a node or member whose create was dropped (which apply-changes --locations-on-ways refuses as a missing reference).
At least one expression is required, positional or from -e; an -e file holding none is refused, and so is a malformed expression, before the input is opened.
Expressions use osmium syntax: highway=primary, amenity, w/building=yes, etc.
Expression syntax
An expression is [nwr/]KEY[!]=VALUE or [nwr/]KEY. The optional nwr/ prefix restricts the expression to element types. Key and value are each matched by the same rules, which follow osmium-tool/src/util.cpp::get_string_matcher:
| Form | Meaning |
|---|---|
foo | exact match |
foo,bar | any one of the comma-separated alternatives (both halves, keys included) |
foo* | prefix match |
*foo, *foo* | substring match (osmium has no separate suffix matcher) |
* | matches anything |
Spaces around each half, and around each comma-list element, are stripped, so highway = primary from an --expressions file names the key highway. The expression is split at the first =; a ! inverts the value match, which still requires the key to match (highway!=primary selects elements that have a highway tag whose value is not primary, not elements without the tag).
The ! is tested on the raw key, before the space stripping above, exactly as get_tag_matcher does. It therefore counts as an inversion marker only when it is the last character before the =. highway !=primary inverts; highway ! = primary and highway! = primary do not, and name the literal keys highway ! and highway! instead. This is a corner worth stating rather than discovering, because both spellings parse without error and select a different set of elements than the reader intended.
pbfhogg tags-filter [OPTIONS] --output <OUTPUT> <FILE> [EXPRESSIONS]...| Flag | Description |
|---|---|
-o, --output <FILE> | Output file |
-O, --overwrite | Replace the output if it already exists. Without it an existing output is refused before any work is done; a symlink is refused either way |
--staging-dir <DIR> | Stage the output in DIR instead of beside it (see Staging directory) |
--input-kind <KIND> | Input kind override: pbf or osc (autodetect from extension by default) |
-R, --omit-referenced | Omit referenced objects (faster, single pass, direct matches only; PBF only). Not with --remove-tags (no referenced objects to strip) or -j (its single pass decodes on the read pipeline's own pool, sized from the machine, which -j does not set) |
--invert-match | Invert match: exclude matching objects, keep non-matching (PBF only). (-i used to be its short; -i now refuses here, naming --invert-match.) |
--remove-tags | Remove tags from referenced objects not directly matched (not with -R; PBF only). (-t used to be its short; -t now refuses here, naming --remove-tags.) |
-e, --expressions <FILE> | Read filter expressions from file (one per line, # comments) |
-j, --jobs <N> | Worker threads for the two-pass mode's classify passes and its decode-and-filter pool, or in OSC mode for the workers filtering the document's batches (see Worker threads). Refused with -R, whose single pass decodes on the read pipeline's own pool, sized from the machine, which -j does not set |
--distrust-metadata | Do not skip blobs on their indexdata or tag index; decode every blob. Blob-level tag-index skipping is a trust boundary with nothing on the other side of it - nothing validates a blob's tag index against its payload - so a file whose index omits a key its elements carry silently loses those elements from the output. This flag trades the skip speedup for an answer that depends only on element data, and waives the indexdata precondition (--force is not needed alongside it). Not valid in OSC mode, which has no blobs. degrade --corrupt-tagdata produces the file this flag exists for. |
--compression | Blob compression [default: zlib] |
--direct-io | Use O_DIRECT on the paths listed in the I/O capability matrix |
--force | Proceed on unindexed input with the slower fallback. Not with --invert-match or --distrust-metadata, which never refuse, nor with -R when the expressions together name every element type (highway, not w/highway): that single pass skips no blob on indexdata and takes unindexed input as it is |
--generator | Override writing program name |
--output-header <K=V> | Set output header fields (repeatable) |
export
Stream a PBF to GeoJSON. Tagged nodes become Points. Tagged ways become LineStrings, or Polygons when they are closed and satisfy the built-in area rules. Untagged nodes and ways are skipped. Relation features are not emitted. Way export reads inline locations declared by the input's LocationsOnWays header feature. With --resolve-way-locations, the sparse join supplies node coordinates from the input. Node-only export needs no locations on ways.
The default geojsonseq format writes one Feature object per newline with no RFC 8142 record-separator byte. geojson writes one FeatureCollection.
pbfhogg export [OPTIONS] <FILE> [EXPRESSIONS]...| Flag | Description |
|---|---|
-o, --output <FILE> | Write to a file instead of stdout |
-O, --overwrite | Replace the output if it already exists. Without it an existing output is refused before any work is done; a symlink is refused either way. Requires -o: stdout is never replaced |
--staging-dir <DIR> | Stage the output in DIR instead of beside it (see Staging directory). Requires -o |
--format <FORMAT> | geojsonseq (default) or geojson |
-t, --type <TYPE> | Export only these kinds: node, way or node,way. relation is refused |
-e, --expressions <FILE> | Read tag expressions from a file, one per line |
--properties <KEYS> | Comma-separated whitelist of tag property keys |
-b, --bbox <BBOX> | min_lon,min_lat,max_lon,max_lat, inclusive, with each edge and each position at the decimicrodegree it rounds to, as for extract; ways match by vertex containment only, so crossing or enclosing geometry without an inside vertex is omitted |
--metadata | Add available @version, @timestamp, @changeset, @uid, @user, and @visible properties |
--resolve-way-locations | Resolve way-node coordinates with sparse add-locations-to-ways inside export. Requires --type way, -o, a Sort.Type_then_ID header and indexdata on every data blob |
--ignore-missing-nodes | With --resolve-way-locations, fill missing coordinates with (0, 0) and report their count |
--tmp-dir <DIR> | With --resolve-way-locations, use this existing writable directory for join scratch. Defaults to the output's directory |
Every feature includes @id and @type. Metadata timestamps are RFC 3339 UTC strings: a whole second prints as YYYY-MM-DDTHH:MM:SSZ, and a sub-second timestamp (possible only under a non-default date_granularity) prints the second holding it followed by its exact milliseconds as .SSS (-1 ms is 1969-12-31T23:59:59.999Z). Under --metadata, a timestamp whose scaling by the block's date_granularity overflows 64-bit milliseconds, or whose second lies outside years 0000 to 9999, is refused, naming the element. Tags that collide with emitted reserved property names are omitted. Polygon exterior rings are closed and counterclockwise. Nodes and ways with invalid geometry are skipped and reported in the stderr summary, after --bbox, expression and type selection. A node or way is invalid when any position it would emit lies outside longitude -180 to 180 or latitude -90 to 90, judged inclusively on the emitted seven-decimal value (so a position that rounds onto a pole is valid, and libosmium's undefined location, 214.7483647 on both axes, is not). An area way is also invalid when its ring has zero signed area at the emitted precision (collinear, or collapsed by rounding).
Features are formatted on the read's decode workers and written in input order. A failed write (a closed stdout pipe included) stops the read at once rather than after the rest of the input; a refused element still leaves the features before it written. Ordinary export on indexed input skips without decoding a blob whose indexdata claims relations, or under --type the kind not selected, and refuses a decoded blob holding a kind its claim does not name (see the kind claim in indexdata-trust).
With --resolve-way-locations, export uses the same sparse join and PBF output checks as add-locations-to-ways --index-type sparse with its default node retention and compression. It hands the checked way blocks to the GeoJSON formatter in memory. If the sparse store estimate or the exact reference-selected store and its extra memory costs exceed the threshold used by automatic ALTW routing, export refuses before allocating the store. Run add-locations-to-ways first, then export the resulting PBF without --resolve-way-locations. All way references count, including those on untagged ways and ways outside the export selection. Unresolved references refuse the run with exit 2 unless --ignore-missing-nodes is given. Referenced nodes outside the join's geographic domain and conflicting duplicate node coordinates still refuse the run, as does a way that exceeds ALTW's PBF output limits. The GeoJSON summary counts invalid geometry among the selected ways, such as zero-area rings. Either GeoJSON format can be used. The destination is published only after the join and export succeed.
diff
Compare two PBF files and show differences. Uses content equality (node coordinates, tags, refs, members) rather than version/timestamp ordering - deterministic regardless of metadata completeness (see DEVIATIONS). Inline LocationsOnWays way coordinates are not content by default: two files whose ways differ only in them are identical.
With --locations, a way whose tags and refs match is also modified when its inline location list differs: a different number of entries (a way carrying no list has none, so a missing list differs from a present one), or any position whose latitude or longitude differs at 1e-7 degrees. Each coordinate is the exact decoded nanodegree value divided by 100 and truncated toward zero, the resolution and rounding libosmium uses, so two producers writing at different granularities compare equal where osmium would read the same location, and values below 1e-7 are not compared. Stored values are compared, not their validity: an undefined location (libosmium writes 2147483647 on both axes) is a value like any other, and whether an inline coordinate matches its node is check --locations' question. Both inputs must declare LocationsOnWays in their header, else the run is refused (exit 2) before any element is compared, whatever -t selects. A byte-identical blob pair is still skipped where the comparison may skip equal blobs, since identical bytes decode to identical locations. --locations applies to -q and -c alike and is refused with --format osc, which cannot express a way-coordinate change. Under -v, a modified way also prints location i: n<ref> (lat, lon) -> n<ref> (lat, lon) for each zero-based position whose location differs, with absent for a side holding no location there and - for a side holding no ref there, coordinates as exact seven-place decimal degrees; more than 1000 such positions print locations: K of N positions differ (details omitted) instead.
With --format osc, generates an OSC diff file instead of text output. Text-only flags (-c, -v, -s/--osmium-summary, -t, --locations) are not valid with --format osc. OSC-only flags (--increment-version, --update-timestamp) are not valid with --format text. Either format exits 0 when the inputs are identical and 1 when they differ; an OSC diff publishes its -o in both cases.
With the global -q, --quiet a text diff prints nothing, neither the diff text nor its summary: the exit code is the answer (0 identical, 1 different). It compares exactly as a text diff without -c does (same paths and refusals) but formats nothing. -o, -c, -v and -s, which only shape that text or its summary, are refused with it, and so is --tmp-dir. A quiet --format osc diff writes its -o as usual and drops only the summary.
With -v, each modified element is followed by indented detail lines: coordinates: (lat, lon) -> (lat, lon) for a node, -ref @i n<id> and +ref @i n<id> for a way's node refs, -member @i type/id "role" and +member @i type/id "role" for a relation (an unknown member type prints as unknown(raw)/id), and -"k"="v", +"k"="v", ~"k": "old" -> "new" for tags. Way refs, member and tag order are content, so detail is never empty for a modified element. Refs and members are ordered edit scripts: all removals, then all insertions, each with its zero-based position in the old list (removals) or the new list (insertions), so a moved member prints as a -member/+member pair of the same member at its old and new positions, and a dropped duplicate as one -member. Removing the marked old items and placing the inserted ones at their new positions, with the kept items filling the rest in order, gives the new list. When several shortest scripts exist the one printed is fixed by the algorithm, not by which item moved. A script of more than 1000 edits, or one too costly to compute, prints one line instead: refs: N -> M, old @a..b -> new @c..d replaced (details omitted) (members: and tags: likewise), with N and M the list lengths and half-open ranges; it says the old range was replaced by the new one, not that every item in them differs. Keyed tag detail also has a 1000-line limit, counting additions, removals, value changes and the order-change line; above it the entire tag detail is replaced by tags: N -> M (details omitted), with the old and new tag counts. Keyed tags favor readability over reconstructing the new order: inserting a new key before or after an existing key can print the same detail. Tags are keyed, without positions: a reorder of keys present on both sides adds tags: order changed, and a tag list with a duplicate key prints an ordered -tag @i "k"="v"/+tag @i "k"="v" edit script instead. Every key, value and role prints as a complete double-quoted literal that is also a valid JSON string, never truncated: " and \ print as \" and \\, newline, carriage return and tab as \n, \r and \t, and every other control character (C0, DEL, C1), U+2028, U+2029 and the Unicode bidi controls (U+061C, U+200E-U+200F, U+202A-U+202E, U+2066-U+2069) as \u with four lowercase hex digits; all other text prints as itself. So each detail record is exactly one line, whichever of LF, CRLF or Unicode line breaks a reader splits on, and = or -> inside a literal is never a separator.
pbfhogg diff [OPTIONS] <OLD> <NEW>| Flag | Description |
|---|---|
--format <FORMAT> | Output format: text (default) or osc |
-c, --suppress-common | Hide unchanged elements (text only) |
-v, --verbose | Show detailed changes for modified elements (text only), at any -j |
-s, --osmium-summary | Print osmium-style summary (Summary: left=N right=N same=N different=N) on stderr instead of the default pbfhogg-format summary. Both formats fire on stderr unless -q (text only; refused with -q) |
-o, --output <FILE> | Write output to file (required for --format osc; refused with -q on a text diff) |
-O, --overwrite | Replace the output if it already exists. Without it an existing output is refused before any work is done; a symlink is refused either way. Requires -o: stdout is never replaced |
--staging-dir <DIR> | Stage the output in DIR instead of beside it (see Staging directory). Requires -o |
-t, --type <TYPE> | Filter by element type (text only) |
--locations | Also compare inline LocationsOnWays way coordinates at 1e-7 degrees; both inputs must declare LocationsOnWays (text only, see above) |
-j, --jobs <N> | Worker threads for decoding and ID-range comparison (see Worker threads). 0 (default) uses one per core. Each input is streamed in file order and output reaches the sink in ID order. The answer is the same at any -j. Applies to both text and --format osc |
--increment-version | Bump versions of deleted elements by 1 (osc only). If a deleted element is already at version 2147483647, exit 2 without publishing an OSC. |
--update-timestamp | Set delete timestamp to current time (osc only) |
--tmp-dir <DIR> | Directory for this run's scratch files (see Scratch files); --format osc only, which keeps per-action XML there, removed on completion. From indexed inputs creates are written straight into the output and only modifies and deletes are kept, plus any create output a busy worker ran ahead with, until it is copied: gzip-compressed for a .osc.gz, plain for a .osc, so a modify- or delete-heavy diff can still approach the output's size. From unindexed inputs every action is kept, as plain XML several times the size of a .osc.gz output. Must exist and be writable; checked before any input is read. Default: the output's directory. A text diff writes no scratch and refuses it |
--direct-io | Use O_DIRECT when reading the PBF inputs; see the I/O capability matrix |
With --format osc, roundtrips content - applying the derived OSC to the old PBF gives a file diff finds identical to the new PBF; metadata, which diff ignores, is outside that check (see DEVIATIONS). A created or modified element whose metadata says it is hidden is written with visible="false", which apply-changes applies as the object's deletion; so the roundtrip holds for snapshots of visible objects. Visibility is compared as well as content: an element hidden or unhidden with unchanged content is written as a modify of the new record (with visible="false" when hidden), carrying its new version; the text diff still compares content only. That holds for elements that fit a PBF block on their own with room to spare. Otherwise apply-changes can refuse, loudly and before publishing anything (see apply-changes). A string XML 1.0 cannot carry (NUL, another control character besides tab, newline and carriage return, or U+FFFE / U+FFFF), which a PBF may hold, makes the run fail without publishing, naming the element. Every OSC reader (apply-changes, merge-changes, OSC tags-filter) refuses an input document holding such a character anywhere, literally or as a character reference, as osmium does; see Output files.
Only values apply-changes reads back. --format osc never writes a value pbfhogg's own OSC reader refuses. A created or modified node outside latitude -90 to 90 or longitude -180 to 180 is refused, and so is one whose coordinate does not fit the PBF representation. An element timestamp outside years 0000 to 9999 is refused too, because YYYY-MM-DDTHH:MM:SSZ cannot spell it, and so is one whose scaling overflows. Each refusal exits 2 and publishes nothing. A clock past 9999 under --update-timestamp is refused before either input is opened. Deleted elements print only ID, version and the override timestamp, so their old values are never checked.
Repeated IDs. Canonical order admits the same kind and ID more than once in a row. A text diff pairs the occurrences of an ID in the order they occur on each side, the first old with the first new and so on, and reports any surplus on one side as deleted or created; the answer does not depend on how the occurrences fall across blobs or on indexdata. An OSC holds one statement per object, and applying it replaces every occurrence of the ID, so --format osc refuses (exit 2, nothing published) a create, modify or delete of an ID that occurs more than once on either side. Repeats unchanged on both sides need no statement and pass. A blob pair skipped as byte-identical is seen only at its first and last ID, which is enough: an ID strictly inside it occurs only there, identically on both sides. An element going backwards is refused as unsorted, as below.
Unrepresentable coordinates. A compared node whose coordinate does not fit an i32 decimicrodegree, on either side, is refused (exit 2) rather than compared at a wrapped value, which could call a node at 429 degrees latitude identical to one at 0; under --locations so is a compared way whose inline location does not fit an i64 nanodegree, and both location lists are read to the end so -c and -v refuse the same pairs. Only elements the comparison decodes are judged: a byte-identical pair it skips and a node present on one side only are not.
An indexed comparison whose ID ranges give no point to cut a work unit within 1 GiB of blobs (one ID repeated across that many adjacent blobs) is refused as a resource limit.
Input checks. Both inputs must claim Sort.Type_then_ID. With both inputs indexed, the comparison is one engine at every -j and -t, and every blob header of both files is checked: it refuses a truncated or malformed frame anywhere in either file, a data blob without indexdata, and blobs out of canonical order as far as their indexdata ID ranges prove it. Every blob the comparison decodes is also refused (exit 2) unless its indexdata is exact (its count and its least and greatest ID are what the blob holds) and its elements are in canonical order; a blob whose range spans negative and positive IDs must also start after the blob before it ends. Each header is checked as the input's stream reaches it, and the rest of both files is read before the run succeeds, so a defect late in a file can be refused after earlier text was written. The body of a blob of a kind -t excludes is never read.
With -c, -q or --format osc, the comparison can skip decoding a pair when both blobs are fresh (neither has a partially consumed block), both claimed ranges are wholly inside the work unit, their claimed ranges and counts match, the range does not span negative and positive IDs, and their compression, declared raw_size and compressed bytes match. A corrupt payload in a skipped pair can pass undetected, and its indexdata is believed: a false range or count on a skipped pair can change the common total and how the blobs around it pair, so the answer can be wrong without a refusal. A diff that prints common elements decodes the pair. Use check --index to verify claimed ranges and counts.
Without indexdata the comparison decodes every block of both files to learn its kind. A block of an earlier kind after a later one, and elements going backwards within a selected kind, are refused as unsorted. Blocks of excluded kinds are classified and dropped without converting their elements, so faults only a conversion sees (a role or user whose string index is out of range) are not refused there. A tag string index out of range is refused when the block is built, whatever its kind. Parallel ranges for each selected kind cut only at IDs the decoder has observed in canonical order. A range that cannot be closed within the memory limit resumes on the element stream.
Created and deleted totals come from the decoded blocks. Only the common total of a byte-identical pair skipped undecoded comes from its claimed count. Run check --index on both inputs to validate the claims a skip believes; use check --index --ids to check their order too. Repair false metadata with cat --reindex, or order with sort --distrust-metadata, before comparing again.
digest
Print a digest of a PBF, in one of three canonical forms. All are independent of compression, blob boundaries, string-table order, granularity and offsets, and indexdata presence. They differ in what they cover, and so in the equality they answer:
--form full(the default,v3). Two files the command accepts get the same digest exactly when they have the same header and the same elements field for field (barring a 128-bit hash collision). It covers element content as below, with coordinates as exact nanodegrees, plus each element's metadata claims (version, millisecond timestamp, changeset, uid, user andvisible, each claimed or not, as every metadata printing output reads them (theinspect --extendedcoverage census counts available values instead, see inspect): a plain element's field is claimed when present on the wire, so an absent timestamp, uid or user differs from a present zero or empty one and an absentvisiblefrom an explicittrue; a version of 0 or below is never a claim; a dense node's versionless slot claims only values padding cannot hold, a non-zero timestamp, a positive changeset or uid, a non-empty user,visiblefalse),LocationsOnWaysway coordinates wherever a way carries them, thepbfhogg.SharedNodePins-v1pins andpbfhogg.WayMembers-v1membership of each way where the header declares those features (and only there: they are authoritative nowhere else), and the header: bbox, required and optional features (each as a set, so order and repetition do not matter), writing program, source and the three replication fields, each with its presence. It is nodiffrelation: it is for checking that two writers of one operation agree, metadata and header included. A dense node and a plain one with the same metadata digest alike, except where the two encodings cannot say the same thing (a dense versioned node claims every metadata field its group'sDenseInfocarries, a changeset of -1 read as 0).--form content(v1). Two files the command accepts get the same digest exactly whendiff --suppress-commonreports them identical: element content only (node coordinates in decimicrodegrees and tags, way tags and refs, relation tags and members), so dense or plain nodes, header fields, metadata and way coordinates do not change it, as diff ignores them. Element content is defined once, incrates/lib/src/content.rs, for both commands.--form content-locations(v4). Two files the command accepts get the same digest exactly whendiff --locations --suppress-commonreports them identical: element content as incontent, plus each way's inline location list asdiff --locationscompares it (entry count, then each position at 1e-7 degrees, truncated toward zero). It refuses, exit2, a file whose header does not declareLocationsOnWays. It is for comparing the inline coordinates of twoLocationsOnWaysproducers, such as pbfhogg's and osmium'sadd-locations-to-waysoutput, without their metadata or header.
pbfhogg digest [OPTIONS] <FILE>| Flag | Description |
|---|---|
--form <FORM> | Canonical form: full (default, v3), content (v1, diff's equality) or content-locations (v4, diff --locations' equality) |
--direct-io | Use O_DIRECT on the paths listed in the I/O capability matrix |
Output, on stdout:
xxh128 v<N> <32 hex digits>
node <count> <32 hex digits>
way <count> <32 hex digits>
relation <count> <32 hex digits>The first line names the algorithm and the form's version. A version names one canonical form and is never reused: a change to a form's definition or serialization gives it a new number, so a stored digest is only comparable with one of the same version. The per-kind lines digest each kind alone, so a mismatch shows which kind differs. In the full form the header is folded into the first line only, so a first line that differs while every kind line matches is a header difference.
The command refuses, in every form, exiting non-zero and printing no digest line, any input on which diff's answer is not a function of element content:
- no
OsmHeaderas the first blob, a secondOsmHeader, or a blob of unknown type; - a header that does not claim
Sort.Type_then_ID; - a data block whose elements are of more than one kind (groups that yield no element, such as an empty dense message or a changeset group, do not count), kinds out of node, way, relation order, or IDs that do not strictly ascend within a kind (duplicates included);
- indexdata on some data blobs and not others, or indexdata whose kind, minimum ID, maximum ID or count disagrees with its block, or on an empty block;
- a tag, role or metadata user name whose string-table index does not resolve;
- a node coordinate whose exact value does not fit the form's coordinate field (an
i32decimicrodegree incontent, ani64nanodegree infull), or an inline way location that does not fit ani64nanodegree (fullandcontent-locations). A digest of such a file would hash a wrapped value; every record that still serializes has the bytes it had before this check, so the form versions are unchanged.
The full form also refuses malformed prepass fields its header declares: under pbfhogg.WayMembers-v1, a way blob without a well-formed field-5 payload, or whose payload counts other than the block's ways or sets a bit past the last; under pbfhogg.SharedNodePins-v1, a way pin bitmap that is not one bit per ref rounded up to whole bytes, or that pins a position past the last ref.
A refusal is the safe answer for a cache keyed on the digest: fall back to the real comparison. The promise is "refuses input failing these checks", not "refuses every corrupt file": a file cut off exactly at a blob boundary is a valid shorter file.
The input is read front to back through one open, with every check made while it decodes, so <FILE> may be a stream (a FIFO, /dev/stdin) as well as a file. A refusal partway through a stream can wait for the stream's writer to write again or close it before the command exits.
getid
Extract or remove elements by ID. By default, keeps only the listed IDs. With --invert, removes the listed IDs and keeps everything else.
Typed IDs accept n123 or node/123 (node), w456 or way/456 (way), and r789 or relation/789 (relation). Bare numeric IDs are accepted only when --default-type is supplied. Without it, a bare ID is an error. This also applies to IDs in --id-file text input.
Negative IDs are IDs like any other, from every source (n-7, node/-7, or a bare -7 under --default-type, which needs no --), and any 64-bit signed ID is accepted. Selection, --invert and -r match the exact signed ID: n7 never selects or removes n-7, and a reference to n-7 pulls in n-7, not n7 (osmium refuses negative text IDs and matches the others by absolute value).
At least one ID source is required (positional IDs, -i or -I). Positional IDs are parsed before the output is checked; the ID files are read after it, so an existing output is refused before a full pass over an -I PBF. Sources that turn out to hold no ID are refused once read.
pbfhogg getid [OPTIONS] --output <OUTPUT> <FILE> [IDS]...| Flag | Description |
|---|---|
-o, --output <FILE> | Output file |
-O, --overwrite | Replace the output if it already exists. Without it an existing output is refused before any work is done; a symlink is refused either way |
--staging-dir <DIR> | Stage the output in DIR instead of beside it (see Staging directory) |
--invert | Invert selection: remove listed IDs instead of keeping them |
-r, --add-referenced | Also include every object the listed ones reference, as osmium's getid -r: the members of listed relations, recursively through relations in relations, then the nodes of every way listed or pulled in. Reads every relation blob once (when a relation is listed); the second relation read, the way read and the output pass read only the blobs whose indexdata ID range holds an ID they need. With no way or relation listed nothing is pulled in, and the run is a plain include. Not with --invert |
--remove-tags | Remove tags from the referenced objects of every kind that were not themselves listed; a listed object keeps its tags even where another references it. Requires -r, which is what emits them (so not with --invert). (-t used to be its short; -t now refuses here, naming --remove-tags.) |
-v, --verbose | Print requested IDs, then report which were not found; only listed IDs are reported, not the objects -r reached that the file lacks (not with --invert, and not with -q, which would drop both lists). Both lists go to stderr. The found set is collected on the write path, so this costs no extra pass over the output. |
-i, --id-file <FILE> | Read IDs from text file (one per line) |
-I, --id-osm-file <FILE> | Read IDs from an OSM/PBF file (all element IDs are collected) |
--default-type <TYPE> | Type for bare numeric IDs: node, way, relation. No type is assumed when this option is omitted. |
--compression | Blob compression [default: zlib] |
--direct-io | Use O_DIRECT on the paths listed in the I/O capability matrix |
--force | Proceed on unindexed input with the slower fallback (see Proceeding without indexdata) |
--generator | Override writing program name |
--output-header <K=V> | Set output header fields (repeatable) |
--verbose is an exhaustive diagnostic with no output cap (--verbose-ids, its former name, now refuses, naming -v, --verbose). Requested IDs are space-separated on one line per kind; missing IDs are printed one per line. With -I, every ID from that input participates, so large inputs can produce very large stderr output. The missing-ID report also collects three vectors, one per kind, requiring O(M) additional ID storage for M missing objects. Omit --verbose when that output and storage are unwanted; the normal command summary remains available.
getparents
Find ways/relations referencing given IDs (reverse lookup).
ID syntax and the optional --default-type behavior are the same as for getid: bare numeric IDs require an explicit default type, and negative IDs are accepted and matched exactly, so the parents of n-7 are the objects referencing n-7, never those referencing n7.
pbfhogg getparents [OPTIONS] --output <OUTPUT> <FILE> [IDS]...| Flag | Description |
|---|---|
-o, --output <FILE> | Output file |
-O, --overwrite | Replace the output if it already exists. Without it an existing output is refused before any work is done; a symlink is refused either way |
--staging-dir <DIR> | Stage the output in DIR instead of beside it (see Staging directory) |
--add-self | Also include the queried objects themselves in the output. (-s used to be its short; -s now refuses here, naming --add-self.) |
-i, --id-file <FILE> | Read IDs from text file (one per line) |
-I, --id-osm-file <FILE> | Read IDs from an OSM/PBF file (all element IDs are collected) |
--default-type <TYPE> | Type for bare numeric IDs: node, way, relation. No type is assumed when this option is omitted. |
--compression | Blob compression [default: zlib] |
--direct-io | Use O_DIRECT on the paths listed in the I/O capability matrix |
--generator | Override writing program name |
--output-header <K=V> | Set output header fields (repeatable) |
add-locations-to-ways
Embed node coordinates in ways. Two index strategies, and auto (the default) to choose between them:
A node a way references that occurs more than once at different coordinates fails the run with exit 2 and nothing published, under every index strategy and with --ignore-missing-nodes too; no record is picked as the winner. Identical repeats are accepted. See DEVIATIONS.md.
- auto (default) - Runs sparse unless the input is sorted and indexed, the page-cache budget can be read from the host, and the estimated sparse store exceeds 80 % of that budget; then it runs external. Where available memory cannot be read (every non-Linux host, containers without a visible cgroup v2 mount) or is at most the 3 GiB the sparse run reserves for itself, it runs sparse. A
Note:on stderr names the choice and why. An input whose indexdata the external index would refuse (blob ranges out of sorted order), or whose node IDs need its wide record (past about 2^38 from zero), runs sparse, and the note says so. When auto runs sparse against a known budget, the exact store is judged again once the first pass has counted the referenced nodes (referenced IDs the file lacks take slots too, and sets of negative IDs take memory), and if it exceeds the same share auto switches to external, with a secondNote:. A file with no ways stays sparse. Otherwise the estimate counts every node, so a sorted file of mostly standalone nodes can be routed to external, whose scratch demand is far higher; pass--index-type sparsethere. Rule and limits in pipeline.md. - sparse - A flat memory-mapped array of 8 bytes per referenced node, in scratch storage; works on any PBF, sorted or not, and joins negative node IDs like any other. How it is laid out is in pipeline.md. Working-set behavior depends on the available page cache; see performance/add-locations-to-ways.md for measurements.
- external - Double radix permutation via 4-stage pipeline with bounded memory and high scratch-disk demand. Requires sorted PBF (Sort.Type_then_ID) and indexdata. See performance/add-locations-to-ways.md for measured resource use. Joins negative node IDs like any other, and any node ID: IDs past about 2^38 from zero take a wider 16-byte scratch record per ref. It has encoding limits the sparse index does not: at most 2^32 way blobs and 2^32 node blobs, and about 2^40 (1.1e12) way node refs in total. Past one, the run fails with exit 2 naming the limit and pointing at sparse, and nothing is published; details in pipeline.md.
--index-type dense was removed; see performance/add-locations-to-ways.md for measured comparisons. dense survives as a hidden value (absent from --help) purely so passing it errors with a pointer to sparse rather than a bare "invalid value".
By default, untagged nodes not referenced by a relation are dropped from output. A relation member is matched by its exact signed ID, so an untagged member n-7 is kept and n7 is not (osmium's --keep-member-nodes folds members onto their absolute value); --inject-prepass marks negative member ways and pins negative shared nodes the same way.
Blobs are found by their indexdata kind, and every blob a backend decodes is held to its claim: a blob holding another kind than it claims, or whose claimed ID range or count is not exact for what it holds (a way-claimed blob with no way included), fails the run with exit 2 on either backend, pointing at check --index and cat --reindex, and nothing is published. Sparse decodes every node and way blob, and the relation blobs unless --keep-untagged-nodes is given without --inject-prepass. --index-type external also refuses, as unsorted, a decoded blob out of order under the sorted header, inside it or behind the blob before; it decodes the node blobs its ID buckets reach and the ones it re-encodes, and drops a node blob whole, undecoded, on its tagdata and ID range when removing untagged nodes. Sparse does not depend on order and joins such a file. See indexdata-trust.md.
Each way blob is written as one output blob unless the coordinates grow it past what a blob can hold: the 32 MiB payload limit, or, compressed, a body that expands past the 32 MiB blob size (long ways whose consecutive nodes lie far apart carry the widest deltas). Such a blob is cut between ways into blobs that fit, each with its own index, under every index strategy and the --force fallback alike; the same holds for any node blob a run re-encodes. Under --inject-prepass each piece carries the pbfhogg.WayMembers-v1 bits of its own ways, and a way blob holding more ways than one blob header has room bits for (about 523,000) is cut by way count even when its payload fits. Nothing a way carries changes. What is still refused (exit 2): a single way that does not fit even with only its own strings, and a cut that needs the last few bytes below the limit.
pbfhogg add-locations-to-ways [OPTIONS] --output <OUTPUT> <FILE>| Flag | Description |
|---|---|
-o, --output <FILE> | Output file |
-O, --overwrite | Replace the output if it already exists. Without it an existing output is refused before any work is done; a symlink is refused either way |
--staging-dir <DIR> | Stage the output in DIR instead of beside it (see Staging directory) |
--index-type <TYPE> | Node index type: auto (default; runtime routing, see above), sparse or external |
--keep-untagged-nodes | Keep all untagged nodes in output |
--inject-prepass | Emit the opt-in pbfhogg.WayMembers-v1 and pbfhogg.SharedNodePins-v1 metadata into the output header, readable back via Blob::way_members / Way::shared_node_pins |
--ignore-missing-nodes | Accept ways whose node references are absent from the input, writing those vertices as (0, 0). Without it the run fails and no output is written: (0, 0) is Null Island, a real coordinate, so a placeholder vertex cannot be told apart from genuine data by any reader. Matches osmium in name and in default. |
--compression | Blob compression [default: zlib] |
--direct-io | Use O_DIRECT on the paths listed in the I/O capability matrix |
--force | Proceed on unindexed input with the slower (sparse, decode-all) fallback. Not with --index-type external or --inject-prepass, which need indexdata whatever --force says; both are refused before any input is opened |
--tmp-dir <DIR> | Directory for this run's scratch files (see Scratch files). Must exist and be writable; checked before any input is read, after the output is checked. Default: the output's directory |
--generator | Override writing program name |
--output-header <K=V> | Set output header fields (repeatable) |
time-filter
Filter a history PBF to a snapshot at a given timestamp.
pbfhogg time-filter [OPTIONS] --output <OUTPUT> <FILE> <TIMESTAMP>The timestamp can be UNIX seconds or RFC3339 UTC (YYYY-MM-DDTHH:MM:SSZ).
Element timestamps are judged in whole seconds, rounded down, so a version is eligible when its timestamp falls within or before the cutoff second (a pre-1970 sub-second timestamp belongs to the second before it, not the one after). An element timestamp whose scaling by the block's date_granularity overflows 64-bit milliseconds is refused as invalid data, naming the element.
The output's replication timestamp is the earlier of the input's and the cutoff; the input's sequence number is kept only when the input's timestamp is known and not after the cutoff, since it names the input's replication state, which the snapshot no longer is (see Output header).
The input must declare Sort.Type_then_ID, and time-filter holds it to that as it reads: an element sorting below the one before it is refused as unsorted (exit 2; the advice is sort --distrust-metadata). A history input (HistoricalInformation) must also carry each object's versions strictly ascending, and an input without that feature must hold each object once; either broken is refused as invalid data. sort --distrust-metadata puts descending versions in order; a repeated version or object survives sort, which keeps every record. No indexdata is read, so a wholly unindexed input is filtered as an indexed one is; a partially indexed input (indexdata on some data blobs and not others) is refused once a read has met both kinds of data blob.
The output holds at most one version of each object and never declares HistoricalInformation, so it can serve as an apply-changes base.
Ways are written without inline coordinates, and an input's LocationsOnWays is dropped with the header.way_metadata_loss warning: the coordinates record node positions as of when the input was written, so a way whose node moved after the cutoff would carry the later position, against the node version the snapshot keeps or a node it drops. Run add-locations-to-ways on the output to locate its ways as of the cutoff.
A history input is filtered blob by blob: each input blob's surviving versions are written in new blocks of up to 8000 elements, an object whose versions straddle a blob boundary written with the blob that holds its surviving version. A block that would be too large for a blob is cut as sort cuts an overlap block (see sort), with the same remaining refusals. Only the surviving versions' payloads are read: a superseded version is judged by its ID, version, timestamp and visibility, so a bad user or role string index on it is not refused. A snapshot input is filtered blob by blob too, and an output block too large for a blob is cut the same way, with the same remaining refusals.
| Flag | Description |
|---|---|
-o, --output <FILE> | Output file |
-O, --overwrite | Replace the output if it already exists. Without it an existing output is refused before any work is done; a symlink is refused either way |
--staging-dir <DIR> | Stage the output in DIR instead of beside it (see Staging directory) |
--compression | Blob compression [default: zlib] |
--direct-io | Use O_DIRECT on the paths listed in the I/O capability matrix |
--generator | Override writing program name |
--output-header <K=V> | Set output header fields (repeatable) |
apply-changes
Apply an OSC diff to a sorted PBF file. Uses blob passthrough -- unmodified blobs are copied as raw bytes without decompression (under --locations-on-ways some are decompressed first and then copied; see below).
Sort order. The base header must claim Sort.Type_then_ID, with or without --locations-on-ways. A base that does not is refused from the header alone (exit 2, nothing published), before the OSC is parsed or any base element is decoded, with the advice pbfhogg sort --distrust-metadata <BASE> -o sorted.osm.pbf. The indexdata check comes first and probes the first data blob: without --force, a base whose first data blob carries no indexdata is refused as unindexed (see Proceeding without indexdata) whatever its header claims, and the sort claim is not reached. A base that claims the order without holding it passes the header check; disorder the run detects is refused later, while the output is written, as refusing to write an unsorted PBF under a Sort.Type_then_ID header, with the same exit code and advice and nothing published. The run checks blob order (kind, then ID) using ID-range bounds and, for decoded blobs, the observed first element; blobs copied without being decoded are checked by their indexdata claims. It also checks element order inside every blob it decodes (below), where an element that also falls outside its blob's claimed range is refused as false indexdata instead. Disorder confined to a blob copied without being decoded can pass undetected.
Snapshots only. A base whose header declares HistoricalInformation is refused from the header (exit 2, nothing published), after the sort check and before the OSC is parsed: the run replaces or deletes every record of a changed ID, which on a history file would overwrite every past version. Make a snapshot with time-filter at the point the changes start from and apply to that. A base without the declaration that repeats an ID has every copy replaced or deleted. The output is a snapshot too, so a <create> or <modify> element with visible="false" is the object's deleted state: it is applied as a delete carrying that element's version claim, the object is absent if that change wins, and a hidden node needs no coordinates (osmium applies it the same way).
Which blobs are unmodified is decided from each blob's indexdata ID range, and a passed-through blob's element count in the statistics is its indexdata claim. A blob whose claimed range misses the diff is copied without being decoded, so a base whose indexdata understates that range gets the blob copied past a change aimed at it. Every blob the run does decode (the ones whose claimed range meets the diff, and under --locations-on-ways the way blobs it searches) must hold exactly the kind, range and count its indexdata claims and be in the order the header's sort claim promises; otherwise the run fails (exit 2) and publishes nothing. See indexdata-trust.md, "Range, count and order claims refused at decode".
A blob the run rewrites keeps its surviving elements' strings by copying their string table indices, and checks each one: a member role or user name index that lies past its block's string table, or a block whose string table does not begin with the empty string, fails the run (exit 2) and publishes nothing, the error naming the element, field and index. A tag key or value index past the table fails the run the same way when the block is decoded, the error naming the index and the blob. Blobs copied unchanged are not checked.
Output blocks are cut at 8000 elements, and also wherever a block would pass the 32 MiB PBF payload limit: a rewritten block carries its source block's whole string table plus the strings of the changed elements written into it, so a large value modified to another large value, or two large creates side by side, is written as more blocks rather than refused. A re-cut first writes blocks that carry only the strings their own elements use, so a surviving element that grew past its source (refreshed --locations-on-ways coordinates, say) is not held back by a large string the changes removed; where that fails it tries again with blocks that carry the source table. A node without metadata that does not fit a block alone in the usual dense form is tried once more as a plain node, which claims the same and is a few bytes smaller. An element that does not fit a block alone in the forms tried, with its own strings, fails the run (exit 2) with the oversize error and publishes nothing; a node with metadata keeps its ordinary encoding and gets no plain retry, and another order of an element's strings could sometimes have fit. The re-cut halves a piece that does not fit, so it can miss a cut that fits only within bytes of the limit (a block's size depends on its neighbours' strings); that also fails with the oversize error. There is no limit on how large one input blob's output may grow: a large string shared by many changed elements that must be cut apart is written once per block, however many blocks that takes (a blob whose output is that large is written twice, the second time streamed to the output, so it is never held in memory whole). apply-changes has no option that changes the block limit. On eligible indexed input the rewrite can preserve unchanged wire fields while computing new indexdata. Inputs that fall outside its framing, enrichment or size checks go through the element writer and the recovery above.
The output header declares no bbox (the OSC can place a node outside the base's). Of the base's replication state it keeps the base URL and drops the timestamp and sequence number, since the output is past them; set the new state with --output-header (see Output header).
The OSC is held in memory for the whole run, and that memory grows with the total parsed change payload, including earlier records for objects changed more than once. For accumulated diffs, merge-changes --simplify collapses each object's history before it is applied.
pbfhogg apply-changes [OPTIONS] --output <OUTPUT> <BASE> <CHANGES>| Flag | Description |
|---|---|
-o, --output <FILE> | Output file |
-O, --overwrite | Replace the output if it already exists. Without it an existing output is refused before any work is done; a symlink is refused either way |
--staging-dir <DIR> | Stage the output in DIR instead of beside it (see Staging directory) |
--locations-on-ways | Keep inline way-node locations current through the merge (see below and DEVIATIONS.md). |
--ignore-missing-nodes | With --locations-on-ways, permit unresolved references to retain the legacy (0,0) fallback instead of failing |
-j, --jobs <N> | Worker threads for the descriptor-first pipeline (see Worker threads). 0 (default) uses the nproc - 2 heuristic (leaves two cores for scanner + drain, minimum 2). An explicit -j N runs exactly N workers, 1 included. |
--compression | Blob compression [default: zlib] |
--direct-io | Use O_DIRECT on the paths listed in the I/O capability matrix |
--io-uring | Use io_uring for output I/O |
--force | Proceed on an unindexed base with the slower fallback, which decodes every blob. The output is indexed on every blob, as plain cat's is: a blob the diff leaves alone keeps its compressed payload under a header carrying indexdata derived from it, a blob no single index describes is re-encoded, and one holding no element is left out. A blob whose elements span more than one kind is refused (exit 2, nothing published), since it cannot be placed in type order; plain cat splits such blobs. Not with --locations-on-ways, which needs an indexed base whatever --force says; the combination is refused before any input is opened |
--allow-version-regression | Accept a change whose version is lower than the version already held for that object. Off by default: precedence is by version, not by position, so feeding diffs out of sequence order is an error naming both versions rather than a silent downgrade. An equal version is always accepted and the later change wins by position (overlapping diffs, regional-extract deletes at the held version). Deletes count -- a delete leaves a versioned tombstone, so a later stale create or modify is refused too. Elements claiming no version are unaffected. The base counts too: a base element whose version is above every version the changes claim for that object (deletes included) is refused rather than downgraded or deleted, where osmium silently keeps the base element. A content-derived patch back to an older snapshot (diff --format osc from a newer to an older file) is such a change set and needs this flag. See DEVIATIONS.md. |
--generator | Override writing program name |
--output-header <K=V> | Set output header fields (repeatable) |
--locations-on-ways
The base must be sorted, indexed and declare LocationsOnWays (refused before the OSC is parsed otherwise); the output declares it too.
Which coordinates change. A surviving base way (one the OSC neither modifies nor deletes), whether its blob is rewritten or would have been copied, takes the OSC's coordinate (the OSC's final state of the node) for each existing inline coordinate whose node the OSC creates or modifies. It is never resolved against base node records: it keeps every other inline coordinate, one for a node the OSC deletes included (counted, see below), and a way with no coordinate arrays is left without them. A way the OSC creates or modifies is written from scratch: OSC coordinates for the nodes the OSC carries, the base's node records for the rest, and none of the old version's inline coordinates. A reference found in neither, or to a node the OSC deletes, fails the run with nothing published (--ignore-missing-nodes writes (0, 0) instead). The run fails as soon as the base's nodes have been read, before any way is written, and the error counts the distinct nodes it could not resolve. A base node record a written way takes its coordinate from must lie in the geographic domain (latitude within +-90 degrees, longitude within +-180, judged on the decimicrodegree value): one outside it fails the run with nothing published, as add-locations-to-ways refuses it. So does a node such a way needs from the base whose records occur more than once at different coordinates; identical repeats are accepted. Base nodes no changed way references are not judged against the domain or for duplicates. Every node of a base node blob the run decompresses (see "What is read") must still fit an i32 decimicrodegree, under any int32 block granularity; a node blob the run copies without decompressing is not judged (DEVIATIONS.md). Only coordinates that differ count as refreshed: a tag-only node edit refreshes nothing where the inline coordinate already agrees, and costs a way blob no rewrite.
Base preparation. The node records a changed way needs must come from the OSC or the base. add-locations-to-ways drops untagged nodes unless given --keep-untagged-nodes, so its default output can fail on an ordinary daily diff: a changed way can reference unchanged untagged nodes whose records are in neither file. Make the base with --keep-untagged-nodes; osmium documents the same requirement.
What is read. A node blob is decompressed when its claimed ID range holds a node a changed way still needs from the base, or when the merge's edit-overlap check selects it, as it would without --locations-on-ways (that check is conservative: an OSC node edit within the range, or one falling between the blob's records in ID order, selects it). Every other node blob is copied without being decompressed. When the OSC creates or modifies at least one node, every way blob is decompressed as well: one the merge would otherwise copy is searched at the wire level (refs and coordinate arrays, without a full parse) and still copied unchanged unless it holds a stale coordinate, in which case it is parsed and rewritten. A diff whose node changes are all deletes leaves those blobs unread. The search fails the run on a blob it cannot decompress, on malformed wire framing of the block, its groups or a Way message (fields it skips included), on malformed ref varints, and on coordinate arrays that are not both absent or both complete and as long as the refs. For a way with coordinate arrays and at least one reference to an OSC-upserted node it also checks that every coordinate of the way converts to an in-range decimicrodegree. It does not decode tag values, Info contents or the string table, so a blob found clean whose errors are confined to those is still copied unchanged; a blob rewritten for any reason is fully parsed. Which blobs are way blobs is their indexdata kind claim (see indexdata-trust.md). Relation blobs are never searched.
Framing. Rewritten blocks are written in the default coordinate and date framing. A surviving way or relation from a source block with another granularity, lat_offset, lon_offset or date_granularity is converted as PBF rebuild precision describes: coordinates truncated toward zero to decimicrodegrees and, under a non-default date_granularity, timestamps rounded down to whole seconds and an overflowing one refused (timestamps with or without --locations-on-ways). Blobs copied unchanged keep their own framing.
Summary. A progress line reports the refresh probe's memory, and the summary adds Inline locations refreshed: R refs in W ways, S way blobs scanned, O rewritten only for this, D refs to deleted nodes kept. S counts way blobs searched that had no merge work of their own; O those rewritten only for a refresh; D references in surviving ways to OSC-deleted nodes, counted only in the way blobs the run searched or rewrote, so it is not a whole-file count. A nonzero D means base and OSC disagree: the OSM API refuses to delete a node a way still uses.
Not a repair. The refresh corrects coordinates for nodes this OSC creates or modifies. A coordinate already stale for any other node stays stale, such as one left by a pbfhogg version that refreshed only the ways the OSC touched. check --locations reports stale coordinates where the file holds the node's record. Rebuilding with add-locations-to-ways recomputes coordinates only from node records, so it repairs a file only from an input holding the current record of every referenced node, not from a default add-locations-to-ways output.
merge-changes
Merge multiple OSC files into one OSC file.
pbfhogg merge-changes [OPTIONS] --output <OUTPUT> <CHANGES>...| Flag | Description |
|---|---|
-o, --output <FILE> | Output file |
-O, --overwrite | Replace the output if it already exists. Without it an existing output is refused before any work is done; a symlink is refused either way |
--staging-dir <DIR> | Stage the output in DIR instead of beside it (see Staging directory) |
--simplify | Keep only the last change per object (type + id). Survivors are written in create, modify and delete groups, each in type then canonical ID order (0, the negative IDs by magnitude, then the positives); osmium sorts by the same object order, without the action groups |
--allow-version-regression | Requires --simplify, which is the mode that resolves conflicts; passing it alone is a usage error. Accepts a later change whose version is lower than one seen earlier in input order. Off by default, so listing the inputs out of sequence order is an error rather than a silent downgrade. An equal version is always accepted and the later change wins. Default (non-simplify) mode preserves the full stream in input order and resolves nothing, so there is nothing for the flag to allow. See DEVIATIONS.md. |
-j, --jobs <N> | Worker threads (see Worker threads). Sizes the encoding pool and the cap on inputs read at once, and the simplify path's chunk fan-out. |
--tmp-dir <DIR> | Directory for this run's scratch files (see Scratch files): output produced for a later input while an earlier one is still being written is held there, so it can approach the output's size. Must exist and be writable; checked before any input is read, after the output is checked. Default: the output's directory. Only several inputs without --simplify, at any -j but 1, can write scratch; a single input, --simplify or -j 1 makes no run directory and refuses the flag (exit 64) |
Without --simplify, each input is read once, in order of the command line, and cut into batches of whole changes that are encoded in parallel. Every batch becomes its own gzip member (or plain fragment) with its own <create>/<modify>/<delete> sections, so a section can be split into adjacent sections of the same action; the changes and their order are unchanged, and the bytes do not depend on -j or the host.
Every change is re-written, not copied: each element is read, checked and written in one normal form (attribute order, coordinate spelling, escaping; an element's nd/member children are written before its tags). Nothing the element carries is dropped. A delete keeps the body its input gave - tags, way node refs, relation members, and a deleted node's lat/lon - as osmium does; Geofabrik diffs give every delete the object's last state. A deleted node's location is both coordinates or neither: one without the other, or a value a created node would be refused for (unparsable, out of range), is refused, where apply-changes, which keeps nothing of a delete but its identity and version, accepts it. A <create> or <modify> node with visible="false" is the object's deleted state and follows the same location rule (it needs no coordinates); it stays in its section with its visible attribute. An empty metadata attribute is written back as it was read (user="" names a blank user, which apply-changes records as distinct from no user; osmium omits it), except an empty visible, which every command reads as absent. uid, changeset and timestamp are passed through unvalidated, so an empty one is written back and apply-changes refuses it, as it does applied directly.
build-geocode-index
Build a reverse geocoding index from a PBF file. Produces a set of binary files (S2 cell index, address points, street segments, admin boundaries, string pool) that can be memory-mapped for sub-millisecond reverse geocoding queries.
Requires an indexed PBF (generated by pbfhogg cat) unless --allow-unindexed is set. An existing output directory is refused before any work unless --overwrite is set, and even then it must hold a geocode index or be empty; any other existing path is refused because publication replaces the whole directory. A directory holds an index when its geocode_header.bin is a regular file (not a symlink) at least a header long that starts with the index format's magic bytes; the format version is not read, so an index from any earlier release can be rebuilt in place. The output path itself cannot be a symlink. An existing output directory that is a mount point, or that has a mount point anywhere below it (a mounted directory or a bind mount over a file), is refused before the build with status 2: replacing it would delete what the mounted filesystem holds. A backup or unpublished staging directory found holding a mount at cleanup is kept and reported instead of removed.
The node phase schedules blobs on their indexdata kind, so a node in a blob labelled way or relation is never indexed; a node above the largest claimed node max_id is refused. See indexdata-trust.md.
pbfhogg build-geocode-index [OPTIONS] --output-dir <DIR> <FILE>| Flag | Description |
|---|---|
-o, --output-dir <DIR> | Output directory for index files |
--street-level <N> | S2 cell level for streets/addresses; must exceed --coarse-level, within the builder's segment-cover limit. Default comes from the builder configuration |
--coarse-level <N> | Fallback cell level for rural areas; must be below --street-level, within the builder's segment-cover limit. Default comes from the builder configuration |
--admin-level <N> | S2 cell level for admin boundaries, within the builder's work limit. Default comes from the builder configuration |
--admin-tolerance <METERS> | How far admin boundary simplification may move a boundary, the same at every admin level. A query farther than this from a boundary gets the answer the unsimplified boundary gives; nearer, it may get the neighbour or no area at that level. 0 keeps every vertex; smaller values make a larger index and slower admin lookups. Default comes from the builder configuration |
--search-radius <M> | Fine-level search distance in meters: a query answers the nearest street, address and interpolation closer than this. At most a fixed number of smallest cell widths at --street-level (see Search radius bounds). Default comes from the builder configuration |
--coarse-search-radius <M> | Coarse-level search distance in meters: the fallback for a class with nothing closer than --search-radius. At most a fixed number of smallest cell widths at --coarse-level. Default comes from the builder configuration |
--direct-io | Use O_DIRECT on the paths listed in the I/O capability matrix |
-O, --overwrite | Replace an existing index (or empty directory) at --output-dir after the new build succeeds. Without it an existing --output-dir is refused before any work. Does not bypass the indexdata requirement |
--staging-dir <DIR> | Stage the new index in DIR instead of beside --output-dir; DIR must not lie inside --output-dir (see Staging directory) |
--allow-unindexed | Accept input without blob-level indexdata (slower fallback path). Does not replace an existing index |
--force | Legacy shorthand equivalent to --overwrite --allow-unindexed. Every use warns that it also grants overwrite, naming the two flags to spell instead |
--tmp-dir <DIR> | Directory for this run's scratch files (see Scratch files). Must exist and be writable; checked before any input is read. Default: the directory containing --output-dir |
A node whose coordinates fall outside the geographic domain fails the whole build, judged on the exact nanodegree value before truncation (latitude within +-90 degrees, longitude within +-180, inclusive), as check --locations judges it. Node, way and relation IDs of either sign are used alike. Incomplete extracts remain usable, and a missing node or member never contributes geometry: no segment joins the two nodes on either side of a missing way node (the street keeps each stretch of consecutive present nodes as a street of its own), a building way with a missing node gives no address point, and an admin boundary whose outer or inner member ways (an empty role counts as outer) are not all present with every node present contributes no area at all, since the rings and holes of what remains are not the boundary's; admin boundary candidates with a missing, unparseable, or unsupported level or no name are skipped; relation members whose roles do not describe outer or inner rings are ignored (an empty role counts as outer), while a way member of a boundary candidate whose role string index names no string in its block fails the build (exit 2), naming the relation, member position and index. Each closed outer ring is its own area, and an inner ring is a hole of every outer ring whose interior contains the inner ring's boundary; where an inner ring touches or crosses an outer ring, which outer it belongs to is not promised. A point is in the area when it is inside the outer ring and inside none of its holes. Relations refused during ring assembly contribute no admin area; among them is any relation with a ring (outer or inner) whose points all lie on one line, judged with longitudes unwrapped across the antimeridian, since such a ring encloses nothing. A ring that simplification would flatten onto a line is stored unsimplified. Rings are not otherwise validated as geometry: inside a ring is decided by even-odd crossing parity, so a ring that crosses itself keeps the regions it encloses an odd number of times; outer rings of one relation that overlap are separate areas whose union matches; and a hole subtracts from each outer ring that owns it, wherever it touches or crosses that ring. For a given set of assembled rings, which outer owns an inner ring does not depend on where the rings start or which way they run. A relation is also refused, with a warning, when any of its rings (outer or inner) is of a shape whose interior can depend on where its walk starts: a ring that winds round a pole, one whose longitudes, unwrapped across the antimeridian, span a full turn, or one with an edge spanning exactly 180 degrees of longitude (which way round it runs is ambiguous). Such a relation contributes no admin area. The PBF header's replication sequence and timestamp are stored in the geocode header exactly as the input holds them: each as a signed 64-bit value with its own presence, so a missing value stays missing, a zero stays zero and a negative timestamp stays negative; no value fails the build. The library reader returns them as Option<i64> from Reader::replication_sequence and Reader::replication_timestamp. The header also records the input PBF's whole-file XXH3-128 (seed zero, over every byte of the file) and its size, so a consumer that hashed its PBF can tell whether an index was built from it; the library reader exposes them as Reader::input_xxh3_128 (formatted {:032x}, the same 32-digit hex as any whole-file XXH3-128) and Reader::input_bytes. The build reads the whole input once more for this, sequentially and beside the passes. The input must not change while it is built: a size change is refused, a same-size rewrite is not detected. Names, house numbers, streets, postcodes and country codes are stored and answered whole, bytes and all: a PBF tag value holding a NUL byte is not cut at it.
The index carries an on-disk format version. A reader accepts only its own version: an index of any other version (such as one built before the input digest or the signed replication fields were recorded, or before the admin cells became the cover admin lookup relies on) is refused with an error telling you to rebuild it with build-geocode-index, and there is no in-place upgrade. Rebuild existing indexes after upgrading.
A way segment is the line straight in latitude and longitude between its two nodes, taken the shorter way around in longitude: the line a query measures its distance to. An admin boundary edge is the edge the query's point-in-polygon test uses. The index lists a street, interpolation way or admin polygon under every cell, at the street, coarse and admin levels, that such a line passes through (an index built by pbfhogg 0.5.0 or earlier can lack a cell the line only clips near its corner; rebuild to gain them). Admin lookup reads only the admin cell holding the query point: the index lists there every admin polygon that can contain it, and marks one that contains every query point the cell is assigned, so it is accepted without a point-in-polygon test.
An address point is a node, or a building way whose nodes are all present, with addr:housenumber and a non-empty addr:street, a non-empty addr:place, or both. A building is placed at the mean of its way's node coordinates, truncated toward zero in decimicrodegrees, a repeated closing node counted again; the mean is not guaranteed to lie inside a concave footprint. Longitude is averaged on the shorter arc: a building across the antimeridian is placed beside it, not near longitude 0, and a building spanning half a turn of longitude or more gives no address point. addr:place is OSM's tag for an address that belongs to a place rather than a street; a query answers it in the address's place field, and street stays empty unless the address also names one. An empty value is no name, so an address whose only names are empty is not indexed. addr:substreet is not read: an address naming only a substreet is not indexed and anchors no interpolation, and one that also names a street or place answers those alone.
An interpolation way is a way with addr:interpolation and no addr:housenumber (a way with both is an addressed object, indexed as a building address when it is one). Its numbers come from the address points on its own nodes: an address whose coordinate equals the node's. No nearby address stands in for a missing one, and the cell levels play no part. It numbers along one street or one place: its own addr:street when it has one, else its own addr:place; otherwise, as OSM tags it, the one street that the addresses at its first and last node share, or, if they share none, the one place that their place addresses share. A place address is one that names a place and no street; an address with a street is numbered along its street, never along its place. Only addresses on the chosen street or place count, and a query answers the range in its street or place field accordingly. Both end nodes must carry a number, and an interior node with a number splits the way: each stretch between two address nodes is its own range (10, 20 and 40 along a way are 10-20 and 20-40, not 10-40), and a stretch with no number between its ends (10 to 12 on an even way) is dropped. all steps by one, even and odd by two, and a digit 1 to 9 by that step from the lower end, with no parity (4 from 10 to 21 is 10, 14, 18 and 21); a query answers the number nearest its position along the range, a tie going to the lower number, whichever way the way runs. The position is the length along the range to the query's nearest point over the range's whole length, each segment measured as a flat distance with longitude scaled by the cosine of its first node's latitude; the nearest point is taken to whole decimicrodegrees first. An interior node with a non-numeric number (12b) is passed over. The way is kept but never answers a query when its ends share no single street or place, an end has no address on it, the addresses at a node carry different house numbers, an end's number is not a plain positive integer (57a, 18-20 and 0 are refused) or an interior number is 0 or too large, two consecutive numbers are equal or an even or odd way's numbers do not all have that parity, a node of the way is missing from the input, or addr:interpolation is anything but all, even, odd or a digit 1 to 9. The build warns with the count and a sample of way IDs.
S2 level bounds
All three cell levels are validated before any input is read, and a violation exits 2 with an explicit message:
- Street and coarse levels must remain within the builder's segment-cover budget. Cell covering emits every cell a way segment passes through, so the cell count of a segment doubles at each level. The builder's rejection message reports its current upper bound and explains the budget.
- Admin level must remain within the builder's polygon flood-fill budget. The number of cells considered grows by a factor of four at each level. The builder's rejection message reports its current upper bound and explains the budget.
--coarse-levelmust be strictly less than--street-level. The coarse index is the fallback for rural queries and must be the coarser of the two.
The reader is deliberately looser and accepts levels up to the S2 limit of 30, since reading does no cell covering: an index written at a higher level by another producer stays readable.
Search radius bounds
A query searches the whole of each radius: it answers the nearest street, address and interpolation closer than the fine radius, each on its own, and for a class with none there the nearest closer than the coarse radius, wherever in the radius it lies. Earlier versions read only the query's cell and its eight neighbours, which reach about one cell width, less than the default radii, so a nearer record could be passed over for a farther one or for nothing. That fix is in the reader and applies to existing indexes; the cells an older index lacks (above) still take a rebuild. The work a query does grows with the square of the radius over the cell width, so a radius wider than a fixed number of smallest cell widths at its own level is refused before any input is read, with a message naming the most that level allows, and a reader refuses to open an index whose header carries one. A longer reach belongs at a coarser level.
Overwriting an existing index
Every build writes a complete generation in a staging directory (beside the output directory, or in --staging-dir) and publishes it only after the build and smoke test succeed. The smoke test opens the written index with the reader's validation and checks that the first address point is listed in its own fine and coarse cell; a failure fails the build. --overwrite (or legacy --force) lets that publication replace an existing index. Failed builds leave the existing index intact. Publication moves the old directory aside, moves the new one into place, then removes the old files. Already-open readers keep their mapped inodes and remain usable. The entire output directory is replaced; use a dedicated directory for the index. Allow disk space for both generations.
Publication uses two renames, so it is not crash-atomic and there is a short pathname gap. On Unix a reader opens the index directory once and every file relative to it (Reader::open, or Reader::open_dir on a handle the caller holds), so an open racing a publication reads one generation or fails; an open that falls in the pathname gap finds no index. On other platforms the reader looks each file up by path, so serialize publication with new reader opens there. Serialize builds with each other everywhere; queries on readers already open need no coordination. A publication killed partway (SIGINT and SIGTERM do not stop one that has started) may leave the old index in a .pbfhogg-backup-* directory beside the output directory; a publication that fails and cannot put the old index back says so and names that directory. SIGKILL, power loss or a second SIGINT/SIGTERM during a build can also leave an incomplete .pbfhogg-tmp-* staging directory beside it (in --staging-dir, when given) because process cleanup does not run. The next command that writes in that directory reports both (see Scratch files) but never removes them: a directory may belong to a concurrent build, and a backup may hold the only recoverable prior index. After confirming no builder is active, inspect abandoned staging directories and preserve or restore any backed-up index before removing scratch. A mount table change after the preflight can still make the final rename fail. On Linux mounts are recognised by the kernel's mount identity, so a bind mount of the same filesystem counts; other platforms compare device numbers, which do not see a second mount of the same filesystem. External writers must also replace files rather than modify mapped inodes: reader open-time string validation cannot protect against truncation, which can fault before a string check can return an error. The one-generation guarantee above further needs a new generation to replace the whole directory: a file replaced inside a published directory can be read beside the other files of the old one. On Unix the reader refuses an index file that is a symlink.
A build that indexes no address points, no streets and no admin polygons fails rather than publishing an empty index. Interpolation ways do not count: they take their numbers from the address points on their end nodes, so without address points none can answer. Indexes containing only some of those kinds, such as an admin-boundaries extract, are legitimate and still build.
Outputs a set of binary files. See performance/geocode.md for measured build times, index size, and peak memory.
The pbfhogg binary carries no benchmark instruments. The synthetic workloads run outside it: reads and writes through the library harness (brokkr bench library-scenario, scenarios decode-* and encode-*), the merge workload and reverse geocoding queries through the pbfhogg-bench instruments (brokkr bench merge-workload, brokkr bench geocode-query).
geocode-query
Answer reverse geocoding queries over an index written by build-geocode-index, the same answers as the library's Reader::query.
pbfhogg geocode-query <INDEX> <POINTS>POINTS holds one query per line: latitude then longitude in decimal degrees, separated by ASCII whitespace. The whole file is parsed before the index is opened, and a blank line, a third field, a value that is not a finite number, or a latitude outside -90 to 90 or longitude outside -180 to 180 refuses the run (exit 2) naming the line, before any answer is printed. An index the reader refuses (wrong format version, a corrupt file) is exit 2 as well, as is a query the reader fails on, naming its line (a corrupt index entry the query reaches, which open does not scan for, is such a failure). Every answer is computed before anything is printed, so an interrupted run prints nothing and a successful run prints exactly one line per input line (an empty POINTS file prints nothing).
Stdout carries one JSON object per query, one per line, in input order:
{"lat":55.6761,"lon":12.5683,
"address":{"lat_e7":556761000,"lon_e7":125683000,"house_number":"1","street":"Example","place":null,"postcode":"1000","distance_m":3.2},
"street":{"name":"Example","snap_lat_e7":556761200,"snap_lon_e7":125683100,"distance_m":1.4},
"interpolation":null,
"admin":[{"admin_level":2,"name":"Danmark","country_code":"DK","area":5.1e13}]}(shown wrapped; each object is a single line). address, street and interpolation are each the nearest of their class within the index's search radii (see Search radius bounds), or null when there is none; an interpolation object has the keys street, place, house_number and distance_m; admin lists the smallest area containing the point at each admin level, ascending by level, and is empty when none does. An absent street, place, postcode or country_code is null; a street name is a string, empty for a highway whose name tag is empty. Every key is always present. lat and lon echo the query in decimal degrees; the _e7 coordinates are decimicrodegrees (degrees times 1e7), distance_m is the reader's flat distance in meters and area the polygon's stored ranking area: its outer ring's planar area in square decimicrodegrees, holes not subtracted. A ring across the antimeridian is measured with its longitudes unwrapped, as containment tests it. An index built before that rule keeps the raw-frame area of such a ring, and one built before rings winding round a pole were refused keeps their raw-frame area too, until it is rebuilt. When the street segment spans exactly 180 degrees of longitude, the snap is the nearest point on either half-world path. Both paths are measured from the segment's lesser endpoint by (longitude, latitude), -180 ordered as +180, so the answer is the same whichever order the way's nodes run and whichever spelling an antimeridian endpoint carries; where the two computed distances are exactly equal, the path running east from that endpoint wins. A snap's longitude lies in (-180, 180]: a snap on the antimeridian is spelled +180, whichever spelling its way's nodes carry.
I/O capability matrix
Where commands use --direct-io (O_DIRECT bypass of page cache) and --io-uring (io_uring async writes), and which paths are affected.
| Command | Direct reads | Direct writes | --io-uring |
|---|---|---|---|
| inspect | Index scan buffered; header probes, --show and full-decode fallback direct; --nodes front probe direct with buffered classify preads | - | - |
| inspect tags | Kind-restricting type/expression probe direct; unfiltered counting, schedule and classify preads buffered | - | - |
| check | ID front read and index check direct; refs, locations and ID body preads buffered | - | - |
| cat | Front reads, passthrough and dedupe direct; clean classify preads buffered | All PBF writes direct | Plain passthrough and dedupe |
| sort | All reads direct, including copied ranges | All PBF writes direct | Yes |
| repack | Front read direct; classify preads buffered | All PBF writes direct | Yes |
| degrade | Front read and raw frames direct; decode classify preads buffered | All PBF writes direct | Yes |
| renumber | All reads direct | All PBF writes direct | - |
| extract | Front reads direct; pread passes buffered; fallback streams direct | Single output direct; config single-pass outputs buffered | - |
| tags-filter | Front read and -R stream direct; two-pass preads and dependency scans buffered | All PBF writes direct; OSC refuses flag | - |
| export | No direct I/O flag | No PBF output | - |
| getid | Front reads and sequential fallback direct; scheduled and ID-file preads buffered | All PBF writes direct | - |
| getparents | Dispatch probe and fallback stream direct; scheduled preads buffered | All PBF writes direct | - |
| time-filter | Header and history stream direct; snapshot classify preads buffered | All PBF writes direct | - |
| add-locations-to-ways | Front reads and unindexed fallback stream direct; index, dependency and external-stage preads buffered | All PBF writes direct | - |
| apply-changes | All base PBF reads direct, including copied ranges; OSC read buffered | All PBF writes direct | Yes |
| diff | All PBF reads direct, including indexed parallel comparison | No PBF output | - |
| digest | All reads direct | - | - |
| build-geocode-index | Indexdata probe and replication header read direct; schedule header walk, Pass 1, Pass 1.5 and Phase 2a preads and the whole-file input digest buffered | Index output buffered, not PBF | - |
| geocode-query | Index memory-mapped, points file buffered; no direct I/O flag | No PBF output | - |
| merge-changes | OSC only; no direct I/O flag | No PBF output | - |
Only the listed paths bypass the page cache. A front read means the header and first-blob indexdata probe, not the bulk scan. check --refs and check --locations alone refuse --direct-io; select --ids or --index too to give it work. Input-dependent fallbacks keep accepting the flag. The flag remains accepted on paths that currently ignore it, including unfiltered inspect tags. A filesystem can also buffer an O_DIRECT open: when statx explicitly reports zero alignment, one Note: per run explains that bypass is not guaranteed. Unavailable alignment information uses the compatibility floor without this note. --quiet suppresses notes.
--io-uring requires the linux-io-uring compile-time feature and sufficient RLIMIT_MEMLOCK.