Skip to content

Fix truncate string upper bound producing an unencodable lone surrogate - #4516

Open
AP24110011695 wants to merge 2 commits into
apache:mainfrom
AP24110011695:fix/truncate-upper-surrogate
Open

AP24110011695 wants to merge 2 commits into
apache:mainfrom
AP24110011695:fix/truncate-upper-surrogate

Conversation

@AP24110011695

Copy link
Copy Markdown
Contributor

Fixes #4514

Summary

truncate_upper_bound_text_string() builds the truncated upper bound by incrementing the last code point of the truncated value. When the last code point is U+D7FF, the successor is U+D800 — a lone surrogate. chr(0xD7FF + 1) does not raise, so the function returned a str that cannot be encoded as UTF-8, and the write path crashed later at manifest serialization (to_bytes → UnicodeEncodeError: surrogates not allowed) via the truncate-metrics stats collector (pyiceberg/io/pyarrow.py, truncate_upper_bound_text_string(self.current_max, self.trunc_length)).

Repro on main (7864d4c):

from pyiceberg.utils.truncate import truncate_upper_bound_text_string
from pyiceberg.conversions import to_bytes
from pyiceberg.types import StringType

bound = truncate_upper_bound_text_string("ab" + chr(0xD7FF) + "x", 3)
# main: 'ab\ud800' — to_bytes(StringType(), bound) raises UnicodeEncodeError

The input itself ("ab\uD7FF") is perfectly valid UTF-8, so this is reachable from ordinary data through write.metadata.metrics.default=truncate(N).

Fix

Mirrors Java's UnicodeUtil.incrementCodePoint (api/src/main/java/org/apache/iceberg/util/UnicodeUtil.java), which pins the same rule: surrogate code points are not Unicode scalar values, so the next scalar value after U+D7FF is U+E000, and U+10FFFF has no successor (walk back to the previous code point). The tightest valid upper bound for a prefix ending in U+D7FF is therefore the prefix with U+E000 in that position — comparison stops at the first differing position, so every string with that prefix is below it, and no valid string lies in between.

The explicit checks replace the try/except ValueError (which only caught the U+10FFFF overflow) with the same None when no position can be incremented.

Tests

Failing-first verified: the two lone-surrogate tests fail on the pre-fix head ('ab\ud800' != 'ab\ue000') and pass after. Also added a code-point-increment parity test mirroring Java's truncateStringUpperBoundIncrementsSurrogatePair (U+1F7FF → U+1F800, passes on both heads — it pins the whole-code-point increment). tests/utils/test_truncate.py 5/5, tests/io/test_pyarrow_stats.py 20/20, ruff + mypy clean on the changed files.

AI disclosure

This PR was developed with AI assistance (Claude); the bug report in #4514 was filed by a human contributor, the fix design was verified against Java's UnicodeUtil semantics, and every test was run locally.

Signed-off-by: Ayush Kumar Saha <225407166+AP24110011695@users.noreply.github.com>

@Fokko Fokko 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.

Thanks for the fix, the U+D7FF to U+E000 mapping matches Java's UnicodeUtil.incrementCodePoint. A few comments inline, mainly the third test.

Comment thread tests/utils/test_truncate.py Outdated
def test_upper_bound_string_truncation_d7ff_after_max_code_point() -> None:
# the last code point has no successor (U+10FFFF), so the previous position is
# incremented, and there the same lone-surrogate rule applies
value = chr(0x10FFFF) + chr(0xD7FF) + "x"

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.

This doesn't hit the walk back: the truncated prefix ends in U+D7FF, so the first iteration bumps it to U+E000 and returns, and the U+10FFFF continue never runs. It's effectively the same as the previous test. Swapping the order exercises it:

value = chr(0xD7FF) + chr(0x10FFFF) + "x"
assert truncate_upper_bound_text_string(value, 2) == chr(0xE000) + chr(0x10FFFF)

(or chr(0xE000) if the trailing code points get dropped, see the comment on truncate.py).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Right — in that order the first iteration already bumps U+D7FF and returns, so the continue never ran. Swapped to chr(0xD7FF) + chr(0x10FFFF) + "x"; with the trailing code points now dropped (3530b49) the expected bound is just chr(0xE000).

Comment thread pyiceberg/utils/truncate.py Outdated
if to_inc == 0x10FFFF:
# no code point above this exists, try incrementing the previous one
continue
if 0xD7FF <= to_inc <= 0xDFFF:

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.

Java only maps exactly U+D7FF to U+E000, and rejects surrogate input with a Preconditions.checkArgument. Mapping the whole U+D800..U+DFFF range silently hides invalid input (the lower bound would still fail to encode). Since Arrow strings are valid UTF-8 this can't come from the write path anyway, so to_inc == 0xD7FF would match Java. Otherwise the "like Java's UnicodeUtil" comment should be adjusted.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed — narrowed to to_inc == 0xD7FF so the behavior matches Java's incrementCodePoint exactly. Arrow strings are valid UTF-8, so surrogate input can't reach this from the write path and there is no reason to map it silently.

Comment thread pyiceberg/utils/truncate.py Outdated
chars[i] = "\ue000"
else:
chars[i] = chr(to_inc + 1)
return "".join(chars)

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.

Not introduced here, but since this mirrors Java: after walking back past a U+10FFFF, the trailing code points are kept, so "a\U0010FFFF" gives "b\U0010FFFF" while Java's setLength(offset) gives "b". Still a valid bound, just looser. Could be return "".join(chars[: len(chars) + i + 1]), fine as a follow up too.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Applied — the return is now "".join(chars[: len(chars) + i + 1]), so walking back past a U+10FFFF yields "b" for "a\u{10FFFF}" like Java's setLength, and the bound is byte-identical to Java's. Tighter, and it also simplified the walk-back test's expectation.

Comment thread tests/utils/test_truncate.py Outdated
bound = truncate_upper_bound_text_string(value, 3)
assert bound == "ab" + chr(0xE000)
# the bound must survive serialization into the manifest
bound.encode("utf-8")

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.

Nit: the equality assert above already guarantees this is encodable. to_bytes(StringType(), bound) would at least cover the actual path that crashed.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done — the test now runs to_bytes(StringType(), bound), the exact serialization path that crashed, instead of a bare encode.

…iling code points

Signed-off-by: Ayush Kumar Saha <225407166+AP24110011695@users.noreply.github.com>

This branch has not been deployed

No deployments
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.

truncate_upper_bound_text_string can return a lone surrogate that fails UTF-8 encoding

2 participants