Skip to content

MOD-19328 write repeated strings once in the RDB (encoding version 5) - #1682

Merged
AvivDavid23 merged 23 commits into
masterfrom
rdb_strings_firstuse
Nov 3, 2026
Merged

AvivDavid23 merged 23 commits into
masterfrom
rdb_strings_firstuse

Conversation

@AvivDavid23

@AvivDavid23 AvivDavid23 commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

What

A string that several JSON values share is written once in the RDB and referred to by id afterwards, so an RDB no longer grows with every copy of a repeated key or value.
RAM already holds one copy of such a string, because ijson interns it.
Writes and reads use the shared-string support in ijson (RedisJSON/ijson#25, merged as 6484ffaf).

The RDB type version goes from 4 to 5. The module still reads version 4.
A module that predates version 5 cannot read a version 5 RDB, and every build of this module writes version 5, also with sharing off. Upgrade every node that may load this module's RDBs (replicas, then the master) before the first save; there is no rollback to an earlier module once a version 5 RDB has been written.

RDB size

Measured by encoding whole synthetic keyspaces in memory with the ijson encoder,
one record per document, and summing the record sizes. "Plain" is the format
before this PR. "Stream" shares strings across documents. "Self-contained"
shares only inside one value. The last column applies LZF to every record, which
is what Redis does to module values when rdbcompression is on (the default on
RoR), and compares stream with plain after the same compression.

Workload Documents Plain Self-contained Stream Stream vs plain
Orders: long repeated keys, shared catalog values 100,000 53.7 MB 47.4 MB (88%) 12.7 MB 24%
Long keys, mostly unique values 100,000 12.9 MB 12.9 MB (100%) 7.4 MB 57%
Wide numeric documents, 40 long shared keys 25,000 32.0 MB 32.0 MB (100%) 11.5 MB 36%
Tiny documents, short keys 100,000 2.3 MB 2.3 MB (100%) 2.3 MB 100%
One large document that repeats strings inside itself 1 4.5 MB 1.4 MB (31%) 1.4 MB 31%

How a value is written

Each value starts with one marker byte.

Marker Form Used for
0 plain CBOR writer off, or nothing to share
1, 2 stream record a normal save on a non-Flex server: strings are shared across keys, and a record depends on the records before it
3 self-contained strings are shared only inside the one value; the reader needs no other record
4 and up refused
  • A save session starts at the persistence START event and ends at ENDED or
    FAILED. A load session starts at the loading START event. A stream record
    with no load session is refused.
  • Self-contained records are written for: Flex (bigredis-enabled), DUMP,
    MIGRATE, the ASM slot snapshot, saves with no session (such as IO threads),
    any save that starts while this node exports slots (counted with
    RedisModuleEvent_ClusterSlotMigration), and any save the core flags in
    RedisModulePersistenceInfo as feeding a replica-of syncer
    (REDISMODULE_PERSISTENCE_FLAG_SYNCER) or as a standard RDB for a backup or
    export (REDISMODULE_PERSISTENCE_FLAG_STDRDB).
  • A core that passes no persistence info, such as OSS, is treated as an ordinary save and streams.
  • A document whose shared strings do not pay for their definitions is
    written plain.

Readers that take one key at a time

A RESTORE has no load session, so a consumer that turns an RDB into one RESTORE per key refuses stream records. The two flags above cover the Enterprise syncer and backup or export. The guide lists the cases the writer cannot tell, under "Readers that take one key at a time": a core without the flags, an OSS dump.rdb imported key by key, replica-of from an OSS source, a compressed replica-of without ASM, and a RoR RDB read by Flex. For those, the RDB has to be written with json-rdb-dictionary-max-memory-percent 0.

Config

json-rdb-dictionary-max-memory-percent (default 20, range 0 to 100, changeable at runtime) caps the memory the writer's table of shared strings uses, as a share of used_memory when a save starts. There is no absolute cap.
The table costs about 22 to 36 bytes per distinct shared string, so at 20% each GB that Redis uses allows about 6 to 9 million of them. The table is new memory in the saving process (BGSAVE, AOF rewrite or full-sync child), on top of its copy-on-write pages.

When the table fills, existing entries keep being referenced, and the new strings that do not fit in that document are written inline.
The table is cleared before the next document and sharing starts again, and the first record
that defines a string after the clear is written as marker 2, so the reader clears its table too. A save never fails, and an RDB is never larger than one written without sharing by more than a few bytes per value.
The cost of a reset is the partly inlined document plus re-defining, once, any string used again afterwards.

0 turns sharing off, across keys and inside a value. Reading is unaffected.
The end-of-save log line reports resets; above 0 means the save ran into the ceiling and the setting can be raised.

Other changes

  • defrag.rs does not reset the string cache while a stream load is running.
  • save_with, save_self_contained and set_dictionary_factory let an external manager serialize
    its values through the same encoder; save_self_contained never joins the save's stream.
  • rdb_persistence re-exports the ijson stream types that HDT's tests use.
  • redis-module is pinned to a3834293, which has the slot-migration event bindings,
    RedisModulePersistenceInfo and the syncer and standard-RDB flags.
  • A refused record is logged at warning during any load, Flex included. Outside a load,
    no_stream refusals warn at the 1st, 2nd, 4th, ... refusal of each incident.
  • docs/docs/use-share-string-in-rdb.md describes the formats, the rules above,
    the safety invariants, the limits and the rollout order.

Testing

  • cargo test -p redis_json --lib: 119 tests, 120 with --features as-library.
  • tests/pytest/test_rdb_dictionary.py (15 flow tests): standalone, replicas, AOF and a one-shard OSS cluster, and the Flex docker harness. One of them pins that a full-sync RDB restores key by key only with the writer off.
  • Not covered by a test here: slot migration against a real cluster, and the Enterprise syncer and backup flags, which need an Enterprise core (RedisJSON/RedisJsonHdt#555 tracks those runs).

Before merging

  • Merge the ijson PR, then pin the ijson dependency to the merged rev (6484ffaf).

Note

High Risk
RDB v5 is mandatory on write and incompatible with older module builds; persistence behavior differs by Flex, migration, and Enterprise flags, with subtle correctness constraints around stream ordering and address-based dictionaries.

Overview
RedisJSON bumps the module RDB type to version 5 and routes save/load through a new rdb_persistence layer so repeated strings are not written in full on every key.

Stream saves (normal RoR SAVE/BGSAVE/replication when allowed) define each shared string once and use short CBOR references across keys, with a memory-budgeted dictionary (json-rdb-dictionary-max-memory-percent, default 20). Self-contained records (marker 3) dedupe only inside one value for Flex, DUMP/MIGRATE, slot-export snapshots, and saves flagged for syncer/standard RDB consumers that restore key-by-key.

The module registers persistence/loading events, a command filter that ends stream sessions before standalone commands, and slot-migration export counting so cross-key streams are not written when they cannot be loaded. save_with / save_self_contained / set_dictionary_factory expose the same framing to other value managers; defrag skips intern-cache reset while a stream load holds dictionary strings.

Dependencies move to pinned ijson (stream encoder/decoder) and redis-module with persistence flags; docs in use-share-string-in-rdb.md, module.conf, and README; plus Rust unit/API tests and test_rdb_dictionary.py flow coverage.

Reviewed by Cursor Bugbot for commit c1e331c. Bugbot is set up for automated code reviews on this repo. Configure here.

@codecov

codecov Bot commented Oct 25, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 77.24289% with 104 lines in your changes missing coverage. Please review.
✅ Project coverage is 87.74%. Comparing base (5280f07) to head (c1e331c).
⚠️ Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
redis_json/src/rdb_persistence.rs 77.47% 98 Missing ⚠️
redis_json/src/redisjson.rs 37.50% 5 Missing ⚠️
redis_json/src/lib.rs 90.90% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #1682      +/-   ##
==========================================
- Coverage   88.50%   87.74%   -0.77%     
==========================================
  Files          17       18       +1     
  Lines        6222     6666     +444     
==========================================
+ Hits         5507     5849     +342     
- Misses        715      817     +102     

☔ 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.

gabsow commented Oct 26, 2026

Copy link
Copy Markdown
Collaborator

[P1] Honor the syncer persistence flag before enabling cross-key records.

The current persistence callback ignores _data, and cross_key_stream_allowed checks only Flex, the dictionary budget, and ASM exports. With the default nonzero budget, an Enterprise replica-of save is therefore eligible to emit markers 1/2.

As the TODO immediately above the callback explains, that syncer converts the RDB into individual RESTORE operations. Those records cannot be decoded independently, and the module refuses them without a load session. This can break full synchronization; normal Redis replica tests do not exercise this conversion path.

RedisLabsModules/redismodule-rs#490 exposes RedisModulePersistenceInfo and REDISMODULE_PERSISTENCE_FLAG_SYNCER, but this PR still pins an earlier bindings revision and does not consume the event metadata.

Before approval:

  • Update the bindings dependency once that change is available, read the versioned persistence metadata, and suppress the cross-key save session when the syncer flag is set. Use the existing self-contained path: marker 3 when intra-value sharing pays, otherwise marker 0.
  • Add a regression test that supplies the flag, saves multiple documents with repeated strings, and loads each emitted record independently with no stream session. Include repetition inside a document to verify that local sharing still works.
  • Cover flag-clear saves, absent metadata on older cores, and end/failure followed by another save. Existing session-cleanup coverage is useful; the new mode should not leave stale state or disable sharing for a later normal save.
  • Validate the real Enterprise replica-of full-sync path before enabling this by default there. Older cores that cannot identify syncer saves need an explicit safe rollout policy.

I ran the current default-feature library suite locally: all 109 tests passed. This finding is from the callback and framing paths; I have not run an Enterprise syncer reproduction.

@gabsow
gabsow self-requested a review October 26, 2026 11:22

gabsow commented Oct 26, 2026

Copy link
Copy Markdown
Collaborator

Follow-up on the OSS validation:

I exercised a real three-node OSS cluster with the module built from c887a52:

  • Completed an ASM slot transfer containing JSON documents with repeated strings, checked destination values, and saved/reloaded the destination RDB.
  • Cancelled ASM while the source snapshot was running, checked the source values, then verified a later normal save returned to stream mode and reloaded correctly.
  • Separately exercised classic MIGRATE during BGSAVE and checked both the destination values and the source snapshot.

These are targeted local checks, not a claim that every concurrent-save or migration combination is covered. The dictionary flow tests also ran across standalone, replica, and AOF configurations: 22 executed tests passed and 20 topology-specific cases were skipped.

The newer 6cb185d now consumes the syncer flag, addressing the callback gap in my earlier comment; its default-feature library suite passed all 110 tests locally. The full integration results above are from the earlier head.

The guide already explains retained decoder strings and reset behavior, so I am not requesting duplicate documentation. Peak RSS on a large production-like dataset remains unmeasured. Enterprise replica-of and Active-Active have not been validated by these OSS runs and need their own integration evidence before claiming that coverage.

gabsow commented Oct 26, 2026

Copy link
Copy Markdown
Collaborator

Please add a companion JSON-HDT integration/testing PR that points to the exact RedisJSON revision under review, including the fixed iJSON dependency, and link the validation results here before closing the Enterprise compatibility review.

The OSS persistence/ASM checks and the syncer-flag unit test do not establish that the real Enterprise consumers handle the new format correctly. The companion PR should cover:

  • Dependencies and adapter: align the RedisJSON and bindings dependencies, ensure the upstream tests come from the tested revision, and update/validate the standard JSON export adapter against the complete v5 framing and loading lifecycle. As the integration guide states, standard exports must use save_with; a dependency bump alone is insufficient.
  • Enterprise replica-of: initial full sync, forced resync, and interruption/retry with repeated strings across keys and within values. Exercise the actual core/syncer handshake and verify that records converted to individual RESTORE operations are independently readable. Include the safe configuration for supported older core/syncer versions without the flag.
  • Active-Active: native persistence/restart and rejoin/convergence under writes, plus standard JSON export/import as a separate path. Passing one format must not be treated as coverage of the other.
  • Compatibility and memory: round-trip standard exports between RedisJSON and HDT, read supported older RDBs, and exercise dictionary resets and expired defining keys. Measure peak memory during save/load on a large dataset with shared strings.

Please record the tested module/core/syncer revisions and which scenarios actually executed, including failures and skips. Explicit Enterprise syncer coverage is needed; green OSS or general Active-Active jobs alone would leave that gap open.

gabsow commented Oct 26, 2026

Copy link
Copy Markdown
Collaborator

[P2] Base the self-contained encoding decision on actual byte savings.

At 6cb185d, pays() uses used.refs * 3 > used.defs. Three bytes is a lower bound on the saving from a reference: passing this check proves a saving, but failing it does not prove that plain CBOR is smaller. The fallback can discard substantial real savings.

I reproduced this in a local unit test using:

  • An object with 20 fields named shared_field_00 through shared_field_19, with integer values.
  • A large_pair array containing the same 256 KiB string twice.
  • A retained clone of the document, so the field names are shared with another resident value.

The encoder reported:

definitions: 22
references: 1
self-contained candidate: 262,527 bytes
selected plain record:   524,652 bytes
selected marker: 0

The test expecting the smaller local record fails. These are serialized record sizes before Redis compression, not measured final RDB sizes or process RSS. This is a size/serialization-efficiency issue, not observed data corruption. The same heuristic is used by save_with, so the decision also matters for external serializers and self-contained paths such as DUMP, MIGRATE, and ASM.

Please add regression coverage for this case and use byte-aware accounting for the decision. One possible supporting iJSON API addition is an encoder metric reporting the actual encoded bytes saved by references and the overhead of definitions. RedisJSON could then compare the net saving without retaining two complete encodings. This is a suggested implementation approach, not a new correctness blocker in the current iJSON codec; it would not require changing the wire format.

Please avoid fixing this by allocating a second full plain encoding solely to compare sizes, given the memory constraints on large databases.

@gabsow

gabsow commented Oct 26, 2026

Copy link
Copy Markdown
Collaborator

Independent review at 6cb185d59b4e377c041258a362a59366662e30a6: changes needed before merge

This covers persistence, replication and compatibility, together with ijson#25 and the JSON-HDT companion. Findings are ordered by severity.

[P0] Cross-key records are on by default, but Enterprise backups are restored through per-key RESTORE

At 6cb185d:

So every replication-style save writes markers 1/2 unless one of those applies.

In Redis Enterprise, a database backup is taken by an extractor. It connects as a replica
(REPLCONF capa eof, REPLCONF req stdrdb, REPLCONF rdb-only 1, SYNC) and never sends
REPLCONF SYNCER, either before or after the syncer change. Import (backup restore, or import from
a file or a live source) feeds each RDB through rl_rdbloader. That tool uses librdb, which always
converts module values into one RESTORE per key.

A RESTORE has no load session, so
decode_stream_record
refuses every marker 1/2 record with no_stream. The resulting backup looks healthy and only fails
when someone tries to restore it. The syncer flag cannot cover this, because the backup RDB comes
from an ordinary replication sync.

The guide's own open question G1 ("before the writer is on by default") is answered by this path,
and the answer is yes.

Requested:

  • Ship with cross-key sharing off by default. Either use an explicit opt-in such as
    json-rdb-cross-key-sharing (default no), or treat missing persistence metadata as
    "self-contained only". Keep marker 3 (sharing inside one value) on, since it is safe for every
    consumer.
  • Enable cross-key mode only where every consumer is known to read the RDB in order, or once the
    core marks every per-key consumer (syncer and req stdrdb / rdb-only extraction) in the
    persistence event.
  • Add a regression test that feeds a v5 RDB with repeated strings through librdb's RESTORE
    conversion (rdb-cli <file> redis ...) into a fresh server and checks every key. Today that test
    would fail on markers 1/2.

[P1] Missing persistence metadata defaults to the unsafe mode

saves_for_syncer
treats NULL data as "not a syncer". Only rl_unstable passes RedisModulePersistenceInfo today:
the core change is merged there, the Flex port was closed unmerged, and the CRDT and release
branches still pass NULL. On every other core, a replica-of source therefore writes stream records
that the destination's per-key RESTORE refuses. The only protection is the manual setting described
in the guide.

Requested:

  • Fail safe. Without metadata from a core known to set the flag, write self-contained records.
  • Check info.version >= 1 before reading flags.
  • Add unit coverage that NULL metadata leads to self-contained records (once the default changes).

[P2] pays() discards large intra-value savings (still open; independently reproduced)

I reproduced the earlier case at 6cb185d. The encoder reports defs=22 refs=1. The marker-3
candidate is 262,527 bytes, but the selected plain record is 524,652 bytes (marker 0). Please use
byte-aware accounting from the encoder rather than refs * 3 > defs, and add that case as a
regression test.

Related: in save_with, the !pays branch runs the caller's serializer a second time. That keeps
peak memory at the larger of the two encodings, because the buffer is reused, but doubles the CPU
cost for every value that falls back.

[P3] The base id is truncated to u32 while the reader compares the full count

begin_record
writes stats().defs as u32. decode_stream_document
compares it with the cumulative u64, which keeps growing across resets. After 2^32 cumulative
definitions in one save, every later stream record is refused, so the RDB was written successfully
but cannot be loaded.

That needs at least about 43 GB of definition bytes in one RDB, so it only affects very large
datasets. It is cheap to define before v5 ships:

  • either specify the base id as "cumulative count mod 2^32" and compare stats().defs as u32;
  • or stop streaming before the counter wraps.

[P3] no_stream refusals outside a load are logged at verbose

The failures above surface to the client only as Bad data format. The reason is logged at
Verbose when no load is running
(rdb_persistence.rs:504-508),
which the default loglevel notice hides. Consider logging no_stream at warning level,
rate-limited, because it always means the format and the consumer don't match.

[Dependency] ijson lock still predates the cache-reset fix

Cargo.lock resolves ijson 5b30551. I bumped it locally to a5f374f and ran the lib suite:
110 passed (default) and 111 passed (as-library). With --features thread_safe,
ivalue_manager::tests::test_get_memory and test_shared_string_memory_across_keys fail on
both ijson revisions. That is pre-existing and not exercised in CI, but worth either fixing or
noting.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

// After a budget miss, the next definition-capable document reuses the cleared table.
pub const DEFAULT_RDB_DICTIONARY_MAX_MEMORY_PERCENT: i64 = 20;
pub static RDB_DICTIONARY_MAX_MEMORY_PERCENT: AtomicI64 =
AtomicI64::new(DEFAULT_RDB_DICTIONARY_MAX_MEMORY_PERCENT);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Default stream encoding breaks key restore

High Severity

The default json-rdb-dictionary-max-memory-percent of 20 arms a cross-key stream on ordinary saves. Marker 1/2 records cannot be decoded by RESTORE or any loader without a load session, so Enterprise backup-restore and import paths that replay one key at a time fail. The guide still lists this as unresolved before turning the writer on.

Additional Locations (2)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit b88ac21. Configure here.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

Comment thread redis_json/src/rdb_persistence.rs Outdated
/// of the persistence event.
fn cross_key_stream_allowed(flex: bool, budget: usize, asm_export: bool, syncer: bool) -> bool {
!flex && budget > 0 && !asm_export && !syncer
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stream records break per-key restore

High Severity

A stream session is opened for ordinary SAVE, BGSAVE, and SYNC while json-rdb-dictionary-max-memory-percent defaults to 20. Marker 1/2 records need an ordered load session, so per-key RESTORE refuses the JSON values. Enterprise backup, RDB import, and replica-of without the syncer flag take that path.

Additional Locations (2)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 10c1e72. Configure here.

@gabsow gabsow left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review at 1c2cf92, against my earlier findings from 6cb185d.

Fixed

  • P0 (backups restored through per-key RESTORE): cross_key_stream_allowed now also checks the STDRDB flag, and b117feda pins that a full-sync RDB restores key by key only without cross-key strings. This holds on cores that pass the persistence flags.
  • P2 (pays()): it now compares the encoder's saved_bytes with defs, instead of refs * 3 > defs.

Still open (inline comments below)

  • P1: a core that passes no persistence metadata still gets cross-key stream records.
  • P3: the base id is still truncated to u32 on write while the reader compares the full count.

Description is stale. It documents json-rdb-dictionary-max-bytes (default 1gb, 0 to disable), but the code has json-rdb-dictionary-max-memory-percent (default 20, 0 turns the writer off). It also does not mention the syncer and stdrdb flags among the cases that write self-contained records. Please bring it in line with the code, since operators will read the description and the guide.

Merge blockers already listed: the ijson dependency is still branch = "rdb_strings_firstuse", and the HDT companion (RedisJsonHdt#555) has not run its Enterprise scenarios yet. I did not run the code; this is from reading the diff, the head source and the earlier thread.

///
/// # Safety
/// `data` is null or points to the `RedisModulePersistenceInfo` the core passed to the callback.
unsafe fn persistence_flags(data: *mut c_void) -> u64 {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1, still open: a core that passes no RedisModulePersistenceInfo reads as flags 0, which means "stream allowed". Only rl_unstable passes the metadata today, as far as I know; the CRDT and release branches pass NULL. On those cores an Enterprise backup (req stdrdb) or replica-of source still writes markers 1/2, which the per-key RESTORE then refuses with no_stream. The backup looks healthy and only fails at restore. Please fail safe: treat missing metadata as self-contained only (marker 3 or 0), and check info.version >= 1 before reading flags. A unit test that passes NULL and expects no session would pin it.

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.

Intended: a core that passes no persistence info is treated like OSS, which streams across keys and keeps the size reduction. Cores with the flags write self-contained records for syncer and standard-RDB saves, and the guide lists the remaining cases under "Readers that take one key at a time".

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK for OSS. OSS cores pass no persistence info either, so failing safe here would turn sharing off for every OSS user, and the guide now lists the cases. The Enterprise exposure comes in through RedisJSON/RedisJsonHdt#555, which pins this repo by rev, so I've moved the ask there: a fail-safe default for that build.

}

fn begin_record(&mut self) -> (u32, Vec<u8>) {
let base_id = self.encoder.stats().defs as u32;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3, still open: the base id is written as defs as u32, but the reader (around line 636) compares found as usize with the full cumulative defs as usize. After 2^32 cumulative definitions in one save every later stream record is refused, so a save that succeeded cannot be loaded. It needs a very large dataset, but it is cheap to settle before v5 ships: either define the base id as the count modulo 2^32 and compare defs as u32, or stop streaming before the counter wraps.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Withdrawing this one. The pinned ijson (a51ca4c) stops defining strings once the cumulative definition count reaches u32::MAX (src/cbor/stream.rs:322, test cumulative_definition_positions_do_not_wrap_after_resets). So defs never exceeds u32::MAX, and defs as u32 is exact. That does depend on this ijson commit, which is one more reason to pin it by rev.

@gabsow gabsow left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Second pass at 1c2cf92, on top of my review from this morning. P1 and the points on the description, the ijson branch pin and the HDT companion still stand. I'm withdrawing P3 (reply on its thread).

New, inline:

  • P2: the writer budget has no absolute cap in the fork child (rdb_persistence.rs:59).
  • P2: v5 is written even with the writer off, so there is no reader-first rollout and no rollback (lib.rs:78).
  • P2: most self-contained saves encode each value twice (rdb_persistence.rs:387).
  • P2: Flex can't load a RoR stream RDB or full sync (rdb_persistence.rs:772).
  • P2: module.conf documents the old config name, and uncommenting it stops Redis from starting.
  • P2: the redis-module rev is 11 commits behind v2.1.3.
  • P3:
    • Flex load refusals are logged at verbose.
    • The no_stream counter never resets.
    • A server-wide command filter patches the session lifetime.
    • The guide still says the writer is off and capped at 1 GiB.
    • The ciborium dev-dependency is on a branch.

CI: the only failures are codecov.

I did not run the code; this is from reading the head source and the pinned ijson.

// uses when the save starts, so the table grows with the dataset; 0 turns the writer off.
// When it is reached the strings defined so far keep being referenced and new ones go inline.
// After a budget miss, the next definition-capable document reuses the cleared table.
pub const DEFAULT_RDB_DICTIONARY_MAX_MEMORY_PERCENT: i64 = 20;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: the default budget is 20% of used_memory, with no absolute cap. The table is new (non-COW) memory in the BGSAVE / AOF-rewrite / full-sync child. On a large RoR shard with many distinct shared strings, that can be several GB on top of the COW pages during every BGSAVE and full sync, on hosts sized for normal fork overhead. The earlier design capped it at 1 GB, and the guide's Limits section (line 322) still describes that cap. Could the effective budget be min(percent of used_memory, absolute cap)?

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.

Deliberately relative, with no absolute cap. At 20% the worst-case keyspace on our 2M-key benchmark stayed near master's peak during the save, and keyspaces with many repeats need far less than that. The Limits section now explains the headroom the table needs in the fork child (e2cdf64).

Comment thread redis_json/src/lib.rs
pub const MODULE_TYPE_NAME: &str = "ReJSON-RL";

pub const REDIS_JSON_TYPE_VERSION: i32 = 4;
pub const REDIS_JSON_TYPE_VERSION: i32 = 5;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: encoding version 5 is written even with json-rdb-dictionary-max-memory-percent 0, so no build of this module produces an RDB the previous release can read. The guide says "Roll out readers first, then writers" (line 361), but there is no reader-only build to roll out. A replica or rollback node on the previous RedisJSON stops loading as soon as it gets an encver 5 value, whatever the setting. Two options: let 0 at module load register and write v4, which gives a real reader-first step and a rollback path, or change the guide to a strict replicas-first order with no rollback.

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.

Fixed the guide (e2cdf64): every build writes version 5, so upgrade every node that may load the RDB (replicas, then the master) before the first save, and there is no rollback to an earlier module once a version 5 RDB has been written.

/// The record keeps that form (marker 3) only when it is smaller than the plain one. Strings that
/// other values share but this one holds once are defined and never referenced, which is what the
/// size check pays for.
fn encode_value(value: &IValue) -> Vec<u8> {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: self-contained saves usually encode each value twice. Owner counts are process-wide, so with repeated keys almost every value defines strings it holds only once. pays() then fails and the value is encoded again as plain CBOR. That covers every DUMP and MIGRATE, every Flex save, and every syncer, STDRDB and ASM-snapshot save. Each pays for a hash-table pass plus a second full encode, and save_with first copies and hashes every string of 8+ bytes into a ContentDictionary. A cheap pre-pass could count repeated addresses inside the value and define only the strings seen twice in it. That avoids both the wasted definitions and the re-encode.

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.

Agreed. Follow-up: count the repeats inside the value before encoding and define only the strings it holds twice, which removes both the wasted definitions and the second encode. It needs an ijson change.

| raw::REDISMODULE_SUBEVENT_LOADING_AOF_START
| raw::REDISMODULE_SUBEVENT_LOADING_REPL_START => {
// Flex never writes a stream and can keep a record undecoded, so it never reads one.
let session = (!BIGREDIS_ENABLED.load(Ordering::Relaxed)).then(LoadSession::new);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Flex never arms a load session, so it can't load any stream RDB. Yet the decision to stream comes from the writer's own Flex flag, not from what the reader can take. Two cases fail every marker 1/2 record with no_stream and abort the load: a RoR master full-syncing to a Flex replica, and a RoR dump.rdb (BGSAVE, not STDRDB) loaded into a Flex shard during a RoR to Flex move. It's listed under Limits, but nothing prevents it (for example, self-contained saves when a Flex reader is possible), and no test covers a mixed topology.

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.

The writer cannot tell that a Flex node will read its RDB. The guide now says so under Flex in Limits, and requires json-rdb-dictionary-max-memory-percent 0 on a RoR source before a move to Flex (e2cdf64).

Comment thread module.conf Outdated
# Changeable at runtime; a BGSAVE child keeps the value it inherited at fork.
# A save whose log line reports resets above 0 ran into the ceiling; raise it to share more.
#
# json-rdb-dictionary-max-bytes 1gb

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: this block documents json-rdb-dictionary-max-bytes (memory units, 0 to 1tb, default 1gb), which no longer exists. The code registers json-rdb-dictionary-max-memory-percent (0-100, default 20). If someone uncomments this line, as the block suggests, Redis refuses to start on the unknown module config. It's the same drift as in the description, but this one ships in the file.

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.

Fixed in e2cdf64: module.conf documents json-rdb-dictionary-max-memory-percent (0 to 100, default 20).

Err(error) => {
let mut message =
format!("JSON RDB dictionary phase=load status=refused reason={error}");
let level = if loading {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: the level comes from LOAD_SESSION.is_some(), and Flex never arms a load session (line 772). So on Flex, a record refused during a file or replica load is logged at verbose, except the first no_stream. Redis then stops loading, with the only line naming the cause below the default log level. Basing it on the context's loading flag (REDISMODULE_CTX_FLAGS_LOADING) instead of the session would keep these at warning.

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.

Fixed in e2cdf64: a refused record counts as part of a load when the server's loading flag is set (RedisModule_GetContextFromIO and REDISMODULE_CTX_FLAGS_LOADING), not only when a load session exists, so a refusal during a Flex load is a warning. Unit test a_refusal_while_the_server_loads_without_a_session_is_a_warning.

Comment thread redis_json/src/rdb_persistence.rs Outdated
} else if error == LoadError::NoStream {
// The RDB went to a consumer that reads it key by key. Every such key fails, so
// warn at the 1st, 2nd, 4th, ... refusal to keep the log readable.
let refusals = NO_STREAM_REFUSALS.get() + 1;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: NO_STREAM_REFUSALS lives for the whole process and never resets, so the 1st/2nd/4th... gate gets sparser with every unrelated incident. Say one failed import produces 1,000 refusals. The first refusal of a later, different import is refusal number 1,001, which is logged at verbose only. To keep the first refusal of each incident at warning, reset the counter per incident (say, after N seconds without a refusal) or rate-limit by time.

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.

Fixed in e2cdf64: a refusal 60 seconds or more after the previous one starts a new incident whose count restarts at 1, so the first refusal of each incident is a warning. Unit test the_no_stream_count_restarts_after_a_quiet_period.

// module-initiated RdbSave that did not publish a persistence-ended event.
// Stop sharing before such a command can produce a standalone DUMP/MIGRATE.
// SAFETY: Redis owns ctx and retains this callback; flags 0 include module calls.
let filter = unsafe {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: this server-wide command filter (every client command, Lua redis.call and RM_Call) exists only to clear a session that outlived its save. It adds a callback to every command, and it still doesn't check the real invariant: that the session belongs to the save writing this IO. Instead, record the pid and the sync/child kind at persistence START, and have encode_for_save ignore a session that doesn't match the current save context. Then the filter isn't needed.

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.

A pid check catches a session inherited across a fork, but not one left over in the same process after a save that never reported its end. I'd keep the filter unless it shows up in a profile.

Comment thread docs/docs/use-share-string-in-rdb.md Outdated
- **Expired keys.** A stream with many expired keys holds their strings until a reset or the end of
the stream, because the core decodes every value before it can drop it.

## Open questions before the writer is on by default

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: this section still reads as if the writer stays off until these questions are settled, and Limits (line 322) still describes a 1 GiB ceiling. This build turns the writer on by default at 20% of used_memory. G1 (Enterprise per-key RESTORE consumers) is the same risk as P1, so the guide shouldn't present it as a gate still ahead.

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.

Fixed in e2cdf64: Limits describes the percent-only budget, and the open-questions gate is replaced by "Readers that take one key at a time", which lists what the syncer and standard-RDB flags cover and the cases they cannot.

Comment thread redis_json/Cargo.toml

[dev-dependencies]
ctor = "0.1.26"
ciborium = { git = "https://github.com/RedisJSON/ciborium", branch = "main" }

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: the new ciborium dev-dependency tracks branch = "main" of a fork, like the ijson branch pin. A fresh lock, here or in HDT, picks up whatever main holds that day. The tests that compare against ciborium output can then change without any change here. Please pin a rev.

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.

ijson depends on ciborium by branch = "main", so a rev here alone builds a second copy of the crate (I tried it). Pinning needs ijson first, then this repo and HDT. Until then Cargo.lock pins the commit.

AvivDavid23 and others added 2 commits November 2, 2026 11:49
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
fix: address review on the RDB string sharing

- Log a refused record at warning when the server is loading, not only
  when a load session exists: Flex arms none, so its refusals were
  verbose.
- Restart the no_stream refusal count after 60 seconds without a
  refusal, so the first refusal of every incident is a warning.
- module.conf documents json-rdb-dictionary-max-memory-percent instead of
  the removed json-rdb-dictionary-max-bytes.
- The guide describes the percent-only budget, the strict upgrade order
  without rollback, RoR to Flex moves, and every reader that takes one
  key at a time.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

There are 3 total unresolved issues (including 2 from previous reviews).

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 1f76049. Configure here.

}

fn begin_record(&mut self) -> (u32, Vec<u8>) {
let base_id = self.encoder.stats().defs as u32;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stream base id truncates past u32

Medium Severity

The writer stores stats().defs as u32 in the stream header while the reader compares that field to the full defs as usize. After u32::MAX cumulative definitions the header wraps, the base-id check fails, and the rest of the load is refused. The guide says new strings stay inline past that point and existing references keep working; this layer never stops emitting stream records or caps the id, and resets make a cumulative count that large possible even when the live table stays within budget.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 1f76049. Configure here.

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.

Not a bug: the cumulative count cannot exceed u32::MAX, so the cast never truncates.

The pinned ijson (6484ffaf) stops defining strings at that limit, in src/cbor/stream.rs:

// Cumulative definition positions must remain representable in a u32 stream header.
if self.stats.defs >= u64::from(u32::MAX) {
    return Choice::Text;
}
  • stats().defs therefore tops out at u32::MAX, so as u32 is exact.
  • Past the limit, new strings stay inline and existing references keep working, as the guide says.
  • The decoder counts only the definitions it reads, so its defs stops at the same value and the base-id check still matches.
  • cumulative_definition_positions_do_not_wrap_after_resets in ijson covers this: with defs = u32::MAX it checks that a new string is not defined, reset_if_needed() returns false, references still resolve, and defs stays at u32::MAX.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

False positive at the pinned ijson (6484ffaf). The encoder stops defining strings once the cumulative count reaches u32::MAX (src/cbor/stream.rs:322), and defs only grows with a definition, so resets can't push it past that. cumulative_definition_positions_do_not_wrap_after_resets pins this, so defs as u32 here is exact.

@gabsow gabsow left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving at 1f76049. Everything from my second pass is settled:

  • Fixed in e2cdf64: module.conf, the Flex log level, the refusal count, and the guide on the budget, rollback and Flex.
  • Checked: the redismodule-rs rev.
  • Agreed as follow-ups: the in-value pre-pass (needs ijson) and the ciborium pin (after ijson). The command filter stays.

The ijson pin is now the merged 6484ffaf.

I accept P1 for OSS as designed, and the guide now lists the cases under "Readers that take one key at a time". Its Enterprise exposure only arrives when RedisJSON/RedisJsonHdt#555 re-pins this repo. So I'm holding that PR instead, on a fail-safe default for that build and on its Enterprise scenarios.

Bugbot's new base-id finding is a false positive (reply on its thread).

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.

2 participants