Skip to content

Cherry-pick: MOD-16873 TS.INCRBY replicate master timestamp when timestamp is local server clock (#2109) - #2156

Merged
AvivDavid23 merged 7 commits into
8.2from
cherry-pick-ca3375a9-to-8.2
Sep 3, 2026
Merged

AvivDavid23 merged 7 commits into
8.2from
cherry-pick-ca3375a9-to-8.2

Conversation

@AvivDavid23

@AvivDavid23 AvivDavid23 commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

MOD-16873 TS.INCRBY replicate master timestamp when timestamp is local server clock (#2109)

  • MOD-16873 TS.INCRBY replicate master timestamp when timestamp is local server clock

  • .

Cherry-pick of ca3375a onto 8.2

Note: had a minor conflict in tests/flow/test_ts_incrby.py (8.2 was missing several test functions this commit adds at the end of the file, including test_incrby_error_cases and test_ts_incrby_NaN) — resolved by taking the incoming tests as-is.


Note

Medium Risk
Changes replication and command parsing for write paths; mistakes could break replica/AOF consistency or mis-handle unusual argument layouts, though behavior is heavily regression-tested.

Overview
Fixes primary/replica timestamp drift for TS.INCRBY and TS.DECRBY when the sample time comes from the server clock (no TIMESTAMP, TIMESTAMP *, or create-on-write without an explicit time). Those cases no longer use RedisModule_ReplicateVerbatim; replication is rewritten like TS.ADD, embedding the master’s resolved millisecond timestamp so replicas and AOF replay do not call RedisModule_Milliseconds() again later.

Argument parsing for TIMESTAMP and LABELS now scans only after <key> <value>, ignores a TIMESTAMP token inside a trailing LABELS block, and returns wrong arity when TIMESTAMP has no following value. Replication insertion puts TIMESTAMP <ts> before a real LABELS clause when needed, and appends at the end when there is no LABELS, so keys named TIMESTAMP, LABELS, or IGNORE do not break rewritten commands.

Flow tests add master/replica coverage (including DEBUG SLEEP delay, labels, restart/reload, and edge-case key names).

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

#2109)

* MOD-16873 `TS.INCRBY` replicate master timestamp when timestamp is local server clock

* .
Comment thread tests/flow/test_ts_incrby.py Outdated
# Add a number to a NaN value, error expected
with pytest.raises(redis.ResponseError):
r.execute_command('TS.incrby', 'tester', '1')
r.execute_command('TS.decrby', 'tester', '1')

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Unreachable TS.DECRBY commands in pytest.raises blocks

Medium Severity

In test_ts_incrby_NaN, both pytest.raises blocks contain two execute_command calls, but only the first one (TS.incrby) ever runs. When it raises redis.ResponseError, the context manager catches it immediately, and the second call (TS.decrby) is never executed. This means TS.DECRBY with NaN values is completely untested — any NaN-handling bug specific to the decrby path would go undetected.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 3a4315a. Configure here.

…crby_arg_validation_before_creation accidentally reintroduced by cherry-pick conflict resolution

None of these three tests were part of ca3375a and none belong on 8.2 at this point; only test_incrby_no_timestamp_replicates_diverging_timestamp is the actual new test from that commit.
When TIMESTAMP is omitted, replication rewrites the command by appending
"TIMESTAMP <ts>" at the very end. If the create-on-write command also
carries a trailing LABELS clause, appending TIMESTAMP after it gets
swallowed as a bogus label/value pair on replicas and AOF-replay, since
LABELS greedily consumes every token that follows it.

Insert TIMESTAMP before the LABELS clause instead of after it.
Comment thread src/module.c Resolved
AvivDavid23 and others added 2 commits September 1, 2026 13:30
… with LABELS (#2160)

* Fix TS.INCRBY/TS.DECRBY replicating a bogus TIMESTAMP label with LABELS

When TIMESTAMP is omitted, replication rewrites the command by appending
"TIMESTAMP <ts>" at the very end. If the create-on-write command also
carries a trailing LABELS clause, appending TIMESTAMP after it gets
swallowed as a bogus label/value pair on replicas and AOF-replay, since
LABELS greedily consumes every token that follows it.

Insert TIMESTAMP before the LABELS clause instead of after it.

* style: clang-format

* test: also verify the replicated sample value/timestamp, not just labels

* Address review: fixed-position TIMESTAMP insert, guard TIMESTAMP-in-LABELS-tail, bounds check, guard replication on write result

- Insert TIMESTAMP right after <key> <value> (index 3) instead of scanning
  for LABELS: avoids matching a key literally named "LABELS" and removes
  the redundant argv scan.
- Detect a "TIMESTAMP" match that falls inside a LABELS tail and treat it
  as a label, not a directive, so primary and replica agree on labels
  even when a label key is literally named "TIMESTAMP".
- Bounds-check TIMESTAMP's value before dereferencing it (was a heap
  over-read when TIMESTAMP was the last token).
- Only replicate when internalAdd() actually succeeded, matching TSDB_add.

Tests: parametrize incrby/decrby, verify AOF-replay (not just live
replication), and add regressions for the key-named-LABELS and
label-named-TIMESTAMP cases plus the missing-value arity guard.

* Address review: fixed-position insert was unsafe (breaks key named IGNORE), fix timestampLoc key-name collision, fix vacuous replica tests, fix restart-check overwrite bug

- Revert the unconditional fixed-position insert: it shifts every other
  clause's operands when a keyword collides with the key name and takes
  multiple operands (e.g. a key named IGNORE), breaking replica/AOF
  parsing entirely. Back to inserting before LABELS only when a real
  LABELS clause exists (labelsLoc > 2); append at the end otherwise.
- Apply the same "> 2" floor to timestampLoc itself: a key named
  "timestamp" was matching RMUtil_ArgIndex at index 1 and getting treated
  as an explicit TIMESTAMP directive.

Tests:
- test_incrby_create_with_key_named_labels_replicates_correctly and
  test_incrby_labels_key_named_timestamp_replicates_correctly were
  vacuous: with no warmup-key handshake, the key reaches the replica via
  the initial full-sync RDB before repl-diskless-sync-delay elapses, so
  the rewritten command is never actually parsed by the replica. Added
  the same handshake test_incrby_create_with_labels_replicates_correctly
  already used.
- The post-restart block in test_incrby_create_with_labels_replicates_correctly
  reused master_sample, overwriting the pre-restart value, so nothing was
  ever compared across the restart. Now captured separately and compared.
- Added test_incrby_create_with_key_named_ignore_replicates_correctly,
  a direct regression test for the IGNORE-key repro above.

Not addressed here (flagged by review as out of scope / follow-up, not
blocking this PR): the pre-existing parseLabelsFromArgs key-name collision
for a key literally named LABELS, and TS.INCRBY accepting a negative
explicit TIMESTAMP.

* Address review: scan for TIMESTAMP/LABELS only past <key> <value>, not the whole argv

Zeroing a late match (previous commit) still broke a key literally named
"TIMESTAMP": RMUtil_ArgIndex returns the FIRST match, which for that key
is the key name at argv[1], not the real directive appended by the
rewrite. Zeroing it discarded the real one too, so master and replica
each resolved their own timestamp - reproduced live with a stalled
replica and a standalone AOF reload.

Fix: scan starting at index 3, where a real TIMESTAMP or LABELS keyword
is the earliest either can legally appear, so the key/value can never be
mistaken for one. Add test_incrby_key_named_timestamp_replicates_correctly
(key named "TIMESTAMP", stalled replica, mirrors
test_incrby_no_timestamp_replicates_diverging_timestamp) - without the
stall this would pass by luck.

* Address review: dedupe replica-wait polling into shared helpers

The "for _ in range(100): ... exists ... time.sleep(0.1) / else: raise"
replica-wait loop was duplicated 10 times across the file, tripping
SonarCloud's new-code duplication gate (6.1%, threshold 3%). Extracted
_wait_for_replica_key() and _wait_for_replica_online() (the latter also
performs the warmup-key handshake), and replaced all 10 call sites.
No behavior change.

* Address review: strengthen key-named-TIMESTAMP test to check actual behavior, not just consistency

test_incrby_key_named_timestamp_replicates_correctly only asserted
master_ts == slave_sample[0], which the pre-PR code also satisfied
(wrong-but-consistent: both sides stored ts=5, the misread value slot,
via ReplicateVerbatim). Add assertGreaterEqual(master_ts, before_ms) so
the test actually catches a regression back to that behavior, not just
a master/replica divergence. Also capture the stall thread's exception
instead of swallowing it, so a broken DEBUG SLEEP can't silently turn
this into a no-op that reports PASS.

@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 2 potential issues.

There are 3 total unresolved issues (including 1 from previous review).

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 43f482d. Configure here.

Comment thread tests/flow/test_ts_incrby.py Resolved
Comment thread tests/flow/test_ts_incrby.py Resolved

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

Requesting changes — the module fix itself is correct, but the test-file conflict resolution broke CI on every leg.

src/module.c is not the problem. A mechanical 3-way cherry-pick of master's two MOD-16873 commits (ca3375a9, then 4f26b4cb) onto 8.2 auto-merges src/module.c cleanly, with zero conflicts, and the result is byte-identical to this PR's head — TSDB_incrby is character-for-character master's final version (the argv + 3 scans, the labelsLoc/timestampLoc reset, the arity guard, the rv == REDISMODULE_OK wrapper) and behaves identically for every argv shape I checked, including the IGNORE/LABELS edge cases the review on #2160 turned up.

The break is in tests/flow/test_ts_incrby.py. The only real conflict was there, because 8.2's test file predates some tests that exist in master's merge-base. Git's 3-way merge presented those pre-existing master tests as conflict context, and the resolution took that context in wholesale rather than trimming it to just the two backported tests. As a result the PR drags in test_incrby_error_cases, test_ts_incrby_NaN, test_ts_incrby_arg_validation_before_creation — the last two need behavior 8.2 doesn't have (NaN-sample support, MOD-8167's validate-before-create reorder); test_incrby_error_cases happens to pass today but is equally out of scope for this backport, none of which exist on 8.2 — and they fail deterministically on every CI leg that reaches the flow suite (all 36 red CI legs show exactly the same two failures — test_ts_incrby_arg_validation_before_creation (DID NOT RAISE ResponseError) and test_ts_incrby_NaN ([ERROR] Unhandled exception: TSDB: invalid value)).

Fix: delete test_incrby_error_cases, test_ts_incrby_NaN, test_ts_incrby_arg_validation_before_creation from tests/flow/test_ts_incrby.py (keep only the tests that are actually part of this backport: the two related to the MOD-16873 replication fix, plus whichever of the new key-name-collision tests apply on this branch). Some commits on this branch already did this correctly via a fixup: commit — the final squash-merge silently reverted it; re-apply that trim on top instead of taking master's file wholesale.

I've confirmed the harness itself (Env, pytest, redis, _get_ts_info, the RLTest pin) is all present and working on 8.2 — once the master-only tests are removed, nothing else should be red on this backport.

Note: a commit on this branch (5276f549, titled exactly "fixup: remove test_incrby_error_cases, test_ts_incrby_NaN, test_ts_incrby_arg_validation_before_creation accidentally reintroduced by cherry-pick conflict resolution") already did this correctly — the final commit silently reverted it. Re-apply that same removal; please keep test_incrby_error_cases out too even though it passes, since it's the same out-of-scope content and its own author already flagged it for removal.

…crby_arg_validation_before_creation reintroduced by MOD-16873 cherry-pick

This branch predates NaN support and the MOD-8167 validate-before-create
fix, and its arg-count/value validation for TS.INCRBY behaves differently,
so all three tests fail here (same reason they were already removed on
this branch before, and got pulled back in by the wholesale test-file
cherry-pick of the LABELS/TIMESTAMP fix).
@sonarqubecloud

sonarqubecloud Bot commented Sep 2, 2026

Copy link
Copy Markdown

@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 - the fix landed and I verified it independently rather than taking the CI-green summary at face value.

Removed/fixed: test_incrby_error_cases, test_ts_incrby_NaN, and test_ts_incrby_arg_validation_before_creation.

Confirmed all three absent by name in the current file (git show pr2156:tests/flow/test_ts_incrby.py). Independently checked the two remaining red legs myself: arm64-bookworm fails on test_defrag:testDefrag (an unrelated fragmentation-ratio flake, plus an artifact-upload permission error) with 238/239 tests otherwise passing, and macos-15 completed all 4 topologies at 243/243 with zero failures before being cancelled at the 6-hour mark - neither is caused by this change.

@AvivDavid23
AvivDavid23 merged commit 6b1587d into 8.2 Sep 3, 2026
56 of 58 checks passed
@AvivDavid23
AvivDavid23 deleted the cherry-pick-ca3375a9-to-8.2 branch September 3, 2026 07:24
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