From c578085840aeaa39b1dfba2bb7496451fe62947a Mon Sep 17 00:00:00 2001 From: Chandler Carruth Date: Fri, 9 Oct 2026 16:58:56 +0000 Subject: [PATCH] Add determinism checks for generated source size and fix a crash (#7917) Benchmarks are only comparable if the source generator produces the same number of lines and bytes for a given configuration with any seed. Test this across many seeds and class shapes, and check it in the compile benchmark for the files it generates. Also check that generation emits every name in its name pools, which the byte count depends on. With field-heavy classes, generation could crash depending on the shuffle. A class becomes a valid type only after its field types are chosen, so references to the last class can only go on its own return and parameter types. When the shuffled pool left more references to it than that, `GetValidTypeName` found no valid type and failed its check. Cap the references to each class at its number of functions and methods, each of which has a return type that can use it, and replace the removed references with fixed types so the byte count stays seed-independent. Assisted-by: Claude Code --- toolchain/benchmarking/compile_benchmark.cpp | 25 ++- toolchain/benchmarking/source_gen.cpp | 42 +++-- toolchain/benchmarking/source_gen_test.cpp | 162 +++++++++++++++++++ 3 files changed, 218 insertions(+), 11 deletions(-) diff --git a/toolchain/benchmarking/compile_benchmark.cpp b/toolchain/benchmarking/compile_benchmark.cpp index d48dadd0b22f..d3594edba31d 100644 --- a/toolchain/benchmarking/compile_benchmark.cpp +++ b/toolchain/benchmarking/compile_benchmark.cpp @@ -298,15 +298,36 @@ static auto BM_CompileApiFileDenseDecls(benchmark::State& state) -> void { double total_lines = 0.0; double total_tokens = 0.0; + ssize_t first_bytes = 0; + ssize_t first_lines = 0; + for (auto _ : llvm::seq(num_files)) { sources.push_back(bench.gen().GenApiFileDenseDecls( target_lines, SourceGen::DenseDeclParams{})); const auto& source = sources.back(); - total_bytes += source.size(); - total_lines += llvm::count(source, '\n'); + ssize_t bytes = source.size(); + ssize_t lines = llvm::count(source, '\n'); + + total_bytes += bytes; + total_lines += lines; if constexpr (L == Lang::Carbon) { total_tokens += carbon_compile_helper.GetTokenizedBuffer(source).size(); } + + // The generator varies each file's content but not its size, which keeps + // results comparable across files and runs. + if (sources.size() == 1) { + first_bytes = bytes; + first_lines = lines; + continue; + } + + CARBON_CHECK(bytes == first_bytes, + "Generated file {0} has {1} bytes but file 0 has {2}.", + sources.size() - 1, bytes, first_bytes); + CARBON_CHECK(lines == first_lines, + "Generated file {0} has {1} lines but file 0 has {2}.", + sources.size() - 1, lines, first_lines); } state.counters["Bytes"] = diff --git a/toolchain/benchmarking/source_gen.cpp b/toolchain/benchmarking/source_gen.cpp index c1e2c196caa7..bf46b3e64297 100644 --- a/toolchain/benchmarking/source_gen.cpp +++ b/toolchain/benchmarking/source_gen.cpp @@ -78,6 +78,7 @@ class SourceGen::ClassGenState { private: auto BuildClassAndTypeNames(SourceGen& gen, int num_classes, int num_types, + int max_refs_per_class, const TypeUseParams& type_use_params) -> void; llvm::SmallVector public_function_param_counts_; @@ -122,11 +123,13 @@ SourceGen::ClassGenState::ClassGenState(SourceGen& gen, int num_classes, gen.GetShuffledInts(num_classes * class_params.private_method_decls, 0, class_params.private_method_decl_params.max_params); + // Each function and method declaration has a return type that can reference + // its own class, so each class has at least this many such type uses. + int decls_per_class = + class_params.public_function_decls + class_params.public_method_decls + + class_params.private_function_decls + class_params.private_method_decls; int num_members = - num_classes * - (class_params.public_function_decls + class_params.public_method_decls + - class_params.private_function_decls + class_params.private_method_decls + - class_params.private_field_decls); + num_classes * (decls_per_class + class_params.private_field_decls); member_names_ = gen.GetShuffledIdentifiers( num_members, /*min_length=*/MinMemberNameLength); int num_params = @@ -135,7 +138,7 @@ SourceGen::ClassGenState::ClassGenState(SourceGen& gen, int num_classes, param_names_ = gen.GetShuffledIdentifiers(num_params); BuildClassAndTypeNames(gen, num_classes, num_members + num_params, - type_use_params); + decls_per_class, type_use_params); } auto SourceGen::ClassGenState::GetValidTypeName() -> llvm::StringRef { @@ -157,6 +160,8 @@ auto SourceGen::ClassGenState::GetValidTypeName() -> llvm::StringRef { return type_names_.pop_back_val(); } + // `BuildClassAndTypeNames` caps the references to each class so that a + // valid type name always remains. CARBON_CHECK(last_type_name_index_ != initial_last_type_name_index, "Failed to find a valid type name with {0} candidates, an " "initial index of {1}, and with {2} classes left to emit!", @@ -187,7 +192,7 @@ auto SourceGen::ClassGenState::GetValidTypeName() -> llvm::StringRef { // declared class names and type references to provide an unpredictable order in // the generated output. auto SourceGen::ClassGenState::BuildClassAndTypeNames( - SourceGen& gen, int num_classes, int num_types, + SourceGen& gen, int num_classes, int num_types, int max_refs_per_class, const TypeUseParams& type_use_params) -> void { // Initially get the sequence of class names without shuffling so we can // compute our type name pool from them prior to any shuffling. @@ -210,15 +215,30 @@ auto SourceGen::ClassGenState::BuildClassAndTypeNames( // class names until there is some remainder of names needed. int num_declared_types = num_types * type_use_params.declared_types_weight / type_weight_sum; - for ([[maybe_unused]] auto _ : llvm::seq(num_declared_types / num_classes)) { + int full_copies = num_declared_types / num_classes; + int remainder = num_declared_types % num_classes; + + // Cap the references to each class so that `GetValidTypeName` finds a valid + // type for any shuffle. A class becomes a valid type after its field types + // are chosen, so references to it can only go on its own return and + // parameter types, or in a later class. The last class defined has only its + // own, and each class has at least `max_refs_per_class` return types. The + // fixed types below replace any references the cap removes, so the pool's + // spellings, and with them the byte count, don't depend on the shuffle. + if (full_copies >= max_refs_per_class) { + full_copies = max_refs_per_class; + remainder = 0; + } + + for ([[maybe_unused]] auto _ : llvm::seq(full_copies)) { llvm::append_range(type_names_, class_names_); } // Now append the remainder number of class names. This is where the class // names being un-shuffled is essential. We're going to have one extra // reference to some fraction of the class names and we want that to be a // stable subset. - type_names_.append(class_names_.begin(), - class_names_.begin() + (num_declared_types % num_classes)); + type_names_.append(class_names_.begin(), class_names_.begin() + remainder); + num_declared_types = full_copies * num_classes + remainder; CARBON_CHECK(static_cast(type_names_.size()) == num_declared_types); // Use each fixed type weight to append the expected number of copies of that @@ -366,6 +386,10 @@ auto SourceGen::GenApiFileDenseDecls(int target_lines, CARBON_CHECK(class_gen_state.private_method_param_counts().empty()); CARBON_CHECK(class_gen_state.class_names().empty()); CARBON_CHECK(class_gen_state.type_names().empty()); + // The identifier lengths in each name pool don't depend on the seed, so + // emitting every name keeps the byte count seed-independent. + CARBON_CHECK(class_gen_state.member_names().empty()); + CARBON_CHECK(class_gen_state.param_names().empty()); return source.TakeStr(); } diff --git a/toolchain/benchmarking/source_gen_test.cpp b/toolchain/benchmarking/source_gen_test.cpp index f0b51146e30a..a33b766cdd61 100644 --- a/toolchain/benchmarking/source_gen_test.cpp +++ b/toolchain/benchmarking/source_gen_test.cpp @@ -36,6 +36,9 @@ using ::testing::Le; using ::testing::MatchesRegex; using ::testing::SizeIs; using ::testing::StrEq; +using ::testing::TestParamInfo; +using ::testing::TestWithParam; +using ::testing::Values; // Tiny helper to sum the sizes of a range of ranges. Uses a template to avoid // hard coding any specific types for the two ranges. @@ -300,5 +303,164 @@ TEST(SourceGenTest, GenApiFileDenseDeclsCppTest) { EXPECT_TRUE(TestCompile(SourceGen::Language::Cpp, source)); } +static auto CountLines(llvm::StringRef source) -> ssize_t { + return llvm::count(source, '\n'); +} + +// Matches a `SourceGen::Language` for which +// `GenApiFileDenseDecls(target_lines, params)` generates files with the same +// byte and line counts using each of `num_seeds` independently seeded +// generators. The files must not all have the same content, which would make +// that match vacuous. +// NOLINTNEXTLINE(modernize-use-trailing-return-type): Macro based function. +MATCHER_P3(GeneratesSeedIndependentSize, target_lines, params, num_seeds, + "generates files of the same size with every seed") { + SourceGen::Language language = arg; + std::string first = + SourceGen(language).GenApiFileDenseDecls(target_lines, params); + bool any_different = false; + for (int i : llvm::seq(1, num_seeds)) { + std::string source = + SourceGen(language).GenApiFileDenseDecls(target_lines, params); + if (source.size() != first.size() || + CountLines(source) != CountLines(first)) { + *result_listener << "where seed iteration " << i << " generated " + << source.size() << " bytes and " << CountLines(source) + << " lines, but seed iteration 0 generated " + << first.size() << " bytes and " << CountLines(first) + << " lines"; + return false; + } + any_different = any_different || source != first; + } + if (!any_different) { + *result_listener << "where all files have the same content"; + return false; + } + return true; +} + +// Each test generates files with one set of parameters, and checks that they +// compile cleanly and have the same size for any seed, which benchmarks need to +// be comparable. Each test runs for both languages. +using GenApiFileDenseDeclsParamsTest = TestWithParam; + +INSTANTIATE_TEST_SUITE_P( + Languages, GenApiFileDenseDeclsParamsTest, + Values(SourceGen::Language::Carbon, SourceGen::Language::Cpp), + [](const TestParamInfo& info) -> std::string { + return info.param == SourceGen::Language::Carbon ? "Carbon" : "Cpp"; + }); + +// Barely enough lines for one class. +TEST_P(GenApiFileDenseDeclsParamsTest, DefaultParamsAt200Lines) { + SourceGen::DenseDeclParams params; + EXPECT_THAT(GetParam(), GeneratesSeedIndependentSize(200, params, 16)); + EXPECT_TRUE(TestCompile( + GetParam(), SourceGen(GetParam()).GenApiFileDenseDecls(200, params))); +} + +TEST_P(GenApiFileDenseDeclsParamsTest, DefaultParamsAt1000Lines) { + SourceGen::DenseDeclParams params; + EXPECT_THAT(GetParam(), GeneratesSeedIndependentSize(1000, params, 16)); + EXPECT_TRUE(TestCompile( + GetParam(), SourceGen(GetParam()).GenApiFileDenseDecls(1000, params))); +} + +TEST_P(GenApiFileDenseDeclsParamsTest, DefaultParamsAt5000Lines) { + SourceGen::DenseDeclParams params; + EXPECT_THAT(GetParam(), GeneratesSeedIndependentSize(5000, params, 16)); + EXPECT_TRUE(TestCompile( + GetParam(), SourceGen(GetParam()).GenApiFileDenseDecls(5000, params))); +} + +TEST_P(GenApiFileDenseDeclsParamsTest, DefaultParamsAt20000Lines) { + SourceGen::DenseDeclParams params; + EXPECT_THAT(GetParam(), GeneratesSeedIndependentSize(20000, params, 16)); + EXPECT_TRUE(TestCompile( + GetParam(), SourceGen(GetParam()).GenApiFileDenseDecls(20000, params))); +} + +// Function declarations only: no methods and no fields. +TEST_P(GenApiFileDenseDeclsParamsTest, OnlyFunctions) { + SourceGen::DenseDeclParams params = { + .class_params = {.public_function_decls = 20, + .public_method_decls = 0, + .private_function_decls = 0, + .private_method_decls = 0, + .private_field_decls = 0}}; + EXPECT_THAT(GetParam(), GeneratesSeedIndependentSize(5000, params, 12)); + EXPECT_TRUE(TestCompile( + GetParam(), SourceGen(GetParam()).GenApiFileDenseDecls(5000, params))); +} + +// Large parameter counts, which wrap onto several lines. +TEST_P(GenApiFileDenseDeclsParamsTest, WrappedParamLists) { + SourceGen::DenseDeclParams params = { + .class_params = {.public_function_decls = 2, + .public_function_decl_params = {.max_params = 16}, + .public_method_decls = 4, + .public_method_decl_params = {.max_params = 16}, + .private_function_decls = 0, + .private_method_decls = 0, + .private_field_decls = 0}}; + EXPECT_THAT(GetParam(), GeneratesSeedIndependentSize(5000, params, 12)); + EXPECT_TRUE(TestCompile( + GetParam(), SourceGen(GetParam()).GenApiFileDenseDecls(5000, params))); +} + +// The default shape scaled up 2x. +TEST_P(GenApiFileDenseDeclsParamsTest, DoubledDefaultShape) { + SourceGen::DenseDeclParams params = { + .class_params = {.public_function_decls = 8, + .public_method_decls = 20, + .private_function_decls = 4, + .private_method_decls = 16, + .private_field_decls = 12}}; + EXPECT_THAT(GetParam(), GeneratesSeedIndependentSize(5000, params, 12)); + EXPECT_TRUE(TestCompile( + GetParam(), SourceGen(GetParam()).GenApiFileDenseDecls(5000, params))); +} + +// A class's fields can't reference it or any later class, so field-heavy +// classes leave few type uses for references to a class. Whether the valid type +// names run out depends on the shuffle, so these tests use many seeds. +TEST_P(GenApiFileDenseDeclsParamsTest, ManyFieldsAndTwoFunctions) { + SourceGen::DenseDeclParams params = { + .class_params = {.public_function_decls = 1, + .public_method_decls = 1, + .private_function_decls = 0, + .private_method_decls = 0, + .private_field_decls = 30}}; + EXPECT_THAT(GetParam(), GeneratesSeedIndependentSize(3000, params, 32)); + EXPECT_TRUE(TestCompile( + GetParam(), SourceGen(GetParam()).GenApiFileDenseDecls(3000, params))); +} + +TEST_P(GenApiFileDenseDeclsParamsTest, ManyFieldsAndOneMethod) { + SourceGen::DenseDeclParams params = { + .class_params = {.public_function_decls = 0, + .public_method_decls = 1, + .private_function_decls = 0, + .private_method_decls = 0, + .private_field_decls = 50}}; + EXPECT_THAT(GetParam(), GeneratesSeedIndependentSize(3000, params, 32)); + EXPECT_TRUE(TestCompile( + GetParam(), SourceGen(GetParam()).GenApiFileDenseDecls(3000, params))); +} + +// No functions or methods, so every type use is a fixed type. +TEST_P(GenApiFileDenseDeclsParamsTest, OnlyFields) { + SourceGen::DenseDeclParams params = { + .class_params = {.public_function_decls = 0, + .public_method_decls = 0, + .private_function_decls = 0, + .private_method_decls = 0, + .private_field_decls = 16}}; + EXPECT_THAT(GetParam(), GeneratesSeedIndependentSize(3000, params, 32)); + EXPECT_TRUE(TestCompile( + GetParam(), SourceGen(GetParam()).GenApiFileDenseDecls(3000, params))); +} + } // namespace } // namespace Carbon::Testing