kividb 1.2.2

A fast Redis®-compatible in-memory store written in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
//! Replication payloads, matching Redis: a write is propagated as the *effect*
//! it had, not as the command the client typed, whenever those differ.
//!
//! Two properties are needed, and they are not the same thing:
//!
//! * **Determinism** — a replica re-running the command must reach the master's
//!   state. `SPOP` picks random members and `XADD … *` mints an ID from the
//!   local clock, so replaying either produces a *different* result on the
//!   other side.
//! * **Idempotence** — replaying must be safe even if the effect is already
//!   present. This is what AOF recovery needs, because a snapshot taken while
//!   writes are in flight may already contain a write that is also in the log.
//!   `INCRBYFLOAT` is perfectly deterministic yet double-applies, which is why
//!   it is rewritten to an absolute `SET`.
//!
//! This was originally reached only from Lua (`redis.call`). The direct client
//! path propagated `ctx.cmd` verbatim, so `SPOP` and `XADD *` diverged a live
//! replica — measured, not theorised: a replica kept a different 12 of 20 set
//! members, and 4 of 5 stream IDs differed by a millisecond.

use crate::commands::ctx::Ctx;
use crate::commands::helpers::parse_utf8;
use crate::read_lock;
use std::time::UNIX_EPOCH;

thread_local! {
    /// What the command now running on this thread did, written down by the
    /// handler itself in a form that can be replayed. See [`effects_begin`].
    static EFFECTS: std::cell::RefCell<Option<Vec<Vec<Vec<u8>>>>> =
        const { std::cell::RefCell::new(None) };
    /// Whether one of those effects changed the dataset, rather than only
    /// metadata. See [`effect_of_metadata`].
    static CHANGED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
    /// Set while a script's `redis.call` runs a command: its effects are
    /// read after it whether or not the write is observed ([`ScriptCall`]).
    static IN_SCRIPT_CALL: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

/// Start recording the running command's effects.
///
/// Most rewrites below can work out what to propagate from the command and
/// its reply. A few cannot: which entries `XREADGROUP … CLAIM` took depends
/// on the clock and on every delivery before it, and whether an
/// `XADD … IDMP` added anything is not in its reply at all. Those handlers
/// call this on entry and [`effect`] for each change they make, and what they
/// recorded is what gets propagated — nothing, if they recorded nothing.
///
/// Thread-local rather than threaded through `Ctx`: the handler and the
/// propagation step run back to back on one thread, and every command that
/// reads the record begins a fresh one first, so a record left behind by a
/// write nobody was listening to is never mistaken for a later command's.
pub(crate) fn effects_begin() {
    EFFECTS.with_borrow_mut(|e| *e = Some(Vec::new()));
    CHANGED.set(false);
}

/// [`effects_begin`], for a command whose record is read only when
/// something reads it: a replica, the backlog, the AOF or a tap
/// (`replication::write_is_observed`), or the script that called it, which
/// counts what it changed by the record (`handler::run_from_script`).
/// Otherwise nothing is recorded, and the command is told so: building the
/// record (`HSETEX key PXAT … FIELDS n field value …`, a copy of every
/// argument) cost `HSETEX` about ten allocations a command with nobody to
/// read it (#543).
///
/// Whether the write is observed cannot change before the record is read:
/// a replica, the backlog and a tap start and stop with the write gate
/// closed (`write_gate::cut`), and this runs inside a write.
///
/// Returns whether effects are being recorded; [`recording`] says the same
/// later on.
#[inline]
pub(crate) fn effects_begin_if_read(ctx: &Ctx<'_>) -> bool {
    CHANGED.set(false);
    let read = super::write_is_observed(ctx) || IN_SCRIPT_CALL.get();
    EFFECTS.with_borrow_mut(|e| {
        if read {
            *e = Some(Vec::new());
        } else if e.is_some() {
            *e = None;
        }
    });
    read
}

/// Whether the running command's effects are being recorded: false after
/// an [`effects_begin_if_read`] that nothing was going to read.
#[inline]
pub(crate) fn recording() -> bool {
    EFFECTS.with_borrow(|e| e.is_some())
}

/// Held while a script's `redis.call` runs a command, whose effects are
/// read after it whether or not anything observes the write.
pub(crate) struct ScriptCall(bool);

impl ScriptCall {
    pub(crate) fn enter() -> Self {
        Self(IN_SCRIPT_CALL.replace(true))
    }
}

impl Drop for ScriptCall {
    fn drop(&mut self) {
        IN_SCRIPT_CALL.set(self.0);
    }
}

/// Record one replayable command as an effect of the running command.
pub(crate) fn effect(parts: Vec<Vec<u8>>) {
    CHANGED.set(true);
    effect_of_metadata(parts);
}

/// [`effect`], for a change Redis does not count as one: replicas and the
/// AOF get it, but `rdb_changes_since_last_save` does not grow. The delivery
/// count and time an `XREADGROUP` of a consumer's own pending entries bumps
/// are such a change (#27): Redis does not even propagate them.
pub(crate) fn effect_of_metadata(parts: Vec<Vec<u8>>) {
    EFFECTS.with_borrow_mut(|e| {
        if let Some(recorded) = e {
            recorded.push(parts);
        }
    });
}

/// Whether the running command's effects changed the dataset (see
/// [`effect_of_metadata`]). Not cleared when the effects are taken.
pub(crate) fn effects_changed_data() -> bool {
    CHANGED.get()
}

fn effects_take() -> Vec<Vec<Vec<u8>>> {
    EFFECTS.with_borrow_mut(|e| e.take()).unwrap_or_default()
}

/// Build one or more commands to send on the replication / AOF stream for a
/// successful write. Empty vec ⇒ nothing to replicate (e.g. a `SPOP` miss).
///
/// `resp` is the reply the command just produced; the rewrites read the effect
/// out of it (which members were popped, which ID was assigned).
pub fn commands_for_propagation(
    ctx: &Ctx<'_>,
    name: &str,
    cmd: &[&[u8]],
    resp: &[u8],
) -> Vec<Vec<Vec<u8>>> {
    // Upper case already, from every caller that runs commands; made so only
    // if it is not.
    let upper;
    let name: &str = if name.bytes().any(|b| b.is_ascii_lowercase()) {
        upper = name.to_ascii_uppercase();
        &upper
    } else {
        name
    };
    match name {
        "SPOP" => spop_feed(cmd, resp),
        "EXPIRE" | "PEXPIRE" | "EXPIREAT" | "PEXPIREAT" => expire_feed(ctx, cmd, resp),
        // A TTL given as "this long from now" means something else to whoever
        // runs the command later — a replica a moment behind, or an AOF
        // replayed after a restart, where every TTL would start over. These
        // are sent with the moment of expiry instead.
        "SET" => set_feed(ctx, cmd),
        "SETEX" | "PSETEX" => setex_feed(ctx, name, cmd),
        "GETEX" => getex_feed(ctx, cmd, resp),
        "MSETEX" => vec![absolute_ttl_options(
            ctx,
            cmd,
            msetex_options_start(cmd),
            &[],
            cmd.get(2).copied(),
        )],
        // Sent as what they did, recorded by the commands themselves: the
        // fields whose deadline changed (`HPEXPIREAT … FIELDS`, with no
        // condition left to weigh), whose time to live went (`HPERSIST`), or
        // that went (`HDEL`); nothing for a call that changed nothing.
        "HEXPIRE" | "HPEXPIRE" | "HEXPIREAT" | "HPEXPIREAT" | "HPERSIST" | "HSETEX" | "HGETEX" => {
            effects_take()
        }
        // A SET of the result, or DEL/UNLINK; see `cmd_increx`.
        "INCREX" => effects_take(),
        "RESTORE" => restore_feed(ctx, cmd),
        "INCRBYFLOAT" => incrbyfloat_feed(cmd, resp),
        "XADD" => xadd_feed(cmd, resp),
        // A `~` trim is sent as what it removed; see `exact_trim_args`.
        "XTRIM" if cmd.get(3).is_some_and(|mark| *mark == b"~") => effects_take(),
        // Propagated as the pending-list changes they made; see `effects_begin`.
        "XREADGROUP" | "XCLAIM" | "XAUTOCLAIM" => effects_take(),
        // Sent by the command itself as it went: the documents `DD` deleted
        // as DELs, then the drop without `DD` (`vector::ft_dropindex`); by a
        // replica to its own AOF too.
        "FT.DROPINDEX" => Vec::new(),
        // Run, not held, while writes are paused, as in Redis, but kept out
        // of the stream meanwhile (`replication::held_back`, #518): a
        // replica, or the AOF replayed, goes without the script, and a
        // client that runs it there gets `NOSCRIPT` and loads it again, as
        // it would from Redis, which never propagates the script cache.
        "SCRIPT" if super::held_back(ctx) => Vec::new(),
        // Sent by the command itself, as one `DEL` of the keys it deleted
        // (`cluster::delete_moved`): which they are, its reply does not say.
        "MIGRATE" => Vec::new(),
        "LMOVEM" | "BLMOVEM" => lmovem_feed(name, cmd, resp),
        "TS.ADD" => ts_add_feed(cmd, resp),
        "TS.MADD" => ts_madd_feed(cmd, resp),
        "TS.INCRBY" | "TS.DECRBY" => ts_incrby_feed(cmd, resp),
        // The fieldset lives in the client's session, which no replica (and no
        // AOF replay) has: send the hash it produced instead.
        "HIMPORT" => crate::commands::hash_import::propagation(ctx.client_id, cmd),
        "BLMOVE" => blocking_move_feed(cmd, resp, "LMOVE", 5),
        "BLPOP" | "BRPOP" | "BZPOPMIN" | "BZPOPMAX" | "BLMPOP" | "BZMPOP" => {
            blocking_pop_feed(name, cmd, resp)
        }
        "BRPOPLPUSH" => blocking_move_feed(cmd, resp, "RPOPLPUSH", 3),
        _ => {
            if cmd.is_empty() {
                return Vec::new();
            }
            vec![cmd.iter().map(|b| b.to_vec()).collect()]
        }
    }
}

/// Replace an auto-generated `XADD` ID (`*`, or `ms-*`) with the concrete ID the
/// master assigned, leaving every other argument alone.
///
/// Without this each side generates its own ID from its own clock, so entries
/// that are logically the same get different identities — and a stream ID *is*
/// the entry's identity, so consumer-group state, `XRANGE` bounds and `XACK`
/// all key differently on the replica.
///
/// An explicit ID is already deterministic and passes through untouched.
fn xadd_feed(cmd: &[&[u8]], resp: &[u8]) -> Vec<Vec<Vec<u8>>> {
    let verbatim = || vec![cmd.iter().map(|b| b.to_vec()).collect::<Vec<Vec<u8>>>()];

    let opts = crate::commands::streams::parse_xadd_options(cmd);
    // An idempotent XADD may have added nothing — a recognised retry replies
    // with the original entry's ID, which looks exactly like a fresh one. The
    // handler recorded what, if anything, it added.
    // Nor is how much a `~` trimmed.
    if opts.idmp.is_some() || opts.approx {
        return effects_take();
    }
    let Some(id_arg) = cmd.get(opts.id_index) else {
        return verbatim();
    };
    // `*` (both ms and seq auto) or `ms-*` (seq auto) — anything else is fixed.
    if !id_arg.contains(&b'*') {
        return verbatim();
    }

    // XADD replies with the assigned ID as a bulk string. Anything else (an
    // error, or NOMKSTREAM's null on a missing key) means no entry was added.
    let Some((_, Some(assigned))) = parse_bulk(resp) else {
        return Vec::new();
    };

    let mut parts: Vec<Vec<u8>> = cmd.iter().map(|b| b.to_vec()).collect();
    parts[opts.id_index] = assigned;
    vec![parts]
}

/// `LMOVEM` propagates as itself when it moved something and as nothing when
/// it did not. `BLMOVEM` propagates as `LMOVEM`: the replica must not wait,
/// and by the time the master replies the elements are there to be moved.
fn lmovem_feed(name: &str, cmd: &[&[u8]], resp: &[u8]) -> Vec<Vec<Vec<u8>>> {
    // A non-empty array reply means elements moved; `*0` and `*-1` do not.
    let moved =
        resp.first() == Some(&b'*') && !resp.starts_with(b"*0\r\n") && !resp.starts_with(b"*-1");
    if !moved {
        return Vec::new();
    }
    let mut parts: Vec<Vec<u8>> = cmd.iter().map(|b| b.to_vec()).collect();
    if name == "BLMOVEM" && parts.len() >= 6 {
        parts.remove(5); // timeout
        parts[0] = b"LMOVEM".to_vec();
    }
    vec![parts]
}

/// `BLMOVE` / `BRPOPLPUSH` propagate as their non-blocking forms, and only
/// when an element actually moved. `timeout_index` is the argument to drop.
fn blocking_move_feed(
    cmd: &[&[u8]],
    resp: &[u8],
    plain_name: &str,
    timeout_index: usize,
) -> Vec<Vec<Vec<u8>>> {
    if !matches!(parse_bulk(resp), Some((_, Some(_)))) {
        return Vec::new();
    }
    let mut parts: Vec<Vec<u8>> = cmd.iter().map(|b| b.to_vec()).collect();
    if parts.len() > timeout_index {
        parts.remove(timeout_index);
    }
    parts[0] = plain_name.as_bytes().to_vec();
    vec![parts]
}

/// `BLPOP`, `BRPOP`, `BZPOPMIN`, `BZPOPMAX`, `BLMPOP` and `BZMPOP` propagate
/// as the pop they made, as in Redis: `LPOP key`, `ZPOPMIN key`, and for the
/// `M` forms `LPOP key count` / `ZPOPMIN key count` with the number taken,
/// all for the key the reply names. A replica, or the AOF replayed, then
/// takes the same elements from the same key: the blocking form, run there,
/// looks at its keys in order and could take from another one than the
/// master did (the master leaves a key to a client that has waited longer).
/// Nothing is sent when nothing was popped.
fn blocking_pop_feed(name: &str, cmd: &[&[u8]], resp: &[u8]) -> Vec<Vec<Vec<u8>>> {
    let verbatim = || vec![cmd.iter().map(|b| b.to_vec()).collect::<Vec<Vec<u8>>>()];
    let Some((elements, header)) = array_header(resp) else {
        // A null reply, or none (a client that has parked): nothing popped.
        if resp.is_empty() || resp.starts_with(b"*-1") || resp.starts_with(b"_") {
            return Vec::new();
        }
        return verbatim();
    };
    if elements < 2 {
        return Vec::new();
    }
    let Some((used, Some(key))) = parse_bulk(&resp[header..]) else {
        return verbatim();
    };
    let plain: &[u8] = match name {
        "BLPOP" => b"LPOP",
        "BRPOP" => b"RPOP",
        "BZPOPMIN" => b"ZPOPMIN",
        "BZPOPMAX" => b"ZPOPMAX",
        // BLMPOP / BZMPOP timeout numkeys key [key ...] LEFT|RIGHT|MIN|MAX ...
        _ => {
            let numkeys = cmd
                .get(2)
                .and_then(|n| std::str::from_utf8(n).ok())
                .and_then(|n| n.parse::<usize>().ok());
            let side = numkeys
                .and_then(|n| 3usize.checked_add(n))
                .and_then(|i| cmd.get(i));
            let plain: &[u8] = match side.map(|s| s.to_ascii_uppercase()).as_deref() {
                Some(b"LEFT") => b"LPOP",
                Some(b"RIGHT") => b"RPOP",
                Some(b"MIN") => b"ZPOPMIN",
                Some(b"MAX") => b"ZPOPMAX",
                _ => return verbatim(),
            };
            let Some((count, _)) = array_header(&resp[header + used..]) else {
                return verbatim();
            };
            if count == 0 {
                return Vec::new();
            }
            return vec![vec![plain.to_vec(), key, count.to_string().into_bytes()]];
        }
    };
    vec![vec![plain.to_vec(), key]]
}

/// The element count of the array whose header starts `resp`, and the
/// header's length; `None` for anything else, a null array among them.
fn array_header(resp: &[u8]) -> Option<(usize, usize)> {
    if resp.first()? != &b'*' {
        return None;
    }
    let line_end = resp.windows(2).position(|w| w == b"\r\n")?;
    let count = std::str::from_utf8(resp.get(1..line_end)?)
        .ok()?
        .parse()
        .ok()?;
    Some((count, line_end + 2))
}

/// `TS.ADD key * value`: the `*` is the master's clock at the moment it ran.
/// A replica (or the AOF, replayed later) would stamp the sample with its own,
/// so the timestamp the master assigned is sent in its place.
fn ts_add_feed(cmd: &[&[u8]], resp: &[u8]) -> Vec<Vec<Vec<u8>>> {
    let mut parts: Vec<Vec<u8>> = cmd.iter().map(|b| b.to_vec()).collect();
    if cmd.len() > 2
        && cmd[2] == b"*"
        && let Some(ts) = parse_resp_integer(resp)
    {
        parts[2] = sample_time(ts);
    }
    vec![parts]
}

/// A sample's time as a TS command replied it, an `i64`, as the `u64` the
/// series holds. A time above `i64::MAX`, which a replica or a replayed AOF
/// takes from a record an older version wrote, is replied as a negative
/// number, which no TS command takes (#592).
fn sample_time(replied: i64) -> Vec<u8> {
    (replied as u64).to_string().into_bytes()
}

/// `TS.MADD` with `*` timestamps: each replaced by the one it was given, read
/// from the matching element of the reply.
///
/// A sample that was refused is left out, as RedisTimeSeries leaves it out:
/// it changed nothing. Sent with its `*`, a replica stamped it with its own
/// clock and could add a sample the master had refused.
fn ts_madd_feed(cmd: &[&[u8]], resp: &[u8]) -> Vec<Vec<Vec<u8>>> {
    if resp.first() != Some(&b'*') || cmd.is_empty() {
        return vec![cmd.iter().map(|b| b.to_vec()).collect()];
    }
    // The reply is an array with one element per sample: `:timestamp`, or an
    // error for a sample that was refused.
    let mut lines = resp.split(|b| *b == b'\n');
    lines.next(); // the array header
    let mut parts: Vec<Vec<u8>> = vec![cmd[0].to_vec()];
    for (sample, line) in cmd[1..].chunks(3).zip(lines) {
        match line.first() {
            Some(b'-') => continue,
            Some(b':') if sample.len() == 3 => {
                let replied = line[1..].trim_ascii();
                parts.push(sample[0].to_vec());
                parts.push(
                    std::str::from_utf8(replied)
                        .ok()
                        .and_then(|t| t.parse::<i64>().ok())
                        .map_or_else(|| replied.to_vec(), sample_time),
                );
                parts.push(sample[2].to_vec());
            }
            _ => parts.extend(sample.iter().map(|b| b.to_vec())),
        }
    }
    if parts.len() == 1 {
        return Vec::new();
    }
    vec![parts]
}

/// `TS.INCRBY` / `TS.DECRBY` default to "now" too; pin the timestamp used.
fn ts_incrby_feed(cmd: &[&[u8]], resp: &[u8]) -> Vec<Vec<Vec<u8>>> {
    let verbatim = || vec![cmd.iter().map(|b| b.to_vec()).collect::<Vec<Vec<u8>>>()];
    let Some(ts) = parse_resp_integer(resp) else {
        return verbatim();
    };
    // Each `TIMESTAMP` option the command read is given the time it used, in
    // its place, so every other word is where it was and reads as it did; a
    // word `TIMESTAMP` that is a label's value is left alone. And the time
    // goes right after the value, before any option, behind 1.2.1's mark
    // (`ts::INCRBY_MARK`), which tells the record from one 1.2.0 sent. Added
    // at the end, as 1.2.0 did, it made a label of a word left over from
    // `LABELS` (#555).
    let mut parts: Vec<Vec<u8>> = cmd.iter().map(|b| b.to_vec()).collect();
    let ts = sample_time(ts);
    for at in crate::commands::ts::incrby_timestamp_options(cmd) {
        parts[at + 1] = ts.clone();
    }
    let at = parts.len().min(3);
    parts.insert(at, ts);
    parts.insert(at, crate::commands::ts::INCRBY_MARK.to_vec());
    vec![parts]
}

fn spop_feed(cmd: &[&[u8]], resp: &[u8]) -> Vec<Vec<Vec<u8>>> {
    if cmd.len() < 2 {
        return Vec::new();
    }
    let key = cmd[1].to_vec();
    match resp.first().copied() {
        Some(b'$') => {
            if let Some((_n, member_opt)) = parse_bulk(resp)
                && let Some(member) = member_opt
            {
                return vec![vec![b"SREM".to_vec(), key, member]];
            }
            Vec::new()
        }
        // `~`: the set a RESP3 client is answered with, from a script too
        // after `redis.setresp(3)`. It was not looked at, and the members
        // popped stayed on the replicas and in the AOF.
        Some(b'*' | b'~') => {
            if let Some((_n, members)) = parse_array(resp) {
                if members.is_empty() {
                    return Vec::new();
                }
                let mut parts = vec![b"SREM".to_vec(), key];
                parts.extend(members);
                return vec![parts];
            }
            Vec::new()
        }
        _ => Vec::new(),
    }
}

fn now_ms() -> i64 {
    std::time::SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis() as i64
}

fn integer_arg(arg: &[u8]) -> Option<i64> {
    parse_utf8(arg).and_then(|s| s.parse().ok())
}

fn owned(cmd: &[&[u8]]) -> Vec<Vec<u8>> {
    cmd.iter().map(|arg| arg.to_vec()).collect()
}

/// When `key` expires, in Unix milliseconds, if it has a TTL.
fn expiry_ms(ctx: &Ctx<'_>, key: &[u8]) -> Option<u64> {
    let shard = crate::store::get_shard(&ctx.store[*ctx.selected_db], key);
    read_lock!(shard).expires(key)
}

/// `cmd` with its time option, looked for from `start`, sent as
/// `PXAT <unix-ms>`, as Redis sends `SET`: the last one given, which is the
/// one that took effect, and none of the others. Only the first was
/// rewritten, so `SET k v EX 10 EX 20` went out as `SET k v PXAT <t> EX 20`,
/// which a replica or a replayed AOF refused.
///
/// `with_argument` names the options that take an argument, so that argument
/// is not read as an option. A relative time (`EX`, `PX`) is sent as the
/// deadline `key` was given here ([`stored_deadline`]).
fn absolute_ttl_options(
    ctx: &Ctx<'_>,
    cmd: &[&[u8]],
    start: usize,
    with_argument: &[&str],
    key: Option<&[u8]>,
) -> Vec<Vec<u8>> {
    let mut times = Vec::new();
    let mut i = start;
    while i < cmd.len() {
        let token = String::from_utf8_lossy(cmd[i]).to_ascii_uppercase();
        if matches!(token.as_str(), "EX" | "PX" | "EXAT" | "PXAT") {
            times.push(i);
            i += 2;
            continue;
        }
        i += if with_argument.contains(&token.as_str()) {
            2
        } else {
            1
        };
    }
    let Some(&last) = times.last() else {
        return owned(cmd);
    };
    let Some(n) = cmd.get(last + 1).and_then(|arg| integer_arg(arg)) else {
        return owned(cmd);
    };
    let at = if cmd[last].eq_ignore_ascii_case(b"EX") {
        stored_deadline(ctx, key, n.saturating_mul(1000))
    } else if cmd[last].eq_ignore_ascii_case(b"PX") {
        stored_deadline(ctx, key, n)
    } else if cmd[last].eq_ignore_ascii_case(b"EXAT") {
        n.saturating_mul(1000)
    } else {
        n
    };
    let mut out: Vec<Vec<u8>> = cmd
        .iter()
        .enumerate()
        .filter(|(j, _)| !times.iter().any(|&t| *j == t || *j == t + 1))
        .map(|(_, arg)| arg.to_vec())
        .collect();
    out.push(b"PXAT".to_vec());
    out.push(at.to_string().into_bytes());
    out
}

/// The deadline a command with a relative time to live of `ms` gave `key`,
/// read back from the key, as `expire_feed` and `getex_feed` send theirs:
/// worked out again here from the clock, it was later than the master's by
/// however long had gone by since, a millisecond now and then, and inside a
/// script, whose commands keep time by the script's frozen clock, by how
/// long the script had run (#602). From the clock only when the key has no
/// deadline (a write that did not happen: a condition that did not hold,
/// which the reader of the stream weighs again and refuses too).
fn stored_deadline(ctx: &Ctx<'_>, key: Option<&[u8]>, ms: i64) -> i64 {
    key.and_then(|key| expiry_ms(ctx, key))
        .and_then(|at| i64::try_from(at).ok())
        .unwrap_or_else(|| now_ms().saturating_add(ms))
}

/// `SET key value [...] EX|PX|EXAT|PXAT time` → the same with `PXAT`.
fn set_feed(ctx: &Ctx<'_>, cmd: &[&[u8]]) -> Vec<Vec<Vec<u8>>> {
    vec![absolute_ttl_options(
        ctx,
        cmd,
        3,
        &["IFEQ", "IFNE", "IFDEQ", "IFDNE"],
        cmd.get(1).copied(),
    )]
}

/// `SETEX key seconds value` / `PSETEX key ms value` → `SET key value PXAT at`.
fn setex_feed(ctx: &Ctx<'_>, name: &str, cmd: &[&[u8]]) -> Vec<Vec<Vec<u8>>> {
    let ttl = match cmd.get(2).and_then(|arg| integer_arg(arg)) {
        Some(ttl) if cmd.len() == 4 => ttl,
        _ => return vec![owned(cmd)],
    };
    let ms = if name == "SETEX" {
        ttl.saturating_mul(1000)
    } else {
        ttl
    };
    vec![vec![
        b"SET".to_vec(),
        cmd[1].to_vec(),
        cmd[3].to_vec(),
        b"PXAT".to_vec(),
        stored_deadline(ctx, Some(cmd[1]), ms)
            .to_string()
            .into_bytes(),
    ]]
}

/// `GETEX` reads; what it changes is the key's TTL, and that is what is sent:
/// `PERSIST`, or the deadline the key was left with, whichever option gave
/// it, or `DEL` for a time that had already come. Only the first option was
/// read, so `GETEX k EX 40 EX 50` went out as 40.
fn getex_feed(ctx: &Ctx<'_>, cmd: &[&[u8]], resp: &[u8]) -> Vec<Vec<Vec<u8>>> {
    // Nothing there, or no option: nothing changed.
    if cmd.len() < 3 || resp.starts_with(b"$-1") || resp.starts_with(b"_") {
        return Vec::new();
    }
    let key = cmd[1];
    if cmd[2..]
        .iter()
        .any(|arg| arg.eq_ignore_ascii_case(b"PERSIST"))
    {
        return vec![vec![b"PERSIST".to_vec(), key.to_vec()]];
    }
    match expiry_ms(ctx, key) {
        Some(at) => vec![vec![
            b"PEXPIREAT".to_vec(),
            key.to_vec(),
            at.to_string().into_bytes(),
        ]],
        None => {
            let shard = crate::store::get_shard(&ctx.store[*ctx.selected_db], key);
            if read_lock!(shard).contains_key(key) {
                // Not what GETEX with a time leaves; sent as it came.
                vec![owned(cmd)]
            } else {
                vec![vec![b"DEL".to_vec(), key.to_vec()]]
            }
        }
    }
}

/// Where the options of `MSETEX numkeys key value [key value ...] [options]`
/// begin.
fn msetex_options_start(cmd: &[&[u8]]) -> usize {
    let numkeys = cmd
        .get(1)
        .and_then(|arg| integer_arg(arg))
        .filter(|n| *n > 0)
        .unwrap_or(0) as usize;
    2usize.saturating_add(numkeys.saturating_mul(2))
}

/// `INCREX` can refuse to move (a bound), can round (BYFLOAT), and can set a
/// TTL only when there is none (ENX): what is sent is where it left the key.
/// `RESTORE key ttl payload …` with a relative TTL → the same with `ABSTTL`
/// and the deadline the key was given here, read back from the key as
/// `expire_feed` does: worked out again from the clock, it was up to 1 ms
/// off what the master keeps, on every replica and in the AOF (#602).
fn restore_feed(ctx: &Ctx<'_>, cmd: &[&[u8]]) -> Vec<Vec<Vec<u8>>> {
    let mut out = owned(cmd);
    let absolute = cmd
        .iter()
        .skip(4)
        .any(|arg| arg.eq_ignore_ascii_case(b"ABSTTL"));
    if !absolute
        && let Some(ttl) = cmd.get(2).and_then(|arg| integer_arg(arg))
        && ttl > 0
    {
        out[2] = stored_deadline(ctx, cmd.get(1).copied(), ttl)
            .to_string()
            .into_bytes();
        out.push(b"ABSTTL".to_vec());
    }
    vec![out]
}

/// `EXPIRE key seconds` / `PEXPIRE key ms` / `EXPIREAT key secs` /
/// `PEXPIREAT key ms` → `PEXPIREAT key at`, or `DEL key` when the key went at
/// once (a TTL of zero or less, a moment that had come).
///
/// An answer of 0 sends nothing: no such key, or a NX/XX/GT/LT condition
/// that did not hold, which leaves the key as it was even when the time asked
/// for would have deleted it (#270). `EXPIREAT` and `PEXPIREAT` were sent as
/// they came, a refused one included.
fn expire_feed(ctx: &Ctx<'_>, cmd: &[&[u8]], resp: &[u8]) -> Vec<Vec<Vec<u8>>> {
    if cmd.len() < 3 {
        return Vec::new();
    }
    // Any bytes: a key that is not text is rewritten as any other is.
    let key = cmd[1];
    if parse_resp_integer(resp) != Some(1) {
        return Vec::new();
    }

    // Redis: a TTL of zero or less deletes the key.
    if integer_arg(cmd[2]).is_some_and(|ttl| ttl <= 0) {
        return vec![vec![b"DEL".to_vec(), cmd[1].to_vec()]];
    }

    // Answered 1 and left no time to live: the key is gone, and so it goes
    // to the readers of the stream. Sending nothing left it there for good.
    let Some(ms) = expiry_ms(ctx, key) else {
        return vec![vec![b"DEL".to_vec(), cmd[1].to_vec()]];
    };
    vec![vec![
        b"PEXPIREAT".to_vec(),
        cmd[1].to_vec(),
        ms.to_string().into_bytes(),
    ]]
}

fn incrbyfloat_feed(cmd: &[&[u8]], resp: &[u8]) -> Vec<Vec<Vec<u8>>> {
    if cmd.len() != 3 {
        return Vec::new();
    }
    // A bulk string; or, if a RESP3 reply is ever a double (`,`), that.
    let val = match parse_bulk(resp) {
        Some((_, Some(val))) => val,
        _ => match resp
            .strip_prefix(b",")
            .and_then(|rest| rest.strip_suffix(b"\r\n"))
        {
            Some(val) => val.to_vec(),
            None => return Vec::new(),
        },
    };
    vec![vec![
        b"SET".to_vec(),
        cmd[1].to_vec(),
        val,
        b"KEEPTTL".to_vec(),
    ]]
}

fn parse_bulk(resp: &[u8]) -> Option<(usize, Option<Vec<u8>>)> {
    if resp.first()? != &b'$' {
        return None;
    }
    let line_end = resp.windows(2).position(|w| w == b"\r\n")?;
    let len_s = std::str::from_utf8(resp.get(1..line_end)?).ok()?;
    let n: isize = len_s.parse().ok()?;
    let header_end = line_end + 2;
    if n < 0 {
        return Some((header_end, None));
    }
    let n = usize::try_from(n).ok()?;
    let body_end = header_end.checked_add(n)?.checked_add(2)?;
    if body_end > resp.len() {
        return None;
    }
    Some((body_end, Some(resp[header_end..header_end + n].to_vec())))
}

/// An array of bulk strings, or a RESP3 set of them (`~`).
fn parse_array(resp: &[u8]) -> Option<(usize, Vec<Vec<u8>>)> {
    if !matches!(resp.first()?, b'*' | b'~') {
        return None;
    }
    let line_end = resp.windows(2).position(|w| w == b"\r\n")?;
    let count_s = std::str::from_utf8(resp.get(1..line_end)?).ok()?;
    let count: usize = count_s.parse().ok()?;
    let mut pos = line_end + 2;
    let mut out = Vec::with_capacity(count);
    for _ in 0..count {
        let tail = resp.get(pos..)?;
        let (consumed, bulk) = parse_bulk(tail)?;
        pos += consumed;
        out.push(bulk?);
    }
    Some((pos, out))
}

fn parse_resp_integer(resp: &[u8]) -> Option<i64> {
    if resp.first()? != &b':' {
        return None;
    }
    let line_end = resp.windows(2).position(|w| w == b"\r\n")?;
    let s = std::str::from_utf8(resp.get(1..line_end)?).ok()?;
    s.parse().ok()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::commands::streams::parse_xadd_options;

    fn cmd(parts: &[&str]) -> Vec<Vec<u8>> {
        parts.iter().map(|s| s.as_bytes().to_vec()).collect()
    }

    fn refs(owned: &[Vec<u8>]) -> Vec<&[u8]> {
        owned.iter().map(|v| v.as_slice()).collect()
    }

    fn bulk(s: &str) -> Vec<u8> {
        format!("${}\r\n{}\r\n", s.len(), s).into_bytes()
    }

    /// The rewrite must replace the argument the executor consumed as the ID.
    /// XADD's ID is positional but its offset depends on the options given, so
    /// a hardcoded index would corrupt a `MAXLEN`/`NOMKSTREAM` command by
    /// overwriting an option value instead — silently, on the wire.
    #[test]
    fn xadd_id_index_matches_executor() {
        // (command, index the ID actually sits at)
        let cases: &[(&[&str], usize)] = &[
            (&["XADD", "k", "*", "f", "v"], 2),
            (&["XADD", "k", "NOMKSTREAM", "*", "f", "v"], 3),
            (&["XADD", "k", "MAXLEN", "5", "*", "f", "v"], 4),
            (&["XADD", "k", "MAXLEN", "~", "5", "*", "f", "v"], 5),
            (&["XADD", "k", "MAXLEN", "=", "5", "*", "f", "v"], 5),
            (
                &[
                    "XADD", "k", "MAXLEN", "~", "5", "LIMIT", "100", "*", "f", "v",
                ],
                7,
            ),
            (&["XADD", "k", "MINID", "~", "5-5", "*", "f", "v"], 5),
            (
                &[
                    "XADD",
                    "k",
                    "NOMKSTREAM",
                    "MAXLEN",
                    "=",
                    "10",
                    "123-4",
                    "f",
                    "v",
                ],
                6,
            ),
        ];
        for (parts, want) in cases {
            let owned = cmd(parts);
            let got = parse_xadd_options(&refs(&owned)).id_index;
            assert_eq!(got, *want, "wrong ID index for {parts:?}");
            // And that index really is the ID-looking token.
            let tok = std::str::from_utf8(&owned[got]).unwrap();
            assert!(
                tok == "*" || tok.contains('-'),
                "index {got} of {parts:?} is {tok:?}, not an ID"
            );
        }
    }

    #[test]
    fn xadd_auto_id_is_rewritten_to_the_assigned_id() {
        let owned = cmd(&["XADD", "s", "*", "f", "v"]);
        let out = xadd_feed(&refs(&owned), &bulk("1786732884990-0"));
        assert_eq!(out.len(), 1);
        assert_eq!(out[0][2], b"1786732884990-0".to_vec());
        // Everything else is untouched.
        assert_eq!(out[0][0], b"XADD".to_vec());
        assert_eq!(out[0][1], b"s".to_vec());
        assert_eq!(out[0][3], b"f".to_vec());
        assert_eq!(out[0][4], b"v".to_vec());
    }

    #[test]
    fn xadd_partial_auto_id_is_rewritten() {
        // `ms-*` auto-generates only the sequence, and is just as divergent.
        let owned = cmd(&["XADD", "s", "5-*", "f", "v"]);
        let out = xadd_feed(&refs(&owned), &bulk("5-3"));
        assert_eq!(out[0][2], b"5-3".to_vec());
    }

    #[test]
    fn xadd_rewrite_lands_after_options() {
        let owned = cmd(&["XADD", "s", "MAXLEN", "=", "5", "*", "f", "v"]);
        let out = xadd_feed(&refs(&owned), &bulk("7-0"));
        assert_eq!(out[0][5], b"7-0".to_vec());
        // The option value must NOT have been clobbered.
        assert_eq!(out[0][4], b"5".to_vec());
    }

    #[test]
    fn xadd_with_an_approximate_trim_is_sent_as_what_the_handler_recorded() {
        // How much `~` trimmed is the handler's to say: nothing is made up
        // from the command.
        let owned = cmd(&["XADD", "s", "MAXLEN", "~", "5", "*", "f", "v"]);
        effects_begin();
        effect(cmd(&["XADD", "s", "MAXLEN", "=", "3", "7-0", "f", "v"]));
        let out = xadd_feed(&refs(&owned), &bulk("7-0"));
        assert_eq!(
            out,
            vec![cmd(&["XADD", "s", "MAXLEN", "=", "3", "7-0", "f", "v"])]
        );
        assert!(xadd_feed(&refs(&owned), &bulk("7-0")).is_empty());
    }

    #[test]
    fn xadd_explicit_id_passes_through_unchanged() {
        let owned = cmd(&["XADD", "s", "5-5", "f", "v"]);
        let out = xadd_feed(&refs(&owned), &bulk("5-5"));
        assert_eq!(out[0], owned);
    }

    #[test]
    fn xadd_that_added_nothing_propagates_nothing() {
        // NOMKSTREAM against a missing key replies null: no entry, nothing to
        // replicate. Propagating verbatim here would create the stream on the
        // replica that the master declined to create.
        let owned = cmd(&["XADD", "s", "NOMKSTREAM", "*", "f", "v"]);
        assert!(xadd_feed(&refs(&owned), b"$-1\r\n").is_empty());
    }

    #[test]
    fn time_series_clock_timestamps_are_pinned() {
        let c = cmd(&["TS.ADD", "k", "*", "1.5", "LABELS", "a", "b"]);
        assert_eq!(
            ts_add_feed(&refs(&c), b":1700000000123\r\n"),
            vec![cmd(&[
                "TS.ADD",
                "k",
                "1700000000123",
                "1.5",
                "LABELS",
                "a",
                "b"
            ])]
        );
        let explicit = cmd(&["TS.ADD", "k", "5", "1.5"]);
        assert_eq!(
            ts_add_feed(&refs(&explicit), b":5\r\n"),
            vec![explicit.clone()]
        );

        let c = cmd(&["TS.MADD", "a", "*", "1", "b", "7", "2", "c", "*", "3"]);
        assert_eq!(
            ts_madd_feed(&refs(&c), b"*3\r\n:100\r\n:7\r\n:101\r\n"),
            vec![cmd(&[
                "TS.MADD", "a", "100", "1", "b", "7", "2", "c", "101", "3"
            ])]
        );

        let c = cmd(&["TS.INCRBY", "k", "2"]);
        assert_eq!(
            ts_incrby_feed(&refs(&c), b":42\r\n"),
            vec![cmd(&["TS.INCRBY", "k", "2", "timestamp", "42"])]
        );
        let c = cmd(&["TS.DECRBY", "k", "2", "TIMESTAMP", "*", "RETENTION", "9"]);
        assert_eq!(
            ts_incrby_feed(&refs(&c), b":42\r\n"),
            vec![cmd(&[
                "TS.DECRBY",
                "k",
                "2",
                "timestamp",
                "42",
                "TIMESTAMP",
                "42",
                "RETENTION",
                "9"
            ])]
        );
    }

    /// A sample `TS.MADD` refused is left out of what is sent; `*` is the
    /// time the master gave.
    /// A time above `i64::MAX`, replied as a negative number, is sent as
    /// the `u64` the series holds (#592).
    #[test]
    fn ts_feeds_send_times_above_i64_max_unsigned() {
        let max = u64::MAX.to_string();
        let c = cmd(&["TS.MADD", "a", &max, "1"]);
        assert_eq!(
            ts_madd_feed(&refs(&c), b"*1\r\n:-1\r\n"),
            vec![cmd(&["TS.MADD", "a", &max, "1"])]
        );
        let c = cmd(&["TS.INCRBY", "a", "1", "TIMESTAMP", &max]);
        assert_eq!(
            ts_incrby_feed(&refs(&c), b":-1\r\n"),
            vec![cmd(&[
                "TS.INCRBY",
                "a",
                "1",
                "timestamp",
                &max,
                "TIMESTAMP",
                &max
            ])]
        );
    }

    #[test]
    fn ts_madd_feed_leaves_out_refused_samples() {
        let c = cmd(&["TS.MADD", "a", "*", "1", "b", "*", "2", "c", "5", "3"]);
        let resp = b"*3\r\n-TSDB: Duplicate sample in BLOCK policy\r\n:101\r\n:5\r\n";
        assert_eq!(
            ts_madd_feed(&refs(&c), resp),
            vec![cmd(&["TS.MADD", "b", "101", "2", "c", "5", "3"])]
        );
        let c = cmd(&["TS.MADD", "a", "*", "1"]);
        assert!(ts_madd_feed(&refs(&c), b"*1\r\n-TSDB: the key does not exist\r\n").is_empty());
    }

    /// Each `TIMESTAMP` option the command read is given the time, where it
    /// is, and the time goes right after the value behind 1.2.1's mark. Not
    /// after a `LABELS` list, where a word left over from the list, which
    /// the command passed over, became a label with it on a replica. A
    /// label's value `TIMESTAMP` is not an option (#555).
    #[test]
    fn ts_incrby_feed_gives_the_time_without_moving_a_word() {
        let cases: &[(&[&str], &[&str])] = &[
            (
                &["TS.INCRBY", "k", "2", "LABELS", "a"],
                &["TS.INCRBY", "k", "2", "timestamp", "42", "LABELS", "a"],
            ),
            (
                &["TS.INCRBY", "k", "2", "LABELS", "a", "b", "c"],
                &[
                    "TS.INCRBY",
                    "k",
                    "2",
                    "timestamp",
                    "42",
                    "LABELS",
                    "a",
                    "b",
                    "c",
                ],
            ),
            (
                &["TS.INCRBY", "k", "2", "LABELS", "a", "b", "UNCOMPRESSED"],
                &[
                    "TS.INCRBY",
                    "k",
                    "2",
                    "timestamp",
                    "42",
                    "LABELS",
                    "a",
                    "b",
                    "UNCOMPRESSED",
                ],
            ),
            (
                &["TS.INCRBY", "k", "2", "LABELS", "a", "TIMESTAMP", "*"],
                &[
                    "TS.INCRBY",
                    "k",
                    "2",
                    "timestamp",
                    "42",
                    "LABELS",
                    "a",
                    "TIMESTAMP",
                    "*",
                ],
            ),
            (
                &[
                    "TS.INCRBY",
                    "k",
                    "2",
                    "TIMESTAMP",
                    "5",
                    "LABELS",
                    "a",
                    "b",
                    "TIMESTAMP",
                    "*",
                    "c",
                ],
                &[
                    "TS.INCRBY",
                    "k",
                    "2",
                    "timestamp",
                    "42",
                    "TIMESTAMP",
                    "42",
                    "LABELS",
                    "a",
                    "b",
                    "TIMESTAMP",
                    "42",
                    "c",
                ],
            ),
        ];
        for (given, sent) in cases {
            let c = cmd(given);
            assert_eq!(
                ts_incrby_feed(&refs(&c), b":42\r\n"),
                vec![cmd(sent)],
                "{given:?}"
            );
        }
    }

    #[test]
    fn blocking_moves_propagate_as_their_non_blocking_forms() {
        let c = cmd(&[
            "BLMOVEM", "s", "d", "LEFT", "RIGHT", "5", "COUNT", "2", "OBO",
        ]);
        let moved = b"*1\r\n$1\r\na\r\n";
        assert_eq!(
            lmovem_feed("BLMOVEM", &refs(&c), moved),
            vec![cmd(&[
                "LMOVEM", "s", "d", "LEFT", "RIGHT", "COUNT", "2", "OBO"
            ])]
        );
        assert!(lmovem_feed("BLMOVEM", &refs(&c), b"*-1\r\n").is_empty());
        assert!(lmovem_feed("BLMOVEM", &refs(&c), b"*0\r\n").is_empty());

        let c = cmd(&["LMOVEM", "s", "d", "LEFT", "RIGHT"]);
        assert_eq!(lmovem_feed("LMOVEM", &refs(&c), moved), vec![c.clone()]);

        let c = cmd(&["BLMOVE", "s", "d", "LEFT", "RIGHT", "0"]);
        assert_eq!(
            blocking_move_feed(&refs(&c), &bulk("a"), "LMOVE", 5),
            vec![cmd(&["LMOVE", "s", "d", "LEFT", "RIGHT"])]
        );
        assert!(blocking_move_feed(&refs(&c), b"$-1\r\n", "LMOVE", 5).is_empty());

        let c = cmd(&["BRPOPLPUSH", "s", "d", "0"]);
        assert_eq!(
            blocking_move_feed(&refs(&c), &bulk("a"), "RPOPLPUSH", 3),
            vec![cmd(&["RPOPLPUSH", "s", "d"])]
        );
    }

    #[test]
    fn blocking_pops_propagate_as_the_pop_they_made() {
        let c = cmd(&["BLPOP", "a", "b", "0"]);
        let popped = b"*2\r\n$1\r\nb\r\n$1\r\nx\r\n";
        assert_eq!(
            blocking_pop_feed("BLPOP", &refs(&c), popped),
            vec![cmd(&["LPOP", "b"])]
        );
        assert!(blocking_pop_feed("BLPOP", &refs(&c), b"*-1\r\n").is_empty());
        assert!(blocking_pop_feed("BLPOP", &refs(&c), b"_\r\n").is_empty());
        assert!(blocking_pop_feed("BLPOP", &refs(&c), b"").is_empty());

        let c = cmd(&["BRPOP", "a", "0"]);
        assert_eq!(
            blocking_pop_feed("BRPOP", &refs(&c), b"*2\r\n$1\r\na\r\n$1\r\nx\r\n"),
            vec![cmd(&["RPOP", "a"])]
        );

        let c = cmd(&["BZPOPMAX", "z1", "z2", "1.5"]);
        let popped = b"*3\r\n$2\r\nz2\r\n$1\r\nm\r\n$1\r\n3\r\n";
        assert_eq!(
            blocking_pop_feed("BZPOPMAX", &refs(&c), popped),
            vec![cmd(&["ZPOPMAX", "z2"])]
        );

        let c = cmd(&["BLMPOP", "0", "2", "a", "b", "right", "COUNT", "5"]);
        let popped = b"*2\r\n$1\r\nb\r\n*2\r\n$1\r\nx\r\n$1\r\ny\r\n";
        assert_eq!(
            blocking_pop_feed("BLMPOP", &refs(&c), popped),
            vec![cmd(&["RPOP", "b", "2"])]
        );

        let c = cmd(&["BZMPOP", "0", "1", "z", "MIN", "COUNT", "3"]);
        let popped = b"*2\r\n$1\r\nz\r\n*1\r\n*2\r\n$1\r\nm\r\n$1\r\n1\r\n";
        assert_eq!(
            blocking_pop_feed("BZMPOP", &refs(&c), popped),
            vec![cmd(&["ZPOPMIN", "z", "1"])]
        );
        assert!(blocking_pop_feed("BZMPOP", &refs(&c), b"*-1\r\n").is_empty());
    }

    #[test]
    fn spop_of_a_resp3_client_is_rewritten_too() {
        let owned = cmd(&["SPOP", "s", "2"]);
        let resp = b"~2\r\n$3\r\nm01\r\n$3\r\nm07\r\n";
        assert_eq!(
            spop_feed(&refs(&owned), resp),
            vec![cmd(&["SREM", "s", "m01", "m07"])]
        );
        assert!(spop_feed(&refs(&owned), b"~0\r\n").is_empty());
        assert!(spop_feed(&refs(&cmd(&["SPOP", "s"])), b"_\r\n").is_empty());
        assert_eq!(
            incrbyfloat_feed(&refs(&cmd(&["INCRBYFLOAT", "f", "1.5"])), b",2.5\r\n"),
            vec![cmd(&["SET", "f", "2.5", "KEEPTTL"])]
        );
    }

    #[test]
    fn spop_is_rewritten_to_srem_of_the_actual_members() {
        let owned = cmd(&["SPOP", "s", "2"]);
        let resp = b"*2\r\n$3\r\nm01\r\n$3\r\nm07\r\n";
        let out = spop_feed(&refs(&owned), resp);
        assert_eq!(
            out[0],
            vec![
                b"SREM".to_vec(),
                b"s".to_vec(),
                b"m01".to_vec(),
                b"m07".to_vec()
            ]
        );
    }

    #[test]
    fn spop_miss_propagates_nothing() {
        let owned = cmd(&["SPOP", "s"]);
        assert!(spop_feed(&refs(&owned), b"$-1\r\n").is_empty());
    }

    #[test]
    fn incrbyfloat_is_rewritten_to_an_absolute_set() {
        // Deterministic, but NOT idempotent: replaying the delta over a
        // snapshot that already contains it would double-apply.
        let owned = cmd(&["INCRBYFLOAT", "f", "1.1"]);
        let out = incrbyfloat_feed(&refs(&owned), &bulk("6.5"));
        assert_eq!(
            out[0],
            vec![
                b"SET".to_vec(),
                b"f".to_vec(),
                b"6.5".to_vec(),
                b"KEEPTTL".to_vec()
            ]
        );
    }
}