Skip to content

perf(kml): make a document's layer names unique in linear time - #763

Merged
giswqs merged 3 commits into
opengeos:mainfrom
gmoralessanchez:perf/kml-unique-layer-names
Nov 10, 2026
Merged

giswqs merged 3 commits into
opengeos:mainfrom
gmoralessanchez:perf/kml-unique-layer-names

Conversation

@gmoralessanchez

@gmoralessanchez gmoralessanchez commented Nov 10, 2026 •

Copy link
Copy Markdown
Collaborator

A KML or KMZ document's layer names are made unique in time linear in its Folders and Documents. It took time quadratic in them, and cubic when they shared a name (#630): terrio info on a 1,654-byte KMZ of 4,000 Folders without a name takes 0.10 s, where it took 28.7 s, and on one of 100,000 named Folders 2.1 s, where it took 24.6 s. The names are the same, in the same order: Folder, Folder (2), Folder (3), and so on.

Closes #630.

Behaviour

layers_of (drivers/vector/kml.rs) made a document's layer names unique in two costly ways. It compared each layer's name with every name before it, and it tried a taken name's suffixes from (2) each time. That cost time quadratic in a document's Folders and Documents, and cubic when they share a name. It now keeps a set of the names taken and, for each name, the next suffix to try, so each layer finds its name in constant expected time.

  • The names are unchanged, in document order.
    • A name an earlier layer has takes the first free suffix: (2), (3), and so on.
    • A suffix that a name given earlier already holds is skipped.
    • A name given later is renamed when an earlier layer holds it, whether that name was generated or given.
  • Why resuming is safe. Names are only ever added, so a suffix found taken stays taken, and a name's next search can resume after the last suffix it took.
  • Both readers go through it: .kml files (parse_styled), and KMZ archives (kmz_styled) for the main document and each layer document.

Before and after

Release CLI, terrio info, measured with /usr/bin/time -v with nothing else heavy running. The CLI was built from e78a5d8 (before) and from this branch (after). The table gives one run before and the median of three runs after.

Document Before After Peak RSS, before → after
4,000 Folders without a name, KMZ (1,654 B) 28.71 s 0.10 s 53.3 → 56.9 MiB
100,000 named Folders, KMZ (277,145 B) 24.61 s 2.08 s 518.5 → 521.5 MiB
the same 4,000 Folders as a .kml file 27.75 s 0.11 s 52.9 → 55.3 MiB
the same 100,000 Folders as a .kml file 25.76 s 2.14 s 525.3 → 528.5 MiB
3,000 containers whose names collide often, .kml 0.77 s 0.09 s 47.7 → 50.3 MiB
  • The output is byte-identical. terrio info prints the same output before and after for all five documents (72,001, 1,800,001, 72,001, 1,800,001 and 54,001 lines), layer names and their order included.
  • The last document holds 3,000 containers: 2,566 Folders and 434 nested Documents. Their names are drawn at random with a fixed seed, and collide often: unnamed containers, repeated names, and names such as a (2) and Folder (5) that a suffix would also produce.
  • The inputs are the issue's script for the first four, and for the last a generator with a fixed seed.
  • One name repeated. In a separate run, with other work on the machine, 100,000 Folders all named roads (KMZ): the CLI built from e78a5d8 had not finished after 586 s, when it was stopped, and this branch's took 3.2 s. Each later roads searched the suffixes from (2) again, against every earlier layer.

Tests and mutations

layer_names_are_made_unique_in_document_order (new, in the kml.rs unit tests) reads one document as KML and as KMZ, and asserts the full list of its 15 layer names.

  • The document mixes:
    • a root layer, named, unnamed and colliding Folders, an unnamed Document, and a nested Folder;
    • an explicit Folder (3), which a later unnamed Folder must skip;
    • an explicit Folder (2) given after the generated one, which must become Folder (2) (2).
  • It passes before and after the change, so the list is the old algorithm's output.

Mutations, each applied to the change and run against the test:

Mutation Result
suffixes start at 1 caught: roads (1), Folder (1)
suffixes start at 3 caught: roads (3), Folder (3) (3)
generated names not recorded as taken, so a later explicit name keeps a generated one caught: Folder (2) twice
a suffix taken without checking it against the names already taken caught: Folder (3) twice
layers processed in reverse order caught: the last layer keeps Folder, and the first becomes doc (2)
each search restarts at (2), as before the change survives, as it should: the names are the same, only the time differs

Checks run

  • cargo fmt --all -- --check
  • cargo clippy --workspace --all-targets -- -D warnings
  • cargo test -p terrio --lib drivers::vector::kml::: 17 passed
  • cargo test -p terrio --no-fail-fast: 3043 passed, 54 ignored
  • pre-commit run on the changed files

Limitations

  • Peak memory does not drop. The 100,000-Folder document's 520 MiB is the read itself, and the set of names adds about 3 MiB.
  • Names are made unique within each document only, as before. A KMZ whose doc.kml holds a Folder roads, and a link named roads to a layer document, gives two layers named roads, before and after this change.

Summary by CodeRabbit

  • Bug Fixes
    • KML and KMZ layers with duplicate or unnamed containers now receive unique, consistent names. Numbered suffixes avoid conflicts with names already in use, while preserving the order of layers in the document.
  • Performance
    • Layer naming is faster for documents with many folders and documents, including those with repeated names.

layers_of compared each layer's name with every name before it, and
tried the suffixes of a taken name from (2) each time: quadratic in a
document's Folders, cubic when they share a name (opengeos#630). A set of the
names taken and, for each name, the next suffix to try make the loop
linear. Names are only ever added, so a suffix found taken stays
taken, and a name's next search resumes after the last suffix it took:
the layers get the same names, in the same order.

Release CLI, terrio info: a 1,654-byte KMZ of 4,000 unnamed Folders
takes 0.10 s (28.71 s before), 100,000 named Folders 2.08 s (24.61 s);
the output is byte-identical before and after on both, on their plain
KML documents, and on a document of 3,000 colliding names. Peak RSS
grows by about 3 MiB for the set of names.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@coderabbitai

coderabbitai Bot commented Nov 10, 2026 •

Copy link
Copy Markdown

Explain Change →

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 35 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used all 2 included reviews currently available.

Learn how review limits work.

Review configuration:

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: ASSERTIVE
  • Plan: Advanced
  • Run ID: fdc8ce30-bfe1-4989-8fb8-8c2166862125
Commits

Reviewing files that changed from the base of the PR and between 905a696 and 3d54f0e.

Files selected for processing: 1

  • crates/terrio/src/drivers/vector/kml.rs

No actionable comments were generated in the recent review.

Walkthrough

The KML/KMZ layer naming logic now tracks assigned names and suffixes to avoid repeated scans when resolving duplicate names. A test checks naming for named and unnamed containers, including collisions, in both KML and KMZ parsing. The changelog records the performance change.

Changes: KML/KMZ layer naming

Layer / File(s) Summary
Unique layer-name assignment
crates/terrio/src/drivers/vector/kml.rs, CHANGELOG.md
layers_of uses a set of assigned names and a per-name suffix counter. Tests cover unnamed and duplicate containers, suffix collisions, nested containers, and matching results for KML and KMZ parsing. The changelog reports the performance change.

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Refactor · Severity of issue fixed: Medium

Possibly related PRs

  • opengeos/terrio#629: It assigns default layer names to linked KML documents, which can collide with names handled by this change.
  • opengeos/terrio#527: It validates requested layer names against dataset names, which this change updates for colliding KML and KMZ layers.
  • opengeos/terrio#601: It routes ZIP fallback reads through the KMZ driver, where this change assigns unique layer names.

Suggested reviewers: giswqs

Merge Risk: Minimal · previous review 905a6

No actionable issue is identified; the change is mergeable after normal checks.

Pre-merge checks: Passed 5

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly summarizes the main change: making KML layer names unique in linear time.
Linked Issues check Passed Issue #630 asks for faster unique layer-name assignment while preserving names and document order across KML and KMZ documents. layers_of now uses a set of taken names and a per-base next-suffix map…
Out of Scope Changes check Passed The changelog entry and the KML/KMZ name-assignment test support the optimization requested by issue #630. The supplied change summary identifies no unrelated changes.
Docstring Coverage Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentat…
Full details: Linked Issues check

Explanation

Issue #630 asks for faster unique layer-name assignment while preserving names and document order across KML and KMZ documents. layers_of now uses a set of taken names and a per-base next-suffix map. It keeps the first available suffix and skips names already taken. parse_styled and the KMZ reader call layers_of for the main document and linked layer documents. The PR summary reports a test that checks the full ordered name list for both KML and KMZ input, plus passing test suites.

Full details: Docstring Coverage

Explanation

Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 1 functions across 1 files. (1 skipped: 1 unsupported.)

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

A rabbit hops through folders in a row,
And gives each layer a name to show.
When names collide, it finds a suffix,
Past names already on the list.
KML and KMZ wear names that flow.
The rabbit nods, then bounds below.

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: ASSERTIVE
  • Plan: Advanced
  • Run ID: 56eec002-cb4d-4e52-a192-3d8669b8b433
Commits

Reviewing files that changed from the base of the PR and between e78a5d8 and 905a696.

Files selected for processing: 2

  • CHANGELOG.md
  • crates/terrio/src/drivers/vector/kml.rs

Included review availability: This review used your included allowance. Your plan provides up to 2 included reviews per hour; 0 remain after this review.

@github-actions

Copy link
Copy Markdown
Contributor

Code review

Bugs: None found. I checked the new layers_of loop against the old one. Both compare each layer's name only with the final names of earlier layers, and both try suffixes (2), (3), … in order. The resume point is safe because every suffix below the stored next value was inserted into taken and names are never removed. The test's expected list also matches a hand trace of the old algorithm. Confidence: high (about 90%).

Security: None. The change is pure in-memory string handling with no new input surface.

Performance: None. Each generated name costs one hash insert, and each base name's suffix counter only moves forward, so total work is linear in the number of generated names. The name.clone() for every layer is negligible next to parsing. Confidence: high.

Quality (nits, low confidence that they matter):

  • next is a vague name for the per-base suffix counter. next_suffix would be clearer.
  • HashMap is imported at the top of the file, but HashSet is spelled std::collections::HashSet inline. The file already does that in other places (around lines 149, 153 and 697), so this is consistent with the file. It is only a nit.
  • The CHANGELOG entry carries benchmark numbers and a rationale. Other entries in that section are similarly detailed, so this matches the file's style, but it is longer than a changelog line usually needs.

CLAUDE.md: AGENTS.md is the applicable guidance. The test name layer_names_are_made_unique_in_document_order is named after behaviour, as AGENTS.md asks. It pins output for both KML and KMZ inputs, which satisfies the regression requirement for a behaviour-preserving change. The PR also reports cargo fmt, Clippy, and the full test run. I did not re-run them, since I have no shell in this review.

I posted no inline comments, because none of the findings above is worth anchoring to a line. The naming nit would need a rename across three lines, so a one-line suggestion block would not apply cleanly.

Change size

Compared with the base branch: the whole PR against main (merge base e78a5d8 to PR head 905a696).

Measure Value
Files changed 2 (added 0, modified 2, removed 0, renamed 0)
Size before 171.3 KB (175,403 B)
Size after 174.3 KB (178,446 B)
Total size change +3.0 KB (+3,043 B)
Path Before After Change
crates/terrio/src/drivers/vector/kml.rs 65.4 KB 68.0 KB +2.5 KB
CHANGELOG.md 105.8 KB 106.3 KB +440 B

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Comment thread crates/terrio/src/drivers/vector/kml.rs Resolved
Comment thread crates/terrio/src/drivers/vector/kml.rs Resolved
@github-actions

Copy link
Copy Markdown
Contributor

Code review

I found no correctness bugs. The new loop gives the same names in the same order as the old scan. A name's next search resumes after the last suffix it took, and every suffix it skips is already taken, so resuming cannot change the result. The layer-0 case and the parent-before-child order also match the old code. I traced the new test's 15 expected names by hand against the algorithm and they agree.

Bugs

  • None found. Confidence: high.

Security

  • None found. The change only touches in-memory name generation. Confidence: high.

Performance

  • None found. Each generated name is skipped at most once overall, since a name B (k) decomposes uniquely into base B and suffix k, so the work is near-linear with hashing. The extra String clones and the roughly 3 MiB set are small by comparison. Confidence: high.

Quality

  • Nit: std::collections::HashSet is fully qualified while HashMap is imported at line 22. Inline comment posted on line 277 with a suggestion. Confidence: high.

Test coverage

  • The new test pins the output, but nothing guards the complexity fix. A revert to the old scan would pass silently. Inline comment posted on the test at line 1344, suggesting a large same-name case as an optional or benchmark-style guard. Confidence: medium, since it is a judgment call about the suite's time budget.

CLAUDE.md / AGENTS.md

  • The identifiers follow the behaviour-based naming rule.
  • The CHANGELOG entry matches the house style of verbose, measured entries.
  • The PR's figures (28.7 s → 0.10 s, and the rest of the table) are consistent between the PR body and the CHANGELOG.
  • The perf claims rest on manual timings, which the PR reports with method details. I did not re-run them. Confidence: high.

Change size

Compared with the base branch: the whole PR against main (merge base c31df7c to PR head c765164).

Measure Value
Files changed 2 (added 0, modified 2, removed 0, renamed 0)
Size before 172.3 KB
Size after 175.2 KB
Total size change +3.0 KB
Path Before After Change
crates/terrio/src/drivers/vector/kml.rs 65.5 KB 68.0 KB +2.5 KB
CHANGELOG.md 106.8 KB 107.2 KB +440 B

Pull requests no longer edit CHANGELOG.md (opengeos#765): the release pull
request writes each version's section from the pull request
descriptions. Restore the file to the merge base so this pull request
no longer conflicts with others there.
@giswqs

giswqs commented Nov 10, 2026

Copy link
Copy Markdown
Member

Pull requests no longer edit CHANGELOG.md (#765): entries at the top of Unreleased made every open pull request conflict with the next one to merge. I pushed a commit that restores the file on this branch, so please pull before pushing again. Your entry isn't lost: the release pull request drafts the changelog from pull request descriptions, so make sure this one opens with a paragraph stating the user-visible change. See "Changelog" in docs/contributing.md.

Comment thread crates/terrio/src/drivers/vector/kml.rs Resolved
@github-actions

Copy link
Copy Markdown
Contributor

Code review

Bugs: None found. I traced the new layers_of loop against the old quadratic loop. Both produce the same names because the set of taken names only grows, so resuming each base name's suffix search where it stopped gives the same result as restarting at (2). I also hand-traced the 15-name expected list in layer_names_are_made_unique_in_document_order against the old algorithm and it matches. Confidence: high.

Security: None found. The change only touches in-memory name bookkeeping. Confidence: high.

Performance: None found. Each suffix a base name tries is attempted at most once across all layers, so the work is linear in the number of layers. The per-duplicate String clone in next.entry(layer.name.clone()) is a minor allocation cost, not a complexity problem. Confidence: high.

Quality:

  • Nit (low): the suffix cursor is named next and n, which read as an iterator and a counter. next_suffix and suffix would be clearer. Posted inline at kml.rs:283.
  • Nit (low): taken uses a fully qualified std::collections::HashSet while HashMap is imported at line 22. The file already mixes these styles at lines 149, 153 and 697, so this is consistency only.
  • Nit (low): the new test checks output but cannot catch a regression back to the quadratic search, since the mutation "each search restarts at (2)" survives by design. A timing or operation-count guard would be fragile, so I would leave it as is.

CLAUDE.md (AGENTS.md): Mostly compliant. The change adds a regression test, the identifiers describe behavior, and the PR records before/after measurements with byte-identical output. Nothing in the changed file needs an SPDX header or NOTICE entry. The PR's known limitation, that names are unique only within each document (not across a KMZ's linked layer documents), is pre-existing and documented.

I could not compile or run the tests in this environment (no shell), so the "tests pass" claims in the PR body are unverified here.

Change size

Compared: the whole PR against main (merge base c31df7c to PR head 3d54f0e).

Measure Value
Files changed 1 (added 0, modified 1, removed 0, renamed 0)
Size before 65.5 KB
Size after 68.0 KB
Total size change +2.5 KB
Path Before After Change
crates/terrio/src/drivers/vector/kml.rs 65.5 KB 68.0 KB +2.5 KB

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

KML: making a document's layer names unique takes time quadratic in its Folders, cubic when they share a name

2 participants