Repository navigation
Optimize HPack - #15674
Optimize HPack#15674
Conversation
A h2c connection spends most of its per request time parsing frame headers and encoding and decoding HPACK, and there was no benchmark covering any of it, so there was no way to tell whether a change to that path was an improvement. Cover frame header and preface parsing, HPACK encoding and decoding of a realistic request and response, and the pieces they are built from: Huffman encoding and decoding, field name and value validation, and ASCII lowercasing.
Signed-off-by: Ludovic Orban <lorban@bitronix.be>
The existing HPACK benchmarks build a fresh encoder and decoder per invocation, which measures the first request on a connection, where every field is a literal. On a long lived connection the dynamic table absorbs the repeated fields: the same request that encodes to 392 octets cold encodes to 12 once the table is warm, so the Huffman coding that dominates the cold path barely runs. Add an encoder and decoder pair warmed the way a connection warms them, so both ends of the range are covered. The decoder is fed exactly the sequence the encoder produced, otherwise its dynamic table would not match. The two paths have quite different profiles, and the steady state one is the better guide for a server holding connections open.
54e1931 to
3baf263
Compare
Signed-off-by: Ludovic Orban <lorban@bitronix.be>
isLegalH2H3FieldName looked up TOKENS[c] per character, which is an array load followed by a dereference of the Token object and a switch on its type; both validators are run for every field on every HPACK encode and decode. isLegalFieldValue additionally re-evaluated the "is this the first or last character" test on every iteration. Classify all 256 ISO-8859-1 characters once, into a flat byte array of bit flags derived from TOKENS, so a character costs one load and one mask. Because the flags of a whole string can be accumulated with &, legality becomes a single test at the end rather than one per character, and the first/last field-vchar test moves out of the loop. Verified against the previous implementations over all 65536 characters and 1.2M strings, which agree in every case.
An entry of the HPACK dynamic table is referenced by index by every message that uses it, and each reference re-derived whether its name and value were legal, which is a full scan of both. On a connection in steady state, where the table absorbs the repeated fields, this was the single largest cost of decoding a message. Memoize the outcome on the entry. The field is immutable, so it cannot change; the memo races benignly, as the field hash in HttpField already does, and HpackContext is single threaded anyway. The outcome is remembered rather than assumed. A field that fails validation is still added to the dynamic table, because the failure only fails its own stream, so a peer could otherwise smuggle an illegal value into the table on a stream it is willing to lose and then reference it freely. Replaying the remembered outcome keeps every later stream that references the entry failing, exactly as before. Verified against the previous implementation with that smuggling sequence: both fail the inserting stream and every later stream that references the entry by index, with the same message. Decoding a request in steady state drops 52%.
Encoding a message walked the field list three times: once to verify every field could be encoded, once inside getCSV() to collect the hop headers named by the Connection header, and once to encode. The first two do not write anything, so they merge into a single pass. That pass also memoizes validation on the dynamic table entry, as the decoder now does. A field already in the table passed the same check when it was added, and re-deriving it is a scan of the name and of the value on every message. Static entries are still checked normally: a field an application named after a pseudo header matches a static entry but must still be rejected. The outcome is memoized rather than assumed, so turning validation off, admitting an illegal field to the table, and turning it back on still rejects it. The lookup is skipped while the dynamic table is empty, where it could only miss; that keeps the first message on a connection, which has nothing to gain here, from paying for it. Verified against the previous implementation across legal fields, pseudo header names, illegal values, repeated encodes that exercise the memo, and the validation off then on sequence: identical in every case. Encoding a request in steady state drops 52%.
An ISO-8859-1 String is byte for byte its encoded bytes, but both decoders built one up by appending one character at a time to a StringBuilder: a bounds check, a position update and a capacity check per octet, for every literal header name and value. HpackDecoder.toISO88591String now decodes straight from the buffer, using the backing array when there is one, so that String construction is a single array copy. The explicit remaining() check preserves the BufferUnderflowException thrown by the previous per-octet reads, which the array path would otherwise not raise. NBitStringDecoder accumulates into a byte array that grows as needed, since it must handle strings split across buffers; the array starts small rather than at the declared length, so a large declared length does not allocate up front.
Signed-off-by: Ludovic Orban <lorban@bitronix.be>
Signed-off-by: Ludovic Orban <lorban@bitronix.be>
…ck with isEmpty() Signed-off-by: Ludovic Orban <lorban@bitronix.be>
3baf263 to
1262b32
Compare
|
I've cleaned up the micro benchmark, and a few nits here and there (I had to modify how 12.1.x vanilla with PR: |
|
@lorban thanks :) |
gregw
left a comment
There was a problem hiding this comment.
Looks good, but I wonder if some/all of this can be moved to a more utility location
| if (_count < _length && !buffer.hasRemaining()) | ||
| return null; | ||
| // An ISO-8859-1 String is byte for byte the encoded bytes, so accumulate | ||
| // the bytes in bulk and decode them in one go, rather than appending one | ||
| // character at a time. | ||
| int available = Math.min(_length - _count, buffer.remaining()); | ||
| if (_bytes == null) | ||
| _bytes = new byte[Math.min(_length, INITIAL_CAPACITY)]; | ||
| if (_count + available > _bytes.length) | ||
| _bytes = ArrayUtil.grow(_bytes, _count + available - _bytes.length, _length); | ||
| buffer.get(_bytes, _count, available); | ||
| _count += available; | ||
|
|
||
| return _builder.build(); | ||
| if (_count < _length) | ||
| return null; | ||
| return new String(_bytes, 0, _length, StandardCharsets.ISO_8859_1); |
There was a problem hiding this comment.
We must have this issue elsewhere. Would it not be better to move this code into a
Iso88591StringBuilder.append(ByteBuffer) method? Or at the very least make it a static method on that class so others can find/use it if they have bulk bytes.
Generally speaking, the logic to have a growing appendable buffer should not be duplicated around the code.
There was a problem hiding this comment.
It's not possible to add a Iso88591StringBuilder.append(ByteBuffer) method that doesn't introduce an extra copy (BB -> byte[] -> StringBuilder -> String) nor a static helper as it would need to be able to return the string (or a boolean indicating the String is ready) plus some way of modifying the byte array reference.
A brand new Iso88591StringBuilder that aggregates directly in a byte[], or completely rewriting the existing Iso88591StringBuilder is doable, but at a sensibly higher engineering cost, though.
Let me see exactly what it would take.
There was a problem hiding this comment.
@gregw I've rewritten Iso88591StringBuilder so that it now has a append(ByteBuffer) method and is backed directly by a byte[] to avoid the extra copy.
…ringBuilder implementation Signed-off-by: Ludovic Orban <lorban@bitronix.be>
| if (_length == _maxLength) | ||
| throw new IllegalStateException("max buffer size overflow"); | ||
|
|
||
| if (_length == _bytes.length) | ||
| _bytes = ArrayUtil.grow(_bytes, _length, _maxLength); | ||
|
|
||
| _bytes[_length] = (byte)(0xff & b); | ||
| _length++; |
There was a problem hiding this comment.
I like this better even if there wasn't a bulk append operation!
… chars Signed-off-by: Ludovic Orban <lorban@bitronix.be>
Signed-off-by: Ludovic Orban <lorban@bitronix.be>
sbordet
left a comment
There was a problem hiding this comment.
Perf improvements LGTM, but not the changes to the Iso...Builder.
Signed-off-by: Ludovic Orban <lorban@bitronix.be>
The HPack parts of #15498 made by @wendigo