-
Notifications
You must be signed in to change notification settings - Fork 513
Expand file tree
/
Copy pathserver.rs
More file actions
6890 lines (6252 loc) · 240 KB
/
Copy pathserver.rs
File metadata and controls
6890 lines (6252 loc) · 240 KB
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
// Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.
//! Integration tests for Materialize server.
#![recursion_limit = "256"]
use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::fmt::Write;
use std::io::Write as _;
use std::net::{IpAddr, Ipv4Addr};
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use std::{iter, thread};
use anyhow::bail;
use chrono::{DateTime, Utc};
use flate2::Compression;
use flate2::write::GzEncoder;
use futures::FutureExt;
use http::Request;
use itertools::Itertools;
use jsonwebtoken::{DecodingKey, EncodingKey};
use mz_auth::password::Password;
use mz_environmentd::test_util::{self, Ca, KAFKA_ADDRS, PostgresErrorExt, make_pg_tls};
use mz_environmentd::{WebSocketAuth, WebSocketResponse};
use mz_frontegg_auth::{
Authenticator as FronteggAuthentication, AuthenticatorConfig as FronteggConfig,
DEFAULT_REFRESH_DROP_FACTOR, DEFAULT_REFRESH_DROP_LRU_CACHE_SIZE,
};
use mz_frontegg_mock::{FronteggMockServer, models::ApiToken, models::UserConfig};
use mz_ore::cast::CastFrom;
use mz_ore::cast::CastLossy;
use mz_ore::cast::TryCastFrom;
use mz_ore::collections::CollectionExt;
use mz_ore::error::ErrorExt;
use mz_ore::metrics::MetricsRegistry;
use mz_ore::now::{NowFn, SYSTEM_TIME, to_datetime};
use mz_ore::retry::Retry;
use mz_ore::{assert_contains, task::RuntimeExt};
use mz_ore::{assert_err, assert_none, assert_ok, task};
use mz_pgrepr::UInt8;
use mz_repr::UNKNOWN_COLUMN_NAME;
use mz_sql::session::user::{ANALYTICS_USER, HTTP_DEFAULT_USER, SYSTEM_USER};
use mz_sql_parser::ast::display::AstDisplay;
use openssl::ssl::{SslConnectorBuilder, SslVerifyMode};
use openssl::x509::X509;
use postgres::config::SslMode;
use postgres_array::Array;
use rand::RngCore;
use rdkafka::ClientConfig;
use rdkafka::admin::{AdminClient, AdminOptions, NewTopic, TopicReplication};
use rdkafka_sys::RDKafkaErrorCode;
use regex::Regex;
use reqwest::blocking::Client;
use reqwest::header::{CONTENT_ENCODING, CONTENT_TYPE};
use reqwest::{StatusCode, Url};
use serde::{Deserialize, Serialize};
use tempfile::TempDir;
use tokio::sync::oneshot;
use tokio_postgres::error::SqlState;
use tracing::info;
use tungstenite::error::ProtocolError;
use tungstenite::{Error, Message, Utf8Bytes};
use uuid::Uuid;
// Allow the use of banned rdkafka methods, because we are just in tests.
#[mz_ore::test]
#[allow(clippy::disallowed_methods)]
fn test_persistence() {
let data_dir = tempfile::tempdir().unwrap();
let harness = test_util::TestHarness::default()
.data_directory(data_dir.path())
.unsafe_mode();
{
let server = harness.clone().start_blocking();
let mut client = server.connect(postgres::NoTls).unwrap();
server.runtime().block_on(async {
let admin: AdminClient<_> = ClientConfig::new()
.set("bootstrap.servers", &*KAFKA_ADDRS)
.create()
.expect("Admin client creation failed");
let new_topic = NewTopic::new("foo", 1, TopicReplication::Fixed(1));
let topic_results = admin
.create_topics([&new_topic], &AdminOptions::new())
.await
.expect("topic creation failed");
match topic_results[0] {
Ok(_) | Err((_, RDKafkaErrorCode::TopicAlreadyExists)) => {}
Err((ref err, _)) => panic!("failed to ensure topic: {err}"),
}
});
client
.batch_execute(&format!(
"CREATE CONNECTION kafka_conn TO KAFKA (BROKER '{}', SECURITY PROTOCOL PLAINTEXT)",
&*KAFKA_ADDRS,
))
.unwrap();
client
.batch_execute(
"CREATE SOURCE src FROM KAFKA CONNECTION kafka_conn (TOPIC 'foo') FORMAT BYTES",
)
.unwrap();
client
.batch_execute("CREATE VIEW constant AS SELECT 1")
.unwrap();
client.batch_execute(
"CREATE VIEW mat (a, a_data, c, c_data) AS SELECT 'a', data, 'c' AS c, data FROM src",
).unwrap();
client.batch_execute("CREATE DEFAULT INDEX ON mat").unwrap();
client.batch_execute("CREATE DATABASE d").unwrap();
client.batch_execute("CREATE SCHEMA d.s").unwrap();
client
.batch_execute("CREATE VIEW d.s.v AS SELECT 1")
.unwrap();
}
let server = harness.start_blocking();
let mut client = server.connect(postgres::NoTls).unwrap();
assert_eq!(
client
.query("SHOW VIEWS", &[])
.unwrap()
.into_iter()
.map(|row| row.get(0))
.collect::<Vec<String>>(),
&["constant", "mat"]
);
assert_eq!(
client
.query_one("SHOW INDEXES ON mat", &[])
.unwrap()
.get::<_, Vec<String>>("key"),
&["a", "a_data", "c", "c_data"],
);
assert_eq!(
client
.query("SHOW VIEWS FROM d.s", &[])
.unwrap()
.into_iter()
.map(|row| row.get(0))
.collect::<Vec<String>>(),
&["v"]
);
// Test that catalog recovery correctly populates `mz_objects`.
assert_eq!(
client
.query(
"SELECT id FROM mz_objects WHERE id LIKE 'u%' ORDER BY 1",
&[]
)
.unwrap()
.into_iter()
.map(|row| row.get(0))
.collect::<Vec<String>>(),
vec!["u1", "u2", "u3", "u4", "u5", "u6", "u7"]
);
}
/// A wrapper around `TestServerWithRuntime` that runs statement logging checks when dropped.
///
/// This guard ensures that all statements have finished executing (have non-NULL `finished_at`
/// and `finished_status` in `mz_internal.mz_recent_activity_log`) before the test completes.
struct TestServerWithStatementLoggingChecks {
server: test_util::TestServerWithRuntime,
}
impl TestServerWithStatementLoggingChecks {
/// Connect to the __internal__ SQL port of the running `environmentd` server.
pub fn connect_internal<T>(&self, tls: T) -> Result<postgres::Client, anyhow::Error>
where
T: postgres::tls::MakeTlsConnect<postgres::Socket> + Send + 'static,
T::TlsConnect: Send,
T::Stream: Send,
<T::TlsConnect as postgres::tls::TlsConnect<postgres::Socket>>::Future: Send,
{
self.server.connect_internal(tls)
}
/// Returns the metrics registry for the test server.
pub fn metrics_registry(&self) -> &MetricsRegistry {
self.server.metrics_registry()
}
}
/// Helper to get statement logging record counts from the metrics registry.
/// Returns (sampled_true_count, sampled_false_count).
#[allow(clippy::disallowed_methods)]
fn get_statement_logging_record_counts(
server: &TestServerWithStatementLoggingChecks,
) -> (u64, u64) {
let metrics = server.metrics_registry().gather();
let record_count_metric = metrics
.into_iter()
.find(|m| m.name() == "mz_statement_logging_record_count")
.expect("mz_statement_logging_record_count metric should exist");
let metric_entries = record_count_metric.get_metric();
let sampled_true = metric_entries
.iter()
.find(|m| {
m.get_label()
.iter()
.any(|l| l.name() == "sample" && l.value() == "true")
})
.map(|m| u64::cast_lossy(m.get_counter().value()))
.unwrap_or(0);
let sampled_false = metric_entries
.iter()
.find(|m| {
m.get_label()
.iter()
.any(|l| l.name() == "sample" && l.value() == "false")
})
.map(|m| u64::cast_lossy(m.get_counter().value()))
.unwrap_or(0);
(sampled_true, sampled_false)
}
impl Drop for TestServerWithStatementLoggingChecks {
#[allow(clippy::disallowed_methods)]
fn drop(&mut self) {
// Don't run checks if we're already panicking, as this could mask the original error.
if std::thread::panicking() {
return;
}
let mut mz_client = self
.server
.connect_internal(postgres::NoTls)
.expect("Failed to connect to internal SQL port for statement logging check");
// Disable RBAC checks so we can query mz_internal tables.
// (We don't need to restore this afterwards, since no more tests run in the same system.)
mz_client
.batch_execute("ALTER SYSTEM SET enable_rbac_checks = false")
.expect("Failed to disable RBAC checks");
// The statement log has a 5-second buffer flush interval, so allow sufficient time.
Retry::default()
.max_duration(Duration::from_secs(30))
.retry(|_| {
let result = mz_client.query_one(
"SELECT count(*)
FROM mz_internal.mz_recent_activity_log
WHERE
(finished_at IS NULL OR finished_status IS NULL)
AND sql NOT LIKE '%__FILTER-OUT-THIS-QUERY__%'
AND finished_status != 'aborted'",
&[],
);
match result {
Ok(row) => {
let count: i64 = row.get(0);
if count == 0 {
Ok(())
} else {
Err(format!("{} statements have not finished", count))
}
}
Err(e) => Err(format!("Query failed: {}", e)),
}
})
.expect("All statements should have finished executing");
}
}
fn setup_statement_logging_core(
max_sample_rate: f64,
sample_rate: f64,
target_data_rate: &str,
test_harness: test_util::TestHarness,
) -> (TestServerWithStatementLoggingChecks, postgres::Client) {
let server = test_harness
.with_system_parameter_default(
"statement_logging_max_sample_rate".to_string(),
max_sample_rate.to_string(),
)
.with_system_parameter_default(
"statement_logging_default_sample_rate".to_string(),
sample_rate.to_string(),
)
.with_system_parameter_default(
"statement_logging_max_data_credit".to_string(),
"".to_string(),
)
.with_system_parameter_default(
"statement_logging_target_data_rate".to_string(),
target_data_rate.to_string(),
)
.with_system_parameter_default(
"statement_logging_use_reproducible_rng".to_string(),
"true".to_string(),
)
.start_blocking();
let client = server.connect(postgres::NoTls).unwrap();
let server = TestServerWithStatementLoggingChecks { server };
(server, client)
}
fn setup_statement_logging(
max_sample_rate: f64,
sample_rate: f64,
target_data_rate: &str,
) -> (TestServerWithStatementLoggingChecks, postgres::Client) {
setup_statement_logging_core(
max_sample_rate,
sample_rate,
target_data_rate,
test_util::TestHarness::default(),
)
}
// Test that we log various kinds of statement whose execution terminates in the coordinator.
#[mz_ore::test]
#[allow(clippy::disallowed_methods)]
fn test_statement_logging_immediate() {
let (server, mut client) = setup_statement_logging(1.0, 1.0, "");
let mut mz_client = server.connect_internal(postgres::NoTls).unwrap();
mz_client
.batch_execute("ALTER SYSTEM SET enable_statement_lifecycle_logging = false")
.unwrap();
mz_client
.batch_execute("ALTER SYSTEM SET statement_logging_max_sample_rate = 1")
.unwrap();
mz_client
.batch_execute("ALTER SYSTEM SET statement_logging_default_sample_rate = 1")
.unwrap();
mz_client
.batch_execute("ALTER SYSTEM SET enable_load_generator_counter = true")
.unwrap();
let successful_immediates: &[&str] = &[
"CREATE VIEW v AS SELECT 1;",
"CREATE DEFAULT INDEX i ON v;",
"CREATE TABLE t (x bigint);",
"INSERT INTO t VALUES (1), (2), (3)",
"UPDATE t SET x=x+1",
"DELETE FROM t;",
"CREATE SECRET s AS 'hunter2';",
"DROP SECRET s;",
"",
"CREATE SOURCE s FROM LOAD GENERATOR COUNTER",
"PREPARE foo AS SELECT * FROM t",
"EXECUTE foo",
"BEGIN",
"DECLARE c CURSOR FOR SELECT * FROM t",
"FETCH FORWARD ALL FROM c",
"COMMIT",
"BEGIN",
"ROLLBACK",
"SET application_name='my_application'",
"SHOW ALL",
"SHOW application_name",
];
let constants: &[&str] = &["1", "2", "3", "hunter2", "my_application"];
for &statement in successful_immediates {
client.execute(statement, &[]).unwrap();
// Enforce a small delay to avoid duplicate `began_at` times, which would make the ordering
// of logged statements non-deterministic when we retrieve them below.
thread::sleep(Duration::from_millis(10));
}
let mut client = server.connect_internal(postgres::NoTls).unwrap();
let seh_query = "
SELECT
mseh.sample_rate,
mseh.began_at,
mseh.finished_at,
mseh.finished_status,
mst.sql,
mpsh.prepared_at,
mst.redacted_sql
FROM mz_internal.mz_statement_execution_history AS mseh
LEFT JOIN
mz_internal.mz_prepared_statement_history AS mpsh
ON mseh.prepared_statement_id = mpsh.id
JOIN
(SELECT DISTINCT sql, sql_hash, redacted_sql FROM mz_internal.mz_sql_text) mst
ON mpsh.sql_hash = mst.sql_hash
WHERE
mst.sql !~~ '%mz_statement_execution_history%' AND
mseh.finished_at IS NOT NULL
ORDER BY mseh.began_at";
// Statement logging happens async, retry until we get the expected number of logged
// statements.
let mut sl = Vec::new();
for _ in 0..10 {
thread::sleep(Duration::from_secs(1));
sl = client.query(seh_query, &[]).unwrap();
if sl.len() >= successful_immediates.len() {
break;
}
}
assert_eq!(sl.len(), successful_immediates.len());
#[derive(Debug)]
struct Record {
sample_rate: f64,
began_at: DateTime<Utc>,
finished_at: DateTime<Utc>,
finished_status: String,
sql: String,
prepared_at: DateTime<Utc>,
redacted_sql: String,
}
for (r, stmt) in std::iter::zip(sl.iter(), successful_immediates) {
let r = Record {
sample_rate: r.get(0),
began_at: r.get(1),
finished_at: r.get(2),
finished_status: r.get(3),
sql: r.get(4),
prepared_at: r.get(5),
redacted_sql: r.get(6),
};
assert_eq!(r.sample_rate, 1.0);
let expected_sql = if r.sql.contains("SECRET")
|| r.sql.contains("INSERT")
|| r.sql.contains("UPDATE")
|| r.sql.contains("EXECUTE")
{
mz_sql::parse::parse(&r.sql)
.unwrap()
.into_element()
.ast
.to_ast_string_redacted()
} else {
stmt.chars().filter(|&ch| ch != ';').collect::<String>()
};
assert_eq!(r.sql, expected_sql);
assert_eq!(r.finished_status, "success");
assert!(r.prepared_at <= r.began_at);
assert!(r.began_at <= r.finished_at);
// NB[btv] -- It would be a bit nicer if we could separately mock
// both the start and end time, but the `NowFn` mechanism doesn't
// appear to give us any way to do that. Instead, let's just check
// that none of these statements took longer than 5s wall-clock time.
assert!(r.finished_at - r.began_at <= chrono::Duration::try_seconds(5).unwrap());
if !r.sql.is_empty() {
let expected_redacted = mz_sql::parse::parse(&r.sql)
.unwrap()
.into_element()
.ast
.to_ast_string_redacted();
assert_eq!(r.redacted_sql, expected_redacted);
for constant in constants {
assert!(!r.redacted_sql.contains(constant));
}
}
}
}
#[mz_ore::test]
#[allow(clippy::disallowed_methods)]
fn test_statement_logging_basic() {
let (server, mut client) = setup_statement_logging(1.0, 1.0, "");
client.execute("SELECT 1", &[]).unwrap();
// We test that queries of this view execute on a cluster.
// If we ever change the threshold for constant folding such that
// this gets to run on environmentd, change this query.
client
.execute(
"CREATE VIEW v AS SELECT * FROM generate_series(1, 10001)",
&[],
)
.unwrap();
client.execute("SELECT * FROM v", &[]).unwrap();
client.execute("CREATE DEFAULT INDEX i ON v", &[]).unwrap();
client.execute("SELECT * FROM v", &[]).unwrap();
let _ = client.execute("SELECT 1/0", &[]);
client.execute("CREATE TABLE t (x int)", &[]).unwrap();
client.execute("SELECT * FROM t", &[]).unwrap();
#[derive(Debug)]
struct Record {
sample_rate: f64,
began_at: DateTime<Utc>,
finished_at: DateTime<Utc>,
finished_status: String,
error_message: Option<String>,
prepared_at: DateTime<Utc>,
execution_strategy: Option<String>,
result_size: Option<i64>,
rows_returned: Option<i64>,
execution_timestamp: Option<u64>,
}
let mut client = server.connect_internal(postgres::NoTls).unwrap();
let result = Retry::default()
.max_duration(Duration::from_secs(30))
.retry(|_| {
let sl_results = client
.query(
"SELECT
mseh.sample_rate,
mseh.began_at,
mseh.finished_at,
mseh.finished_status,
mseh.error_message,
mpsh.prepared_at,
mseh.execution_strategy,
mseh.result_size,
mseh.rows_returned,
mseh.execution_timestamp
FROM
mz_internal.mz_statement_execution_history AS mseh
LEFT JOIN
mz_internal.mz_prepared_statement_history AS mpsh
ON mseh.prepared_statement_id = mpsh.id
JOIN
(SELECT DISTINCT sql, sql_hash, redacted_sql FROM mz_internal.mz_sql_text) AS mst
ON mpsh.sql_hash = mst.sql_hash
WHERE (mst.sql ~~ 'SELECT%'
AND mst.sql !~~ '%unique string to prevent this query showing up in results after retries%'
AND mst.sql !~~ '%pg_catalog.pg_type%' --this gets executed behind the scenes by tokio-postgres
OR mst.sql ~~ 'CREATE TABLE%')
AND mseh.finished_at IS NOT NULL
ORDER BY mseh.began_at",
&[],
)
.unwrap();
if sl_results.len() == 6 {
Ok(sl_results)
} else {
Err(sl_results.len())
}
});
let sl_results = match result {
Ok(rows) => rows
.into_iter()
.map(|r| Record {
sample_rate: r.get(0),
began_at: r.get(1),
finished_at: r.get(2),
finished_status: r.get(3),
error_message: r.get(4),
prepared_at: r.get(5),
execution_strategy: r.get(6),
result_size: r.get(7),
rows_returned: r.get(8),
execution_timestamp: r.get::<_, Option<UInt8>>(9).map(|UInt8(val)| val),
})
.collect::<Vec<_>>(),
Err(rows) => {
panic!("number of results never became correct: {rows}");
}
};
// The two queries on generate_series(1,10001) execute at the maximum timestamp
assert_eq!(
sl_results
.iter()
.filter(|r| r.execution_timestamp == Some(u64::MAX))
.count(),
2
);
// The two queries that can be satisfied by envd (SELECT 1 and SELECT 1/0) have no execution timestamp
assert_eq!(
sl_results
.iter()
.filter(|r| r.execution_timestamp.is_none())
.count(),
2
);
// All other queries have an execution timestamp, in particular, including `CREATE TABLE`.
assert_eq!(sl_results.len(), 6);
for r in &sl_results {
assert_eq!(r.sample_rate, 1.0);
assert!(r.prepared_at <= r.began_at);
assert!(r.began_at <= r.finished_at);
// It would be nice to be able to control
// execution timestamp via a `NowFn`, but
// that is hard to get right and interferes with our logic
// about when to flush to persist. So instead, just check that they're sane.
if let Some(ts) = r.execution_timestamp {
if ts != u64::MAX {
let ts = to_datetime(ts);
assert!((ts - r.prepared_at).abs() < chrono::Duration::try_seconds(5).unwrap())
}
}
}
assert!(sl_results[0].result_size.unwrap_or(0) > 0);
assert_eq!(sl_results[0].rows_returned, Some(1));
assert_eq!(sl_results[0].finished_status, "success");
assert_eq!(
sl_results[0].execution_strategy.as_ref().unwrap(),
"constant"
);
assert!(sl_results[1].result_size.unwrap_or(0) > 0);
assert_eq!(sl_results[1].rows_returned, Some(10001));
assert_eq!(sl_results[1].finished_status, "success");
assert_eq!(
sl_results[1].execution_strategy.as_ref().unwrap(),
"standard"
);
assert!(sl_results[2].result_size.unwrap_or(0) > 0);
assert_eq!(sl_results[2].rows_returned, Some(10001));
assert_eq!(sl_results[2].finished_status, "success");
assert_eq!(
sl_results[2].execution_strategy.as_ref().unwrap(),
"fast-path"
);
assert_eq!(sl_results[3].finished_status, "error");
assert!(
sl_results[3]
.error_message
.as_ref()
.unwrap()
.contains("division by zero")
);
assert_none!(sl_results[3].result_size);
assert_none!(sl_results[3].rows_returned);
// Verify metrics show all statements were sampled (100% sample rate means no unsampled).
let (sampled_true, sampled_false) = get_statement_logging_record_counts(&server);
assert!(
sampled_true > 0,
"some statements should be sampled with 100% rate"
);
assert_eq!(
sampled_false, 0,
"no statements should be unsampled with 100% rate"
);
// Verify statement_logging_actual_bytes metric is being tracked.
// With 100% sample rate, actual_bytes should equal unsampled_bytes.
let metrics = server.metrics_registry().gather();
let actual_bytes = metrics
.iter()
.find(|m| m.name() == "mz_statement_logging_actual_bytes")
.expect("mz_statement_logging_actual_bytes metric should exist")
.get_metric()[0]
.get_counter()
.value();
let unsampled_bytes = metrics
.iter()
.find(|m| m.name() == "mz_statement_logging_unsampled_bytes")
.expect("mz_statement_logging_unsampled_bytes metric should exist")
.get_metric()[0]
.get_counter()
.value();
assert!(
actual_bytes > 0.0,
"actual_bytes should be > 0 with 100% sample rate"
);
assert_eq!(
actual_bytes, unsampled_bytes,
"with 100% sample rate, actual_bytes should equal unsampled_bytes"
);
}
#[allow(clippy::disallowed_methods)]
fn run_throttling_test(use_prepared_statement: bool) {
// The `target_data_rate` should be
// - high enough so that the `SELECT 1` queries get throttled (even with high CPU load due to
// other tests running in parallel),
// - but low enough that the `SELECT 2` query after the sleep doesn't get throttled.
let (server, mut client) = setup_statement_logging(1.0, 1.0, "200");
thread::sleep(Duration::from_secs(2));
if use_prepared_statement {
let statement = client.prepare("SELECT 1").unwrap();
for _ in 0..100 {
client.execute(&statement, &[]).unwrap();
}
} else {
for _ in 0..100 {
client.execute("SELECT 1", &[]).unwrap();
}
}
thread::sleep(Duration::from_secs(4));
client.execute("SELECT 2", &[]).unwrap();
let mut client = server.connect_internal(postgres::NoTls).unwrap();
let logs = Retry::default()
.max_duration(Duration::from_secs(60))
.retry(|_| {
let sl_results = client
.query(
"SELECT
sql,
throttled_count
FROM mz_internal.mz_statement_execution_history mseh
JOIN mz_internal.mz_prepared_statement_history mpsh
ON mseh.prepared_statement_id = mpsh.id
JOIN (SELECT DISTINCT sql, sql_hash, redacted_sql FROM mz_internal.mz_sql_text) mst
ON mpsh.sql_hash = mst.sql_hash
WHERE sql IN ('SELECT 1', 'SELECT 2')",
&[],
)
.unwrap();
if sl_results.iter().any(|stmt| {
let sql: String = stmt.get(0);
sql == "SELECT 2"
}) {
Ok(sl_results)
} else {
Err(())
}
})
.expect("Never saw last statement (`SELECT 2`)");
let throttled_count = logs
.iter()
.map(|log| {
let UInt8(throttled_count) = log.get(1);
throttled_count
})
.sum::<u64>();
assert!(
throttled_count > 0,
"at least some statements should have been throttled"
);
assert_eq!(logs.len() + usize::cast_from(throttled_count), 101);
}
#[mz_ore::test]
fn test_statement_logging_throttling() {
run_throttling_test(false);
}
#[mz_ore::test]
fn test_statement_logging_prepared_statement_throttling() {
run_throttling_test(true);
}
#[mz_ore::test]
#[allow(clippy::disallowed_methods)]
fn test_statement_logging_subscribes() {
let (server, mut client) = setup_statement_logging(1.0, 1.0, "");
let cancel_token = client.cancel_token();
// This should finish
client
.execute(
"SUBSCRIBE TO (SELECT * FROM generate_series(1, 10001))",
&[],
)
.unwrap();
let handle = thread::spawn(move || {
client.execute("CREATE TABLE t (x int)", &[]).unwrap();
// This should not finish until it's canceled.
let _ = client.execute("SUBSCRIBE TO (SELECT * FROM t)", &[]);
});
while !handle.is_finished() {
thread::sleep(Duration::from_secs(1));
cancel_token.cancel_query(postgres::NoTls).unwrap();
}
handle.join().unwrap();
let mut client = server.connect_internal(postgres::NoTls).unwrap();
let seh_query = "
SELECT
mseh.sample_rate,
mseh.began_at,
mseh.finished_at,
mseh.finished_status,
mpsh.prepared_at,
mseh.execution_strategy
FROM mz_internal.mz_statement_execution_history AS mseh
LEFT JOIN
mz_internal.mz_prepared_statement_history AS mpsh
ON mseh.prepared_statement_id = mpsh.id
JOIN
mz_internal.mz_sql_text AS mst
ON mpsh.sql_hash = mst.sql_hash
WHERE
mst.sql ~~ 'SUBSCRIBE%' AND
mseh.finished_at IS NOT NULL
ORDER BY mseh.began_at";
// Statement logging happens async, retry until we get the expected number of logged
// statements.
let mut sl = Vec::new();
for _ in 0..10 {
thread::sleep(Duration::from_secs(1));
sl = client.query(seh_query, &[]).unwrap();
if sl.len() >= 2 {
break;
}
}
assert_eq!(sl.len(), 2);
struct Record {
sample_rate: f64,
began_at: DateTime<Utc>,
finished_at: DateTime<Utc>,
finished_status: String,
prepared_at: DateTime<Utc>,
execution_strategy: Option<String>,
}
let sl_subscribes = sl
.into_iter()
.map(|r| Record {
sample_rate: r.get(0),
began_at: r.get(1),
finished_at: r.get(2),
finished_status: r.get(3),
prepared_at: r.get(4),
execution_strategy: r.get(5),
})
.collect::<Vec<_>>();
for r in &sl_subscribes {
assert_eq!(r.sample_rate, 1.0);
assert!(r.prepared_at <= r.began_at);
assert!(r.began_at <= r.finished_at);
assert_none!(r.execution_strategy);
}
assert_eq!(sl_subscribes[0].finished_status, "success");
assert_eq!(sl_subscribes[1].finished_status, "canceled");
}
/// Test that we are sampling approximately 50% of statements.
/// Relies on two assumptions:
/// (1) that the effective sampling rate for the session is 50%,
/// (2) that we are using the deterministic testing RNG.
#[allow(clippy::disallowed_methods)]
fn test_statement_logging_sampling_inner(
server: TestServerWithStatementLoggingChecks,
mut client: postgres::Client,
) {
for i in 0..50 {
client.execute(&format!("SELECT {i}"), &[]).unwrap();
// Enforce a small delay to avoid duplicate `began_at` times, which would make the ordering
// of logged statements non-deterministic when we retrieve them below.
thread::sleep(Duration::from_millis(10));
}
// 23 randomly sampled out of 50 with 50% sampling. Seems legit!
let expected_sqls = [
2, 4, 5, 6, 9, 15, 17, 18, 19, 20, 21, 23, 24, 25, 31, 32, 33, 36, 37, 42, 46,
]
.into_iter()
.map(|i| format!("SELECT {i}"))
.collect::<Vec<_>>();
let mut internal_client = server.connect_internal(postgres::NoTls).unwrap();
let seh_query = "
SELECT mst.sql
FROM mz_internal.mz_statement_execution_history AS mseh
JOIN
mz_internal.mz_prepared_statement_history AS mpsh
ON mseh.prepared_statement_id = mpsh.id
JOIN
mz_internal.mz_sql_text AS mst
ON mpsh.sql_hash = mst.sql_hash
WHERE mst.sql ~~ 'SELECT%' AND mst.sql !~~ '%mz_statement_execution_history%'
ORDER BY mseh.began_at ASC";
// Statement logging happens async, retry until we get the expected number of logged
// statements.
let mut sl = Vec::new();
for _ in 0..10 {
thread::sleep(Duration::from_secs(1));
sl = internal_client.query(seh_query, &[]).unwrap();
if sl.len() >= expected_sqls.len() {
break;
}
}
let sqls: Vec<String> = sl.into_iter().map(|r| r.get(0)).collect();
assert_eq!(sqls, expected_sqls);
// Verify the statement_logging_record_count metric correctly tracks sampled vs unsampled.
// With 50% sampling and deterministic RNG, exactly 21 of 50 statements should be sampled.
let (sampled_true, sampled_false) = get_statement_logging_record_counts(&server);
assert_eq!(
sampled_true, 21,
"expected 21 statements to be sampled with 50% rate and deterministic RNG"
);
assert_eq!(
sampled_false, 29,
"expected 29 statements to not be sampled with 50% rate and deterministic RNG"
);
}
#[mz_ore::test]
fn test_statement_logging_sampling() {
let (server, client) = setup_statement_logging(1.0, 0.5, "");
test_statement_logging_sampling_inner(server, client);
}
/// Test that we are not allowed to set `statement_logging_sample_rate`
/// arbitrarily high, but that it is constrained by `statement_logging_max_sample_rate`.
#[mz_ore::test]
fn test_statement_logging_sampling_constrained() {
let (server, client) = setup_statement_logging(0.5, 1.0, "");
test_statement_logging_sampling_inner(server, client);
}
/// Test that the `mz_statement_logging_unsampled_bytes` metric tracks the total bytes
/// of SQL text that would have been logged if statement logging were fully enabled.
/// We set `sample_rate=0.0` so no statements are actually sampled/logged, but the
/// unsampled_bytes metric still gets incremented for every executed statement.
#[mz_ore::test]
#[allow(clippy::disallowed_methods)]
fn test_statement_logging_unsampled_metrics() {
// Use sample_rate=0.0 so statements are not sampled, but unsampled_bytes metric is still tracked.
let (server, mut client) = setup_statement_logging(1.0, 0.0, "");
let batch_queries = [
"SELECT 'Hello, world!';SELECT 1;;",
"SELECT 'Hello, world again!'",
];
let batch_total: usize = batch_queries
.iter()
.map(|s| s.as_bytes().iter().filter(|&&ch| ch != b';').count())
.sum();
let single_queries = ["SELECT 'foo'", "SELECT 'bar';;;"];
let single_total: usize = single_queries
.iter()
.map(|s| s.as_bytes().iter().filter(|&&ch| ch != b';').count())
.sum();
let prepared_queries = ["SELECT 'baz';;;", "SELECT 'quux';"];
let prepared_total: usize = prepared_queries
.iter()
.map(|s| s.as_bytes().iter().filter(|&&ch| ch != b';').count())
.sum();
let named_prepared_inner = "SELECT 42";
let named_prepared_outer = format!("PREPARE p AS {named_prepared_inner};EXECUTE p;");
let named_prepared_outer_len = named_prepared_outer
.as_bytes()
.iter()
.filter(|&&ch| ch != b';')
.count();
for q in batch_queries {
client.batch_execute(q).unwrap();
}
for q in single_queries {
client.execute(q, &[]).unwrap();
}
for q in prepared_queries {
let s = client.prepare(q).unwrap();
client.execute(&s, &[]).unwrap();
}
client.batch_execute(&named_prepared_outer).unwrap();
// This should NOT be logged, since we never actually execute it.
client.prepare("SELECT 'Hello, not counted!'").unwrap();
let expected_total = batch_total + single_total + prepared_total + named_prepared_outer_len;
let metric_value = server
.metrics_registry()
.gather()
.into_iter()
.find(|m| m.name() == "mz_statement_logging_unsampled_bytes")
.unwrap()
.take_metric()[0]
.get_counter()
.value();
let metric_value = usize::cast_from(u64::try_cast_from(metric_value).unwrap());
assert_eq!(expected_total, metric_value);
// Also verify that statement_logging_record_count shows all statements as not sampled
// (since we're using 0% sample rate).
let (sampled_true, _sampled_false) = get_statement_logging_record_counts(&server);
assert_eq!(
sampled_true, 0,
"no statements should be sampled with 0% sample rate"
);
}
#[mz_ore::test]
#[allow(clippy::disallowed_methods)]
fn test_enable_internal_statement_logging() {
let (server, mut client) = setup_statement_logging_core(