Dever v0.0.2
This commit is contained in:
commit
e6e175ebcf
816 files changed
+120349
No files matched your search
@@ -0,0 +1,27 @@
|
||||
//! 同一原生缓存预算分别核对起始与增长后的工作集,不更改业务负载或验收门槛。
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
#[ignore = "two-minute SQLite page-cache diagnostic with 1048576 initial Model rows"]
|
||||
fn bounded_small_cache_contention() {
|
||||
small_cache("api-tenant-cache-small", 32768);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "two-minute SQLite page-cache diagnostic with 3200000 initial Model rows"]
|
||||
fn bounded_small_cache_growth() {
|
||||
small_cache("api-tenant-cache-small-grown", 100000);
|
||||
}
|
||||
|
||||
fn small_cache(label: &str, rows: i64) {
|
||||
let config = Config {
|
||||
rows,
|
||||
http_connections: 8,
|
||||
..Config::contention()
|
||||
};
|
||||
super::exercise(
|
||||
label,
|
||||
serde_json::json!({"type":"sqlite","path":"data/control.db","tenant_directory":"data/tenants","max_connections":2,"cache_size_kib":64}),
|
||||
Run::Load(config),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
//! 固定窗口统计和大型负载门槛;失败前也保存原始样本,不混入预热或预期拒绝。
|
||||
use super::*;
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::collections::BTreeMap;
|
||||
mod process;
|
||||
pub(super) use process::ProcessSamples;
|
||||
|
||||
pub(super) fn pin_cpus(server: &Server, replica: Option<&Server>) {
|
||||
assert_eq!(
|
||||
fs::read_to_string("/sys/fs/cgroup/cpu.max").unwrap().trim(),
|
||||
"400000 100000"
|
||||
);
|
||||
assert_eq!(
|
||||
fs::read_to_string("/sys/fs/cgroup/memory.max")
|
||||
.unwrap()
|
||||
.trim(),
|
||||
"8589934592"
|
||||
);
|
||||
let list =
|
||||
std::env::var("DEVER_TEST_LOAD_CPUS").expect("set DEVER_TEST_LOAD_CPUS to four CPU IDs");
|
||||
let cpus: [u32; 4] = list
|
||||
.split(',')
|
||||
.map(str::parse::<u32>)
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.expect("parse DEVER_TEST_LOAD_CPUS")
|
||||
.try_into()
|
||||
.expect("DEVER_TEST_LOAD_CPUS requires four CPU IDs");
|
||||
let mut distinct = cpus;
|
||||
distinct.sort_unstable();
|
||||
assert!(distinct.windows(2).all(|pair| pair[0] != pair[1]));
|
||||
let [first, second, third, driver] = cpus;
|
||||
let service = if replica.is_some() {
|
||||
list
|
||||
} else {
|
||||
format!("{first},{second},{third}")
|
||||
};
|
||||
let driver = driver.to_string();
|
||||
let processes = [Some(server), replica]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|server| (server.child.id(), &service))
|
||||
.chain([(std::process::id(), &driver)]);
|
||||
for (pid, affinity) in processes {
|
||||
success(
|
||||
Command::new("taskset")
|
||||
.args(["-apc", affinity, &pid.to_string()])
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
}
|
||||
println!("Load CPU affinity: server={service}, driver={driver}");
|
||||
}
|
||||
|
||||
pub(super) fn finish(
|
||||
config: Config,
|
||||
root: &Path,
|
||||
binary: &Path,
|
||||
elapsed: Duration,
|
||||
processes: ProcessSamples,
|
||||
samples: &[Samples],
|
||||
) -> serde_json::Value {
|
||||
let ProcessSamples {
|
||||
combined: resources,
|
||||
replicas,
|
||||
postgres,
|
||||
..
|
||||
} = processes;
|
||||
let warmup_ms = config.warmup_seconds * 1000;
|
||||
let measured = |time: u64| {
|
||||
time >= warmup_ms && (config.seconds == 0 || time < warmup_ms + config.seconds * 1000)
|
||||
};
|
||||
let mut windows: BTreeMap<u64, (Vec<u64>, usize)> = BTreeMap::new();
|
||||
let mut successful = Vec::new();
|
||||
let mut rejected = 0;
|
||||
for (time, latency, status) in samples.iter().flat_map(|sample| &sample.latency) {
|
||||
if !measured(*time) {
|
||||
continue;
|
||||
}
|
||||
let (window, conflicts) = windows.entry((time - warmup_ms) / 60000).or_default();
|
||||
if *status == 200 {
|
||||
successful.push(*latency);
|
||||
window.push(*latency);
|
||||
} else {
|
||||
assert_eq!(*status, 409);
|
||||
rejected += 1;
|
||||
*conflicts += 1;
|
||||
}
|
||||
}
|
||||
successful.sort_unstable();
|
||||
let quantile = |values: &[u64], p: usize| values[(values.len() * p).div_ceil(100) - 1];
|
||||
let duration = if config.seconds == 0 {
|
||||
elapsed.as_secs_f64()
|
||||
} else {
|
||||
config.seconds as f64
|
||||
};
|
||||
let windows: Vec<_> = windows
|
||||
.into_iter()
|
||||
.map(|(index, (mut times, conflicts))| {
|
||||
times.sort_unstable();
|
||||
let seconds = (duration - index as f64 * 60.0).min(60.0);
|
||||
serde_json::json!({"index":index,"seconds":seconds,"successes":times.len(),
|
||||
"expected_conflicts":conflicts,"success_throughput":times.len() as f64/seconds,
|
||||
"p50_ns":quantile(×,50),"p95_ns":quantile(×,95),"p99_ns":quantile(×,99)})
|
||||
})
|
||||
.collect();
|
||||
let measured_resources: Vec<_> = resources
|
||||
.iter()
|
||||
.filter(|sample| measured(sample["elapsed_ms"].as_u64().unwrap()))
|
||||
.collect();
|
||||
let peak = |field: &str| {
|
||||
measured_resources
|
||||
.iter()
|
||||
.map(|sample| sample[field].as_u64().unwrap())
|
||||
.max()
|
||||
.unwrap()
|
||||
};
|
||||
let midpoint = warmup_ms + (duration * 500.0) as u64;
|
||||
let (first, second): (Vec<_>, Vec<_>) = measured_resources
|
||||
.iter()
|
||||
.partition(|sample| sample["elapsed_ms"].as_u64().unwrap() < midpoint);
|
||||
let rss_median = |samples: Vec<&&serde_json::Value>| {
|
||||
median(
|
||||
samples
|
||||
.iter()
|
||||
.map(|sample| sample["rss_kib"].as_u64().unwrap())
|
||||
.collect(),
|
||||
)
|
||||
};
|
||||
let first_rss = rss_median(first);
|
||||
let second_rss = rss_median(second);
|
||||
let slope_ok = first_rss
|
||||
.zip(second_rss)
|
||||
.is_some_and(|(first, second)| second <= first * 1.10);
|
||||
let resource_ok =
|
||||
peak("rss_kib") <= 262144 && peak("descriptors") <= 512 && peak("threads") <= 32;
|
||||
let windows_ok = windows.iter().all(|window| {
|
||||
window["success_throughput"].as_f64().unwrap() >= 1000.0
|
||||
&& window["p99_ns"].as_u64().unwrap() <= 200000000
|
||||
});
|
||||
let slo_ok = windows.len() == 60
|
||||
&& measured_resources.len() >= 3600
|
||||
&& resource_ok
|
||||
&& slope_ok
|
||||
&& windows_ok;
|
||||
let digest = |path: &Path| format!("{:x}", Sha256::digest(fs::read(path).unwrap()));
|
||||
let setting: serde_json::Value =
|
||||
serde_json::from_slice(&fs::read(root.join("config/setting.json")).unwrap()).unwrap();
|
||||
// 大量逐请求样本单独写一次,后续更新业务核对状态时只重写小型摘要。
|
||||
let raw = root.join("load-samples.json");
|
||||
let mut output = std::io::BufWriter::new(fs::File::create(&raw).unwrap());
|
||||
serde_json::to_writer(
|
||||
&mut output,
|
||||
&samples
|
||||
.iter()
|
||||
.map(|sample| &sample.latency)
|
||||
.collect::<Vec<_>>(),
|
||||
)
|
||||
.unwrap();
|
||||
output.into_inner().unwrap();
|
||||
let mut report = serde_json::json!({"config":config,"seconds":duration,"total_seconds":elapsed.as_secs_f64(),
|
||||
"allocation_profiler":std::env::var_os("DEVER_TEST_HEAPTRACK_PRELOAD").map(PathBuf::from),
|
||||
"service_configuration":{"backend":setting["database"]["default"]["type"],"http_limits":setting["http"]["limits"],"tenant":setting["tenant"],
|
||||
"job":setting["job"],"connections_per_pool":setting["database"]["default"]["max_connections"],
|
||||
"sqlite_cache_size_kib_per_connection":setting["database"]["default"]["cache_size_kib"]},
|
||||
"contract":"Real release Dever HTTP/Model tenant project using the recorded backend, signed Cookie, live Provider/roles/component checks; deterministic ten-request cycle: seven full-record page reads, one transaction write, one durable user Job and one expected rollback conflict. Each request opens its own connection through the existing Server helper. Preparation, warmup, queue drain and final SQL verification are outside measured time.",
|
||||
"limitations":"Current Dever only; not a four-way performance result, complete PostgreSQL/Worker/cron matrix or universal large-project readiness. Bounded profiles verify functionality and capacity only; they do not evaluate one-hour SLOs.",
|
||||
"binary_sha256":digest(binary),"compiler_sha256":digest(Path::new(env!("CARGO_BIN_EXE_dever"))),
|
||||
"test_binary_sha256":digest(&std::env::current_exe().unwrap()),
|
||||
"fixture_sha256":format!("{:x}",Sha256::digest(include_str!("../../tenant.rs"))),
|
||||
"load_source_sha256":format!("{:x}",Sha256::digest(include_str!("../load.rs"))),
|
||||
"metrics_source_sha256":format!("{:x}",Sha256::digest(include_str!("metrics.rs"))),
|
||||
"requests":successful.len()+rejected,"successful_requests":successful.len(),
|
||||
"submitted_jobs_including_warmup":samples.iter().map(|sample| sample.jobs).sum::<i64>(),
|
||||
"success_throughput":successful.len() as f64/duration,"expected_conflicts":rejected,
|
||||
"p50_ns":quantile(&successful,50),"p95_ns":quantile(&successful,95),"p99_ns":quantile(&successful,99),
|
||||
"windows":windows,"resources":resources,"peak_rss_kib":peak("rss_kib"),
|
||||
"peak_descriptors":peak("descriptors"),"peak_threads":peak("threads"),
|
||||
"rss_trend":{"first_half_median_kib":first_rss,"second_half_median_kib":second_rss,
|
||||
"ratio":first_rss.zip(second_rss).map(|(first,second)|second/first)},
|
||||
"slo_evaluated":config.evaluate_slo,"performance_slo_passed":if config.evaluate_slo {Some(slo_ok)} else {None},
|
||||
"slo_passed":if config.evaluate_slo {Some(false)} else {None},
|
||||
"slo_targets":{"window_seconds":60,"windows":60,"min_success_qps":1000,"max_p99_ns":200000000,
|
||||
"max_rss_kib":262144,"max_descriptors":512,"max_threads":32,"max_rss_half_median_ratio":1.10},
|
||||
"raw_columns":["completion_ms","latency_ns","status"],"raw_samples_file":"load-samples.json",
|
||||
"functional_verified":false});
|
||||
report["service_instances"] = (1 + usize::from(config.replica)).into();
|
||||
if config.replica {
|
||||
report["replica_resource_samples"] = serde_json::json!(replicas);
|
||||
report["postgres_resource_samples"] = serde_json::json!(postgres);
|
||||
}
|
||||
save(root, &report);
|
||||
println!(
|
||||
"Tenant load measured: {} requests; {}",
|
||||
successful.len() + rejected,
|
||||
root.join("load-results.json").display()
|
||||
);
|
||||
report
|
||||
}
|
||||
|
||||
fn median(mut values: Vec<u64>) -> Option<f64> {
|
||||
if values.is_empty() {
|
||||
return None;
|
||||
}
|
||||
values.sort_unstable();
|
||||
let middle = values.len() / 2;
|
||||
Some(if values.len().is_multiple_of(2) {
|
||||
values[middle - 1] as f64 / 2.0 + values[middle] as f64 / 2.0
|
||||
} else {
|
||||
values[middle] as f64
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rss_median_uses_every_sample_and_does_not_treat_missing_measurements_as_zero() {
|
||||
assert_eq!(median(vec![]), None);
|
||||
assert_eq!(median(vec![100, 130, 110]), Some(110.0));
|
||||
assert_eq!(median(vec![120, 100, 110, 130]), Some(115.0));
|
||||
assert_eq!(median(vec![100, 100, 200]), Some(100.0));
|
||||
}
|
||||
|
||||
pub(super) fn save(root: &Path, report: &serde_json::Value) {
|
||||
fs::write(
|
||||
root.join("load-results.json"),
|
||||
serde_json::to_vec(report).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
//! 两个服务进程的份额单列;PostgreSQL 用 PSS 避免将共享页重复计入。
|
||||
use super::*;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub(in crate::api::tenant::load) struct ProcessSamples {
|
||||
database: Option<u32>,
|
||||
pub(super) combined: Vec<Value>,
|
||||
pub(super) replicas: Vec<[Value; 2]>,
|
||||
pub(super) postgres: Vec<Value>,
|
||||
}
|
||||
|
||||
impl ProcessSamples {
|
||||
pub(in crate::api::tenant::load) fn new(replica: bool) -> Self {
|
||||
Self {
|
||||
database: replica.then(|| {
|
||||
std::env::var("DEVER_TEST_POSTGRES_PID")
|
||||
.unwrap()
|
||||
.parse()
|
||||
.unwrap()
|
||||
}),
|
||||
combined: Vec::new(),
|
||||
replicas: Vec::new(),
|
||||
postgres: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::api::tenant::load) fn sample(
|
||||
&mut self,
|
||||
server: &Server,
|
||||
replica: Option<&Server>,
|
||||
begin: Instant,
|
||||
) -> &Value {
|
||||
let mut combined = resources(server.child.id(), begin);
|
||||
if let Some(replica) = replica {
|
||||
let first = combined.clone();
|
||||
let second = resources(replica.child.id(), begin);
|
||||
for field in [
|
||||
"rss_kib",
|
||||
"anonymous_rss_kib",
|
||||
"file_rss_kib",
|
||||
"data_kib",
|
||||
"threads",
|
||||
"descriptors",
|
||||
"cpu_ticks",
|
||||
] {
|
||||
combined[field] =
|
||||
(first[field].as_u64().unwrap() + second[field].as_u64().unwrap()).into();
|
||||
}
|
||||
self.replicas.push([first, second]);
|
||||
}
|
||||
if let Some(pid) = self.database
|
||||
&& self.combined.len().is_multiple_of(20)
|
||||
{
|
||||
self.postgres.push(database_resources(pid, begin));
|
||||
}
|
||||
self.combined.push(combined);
|
||||
self.combined.last().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
fn database_resources(pid: u32, begin: Instant) -> Value {
|
||||
let parent = pid.to_string();
|
||||
let children = fs::read_to_string(format!("/proc/{pid}/task/{pid}/children")).unwrap();
|
||||
let mut pss = 0;
|
||||
let mut rss = 0;
|
||||
let mut ticks = 0;
|
||||
let mut processes = 0;
|
||||
for (index, pid) in std::iter::once(parent.as_str())
|
||||
.chain(children.split_whitespace())
|
||||
.enumerate()
|
||||
{
|
||||
let read = |file| match fs::read_to_string(format!("/proc/{pid}/{file}")) {
|
||||
// 已退出的后端由 postmaster 的子进程 CPU 计数回收;没有可采样的 RSS。
|
||||
Err(error) if index != 0 && matches!(error.raw_os_error(), Some(2 | 3)) => None,
|
||||
result => Some(result.unwrap()),
|
||||
};
|
||||
let Some(stat) = read("stat") else { continue };
|
||||
ticks += cpu_ticks(&stat, index == 0);
|
||||
let Some(memory) = read("smaps_rollup") else {
|
||||
continue;
|
||||
};
|
||||
let kib = |field| {
|
||||
memory
|
||||
.lines()
|
||||
.find_map(|line| line.strip_prefix(field))
|
||||
.unwrap()
|
||||
.split_whitespace()
|
||||
.next()
|
||||
.unwrap()
|
||||
.parse::<u64>()
|
||||
.unwrap()
|
||||
};
|
||||
pss += kib("Pss:");
|
||||
rss += kib("Rss:");
|
||||
processes += 1;
|
||||
}
|
||||
json!({"elapsed_ms":begin.elapsed().as_millis(),"cpu_ticks":ticks,"pss_kib":pss,
|
||||
"rss_sum_kib":rss,"processes":processes})
|
||||
}
|
||||
|
||||
fn cpu_ticks(stat: &str, include_reaped_children: bool) -> u64 {
|
||||
stat.rsplit_once(')')
|
||||
.unwrap()
|
||||
.1
|
||||
.split_whitespace()
|
||||
.skip(11)
|
||||
.take(if include_reaped_children { 4 } else { 2 })
|
||||
.map(|field| field.parse::<u64>().unwrap())
|
||||
.sum()
|
||||
}
|
||||
|
||||
fn resources(pid: u32, begin: Instant) -> serde_json::Value {
|
||||
let status = fs::read_to_string(format!("/proc/{pid}/status")).unwrap();
|
||||
let field = |name| {
|
||||
status
|
||||
.lines()
|
||||
.find(|line| line.starts_with(name))
|
||||
.unwrap()
|
||||
.split_whitespace()
|
||||
.nth(1)
|
||||
.unwrap()
|
||||
.parse::<u64>()
|
||||
.unwrap()
|
||||
};
|
||||
let descriptors = fs::read_dir(format!("/proc/{pid}/fd")).unwrap().count();
|
||||
let stat = fs::read_to_string(format!("/proc/{pid}/stat")).unwrap();
|
||||
serde_json::json!({"elapsed_ms":begin.elapsed().as_millis(),"rss_kib":field("VmRSS:"),
|
||||
"anonymous_rss_kib":field("RssAnon:"),"file_rss_kib":field("RssFile:"),
|
||||
"data_kib":field("VmData:"),"threads":field("Threads:"),"descriptors":descriptors,
|
||||
"cpu_ticks":cpu_ticks(&stat, false)})
|
||||
}
|
||||
Reference in new issue
Block a user