Skip to content

guard empty piece before exactMatchSearch in unigram PieceToId - #1325

Merged
taku910 merged 1 commit into
google:masterfrom
sahvx655-wq:unigram-piecetoid-empty
Sep 8, 2026
Merged

taku910 merged 1 commit into
google:masterfrom
sahvx655-wq:unigram-piecetoid-empty

Conversation

@sahvx655-wq

Copy link
Copy Markdown
Contributor

While tracing why an empty token round-tripped to a real vocabulary id, I found unigram::Model::PieceToId forwarding piece.size() straight into Darts::DoubleArray::exactMatchSearch. As darts.h documents, a length of 0 is not "match zero bytes" but "the key is a zero-terminated C string", so the search abandons the length entirely and scans piece.data() forward until it meets a NUL. For an empty piece that means it reads whatever lies at and after data(): a zero-length view onto live bytes spuriously matches the following key (an empty field from absl::StrSplit in spm_decode --input_format=piece, or a caller-supplied absl::string_view slice, comes back as a non-<unk> id), and a view onto a non-terminated buffer runs off the end. I reproduced the latter directly against a darts trie under AddressSanitizer and it reports a heap-buffer-overflow READ inside the C-string scan; the base ModelInterface::PieceToId never has this problem because it resolves empty pieces through its hash map.

The root cause is passing an untrusted length of 0 to an API whose zero has special meaning, so the fix returns unk_id_ for an empty piece before the trie is touched. That matches the base-class contract and the existing PieceToId("") expectation, adds no work on the normal path, and leaves every non-empty lookup untouched. Left unfixed this is an out-of-bounds read reachable from the public decode surface, and a correctness bug that silently turns empty tokens into arbitrary vocabulary ids. The added PieceToIdEmptyPieceTest fails on the current code (an empty view over "ab" returns 5) and passes with the change.

@taku910
taku910 merged commit 05edbcc into google:master Sep 8, 2026
37 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.

3 participants