Commit 94948b0b authored by Tobias Koppers's avatar Tobias Koppers

Per function stats

parent 2f7873f8
......@@ -4418,6 +4418,7 @@ dependencies = [
"anyhow",
"clap",
"next-api",
"pot",
"rustc-hash 2.1.1",
"turbo-persistence",
"twox-hash 2.1.0",
......
......@@ -286,6 +286,7 @@ debug = true
[workspace.dependencies]
# Workspace crates
next-swc-napi = { path = "crates/napi" }
next-api = { path = "crates/next-api" }
next-build = { path = "crates/next-build" }
next-core = { path = "crates/next-core" }
......
......@@ -18,6 +18,7 @@ workspace = true
anyhow = { workspace = true }
clap = { workspace = true, features = ["derive"] }
next-api = { workspace = true }
pot = "3.0.0"
rustc-hash = { workspace = true }
turbo-persistence = { workspace = true }
twox-hash = { workspace = true }
use std::{collections::HashMap, hash::Hasher, path::PathBuf};
use std::{
collections::HashMap,
fs,
hash::Hasher,
io::{Write, stdout},
path::PathBuf,
};
use anyhow::{Context, Result, bail};
use clap::Parser;
......@@ -6,6 +12,197 @@ use rustc_hash::FxHashMap;
use turbo_persistence::{OwnedLookupEntry, SerialScheduler, TurboPersistence};
use twox_hash::XxHash64;
/// POT configuration matching the backend's serialization
const POT_CONFIG: pot::Config = pot::Config::new().compatibility(pot::Compatibility::V4);
/// Load the .functions.map file and return a mapping from function ID to function name
fn load_function_names(cache_path: &std::path::Path) -> Result<FxHashMap<u64, String>> {
let functions_map_path = cache_path.join(".functions.map");
if !functions_map_path.exists() {
eprintln!(
"Warning: .functions.map file not found at {}",
functions_map_path.display()
);
return Ok(FxHashMap::default());
}
let content = fs::read_to_string(&functions_map_path)
.with_context(|| format!("Failed to read {}", functions_map_path.display()))?;
let mut map = FxHashMap::default();
for line in content.lines() {
// Each line format: "<id> <name>"
if let Some((id_str, name)) = line.split_once(' ') {
if let Ok(id) = id_str.parse::<u64>() {
map.insert(id, name.to_string());
}
}
}
Ok(map)
}
/// Deserialize a value as pot::Value to extract enum variant names
fn deserialize_as_pot_value(bytes: &[u8]) -> Result<pot::Value<'_>> {
POT_CONFIG
.deserialize(bytes)
.context("Failed to deserialize as pot::Value")
}
/// Extract enum variant name from a pot::Value that represents a CachedDataItem
fn extract_variant_name(value: &pot::Value) -> Result<String> {
// A CachedDataItem enum is serialized as mappings with the variant name as key
if let pot::Value::Mappings(mappings) = value {
if let Some((key, _)) = mappings.first() {
if let pot::Value::String(variant_name) = key {
return Ok(variant_name.to_string());
}
}
}
bail!("Invalid CachedDataItem format")
}
/// Serialize a pot::Value back to bytes and return (bytes, hash)
fn serialize_and_hash_pot_value(value: &pot::Value) -> Result<(Vec<u8>, u64)> {
// Serialize the pot::Value back to bytes
let bytes = POT_CONFIG
.serialize(value)
.context("Failed to serialize pot::Value")?;
// Hash the bytes
let mut hasher = XxHash64::with_seed(0);
hasher.write(&bytes);
let hash = hasher.finish();
Ok((bytes, hash))
}
/// Extract function ID from a CachedTaskType pot::Value
/// CachedTaskType is serialized as a tuple: (FunctionAndArg, this)
/// FunctionAndArg is serialized as a sequence: [function_id, arg]
fn extract_function_id(value: &pot::Value) -> Result<u64> {
// CachedTaskType is serialized as a Sequence (tuple)
if let pot::Value::Sequence(seq) = value {
// First element should be FunctionAndArg (also a sequence)
if let Some(pot::Value::Sequence(function_and_arg)) = seq.first() {
// First element of FunctionAndArg is the function_id
if let Some(function_id_value) = function_and_arg.first() {
// The function_id is an integer - serialize it and deserialize as u64
let id_bytes = POT_CONFIG
.serialize(function_id_value)
.context("Failed to serialize function ID")?;
let id: u64 = POT_CONFIG
.deserialize(&id_bytes)
.context("Failed to deserialize function ID as u64")?;
return Ok(id);
}
}
}
bail!("Could not extract function_id from CachedTaskType")
}
/// Per-variant statistics
#[derive(Default, Debug)]
struct VariantStats {
/// Total count of this variant
count: u64,
/// Total size in bytes
total_size: u64,
/// Map of hash -> (count, size) for deduplication tracking
unique_hashes: FxHashMap<u64, (u64, u64)>,
}
/// Statistics for CachedDataItem variants - using HashMap to avoid hard-coding variants
#[derive(Default, Debug)]
struct CachedDataItemStats {
/// Maps variant name to its statistics
variant_stats: FxHashMap<String, VariantStats>,
}
impl CachedDataItemStats {
fn add_variant(&mut self, variant_name: String, value_hash: u64, size: u64) {
let stats = self
.variant_stats
.entry(variant_name)
.or_insert_with(Default::default);
stats.count += 1;
stats.total_size += size;
// Track unique hashes: increment count and add to total size for this hash
stats
.unique_hashes
.entry(value_hash)
.and_modify(|(count, total_size)| {
*count += 1;
*total_size += size;
})
.or_insert((1, size));
}
fn total(&self) -> u64 {
self.variant_stats.values().map(|s| s.count).sum()
}
}
/// Statistics for ReverseTaskCache function IDs
#[derive(Default, Debug)]
struct FunctionIdStats {
/// Maps function_id to count
function_counts: FxHashMap<u64, u64>,
}
impl FunctionIdStats {
fn add_function(&mut self, function_id: u64) {
*self.function_counts.entry(function_id).or_insert(0) += 1;
}
fn total(&self) -> u64 {
self.function_counts.values().sum()
}
fn top_n(&self, n: usize) -> Vec<(&u64, &u64)> {
let mut entries: Vec<_> = self.function_counts.iter().collect();
entries.sort_by(|a, b| b.1.cmp(a.1).then_with(|| a.0.cmp(b.0)));
entries.into_iter().take(n).collect()
}
}
/// Statistics for TaskMeta/TaskData sizes by function ID
#[derive(Default, Debug)]
struct SizeByFunctionStats {
/// Maps function_id to (total_size, count)
function_stats: FxHashMap<u64, (u64, u64)>,
}
impl SizeByFunctionStats {
fn add_size(&mut self, function_id: u64, size: u64) {
self.function_stats
.entry(function_id)
.and_modify(|(total_size, count)| {
*total_size += size;
*count += 1;
})
.or_insert((size, 1));
}
fn total_size(&self) -> u64 {
self.function_stats.values().map(|(size, _)| size).sum()
}
fn total_count(&self) -> u64 {
self.function_stats.values().map(|(_, count)| count).sum()
}
fn top_n(&self, n: usize) -> Vec<(&u64, &(u64, u64))> {
let mut entries: Vec<_> = self.function_stats.iter().collect();
// Sort by size (descending)
entries.sort_by(|a, b| b.1.0.cmp(&a.1.0).then_with(|| a.0.cmp(b.0)));
entries.into_iter().take(n).collect()
}
}
/// CLI tool for analyzing Next.js Turbopack cache statistics
#[derive(Parser, Debug)]
#[command(name = "next-persistence-tools")]
......@@ -30,6 +227,16 @@ struct FamilyStats {
unique_value_hashes: FxHashMap<u64, (u64, u64)>,
min_entry_size: Option<u64>,
max_entry_size: Option<u64>,
/// CachedDataItem statistics (only for TaskMeta and TaskData families)
cached_data_stats: Option<CachedDataItemStats>,
/// Function ID statistics (only for ReverseTaskCache family)
function_id_stats: Option<FunctionIdStats>,
/// Size by function ID statistics (only for TaskMeta and TaskData families)
size_by_function_stats: Option<SizeByFunctionStats>,
/// Count of entries that failed to deserialize as CachedDataItems
deserialization_failures: u64,
/// First 10 deserialization errors
deserialization_errors: Vec<String>,
}
impl FamilyStats {
......@@ -68,6 +275,60 @@ impl FamilyStats {
);
}
fn process_cached_data_items(&mut self, entry: &OwnedLookupEntry) -> Result<()> {
// Deserialize the value as pot::Value to get a Vec of items
let pot_value = deserialize_as_pot_value(&entry.value)?;
// Expect a sequence (Vec)
let items = match pot_value {
pot::Value::Sequence(seq) => seq,
_ => bail!("Expected a sequence of CachedDataItems"),
};
// Ensure we have stats tracking initialized
let stats = self.cached_data_stats.get_or_insert_with(Default::default);
// Process each item
for item in items {
let variant_name = extract_variant_name(&item)?;
// Serialize the item to get its size and hash
let (bytes, value_hash) = serialize_and_hash_pot_value(&item)?;
let size = bytes.len() as u64;
stats.add_variant(variant_name, value_hash, size);
}
Ok(())
}
fn process_reverse_task_cache(&mut self, entry: &OwnedLookupEntry) -> Result<()> {
// Deserialize the value as pot::Value (it's a CachedTaskType)
let pot_value = deserialize_as_pot_value(&entry.value)?;
// Extract the function ID
let function_id = extract_function_id(&pot_value)?;
// Ensure we have stats tracking initialized
let stats = self.function_id_stats.get_or_insert_with(Default::default);
stats.add_function(function_id);
Ok(())
}
fn track_size_by_function(
&mut self,
entry: &OwnedLookupEntry,
task_to_function_map: &FxHashMap<Vec<u8>, u64>,
) {
// Look up the function ID for this task ID (key)
if let Some(&function_id) = task_to_function_map.get(entry.key.as_ref()) {
let size = entry.value.len() as u64;
let stats = self
.size_by_function_stats
.get_or_insert_with(Default::default);
stats.add_size(function_id, size);
}
}
fn avg_entry_size(&self) -> u64 {
if self.entry_count == 0 {
0
......@@ -128,6 +389,14 @@ fn format_size(bytes: u64) -> String {
}
}
fn format_function_name(function_id: u64, function_names: &FxHashMap<u64, String>) -> String {
function_names
.get(&function_id)
.map(|s| s.as_str())
.unwrap_or("(unknown)")
.to_string()
}
fn main() -> Result<()> {
let args = Args::parse();
......@@ -144,6 +413,42 @@ fn main() -> Result<()> {
TurboPersistence::open_read_only(args.cache_path.clone())
.context("Failed to open TurboPersistence database")?;
// Load function names from .functions.map
let function_names = load_function_names(&args.cache_path)?;
if !function_names.is_empty() {
println!("Loaded {} function names", function_names.len());
println!();
}
// First pass: Build task_id -> function_id map from ReverseTaskCache (family 4)
println!("Building task ID to function ID map from ReverseTaskCache...");
let mut task_to_function_map: FxHashMap<Vec<u8>, u64> = FxHashMap::default();
match db.iter(4, false) {
Ok(iter) => {
for entry_result in iter {
if let Ok(entry) = entry_result {
// Deserialize the value to get the function ID
if let Ok(pot_value) = deserialize_as_pot_value(&entry.value) {
if let Ok(function_id) = extract_function_id(&pot_value) {
// Store task_id (key) -> function_id mapping
task_to_function_map.insert(entry.key.to_vec(), function_id);
}
}
}
}
}
Err(e) => {
eprintln!("Warning: Failed to read ReverseTaskCache: {}", e);
}
}
println!(
"Mapped {} task IDs to function IDs",
task_to_function_map.len()
);
println!();
// Collect statistics for each family
let mut family_stats: HashMap<usize, FamilyStats> = HashMap::new();
let mut total_entries = 0u64;
......@@ -156,6 +461,7 @@ fn main() -> Result<()> {
for family in 0..5 {
let family_name = FAMILY_NAMES.get(family).unwrap_or(&"Unknown");
print!("Processing family {}: {}... ", family, family_name);
stdout().flush().unwrap();
let stats = family_stats.entry(family).or_default();
......@@ -167,6 +473,32 @@ fn main() -> Result<()> {
match entry_result {
Ok(entry) => {
stats.add_entry(&entry);
// For TaskMeta (1) and TaskData (2), also deserialize and analyze
// CachedDataItems and track size by function ID
if family == 1 || family == 2 {
if let Err(e) = stats.process_cached_data_items(&entry) {
stats.deserialization_failures += 1;
// Capture first 10 errors
if stats.deserialization_errors.len() < 10 {
stats.deserialization_errors.push(format!("{:#}", e));
}
}
// Track size by function ID
stats.track_size_by_function(&entry, &task_to_function_map);
}
// For ReverseTaskCache (4), extract function IDs
if family == 4 {
if let Err(e) = stats.process_reverse_task_cache(&entry) {
stats.deserialization_failures += 1;
// Capture first 10 errors
if stats.deserialization_errors.len() < 10 {
stats.deserialization_errors.push(format!("{:#}", e));
}
}
}
family_entries += 1;
total_entries += 1;
}
......@@ -301,6 +633,230 @@ fn main() -> Result<()> {
0.0
};
println!(" % of total: {:.1}%", pct);
// Display deserialization failures for TaskMeta, TaskData, and ReverseTaskCache
if (family == 1 || family == 2 || family == 4) && stats.deserialization_failures > 0 {
println!(
" Deserialization failures: {} ({:.1}% of entries)",
stats.deserialization_failures,
(stats.deserialization_failures as f64 / stats.entry_count as f64) * 100.0
);
if !stats.deserialization_errors.is_empty() {
println!(" First {} error(s):", stats.deserialization_errors.len());
for (i, error) in stats.deserialization_errors.iter().enumerate() {
println!(" {}. {}", i + 1, error);
}
}
}
if let Some(cached_stats) = &stats.cached_data_stats {
println!();
println!(" CachedDataItem Variant Statistics:");
println!(
" ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────"
);
println!(
" {:<30} {:>10} {:>10} {:>12} {:>15} {:>15} {:>15} {:>10}",
"Variant",
"Count",
"Unique",
"Duplication",
"Total Size",
"Avg Size",
"Dup. Size",
"Dup. %"
);
println!(
" ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────"
);
let total = cached_stats.total();
if total > 0 {
// Sort by variant name for consistent output
let mut variants: Vec<_> = cached_stats.variant_stats.iter().collect();
variants.sort_by_key(|(name, _)| *name);
for (variant_name, variant_stats) in variants {
let unique_count = variant_stats.unique_hashes.len();
let duplication_pct = if variant_stats.count > 0 {
(1.0 - unique_count as f64 / variant_stats.count as f64) * 100.0
} else {
0.0
};
let avg_size = if variant_stats.count > 0 {
variant_stats.total_size / variant_stats.count
} else {
0
};
// Calculate duplicated size: for each hash with count > 1,
// the duplicated size is (total_size - size_of_first_occurrence)
let duplicated_size: u64 = variant_stats
.unique_hashes
.values()
.filter_map(|&(count, total_size)| {
if count > 1 {
// Size per occurrence
let size_per_occurrence = total_size / count;
// Duplicated size = total - first occurrence
Some(size_per_occurrence * (count - 1))
} else {
None
}
})
.sum();
let duplicated_size_pct = if variant_stats.total_size > 0 {
(duplicated_size as f64 / variant_stats.total_size as f64) * 100.0
} else {
0.0
};
println!(
" {:<30} {:>10} {:>10} {:>11.1}% {:>15} {:>15} {:>15} {:>9.1}%",
variant_name,
variant_stats.count,
unique_count,
duplication_pct,
format_size(variant_stats.total_size),
format_size(avg_size),
format_size(duplicated_size),
duplicated_size_pct
);
}
println!(
" ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────"
);
println!(" {:<30} {:>10}", "Total Items:", total);
}
}
// Display Size by Function ID statistics for TaskMeta and TaskData
if family == 1 || family == 2 {
if let Some(size_stats) = &stats.size_by_function_stats {
println!();
println!(" Top 20 Functions by Size:");
let total_size = size_stats.total_size();
let total_count = size_stats.total_count();
if total_size > 0 {
let top_functions = size_stats.top_n(20);
// Measure the maximum function name length in top 20
let max_func_len = top_functions
.iter()
.map(|(function_id, _)| {
format_function_name(**function_id, &function_names).len()
})
.max()
.unwrap_or(50)
.max(20); // Minimum width of 20
// Calculate separator length
let separator_len = max_func_len + 4 + 15 + 15 + 6; // padding + two columns + spaces
let separator = "─".repeat(separator_len);
println!(" {}", separator);
println!(
" {:<width$} {:>15} {:>15}",
"Function",
"Count",
"Total Size",
width = max_func_len
);
println!(" {}", separator);
for (function_id, (size, count)) in top_functions {
let func_name = format_function_name(*function_id, &function_names);
println!(
" {:<width$} {:>15} {:>15}",
func_name,
count,
format_size(*size),
width = max_func_len
);
}
println!(" {}", separator);
println!(
" {:<width$} {:>15} {:>15}",
"Total Functions:",
size_stats.function_stats.len(),
"",
width = max_func_len
);
println!(
" {:<width$} {:>15} {:>15}",
"Total:",
total_count,
format_size(total_size),
width = max_func_len
);
}
}
}
// Display Function ID statistics for ReverseTaskCache
if family == 4 {
if let Some(func_stats) = &stats.function_id_stats {
println!();
println!(" Top 20 Functions:");
let total_funcs = func_stats.total();
if total_funcs > 0 {
let top_functions = func_stats.top_n(20);
// Measure the maximum function name length in top 20
let max_func_len = top_functions
.iter()
.map(|(function_id, _)| {
format_function_name(**function_id, &function_names).len()
})
.max()
.unwrap_or(50)
.max(20); // Minimum width of 20
// Calculate separator length
let separator_len = max_func_len + 4 + 15 + 3; // padding + one column + spaces
let separator = "─".repeat(separator_len);
println!(" {}", separator);
println!(
" {:<width$} {:>15}",
"Function",
"Count",
width = max_func_len
);
println!(" {}", separator);
for (function_id, count) in top_functions {
let func_name = format_function_name(*function_id, &function_names);
println!(
" {:<width$} {:>15}",
func_name,
count,
width = max_func_len
);
}
println!(" {}", separator);
println!(
" {:<width$} {:>15}",
"Total Functions:",
func_stats.function_counts.len(),
width = max_func_len
);
println!(
" {:<width$} {:>15}",
"Total Entries:",
total_funcs,
width = max_func_len
);
}
}
}
}
}
......
......@@ -285,6 +285,10 @@ impl<S: ParallelScheduler> TurboPersistence<S> {
for entry in entries {
let entry = entry?;
let path = entry.path();
let file_name = path.file_name();
if file_name.is_some_and(|s| s.as_encoded_bytes().starts_with(b".")) {
continue;
}
if let Some(ext) = path.extension().and_then(|s| s.to_str()) {
let seq: u32 = path
.file_stem()
......@@ -331,17 +335,12 @@ impl<S: ParallelScheduler> TurboPersistence<S> {
// ignore blobs and sst, they are read when needed
}
_ => {
if !path
.file_name()
.is_some_and(|s| s.as_encoded_bytes().starts_with(b"."))
{
bail!("Unexpected file in persistence directory: {:?}", path);
}
}
}
}
} else {
match path.file_stem().and_then(|s| s.to_str()) {
match file_name.and_then(|s| s.to_str()) {
Some("CURRENT") => {
// Already read
}
......@@ -349,16 +348,11 @@ impl<S: ParallelScheduler> TurboPersistence<S> {
// Ignored, write-only
}
_ => {
if !path
.file_name()
.is_some_and(|s| s.as_encoded_bytes().starts_with(b"."))
{
bail!("Unexpected file in persistence directory: {:?}", path);
}
}
}
}
}
meta_files.retain(|seq| !deleted_files.contains(seq));
meta_files.sort_unstable();
......@@ -405,6 +399,11 @@ impl<S: ParallelScheduler> TurboPersistence<S> {
self.inner.read().meta_files.is_empty()
}
/// Returns true if the database is opened in read-only mode.
pub fn is_read_only(&self) -> bool {
self.read_only
}
/// Starts a new WriteBatch for the database. Only a single write operation is allowed at a
/// time. The WriteBatch need to be committed with [`TurboPersistence::commit_write_batch`].
/// Note that the WriteBatch might start writing data to disk while it's filled up with data.
......
use std::{
cmp::max,
fs::OpenOptions,
io::BufWriter,
path::PathBuf,
sync::Arc,
thread::available_parallelism,
......@@ -11,7 +13,9 @@ use parking_lot::Mutex;
use turbo_persistence::{
ArcSlice, CompactConfig, KeyBase, StoreKey, TurboPersistence, ValueBuffer,
};
use turbo_tasks::{JoinHandle, message_queue::TimingEvent, spawn, turbo_tasks};
use turbo_tasks::{
JoinHandle, message_queue::TimingEvent, registry::iter_functions, spawn, turbo_tasks,
};
use crate::database::{
key_value_database::{KeySpace, KeyValueDatabase},
......@@ -41,7 +45,19 @@ pub struct TurboKeyValueDatabase {
impl TurboKeyValueDatabase {
pub fn new(versioned_path: PathBuf, is_ci: bool, is_short_session: bool) -> Result<Self> {
let mappings_path = versioned_path.join(".functions.map");
let db = Arc::new(TurboPersistence::open(versioned_path)?);
if db.is_empty() && !db.is_read_only() {
let mappings_file = OpenOptions::new()
.create(true)
.append(true)
.open(mappings_path)?;
let mut mappings_file = BufWriter::new(mappings_file);
for (id, func) in iter_functions() {
use std::io::Write;
writeln!(mappings_file, "{} {}", *id as u32, func.global_name())?;
}
}
Ok(Self {
db: db.clone(),
compact_join_handle: Mutex::new(None),
......
......@@ -5,7 +5,7 @@
mod backend;
mod backing_storage;
mod data;
pub mod data;
mod data_storage;
mod database;
mod kv_backing_storage;
......
......@@ -237,6 +237,10 @@ impl NativeFunction {
}
}
pub fn global_name(&self) -> &'static str {
self.global_name
}
pub fn span(&'static self, persistence: TaskPersistence, reason: TaskExecutionReason) -> Span {
let flags = match persistence {
TaskPersistence::Persistent => "",
......
......@@ -117,6 +117,13 @@ impl<T: RegistryItem> Registry<T> {
))
}
}
pub fn iter(&self) -> impl Iterator<Item = (T::Id, &'static T)> + '_ {
self.id_to_item
.iter()
.enumerate()
.map(|(i, &item)| (T::Id::from(NonZeroU16::new((i + 1) as u16).unwrap()), item))
}
}
static FUNCTIONS: Lazy<Registry<NativeFunction>> = Lazy::new(|| {
......@@ -139,6 +146,10 @@ pub fn validate_function_id(id: FunctionId) -> Option<Error> {
FUNCTIONS.validate_id(id)
}
pub fn iter_functions() -> impl Iterator<Item = (FunctionId, &'static NativeFunction)> {
FUNCTIONS.iter()
}
static VALUES: Lazy<Registry<ValueType>> = Lazy::new(|| {
// Inventory does not guarantee an order. So we sort by the global name to get a stable order
// This ensures that assigned ids are also stable which is important since they are serialized.
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment