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
//! Confronts every declared response type with the reply shape the server
//! actually sent for it.
//!
//! `response_probe` writes one line per distinct
//! `(command, declared R, observed RESP kind)` while the suite runs. This
//! module reads that dump back and applies the rules below, which encode what
//! `RespDeserializer` does rather than what the command's doc-comment claims:
//! a `Null` read as `bool` is `false`, read as an integer it is `0`, and a
//! reply read as `()` is discarded whatever it carried. Each of those is a way
//! for a wrong `R` to return a plausible value forever.
//!
//! It runs as a second invocation, after a full suite run has produced the
//! dump, because the harness gives no ordering guarantee that would let one run
//! both collect and report:
//!
//! ```text
//! ./run_tests.sh
//! RUSTIS_RESPONSE_SHAPE_REPORT=1 ./run_tests.sh response_shape
//! ```
use crate::tests::response_probe::dump_path;
use std::collections::BTreeSet;
/// A row the rules accept, with the reason it is accepted. Anything reported
/// and not listed here fails the test.
const BASELINE: &str = include_str!("response_shape_baseline.tsv");
/// What a declared `R` reduces to for the purpose of judging a reply.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
enum Category {
/// `()` — the reply is discarded, whatever it holds.
Unit,
Bool,
Int,
Float,
Str,
Collection,
/// A struct or enum decoded from the reply.
Custom,
/// `Value` and friends: shape is the caller's business, never wrong here.
Any,
}
/// A declared `R` reduced to what judging it needs: its category, and whether
/// it was wrapped in an `Option` — which is the type saying an absent reply is
/// expected, so a null stops being evidence of anything.
struct Declared {
category: Category,
optional: bool,
}
fn categorize(declared: &str) -> Declared {
let declared = declared.trim();
if let Some(inner) = declared
.strip_prefix("Option<")
.and_then(|d| d.strip_suffix('>'))
{
return Declared {
category: categorize(inner).category,
optional: true,
};
}
Declared {
category: category_of(declared),
optional: false,
}
}
fn category_of(declared: &str) -> Category {
// A tuple is read off a collection whatever its members are.
if declared.starts_with('(') && declared != "()" {
return Category::Collection;
}
if let Some((head, _)) = declared.split_once('<') {
return match head {
"Vec" | "VecDeque" | "HashSet" | "BTreeSet" | "HashMap" | "BTreeMap" => {
Category::Collection
}
_ => Category::Custom,
};
}
match declared {
"()" => Category::Unit,
"bool" => Category::Bool,
"u8" | "u16" | "u32" | "u64" | "u128" | "usize" | "i8" | "i16" | "i32" | "i64" | "i128"
| "isize" => Category::Int,
"f32" | "f64" => Category::Float,
"String" | "BulkString" | "str" | "char" => Category::Str,
"Value" => Category::Any,
_ => Category::Custom,
}
}
/// The reply kinds a declared type can decode without silently inventing a
/// value.
fn accepts(declared: &Declared, kind: &str) -> bool {
// An empty collection is judged as the collection it is; the emptiness only
// qualifies how much the observation proves.
let base = kind.strip_prefix("Empty").unwrap_or(kind);
// A null is what `Option` exists for, and nothing else here tolerates it:
// every non-optional category turns it into a default — `false`, `0`, an
// empty string — with no way for the caller to tell.
if base == "Null" {
return declared.optional || matches!(declared.category, Category::Unit | Category::Any);
}
match declared.category {
// `Value` describes whatever came, null included.
Category::Any => true,
// Only `+OK` carries nothing. Anything else was data, and `()` threw it
// away — the `cluster_getkeysinslot` defect exactly.
Category::Unit => kind == "SimpleString(OK)",
Category::Bool => matches!(
kind,
"Integer(0)" | "Integer(1)" | "Boolean" | "SimpleString(OK)"
),
// Redis answers numbers as bulk strings as readily as as integers
// (`GET` on a counter), and the deserializer parses the digits.
Category::Int => base.starts_with("Integer") || base == "BulkString",
Category::Float => base.starts_with("Integer") || matches!(base, "Double" | "BulkString"),
Category::Str => matches!(base, "BulkString" | "SimpleString" | "SimpleString(OK)"),
Category::Collection => matches!(base, "Array" | "IntegerArray" | "Set" | "Map" | "Push"),
Category::Custom => matches!(
base,
"Array" | "Map" | "Set" | "BulkString" | "SimpleString" | "SimpleString(OK)"
),
}
}
/// A row of the dump.
struct Row {
command: String,
declared: String,
kind: String,
/// `false` when the declared type refused the reply. Such a mismatch is
/// loud — the caller got an error — and it is not what this report hunts.
decoded: bool,
}
fn parse(content: &str) -> Vec<Row> {
content
.lines()
.map(str::trim_end)
.filter(|line| !line.is_empty() && !line.starts_with('#'))
.filter_map(|line| {
let mut fields = line.split('\t');
Some(Row {
command: fields.next()?.to_owned(),
declared: fields.next()?.to_owned(),
kind: fields.next()?.trim().to_owned(),
decoded: fields.next().is_none_or(|o| o.trim() != "refused"),
})
})
.collect()
}
fn key(row: &Row) -> String {
format!("{}\t{}\t{}", row.command, row.declared, row.kind)
}
#[test]
fn response_shape_report() {
if std::env::var("RUSTIS_RESPONSE_SHAPE_REPORT").is_err() {
println!(
"skipped: set RUSTIS_RESPONSE_SHAPE_REPORT=1 and run after a full suite run, \
which is what fills {}",
dump_path()
);
return;
}
let path = dump_path();
let content = std::fs::read_to_string(&path).unwrap_or_else(|e| {
panic!("no probe dump at {path} ({e}); run the whole suite first, it writes it")
});
let rows = parse(&content);
assert!(
!rows.is_empty(),
"{path} is empty: the suite recorded nothing"
);
let accepted: BTreeSet<String> = parse(BASELINE).iter().map(key).collect();
let mut unexplained = Vec::new();
for row in &rows {
// A command that answered an error made no claim about its shape.
if row.kind == "Error" {
continue;
}
// The type refused the reply, so the caller was told rather than handed
// a coerced value. That is a negative test, not a silent mismatch.
if !row.decoded {
continue;
}
if accepts(&categorize(&row.declared), &row.kind) {
continue;
}
if accepted.contains(&key(row)) {
continue;
}
unexplained.push(row);
}
println!(
"{} observations, {} unexplained",
rows.len(),
unexplained.len()
);
if !unexplained.is_empty() {
let mut report = String::from(
"declared response types the server's reply contradicts.\n\
Read each against COMMAND DOCS or the raw reply, then either fix the \
type or add the row to response_shape_baseline.tsv with its reason.\n\n",
);
for row in &unexplained {
report.push_str(&format!(
" {:<32} {:<40} answered {}\n",
row.command, row.declared, row.kind
));
}
panic!("{report}");
}
}