zstd icon indicating copy to clipboard operation
zstd copied to clipboard

ZDICT_finalizeDictionary keeps the start of the content instead of the end when it truncates

Open tsenart opened this issue 3 weeks ago • 1 comments

Describe the bug

lib/zdict.h (lines 245–249) says of ZDICT_finalizeDictionary():

If the header + the content doesn't fit in maxDictSize the beginning of the content is truncated to make room, since it is presumed that the most profitable content is at the end of the dictionary, since that is the cheapest to reference.

The code keeps the beginning instead. In lib/dictBuilder/zdict.c, the shrink step at line 902 reduces dictContentSize, but it does not advance customDictContent. So the memmove at line 935 copies the first dictContentSize bytes, and the end of the content is dropped.

The returned dictionary is valid, and data compressed with it decompresses correctly. Only the choice of retained bytes differs from the documentation.

To Reproduce

On dev (3b8634e0):

  1. Make 101 bytes of content, content[k] = (unsigned char)(k * 37 + 11). For samples i = 0 through 7, set sizes[i] = 1024 and samples[i * 1024 + j] = (unsigned char)(32 + ((j * 7 + i * 13) % 95)) for j = 0 through 1023. Use ZDICT_params_t params = { 0, 0, 32768 }.
  2. Call ZDICT_finalizeDictionary(dst, 256, content, 101, samples, sizes, 8, params).
  3. The call returns 256 bytes: a 165-byte header followed by 91 bytes of content. Those 91 bytes are content[0..91). The documentation says they should be content[10..101).

A minimal program, saved as dict-repro.c at the source root:

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

int main(void)
{
    unsigned char content[101], samples[8 * 1024], dst[256];
    size_t sizes[8], i, j, result, header, kept;
    ZDICT_params_t params = { 0, 0, 32768 };

    for (i = 0; i < sizeof(content); ++i)
        content[i] = (unsigned char)(i * 37 + 11);
    for (i = 0; i < 8; ++i) {
        sizes[i] = 1024;
        for (j = 0; j < 1024; ++j)
            samples[i * 1024 + j] = (unsigned char)(32 + ((j * 7 + i * 13) % 95));
    }
    result = ZDICT_finalizeDictionary(dst, sizeof(dst), content, sizeof(content),
                                      samples, sizes, 8, params);
    if (ZDICT_isError(result)) {
        fprintf(stderr, "%s\n", ZDICT_getErrorName(result));
        return 1;
    }
    header = ZDICT_getDictHeaderSize(dst, result);
    if (ZDICT_isError(header) || header > result) return 1;
    kept = result - header;
    if (kept > sizeof(content)) return 1;
    printf("result=%zu header=%zu retained=%zu prefix=%d suffix=%d\n",
           result, header, kept,
           memcmp(dst + header, content, kept) == 0,
           memcmp(dst + header, content + sizeof(content) - kept, kept) == 0);
    return 0;
}
make -C lib libzstd.a
cc -O2 -Ilib dict-repro.c lib/libzstd.a -pthread -o dict-repro
./dict-repro

On dev it prints result=256 header=165 retained=91 prefix=1 suffix=0. When the end is kept, it prints prefix=0 suffix=1.

In a matrix of 2,160 calls (3 byte patterns, content lengths from 0 to 4,096, 6 spare capacities, 2 levels, and separate or overlapping buffers), 624 calls truncate, and all 624 keep the start instead of the end.

Who reaches it

The default ZDICT_trainFromBuffer() reaches it, through fastCover. So do explicit fastCover and COVER, the optimizers, and zstd --train, --train-fastcover and --train-cover with --maxdict. The legacy trainer uses a different helper and is not affected.

Expected behavior

The code and the documentation should agree. Either fix seems possible, and we would like your view on which one you prefer:

  1. Change the code to keep the end of the content: advance the source by the number of dropped bytes before the copy. We have a small patch for this, which we checked with overlapping buffers and short-content padding.
  2. Change the documentation to say that the end of the content is dropped.

Option 1 changes the bytes of newly trained dictionaries. Existing dictionaries still work. On a held-out test of 457 samples of 1 KB each, taken from zstd's own C sources, the compressed size with the default trainer changed as follows. Smaller is better.

maxDictSize Now Keeping the end Change
256 189,041 191,353 +1.22%
1,024 179,479 180,393 +0.51%
4,096 165,208 165,717 +0.31%
16,384 148,632 148,409 −0.15%
65,536 131,561 131,457 −0.08%

Across the default, fastCover, COVER and optimizer modes, the compressed-size changes range from −0.76% to +1.22%. For the default trainer shown in the table, retaining the end gives smaller compressed totals at capacities 16,384 and 65,536, and larger totals at 256, 1,024 and 4,096. Other modes also have mixed results. This is one corpus; these results do not establish which end is generally more profitable to retain.

Desktop

  • OS: Linux
  • Compiler: GCC 14.2.0
  • Reproducer flags: -O2
  • Build system: Make
  • Source: dev, 3b8634e055a420526d481f50c4def45e6358c51c

Additional context

I searched open and closed issues and PRs for the finalizer and content truncation and did not find this retained-prefix mismatch. The related #4750 concerns the caller's shrinking loop, not this choice of retained bytes. This was found and checked with Perfloop, an AI tool. I am happy to open the patch for option 1 if you want it.

tsenart avatar Nov 10 '26 15:11 tsenart

Hi @tsenart, thanks for the detailed report and the repro. I saw you already have a patch for option 1 and offered to open it. Do you plan to open that PR yourself? If you'd rather hand it over, I'm happy to pick up option 1 instead (branched from dev, with a reproducer/test) — I just don't want to duplicate work you already have ready. Either way, the option 1 vs option 2 call seems like the maintainers' to make first.

0xABCD01 avatar Nov 11 '26 11:11 0xABCD01