#1805·lz4

LZ4_compress_fast_continue: an 8-byte dictionary makes a periodic 4 KiB page 31x larger (49 -> 1543 bytes)

Author: martinusCreated Sep 23, 2026Updated Sep 23, 2026

Hi, I ran into a weird case while benchmarking zram's lz4 backend with a dictionary (kernel commit f0f6f7871430 added dictionary support). A 4096-byte page that compresses to 49 bytes without a dictionary compresses to 1543 bytes with one, and a dictionary of just 8 bytes is enough to trigger it. Reproducer against dev at 0774d05 (1.10.0), gcc 16.2, x86-64:

c
#include "lz4.h"

#include <stdio.h>
#include <string.h>

int main(void) {
    /* 4096 bytes: 8 x 0xff, then 16 x 0x00 and 16 x 0xff alternating */
    char page[4096];
    for (int i = 0; i < 4096; ++i) {
        page[i] = ((i + 8) / 16) % 2 == 0 ? (char)0xff : 0;
    }
    static char const dict[8] = {0, 0, 0, 0, 0, 0, 0, 4};
    char out[LZ4_COMPRESSBOUND(4096)];
    LZ4_stream_t s;

    LZ4_initStream(&s, sizeof(s));
    printf("no dict: %d\n", LZ4_compress_fast_continue(&s, page, out, 4096, sizeof(out), 1));

    LZ4_initStream(&s, sizeof(s));
    LZ4_loadDict(&s, dict, sizeof(dict));
    printf("dict:    %d\n", LZ4_compress_fast_continue(&s, page, out, 4096, sizeof(out), 1));
    return 0;
}
no dict: 49
dict:    1543

Same with LZ4_loadDictSlow, and with the lz4 1.9.4 that the Python bindings ship. HC is fine, 36 bytes with the dictionary.

As far as I can say from the LZ4_DEBUG=7 trace, this is what happens: the match at position 8 goes into the dictionary (7 bytes, offset 16) instead of the 1 literal + 15-byte run that the no-dictionary case finds there. After that, all 510 remaining matches come from the "Test next position" path (lz4.c line 1253 on dev), 5 to 11 bytes each with offsets 2 and 21 to 27, and the parser never gets back to the main search loop. So it never finds the match at offset 32 that covers the remaining 4019 bytes. Without a dictionary the same chain of short matches starts too, but it breaks after 72 bytes, so I guess the no-dictionary result is partly luck as well.

Rotating the page shows it is the dictionary though. Without one, all 32 rotations compress to 36 to 49 bytes. With the 8-byte dictionary, 8 of the 32 rotations go to 1540 to 1547 bytes.

On real data it is rare. I measured 455 239 swapped pages from a zram device, with a 64 KiB dictionary from zstd --train: 107 pages got more than twice as large with the dictionary, that's 0.01% of the memory zram needs for all the pages. The dictionary still saves 2.4% overall. But zram stores a page uncompressed when it compresses to 3625 bytes or more, so a blowup like this can cost the full 4 KiB.