Skip to content

Encode repeated fields in linear time on Julia 1.12+ - #318

Merged
quinnj-bot[bot] merged 2 commits into
masterfrom
claude/encode-without-truncate-growth
Nov 25, 2026
Merged

quinnj-bot[bot] merged 2 commits into
masterfrom
claude/encode-without-truncate-growth

Conversation

@quinnj-bot

@quinnj-bot quinnj-bot Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Problem

On Julia 1.12 and later, encoding a repeated message field into an IOBuffer is quadratic in the number of elements. For a message with a repeated field of small messages (Julia 1.12.6):

elements encode time allocated
20,000 185 ms
80,000 6.4 s gigabytes

On Julia 1.10 the same encodes are linear.

Cause

_with_size reserves one byte for a value's length with truncate(io, position + 1) before encoding the value, once per element. Since Julia 1.12's IOBuffer rewrite, growing a buffer with truncate always allocates new memory and copies the whole buffer, even when the existing memory has room (1.10/1.11 only reallocated when the data was too small). So every element copies everything encoded so far. I'll propose the Base fix separately; this PR fixes ProtoBuf on the Julia versions already released.

Change

When the buffer's position is at its end (the usual case), _with_size appends the reserved byte with write. That grows the buffer with Base's amortized over-allocation. The second truncate, used when a length needs more than one byte, appends too. A position inside existing data keeps the truncate + seek path, which only shrinks and so doesn't copy.

The output bytes are unchanged.

Verification

  • Benchmark (Julia 1.12.6), repeated field of messages with a oneof: 80,000 elements 6.4 s → 23 ms before Avoid repeated union-splitting on oneof fields in generated encode methods #316 merged, and 4.6 ms on top of Avoid repeated union-splitting on oneof fields in generated encode methods #316. The independent review measured 5.2 s → 4.8 ms, with 71 GiB → 3.4 MiB allocated. Encoded bytes are identical. Julia 1.10 is unchanged (4.4 ms vs 4.2 ms).
  • New test in test/test_encode.jl: 20,000 _with_size calls into one buffer must allocate under 2 MB, and the bytes must match.
    • Julia 1.12.6: 1.6 GB allocated before, 221 KB with the fix.
    • Julia 1.10: 240 KB either way.
  • Full test suite passes on Julia 1.12.6 and 1.10; the independent review also ran 1.11.9.
  • A buffer built from a vector that starts partway into its memory (after popfirst!, say) keeps that offset. The re-size copy now indexes io.data through io.ptr, so a value of 128+ bytes lands correctly there too. Master already got this wrong on 1.11. There's a test for it and for a position inside existing data.

🤖 Generated with Claude Code

`_with_size` reserved the byte for a value's length with
`truncate(io, position + 1)`. On Julia 1.12 and later, `truncate` allocates
new memory and copies the whole buffer every time it grows it, so encoding a
repeated message field was quadratic in its length: 80,000 elements took
6.4 s and allocated gigabytes. When the buffer's position is at its end
(the usual case), append the byte with `write` instead, which grows the
buffer with amortized over-allocation. The second `truncate`, for a length
that needs more than one byte, now appends too. A position inside the
buffer keeps the `truncate` path, which only shrinks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@codecov

codecov Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.33%. Comparing base (8ec6d8e) to head (4afb16f).

Additional details and impacted files
@@           Coverage Diff           @@
##           master     #318   +/-   ##
=======================================
  Coverage   94.32%   94.33%           
=======================================
  Files          25       25           
  Lines        3298     3299    +1     
=======================================
+ Hits         3111     3112    +1     
  Misses        187      187           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@quinnj-bot quinnj-bot Bot left a comment

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.

[review generated via AI]

Independent review of dfb3c05. The speedup is real and the regression test is good. But this change makes one kind of buffer produce wrong bytes on Julia 1.12+, silently. A two-line fix is below; I'd hold the merge for it.

Bug: wrong bytes when the IOBuffer wraps a Vector that starts past the beginning of its memory

Fails on 1.12.6 and 1.13.4 with this PR. Passes on master with those versions.

using ProtoBuf; const Codecs = ProtoBuf.Codecs
buf = zeros(UInt8, 300); popfirst!(buf)            # data now starts 1 byte into its memory
io = IOBuffer(buf; read=true, write=true, truncate=true)
Codecs._with_size(Codecs._encode, io, io, collect(1:128))   # 129-byte value -> 2-byte length
take!(io) == vcat(UInt8(129), UInt8(1), UInt8.(1:127), UInt8(128), UInt8(1))  # false

The public API hits it too. Take message Blob { bytes data = 1; } message Outer { repeated Blob blobs = 1; Blob single = 2; }. Encoding Outer(Blob[], Blob(collect(UInt8, 1:200))) into that io with PB.encode(PB.ProtoEncoder(io), msg) gets the last byte wrong. The result decodes without error, but the payload is wrong.

Cause. Since 1.11, IOBuffer(v::Vector) keeps v's offset into its memory (io.offset on 1.11, io.offset_or_compacted on 1.12+). So the data for position p is at io.data[p + offset + 1], not io.data[p + 1]. The unsafe_copyto!(io.data, initpos + ...) in the multi-byte-length path assumes the offset is zero. On master with 1.12+, the second truncate always reallocated right before that copy, and reallocating drops the offset, so the copy happened to be correct. write only reallocates when the buffer is out of room. With room to spare, the offset survives and the copy moves the wrong bytes. On 1.11, master already gets this wrong, because truncate there doesn't reallocate when there is room.

Such vectors are easy to get without trying: popfirst!, deleteat!(v, 1:k), or on 1.12+ take! on a PipeBuffer after reading a prefix (it wraps the rest of the memory without copying).

Suggested fix. Use io.ptr, which is an index into io.data on 1.10 through 1.13:

            # Move the data right after the correct size. `io.ptr` indexes `io.data`;
            # positions don't when the buffer starts at an offset into its memory.
            dst = io.ptr - encoded_size
            unsafe_copyto!(io.data, dst, io.data, dst - (encoded_size_len - encoded_size_len_guess), encoded_size)

And a test, next to the new one:

    # Buffer whose data starts at an offset into its memory, value needing a 2-byte length
    buf = zeros(UInt8, 300); popfirst!(buf)
    io = IOBuffer(buf; read=true, write=true, truncate=true)
    Codecs._with_size(Codecs._encode, io, io, collect(1:128))
    @test take!(io) == vcat(UInt8(129), UInt8(1), UInt8.(collect(1:127)), UInt8(128), UInt8(1))

With both changes applied locally, the test fails on this PR with 1.11.9, 1.12.6, and 1.13.4, and passes with the fix. The case matrix below gives identical bytes on 1.10 through 1.13, including all the offset cases. The full suite passes on 1.12.6 and 1.11.9.

Smaller notes

  • The else branch (truncate + seek for a position inside existing data) has no test. No test seeks before encoding, and codecov/patch reports 5 of 7 changed lines hit. My matrix shows that branch gives the same bytes as master. A case like write(io, "xxxxx"); seek(io, 1); _with_size(...) would cover it.
  • The test comment says the old code allocated "~800 MB". I measured 1.6 GB on 1.12.6 and 1.13.4, which matches the PR description.
  • A seekable IOBuffer(append=true) was already broken: master writes wrong bytes. With this PR it throws InexactError: trunc(UInt32, -1) instead. That is louder, not a regression.
  • A full buffer (maxsize reached exactly at the start position) now fails with ProtoBuf's "Failed to write to IOBuffer…" ArgumentError instead of Base's "truncate failed…". It is the same exception type, and no test checks the message.

What I checked (identical bytes on master and this PR, Julia 1.10.11 / 1.11.9 / 1.12.6 / 1.13.4)

  • Value sizes giving 1-, 2-, 3-, and 4-byte lengths (3 B, 129 B, 300 B, 16 KiB, 2 MiB).
  • Position at the end, at the end after a prefix, and in the middle (existing bytes after the position).
  • Write-only IOBuffer(read=false, write=true). eof doesn't check readability on any of these versions.
  • PipeBuffer, which takes the non-seekable branch and is unchanged.
  • Reusing the buffer after take!, and sizehint.
  • Buffers sized exactly to maxsize (7 B, 130 B, 2^14+3 B), and buffers that are too small (same errors as master).
  • Nested messages through encode, with round-trip decode.

Regression test: on master it fails with 1.12.6 and 1.13.4 (1.6 GB allocated). With this PR it passes (221 KB). On 1.10 and 1.11 it allocates 240 KB with either version. The 2 MB limit leaves about 9× headroom.

Full suite on this PR: 3948 + JET 141 + Aqua 11 pass on 1.12.6 and 1.10.11.

Benchmark

Batch { repeated Prim items }, where Prim { int32 tag; oneof { int64 a; double b } }. Encode into IOBuffer(), minimum of 3–5 runs. Apple silicon with 14 cores, load average 5–8.

Julia items master this PR allocated (master → PR)
1.12.6 10,000 41.8 ms 0.62 ms 1.1 GiB → 0.42 MiB
1.12.6 40,000 1353 ms 2.39 ms 17.5 GiB → 1.68 MiB
1.12.6 80,000 5194 ms 4.80 ms 71.4 GiB → 3.35 MiB
1.10.11 80,000 4.40 ms 4.24 ms 2.44 MiB both

Encoded bytes are identical on master and the PR in every row. The suggested fix runs at the PR's speed: 4.97 ms on 1.12 and 4.21 ms on 1.10 at 80,000 items.

The copy that makes room for a length of 2+ bytes indexed io.data by stream
position. A buffer built from a vector that starts partway into its memory
(after popfirst! or deleteat!, say) keeps that offset, so the copy moved the
wrong bytes. Growing with truncate used to reallocate and drop the offset;
appending keeps it. io.ptr indexes io.data directly. Also test a position
inside existing data (truncate path) and correct the allocation figure.

Found by the independent review of this PR.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@quinnj-bot

quinnj-bot Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor Author

[comment generated via AI] Thanks for the careful review. You're right about buffers that start at an offset into their memory. Pushed the io.ptr-based copy with your test, plus a test for a position inside existing data (the kept truncate path), and corrected the allocation figure in the test comment to ~1.6 GB. Both new tests pass on 1.10.11, 1.12.6 and 1.13.4, and the full suite passes on 1.12.6.

The fix also corrects the same input on Julia 1.11, where master already wrote the wrong bytes.

On the benchmark gap (22.5 ms vs your 4.8 ms for 80k items): my 22.5 ms run was on a branch from before #316 merged, so it still had the slower oneof encoding. With #316 my harness gives 4.6 ms, which matches yours. I'll fix the description.

@quinnj-bot
quinnj-bot Bot merged commit 94a9236 into master Nov 25, 2026
17 checks passed
@quinnj-bot
quinnj-bot Bot deleted the claude/encode-without-truncate-growth branch November 25, 2026 06:21
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.

1 participant