Skip to content

fix(backend): validate aspatial geopackage layer writes & add test co… - #1654

Merged
giswqs merged 4 commits into
opengeos:mainfrom
RohithPariki:fix/write-geopackage-aspatial
Aug 3, 2026
Merged

fix(backend): validate aspatial geopackage layer writes & add test co…#1654
giswqs merged 4 commits into
opengeos:mainfrom
RohithPariki:fix/write-geopackage-aspatial

Conversation

@RohithPariki

@RohithPariki RohithPariki commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

What

_write_geopackage accepted any layer name that existed in the GeoPackage, including aspatial tables (those with geometry_type = None). Passing an aspatial table name caused an OGR crash at write time instead of a clean HTTP error

Why

The existing guard only checked if layer not in names (404 for missing), but didnt check whether the matched layer was actually a spatial table.

Fix

Add a second check if layer not in spatial after 404 guard, returning 400 with clear message: "Layer 'X' is an aspatial table and cannot be written".

Tests

  • test_write_geopackage_rejects_aspatial_layer - verifies the new 400 path
  • test_fix_geometries_leaves_unfixable_unchanged - covers the previously untested unfixable branch in _fix_geometries (geometry that make_valid cant repair is left unchanged and counted)

All 119 existing + new vector tests pass.

Summary by CodeRabbit

  • Bug Fixes
    • GeoPackage write-back now rejects explicitly selected non-spatial tables with a clear HTTP 400 error.
    • GeoPackages containing no spatial layers now return a clear HTTP 400 error.
    • Missing layers continue to return HTTP 404 errors.
    • Geometry repair now preserves unrepairable degenerate polygons and reports them accurately.

@coderabbitai

coderabbitai Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: d9c2f8db-e88a-4e04-846b-da971b3cbfff

📥 Commits

Reviewing files that changed from the base of the PR and between 0bbe10d and b12ffbb.

📒 Files selected for processing (3)
  • backend/geolibre_server/geolibre_server/app/vector.py
  • backend/geolibre_server/tests/test_vector.py
  • backend/geolibre_server/tests/test_vector_ops.py

📝 Walkthrough

Walkthrough

GeoPackage write-back now derives writable layers from geometry metadata and rejects aspatial-only targets with HTTP 400. Tests cover missing spatial layers and unrepairable degenerate geometries.

Changes

Vector validation

Layer / File(s) Summary
Validate GeoPackage write targets
backend/geolibre_server/geolibre_server/app/vector.py, backend/geolibre_server/tests/test_vector.py
The write path rejects explicitly selected aspatial tables and GeoPackages without spatial layers. Tests verify the HTTP 400 responses and error details.
Preserve unrepairable geometries
backend/geolibre_server/tests/test_vector_ops.py
Parameterized tests verify that exceptions and empty make_valid results preserve the original degenerate polygon and report it as unrepaired.

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

Suggested reviewers: giswqs

Poem

A rabbit checks each layer with care,
Aspatial tables wait outside.
A broken shape stays unchanged,
Its unrepaired state is logged.
Tests hop through each guarded path.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly identifies the backend fix for validating aspatial GeoPackage layer writes and adding related tests.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@backend/geolibre_server/geolibre_server/app/vector.py`:
- Around line 232-236: Update the target-layer selection in _write_geopackage so
an omitted layer is resolved only from spatial layers; do not fall back to
names[0] when the GeoPackage contains only aspatial layers. Return the existing
“No feature layer to write” response for that case, and add a layer=None test
covering an aspatial-only GeoPackage.

In `@backend/geolibre_server/tests/test_vector_ops.py`:
- Around line 1206-1209: Add a second test case alongside the existing
mock_make_valid exception case that makes shapely.validation.make_valid return
an empty geometry. Exercise the empty-result repair path in the relevant vector
operation and assert that the original geometry is preserved and the unrepaired
count matches the exception case.
- Around line 1206-1207: Update mock_make_valid to annotate its return type as
NoReturn, rename the unused geom parameter to _geom, and raise ValueError
without the unnecessary inline message.

In `@backend/geolibre_server/tests/test_vector.py`:
- Around line 328-331: Update the mock_list_layers helper signature to annotate
its path parameter as unused and provide an explicit pandas DataFrame return
type, resolving Ruff ANN202 and ARG001 while preserving its existing DataFrame
result.
- Around line 335-338: Update the assertion following vector_write in the test
to compare exc.value.detail against the complete expected error message, rather
than checking only for the “aspatial table” substring; preserve the existing 400
status-code assertion.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 481585cf-2f9d-48c1-b43d-18729b1b9146

📥 Commits

Reviewing files that changed from the base of the PR and between 483c663 and 1f2a002.

📒 Files selected for processing (3)
  • backend/geolibre_server/geolibre_server/app/vector.py
  • backend/geolibre_server/tests/test_vector.py
  • backend/geolibre_server/tests/test_vector_ops.py

Comment thread backend/geolibre_server/geolibre_server/app/vector.py
Comment thread backend/geolibre_server/tests/test_vector_ops.py Outdated
Comment thread backend/geolibre_server/tests/test_vector_ops.py Outdated
Comment thread backend/geolibre_server/tests/test_vector.py Outdated
Comment thread backend/geolibre_server/tests/test_vector.py Outdated
@github-actions

github-actions Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

🔍 Cloudflare PR preview

Item Value
Site https://ce263571.geolibre-preview.pages.dev
Demo app https://ce263571.geolibre-preview.pages.dev/demo/
Commit 0bbe10d

@giswqs

giswqs commented Aug 2, 2026

Copy link
Copy Markdown
Member

/claude-review

raise HTTPException(
status_code=400,
detail=f"Layer '{layer}' is an aspatial table and cannot be written",
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor nit: the function's Raises docstring (a few lines up) still only says "The named layer is absent, or the file has several feature layers and none was specified" — worth extending it to mention this new aspatial-table 400 case so the docs stay in sync with the code. Not blocking.

@github-actions

github-actions Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

Code review

Bugs: None found. The new if layer not in spatial: check (backend/geolibre_server/geolibre_server/app/vector.py:232-236) correctly sits after the existing 404 "unknown layer" guard and before the elif spatial: auto-selection branch, so it only fires when a caller explicitly names an existing-but-aspatial table. Confidence: high.

Security: No issues found — no new input paths, injection surface, or secret handling introduced.

Performance: No issues found — the fix reuses the already-computed spatial list; no extra I/O or complexity added.

Quality:

  • Minor: _write_geopackage's docstring Raises section wasn't updated to mention the new 400/aspatial-table case (left an inline nit with a suggested wording). Confidence: high (cosmetic only, non-blocking).
  • The new test_fix_geometries_leaves_unfixable_unchanged test uses a degenerate 3-point ring ([[0,0],[1,1],[0,0]]) and asserts on GeoPandas' specific coordinate-padding behavior when serializing it back to GeoJSON. I initially suspected this geometry might fail to construct at all (GEOS typically requires 0 or ≥4 ring points), but found a pre-existing passing test (test_smooth_degenerate_ring_collapses_to_empty, line 955) using the identical coordinate pattern, which confirms this geometry does load without raising. So no actual bug — just flagging that the assertion is tied to shapely/geopandas serialization internals rather than purely the function's own logic, which is somewhat fragile across library versions. Confidence: low, informational only.

CLAUDE.md: No violations — this is a backend-only bugfix/test change with no dependency, lockfile, i18n, or menu-catalog impact, so none of the repo's special sync rules apply.

Overall this is a small, well-targeted, low-risk fix with solid test coverage following existing patterns in the file.

@github-actions

github-actions Bot commented Aug 2, 2026

Copy link
Copy Markdown
Contributor

🔍 GitHub Pages PR preview

Item Value
Site Deploy failed. See the job log.
Demo app Unavailable
Commit 0bbe10d

RohithPariki and others added 2 commits August 3, 2026 15:06
The explicit-layer guard rejected an aspatial table, but the auto-select
path did not: with no layer specified, a GeoPackage whose only table is
aspatial fell through to the `len(names) == 1` fallback and handed OGR
the very table the guard above rejects, failing with a DataLayerError
instead of a clean 400. That fallback is redundant for every other case
(a single spatial layer is already covered by `spatial[0]`), so drop it
and let the existing "No feature layer to write" response handle it.

Also address review follow-ups: assert the full error detail, annotate
the test mocks (Ruff ANN202/ARG001), cover both unfixable branches of
_fix_geometries (make_valid raising vs returning empty), and extend the
Raises: docstring to mention the aspatial-table 400.
@giswqs

giswqs commented Aug 3, 2026

Copy link
Copy Markdown
Member

Pushed b12ffbb addressing the review feedback — thanks @RohithPariki for catching the aspatial write path in the first place.

The major one (vector.py:232-236): the new explicit-layer guard was right, but the auto-select path had the same hole. With layer=None, a GeoPackage whose only table is aspatial fell through to elif len(names) == 1: target_layer = names[0] and handed OGR exactly the table the guard above rejects. That fallback is redundant for every other case — a lone spatial layer is already covered by elif spatial: target_layer = spatial[0] — so it is gone, and the existing No feature layer to write 400 now covers it.

Verified rather than assumed: the new test_write_geopackage_rejects_aspatial_only_file fails on the pre-fix code with pyogrio.errors.DataLayerError: Layer 'aspatial_data' could not be opened, and passes after.

The rest:

  • test_vector.py — assert the complete exc.value.detail instead of the "aspatial table" substring; mock_list_layers(_path: str) -> pd.DataFrame (ANN202/ARG001).
  • test_vector_ops.pytest_fix_geometries_leaves_unfixable_unchanged is now parametrized over raises / returns_empty, so both branches of _repair are exercised (make_valid raising, and returning an empty geometry); mock annotated (_geom: object) -> NoReturn with a bare raise ValueError.
  • Extended the Raises: docstring on _write_geopackage to mention the aspatial-table 400 (@github-actions' nit).

Backend suite: 372 passed, 23 skipped. pre-commit run --files on the three changed paths is clean.

@giswqs
giswqs merged commit fda21c4 into opengeos:main Aug 3, 2026
11 of 12 checks passed
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.

2 participants