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
//! Proof 5, second clause: a long command file run as a flow stays flat.
//!
//! # What is measured, and what stands in for what
//!
//! `stream_file` needs a server, and this host has none, so the run itself
//! cannot be driven end to end here. What is driven is every part of that loop
//! that is not the round trip: the cut hands the statements over, the output
//! operations decide each record, and the writer emits it. The one link left
//! out is the call that asks the server, which returns one record and is
//! awaited and dropped inside the loop.
//!
//! That is stated rather than glossed, because a proof that quietly measured
//! less than it claimed would be worth nothing. What it does establish is the
//! property the clause is about: nothing in the loop holds a collection that
//! grows with the count of statements. The heap is counted, not reasoned about.
//!
//! This file carries one test on purpose. The counter is global to the process,
//! so a second test running beside it would be measuring both.
use std::alloc::{GlobalAlloc, Layout, System};
use std::sync::atomic::{AtomicUsize, Ordering};
use mariadb_cli::cli::globals::OutputFormat;
use mariadb_cli::output::format::{for_format, END_OF_STREAM_KEY, ROW_COUNT_KEY};
use mariadb_cli::output::ops::Step;
use mariadb_cli::output::stream::Stream;
use mariadb_cli::output::Row;
use serde_json::json;
/// Bytes handed out and not yet given back.
static LIVE: AtomicUsize = AtomicUsize::new(0);
/// The system allocator, counting what it lends.
struct Counting;
// SAFETY: every call is forwarded to the system allocator unchanged, and the
// only addition is an atomic counter, which allocates nothing itself.
unsafe impl GlobalAlloc for Counting {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
let pointer = unsafe { System.alloc(layout) };
if !pointer.is_null() {
LIVE.fetch_add(layout.size(), Ordering::Relaxed);
}
pointer
}
unsafe fn dealloc(&self, pointer: *mut u8, layout: Layout) {
LIVE.fetch_sub(layout.size(), Ordering::Relaxed);
unsafe { System.dealloc(pointer, layout) };
}
unsafe fn realloc(&self, pointer: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
let moved = unsafe { System.realloc(pointer, layout, new_size) };
if !moved.is_null() {
LIVE.fetch_sub(layout.size(), Ordering::Relaxed);
LIVE.fetch_add(new_size, Ordering::Relaxed);
}
moved
}
}
#[global_allocator]
static ALLOCATOR: Counting = Counting;
/// Bytes the process is holding right now.
fn live() -> usize {
LIVE.load(Ordering::Relaxed)
}
/// The record one statement produces, built exactly as `record_of` builds it.
///
/// The outcome is the shape a read answers with, and the record carries the
/// position and the outcome and never the statement's own text.
fn record_for(piece: &mariadb_cli::exec::script::Piece) -> Row {
let mut record = Row::new();
record.insert("statement".to_owned(), json!(piece.index));
record.insert("line".to_owned(), json!(piece.line));
record.insert("outcome".to_owned(), json!({"read": true, "row_count": 1}));
record
}
/// FR-028. Every statement of the file is run in order and produces its own
/// record carrying its position and its outcome.
///
/// FR-032. The continuous path admits this invocation and, once the loop has
/// settled, holds the same number of bytes at the twenty thousandth record as
/// at the sixteenth.
///
/// FR-132. The run that reached its end closes with the record that declares
/// the answer whole, carrying the count of what was emitted.
///
/// A long command file run as a flow holds no more at its end than at its start.
#[test]
fn a_long_command_file_run_as_a_flow_holds_nothing_that_grows_with_it() {
let statements = 20_000;
let mut file = String::new();
for index in 0..statements {
use std::fmt::Write as _;
// Written straight into the file rather than through a second string
// built only to be copied in and dropped, twenty thousand times over.
let _ = writeln!(file, "SELECT {index};");
}
// The pipeline and the writer the flow really uses, with the ordinary
// flags on rather than an empty pipeline that would decide nothing.
let argv: Vec<String> = [
"mariadb-cli",
"--output-format",
"ndjson",
"--select",
"statement,outcome",
"query",
"file",
"carga.sql",
]
.iter()
.map(|part| (*part).to_owned())
.collect();
let cli = <mariadb_cli::cli::Cli as clap::Parser>::try_parse_from(argv).expect("parses");
let scratch = tempfile::tempdir().expect("a scratch directory");
let config =
mariadb_cli::config::Config::load(Some(scratch.path())).expect("an empty location loads");
// The gate must admit this invocation, or the flow being measured is not
// the one the product would take.
assert!(
mariadb_cli::dispatch::flow::applies(&cli, &config),
"a line-oriented run of a file must reach the continuous path"
);
let pipeline = cli.globals.pipeline(&config).expect("a pipeline");
let columns: Vec<String> = mariadb_cli::exec::script::FILE_COLUMNS
.iter()
.map(|name| (*name).to_owned())
.collect();
let walk = mariadb_cli::exec::script::split(&file, ";").expect("the file is readable");
// The records go to a channel that keeps nothing. Collecting them into a
// buffer here would measure the buffer growing, which is the reader's cost
// and not the flow's: the product writes to the standard channel, which a
// reader consumes as it arrives.
let before = live();
let mut stage = pipeline.flow();
let mut flow = Stream::open(
std::io::sink(),
for_format(OutputFormat::Ndjson),
&closing_tail(),
&columns,
)
.expect("opens");
let mut seen = 0;
let mut settled = 0;
for piece in walk {
// Standing in for the one link that needs a server: a record is made
// for this statement, and it is dropped before the next one arrives.
let record = record_for(&piece);
drop(piece);
seen += 1;
match stage.offer(record) {
Step::Emit(shaped) => flow.write(&shaped).expect("writes"),
Step::Skip | Step::Stop => {}
}
// The loop settles after the first few statements, once the writer's
// line buffer and the walk have taken what they take. From there the
// heap must not move, however many statements are still to come.
// Written against the settling point rather than as a chain of ifs,
// because the count stands in three places and only two of them were
// spelled out. The stretch before the point is where the heap is still
// allowed to move, and leaving it unwritten made it read like a case
// nobody had considered. The minimum compiler this crate supports asks
// for this shape; the newer one no longer does, and the shape is the
// one that answers both.
match seen.cmp(&16) {
std::cmp::Ordering::Less => {}
std::cmp::Ordering::Equal => settled = live() - before,
std::cmp::Ordering::Greater => {
assert_eq!(
live() - before,
settled,
"the flow grew at statement {seen}"
);
}
}
}
assert_eq!(seen, statements, "every statement is run");
assert_eq!(stage.emitted(), statements, "every record is emitted");
assert!(stage.is_whole(), "nothing cut this answer");
assert_eq!(flow.emitted(), statements as u64);
// The record that declares the answer whole is written only on reaching
// the end, which is what FR-132 asks of every flow.
let written = flow.finish(&closing_tail(), &[], None).expect("closes");
assert_eq!(written, statements as u64);
// What the flow settled at is the file's blanked twin, which the cut reads
// and which does not grow with the count of statements, plus the writer's
// one reused line. Twenty thousand records cost nothing beyond that.
assert!(
settled < file.len() + 64 * 1024,
"the flow settled holding {settled} bytes over a {} byte file, so it is holding \
records rather than emitting them",
file.len()
);
// FR-132: the record that declares the answer whole is written on reaching
// the end, and a reader that does not see it knows the run was cut. The
// bytes are read here rather than above, because a buffer that keeps them
// is exactly what the measurement must not have.
let mut kept: Vec<u8> = Vec::new();
let short = mariadb_cli::exec::script::split("SELECT 1;\nSELECT 2;\n", ";").expect("readable");
let mut closing = Stream::open(
&mut kept,
for_format(OutputFormat::Ndjson),
&closing_tail(),
&columns,
)
.expect("opens");
for piece in short {
closing.write(&record_for(&piece)).expect("writes");
}
assert_eq!(
closing.finish(&closing_tail(), &[], None).expect("closes"),
2
);
let lines: Vec<&str> = std::str::from_utf8(&kept)
.expect("the channel carries text")
.lines()
.collect();
let last: serde_json::Value =
serde_json::from_str(lines.last().expect("a last line")).expect("the last line parses");
assert_eq!(last[END_OF_STREAM_KEY], json!(true), "got {last}");
assert_eq!(last[ROW_COUNT_KEY], json!(2), "got {last}");
}
/// The tail a flow closes with, carrying no destination.
///
/// These proofs measure the closing record itself, so nothing about a
/// destination is invented here.
fn closing_tail() -> mariadb_cli::output::Envelope {
mariadb_cli::output::Envelope::new("query run", serde_json::json!({}))
}