Repository navigation
MOD-19328 write repeated strings once in the RDB (encoding version 5) - #1682
Conversation
… remove max-def-bytes
252f434 to
c887a52
Compare
Codecov Report❌ Patch coverage is
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. 🚀 New features to boost your workflow:
|
|
[P1] Honor the syncer persistence flag before enabling cross-key records. The current persistence callback ignores 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 Before approval:
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. |
|
Follow-up on the OSS validation: I exercised a real three-node OSS cluster with the module built from c887a52:
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. |
|
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:
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. |
|
[P2] Base the self-contained encoding decision on actual byte savings. At 6cb185d, I reproduced this in a local unit test using:
The encoder reported: 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 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. |
Independent review at
|
| // 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); |
There was a problem hiding this comment.
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)
Reviewed by Cursor Bugbot for commit b88ac21. Configure here.
| /// 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 | ||
| } |
There was a problem hiding this comment.
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)
Reviewed by Cursor Bugbot for commit 10c1e72. Configure here.
gabsow
left a comment
There was a problem hiding this comment.
Re-review at 1c2cf92, against my earlier findings from 6cb185d.
Fixed
- P0 (backups restored through per-key RESTORE):
cross_key_stream_allowednow also checks theSTDRDBflag, andb117fedapins 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'ssaved_byteswithdefs, instead ofrefs * 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 { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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".
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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.confdocuments the old config name, and uncommenting it stops Redis from starting. - P2: the
redis-modulerev is 11 commits behind v2.1.3. - P3:
- Flex load refusals are logged at verbose.
- The
no_streamcounter 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
ciboriumdev-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; |
There was a problem hiding this comment.
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)?
There was a problem hiding this comment.
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).
| pub const MODULE_TYPE_NAME: &str = "ReJSON-RL"; | ||
|
|
||
| pub const REDIS_JSON_TYPE_VERSION: i32 = 4; | ||
| pub const REDIS_JSON_TYPE_VERSION: i32 = 5; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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> { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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).
| # 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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| } 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; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| - **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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
|
||
| [dev-dependencies] | ||
| ctor = "0.1.26" | ||
| ciborium = { git = "https://github.com/RedisJSON/ciborium", branch = "main" } |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
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.
There was a problem hiding this comment.
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).
❌ 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; |
There was a problem hiding this comment.
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)
Reviewed by Cursor Bugbot for commit 1f76049. Configure here.
There was a problem hiding this comment.
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().defstherefore tops out atu32::MAX, soas u32is 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
defsstops at the same value and the base-id check still matches. cumulative_definition_positions_do_not_wrap_after_resetsin ijson covers this: withdefs = u32::MAXit checks that a new string is not defined,reset_if_needed()returns false, references still resolve, anddefsstays atu32::MAX.
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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
ciboriumpin (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).


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
rdbcompressionis on (the default onRoR), and compares stream with plain after the same compression.
How a value is written
Each value starts with one marker byte.
FAILED. A load session starts at the loading START event. A stream record
with no load session is refused.
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 inRedisModulePersistenceInfoas feeding a replica-of syncer(
REDISMODULE_PERSISTENCE_FLAG_SYNCER) or as a standard RDB for a backup orexport (
REDISMODULE_PERSISTENCE_FLAG_STDRDB).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.rdbimported 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 withjson-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 ofused_memorywhen 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.rsdoes not reset the string cache while a stream load is running.save_with,save_self_containedandset_dictionary_factorylet an external manager serializeits values through the same encoder;
save_self_containednever joins the save's stream.rdb_persistencere-exports the ijson stream types that HDT's tests use.redis-moduleis pinned toa3834293, which has the slot-migration event bindings,RedisModulePersistenceInfoand the syncer and standard-RDB flags.no_streamrefusals warn at the 1st, 2nd, 4th, ... refusal of each incident.docs/docs/use-share-string-in-rdb.mddescribes 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.Before merging
ijsondependency to the mergedrev(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_persistencelayer 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_factoryexpose 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) andredis-modulewith persistence flags; docs inuse-share-string-in-rdb.md,module.conf, and README; plus Rust unit/API tests andtest_rdb_dictionary.pyflow coverage.Reviewed by Cursor Bugbot for commit c1e331c. Bugbot is set up for automated code reviews on this repo. Configure here.