Skip to content

Separate GeoHash/GeoHashRaw - #8618

Merged
xzfc merged 3 commits into
devfrom
geohash-normalized
Apr 7, 2026
Merged

xzfc merged 3 commits into
devfrom
geohash-normalized

Conversation

@xzfc

@xzfc xzfc commented Apr 7, 2026 •

Copy link
Copy Markdown
Member

Why: see coderabbitai comment. In short, we read GeoHash values from index files without validation. Invalid values (e.g. wrong length) can cause panics in some methods. Valid complaint, but not related to changes in the said pull request.

In this PR, GeoHash is separated into two structs, like so:

// Always valid. Stored only in-memory.
struct GeoHash(u64);

// Not validated. Stored on-disk.
#[repr(C)]
struct GeoHashRaw(pub u64);

The new method GeoHashRaw::normalize() converts GeoHashRaw into valid GeoHash.

@xzfc
xzfc marked this pull request as ready for review April 7, 2026 11:33
@coderabbitai

coderabbitai Bot commented Apr 7, 2026

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

The pull request refactors the GeoHash type from a named-field struct with an explicit #[repr(C)] annotation to a tuple struct GeoHash(u64). A new public GeoHashRaw(pub u64) type is introduced for unchecked serialization/deserialization of geohash bit patterns, with a normalize() method that converts raw patterns to validated GeoHash instances. A module-level constant GEOHASH_MAX_LENGTH is replaced with associated constants on GeoHash, including MAX_LEN, LEN_MASK, LEN_BITS, CHAR_BITS, and BASE32. The changes propagate through two geo_index modules, where read paths and comparison operations now normalize stored hashes before processing, while the public query API parameters remain unchanged.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.74% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the main change: separating GeoHash into two distinct types (GeoHash and GeoHashRaw) for handling validated in-memory vs. raw on-disk representations.
Description check ✅ Passed The description is directly related to the changeset, explaining the motivation and the separation of GeoHash/GeoHashRaw types with code examples and implementation details.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch geohash-normalized

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 and usage tips.

@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: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
lib/segment/src/index/field_index/geo_index/immutable_geo_index.rs (1)

56-86: ⚠️ Potential issue | 🟠 Major

Sort and merge after normalizing mmap hashes.

hash.normalize() can reorder keys or collapse multiple raw buckets into the same GeoHash, but this path preserves mmap order via collect(). The later binary_search_by calls on counts_per_hash and points_map assume normalized, unique ordering, so malformed on-disk entries can still make the immutable index return incomplete counts or point sets. Sorting/merging by normalized hash here, or rejecting corrupted input during load, would restore that invariant.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/segment/src/index/field_index/geo_index/immutable_geo_index.rs` around
lines 56 - 86, counts_per_hash and points_map are built from mmap entries but
use hash.normalize() which can collapse/reorder keys; you must ensure the
normalized keys are unique and ordered before relying on later binary_search_by
calls. Update the code that builds points_map (and counts_per_hash) to group
entries by hash.normalize(), merge their ids vectors and counts for duplicate
normalized GeoHash keys (or explicitly reject/corrupt input if duplicates are
unexpected), then sort the resulting collections by the normalized hash so they
are strictly ordered and unique for subsequent binary_search_by on
counts_per_hash and points_map. Ensure you perform the same normalize+merge+sort
logic for index.storage.points_map items (the PointKeyValue processing) and for
index.storage.counts_per_hash so invariants are restored.
🧹 Nitpick comments (1)
lib/segment/src/index/field_index/geo_hash.rs (1)

266-266: Use an explicit Coord::from conversion here.

This new call site goes against the repo rule to avoid implicit .into() conversions when the destination type matters for readability.

As per coding guidelines, "Prefer explicit SomeType::from(x) over implicit x.into() in Rust".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/segment/src/index/field_index/geo_hash.rs` at line 266, The call uses an
implicit conversion ((lon, lat).into()) which violates the repo guideline;
replace the implicit .into() with an explicit Coord::from(...) conversion so the
destination type is clear (i.e., pass Coord::from((lon, lat)) into encode(...,
GeoHash::MAX_LEN)). Update the expression that sets encoded_string and any
similar sites to use Coord::from rather than .into().
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@lib/segment/src/index/field_index/geo_hash.rs`:
- Around line 147-149: The loop currently calls position(...).unwrap() which
panics on invalid base32 chars; change it to handle missing positions and return
an Err from the conversion path instead. Replace position(|x| x == c).unwrap()
with something like position(...).ok_or(YourError::InvalidBase32Byte(*c)) (or
map to the crate's existing error type) and propagate that Result out of the
routine used by TryFrom<String>/TryFrom<EcoString>; ensure the TryFrom
implementations (and any helper used in GeoHash::new() path) return Result and
propagate the error instead of panicking. Keep references: GeoHash::BASE32,
Self::shift_value(i), GeoHash::new(), and the TryFrom<String>/TryFrom<EcoString>
impls.

In `@lib/segment/src/index/field_index/geo_index/mmap_geo_index.rs`:
- Around line 324-327: The code currently binary-searches the mmap slices using
x.hash.normalize() (e.g. in self.storage.counts_per_hash.binary_search_by in
points_of_hash/values_of_hash/stored_sub_regions), but normalize() is not
monotonic over the on-disk raw u64 ordering so this can miss or mis-locate
entries; update the code to stop relying on normalize() at search time and
instead validate and canonicalize the mmap once during open(): implement a check
in open() that computes normalized keys for the mapped arrays, ensures they are
sorted and unique (or reject/rebuild the file if not), and then switch
binary_search_by to either (a) binary-search on the raw stored key and normalize
the lookup key accordingly or (b) binary-search on a precomputed normalized-key
in-memory index created at open(); reference functions: open(), points_of_hash,
values_of_hash, stored_sub_regions, and the binary_search_by call to locate
where to perform the validation or build the auxiliary index.

---

Outside diff comments:
In `@lib/segment/src/index/field_index/geo_index/immutable_geo_index.rs`:
- Around line 56-86: counts_per_hash and points_map are built from mmap entries
but use hash.normalize() which can collapse/reorder keys; you must ensure the
normalized keys are unique and ordered before relying on later binary_search_by
calls. Update the code that builds points_map (and counts_per_hash) to group
entries by hash.normalize(), merge their ids vectors and counts for duplicate
normalized GeoHash keys (or explicitly reject/corrupt input if duplicates are
unexpected), then sort the resulting collections by the normalized hash so they
are strictly ordered and unique for subsequent binary_search_by on
counts_per_hash and points_map. Ensure you perform the same normalize+merge+sort
logic for index.storage.points_map items (the PointKeyValue processing) and for
index.storage.counts_per_hash so invariants are restored.

---

Nitpick comments:
In `@lib/segment/src/index/field_index/geo_hash.rs`:
- Line 266: The call uses an implicit conversion ((lon, lat).into()) which
violates the repo guideline; replace the implicit .into() with an explicit
Coord::from(...) conversion so the destination type is clear (i.e., pass
Coord::from((lon, lat)) into encode(..., GeoHash::MAX_LEN)). Update the
expression that sets encoded_string and any similar sites to use Coord::from
rather than .into().
🪄 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: CHILL

Plan: Pro

Run ID: 9fd90eff-04f0-424b-a011-76333d83d6bc

📥 Commits

Reviewing files that changed from the base of the PR and between cc3e20c and e57772c.

📒 Files selected for processing (3)
  • lib/segment/src/index/field_index/geo_hash.rs
  • lib/segment/src/index/field_index/geo_index/immutable_geo_index.rs
  • lib/segment/src/index/field_index/geo_index/mmap_geo_index.rs

Comment on lines 147 to 149
for (i, c) in s.iter().enumerate() {
let index = BASE32_CODES.iter().position(|x| x == c).unwrap() as u64;
let index = GeoHash::BASE32.iter().position(|x| x == c).unwrap() as u64;
packed |= index << Self::shift_value(i);

This comment was marked as off-topic.

Comment on lines 324 to +327
if let Ok(index) = self
.storage
.counts_per_hash
.binary_search_by(|x| x.hash.cmp(&hash))
.binary_search_by(|x| x.hash.normalize().cmp(&hash))

This comment was marked as off-topic.

@xzfc
xzfc merged commit 1b23628 into dev Apr 7, 2026
15 checks passed
@xzfc
xzfc deleted the geohash-normalized branch April 7, 2026 11:59
timvisee pushed a commit that referenced this pull request May 8, 2026
* GeoHash: convert to tuple struct for consistency

* GeoHash: clarify code

* Separate `GeoHash`/`GeoHashRaw`
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