Add CompatibilityLevel type for backwards-incompatible GN changes

Fuchsia has, on several occasions, broken because of backwards-incompatible changes to gn. Eg. https://gn-review.googlesource.com/c/gn/+/29120

Discussions on that CL and offline have come to the conclusion that
CompatibilityLevel is an acceptable solution for fuchsia.

Change-Id: Iebf66e4a0fd7a9a4b204f1c04dbf82f96a6a6964
Reviewed-on: https://gn-review.googlesource.com/c/gn/+/29500
Reviewed-by: Takuto Ikuta <tikuta@google.com>
Commit-Queue: Matt Stark <msta@google.com>
diff --git a/build/gen.py b/build/gen.py
index a1ed2b5..8e0fbc7 100755
--- a/build/gen.py
+++ b/build/gen.py
@@ -755,6 +755,7 @@
               'src/gn/command_refs.cc',
               'src/gn/command_suggest.cc',
               'src/gn/commands.cc',
+              'src/gn/compatibility_level.cc',
               'src/gn/compile_commands_writer.cc',
               'src/gn/rust_project_writer.cc',
               'src/gn/config.cc',
@@ -920,6 +921,7 @@
         'src/gn/command_format_unittest.cc',
         'src/gn/command_suggest_unittest.cc',
         'src/gn/commands_unittest.cc',
+        'src/gn/compatibility_level_unittest.cc',
         'src/gn/compile_commands_writer_unittest.cc',
         'src/gn/config_unittest.cc',
         'src/gn/config_values_extractors_unittest.cc',
diff --git a/docs/reference.md b/docs/reference.md
index e55a46c..1e117bb 100644
--- a/docs/reference.md
+++ b/docs/reference.md
@@ -7994,6 +7994,18 @@
       rules instead of stamp files whenever possible. This results in smaller
       Ninja build plans, but requires at least Ninja 1.11.
 
+  compatibility_level [optional]
+      An integer specifying the backwards-compatibility level for this project.
+      When GN introduces a backwards-incompatible change, it is gated behind a
+      new compatibility level so projects can opt out until their codebase is
+      updated.
+
+      If not explicitly set, we assume the latest compatibility level.
+
+      Unless we have requests to extend this deadline for a particular
+      compatibility level, GN will generally support old levels for at least 1
+      month (longer for large changes).
+
   experimental_collect_validations_metadata [optional]
       NOTE: This flag is experimental and will be removed in the future.
 
diff --git a/src/gn/build_settings.h b/src/gn/build_settings.h
index f9cda86..7239594 100644
--- a/src/gn/build_settings.h
+++ b/src/gn/build_settings.h
@@ -16,6 +16,7 @@
 #include "base/files/file_path.h"
 #include "gn/args.h"
 #include "gn/check_includes_strict_exceptions.h"
+#include "gn/compatibility_level.h"
 #include "gn/label.h"
 #include "gn/label_pattern.h"
 #include "gn/scope.h"
@@ -189,6 +190,14 @@
     experimental_collect_validations_metadata_ = value;
   }
 
+  // Compatibility level specified in the .gn file.
+  bool SupportsCompatibilityLevel(CompatibilityLevel level) const {
+    return compatibility_level_.supports(level);
+  }
+  void set_compatibility_level(CompatibilityLevel level) {
+    compatibility_level_ = level;
+  }
+
  private:
   Label root_target_label_;
   std::vector<LabelPattern> root_patterns_;
@@ -204,6 +213,7 @@
   Version ninja_required_version_{1, 7, 2};
   bool no_stamp_files_ = true;
   bool experimental_collect_validations_metadata_ = false;
+  CompatibilityLevel compatibility_level_;
 
   SourceFile build_config_file_;
   SourceFile arg_file_template_path_;
diff --git a/src/gn/compatibility_level.cc b/src/gn/compatibility_level.cc
new file mode 100644
index 0000000..cd8905f
--- /dev/null
+++ b/src/gn/compatibility_level.cc
@@ -0,0 +1,54 @@
+// Copyright 2026 The GN Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "gn/compatibility_level.h"
+
+#include <string>
+
+#include "base/strings/string_number_conversions.h"
+#include "gn/value.h"
+
+// static
+Result<CompatibilityLevel> CompatibilityLevel::Parse(const Value* value) {
+  if (!value) {
+    return CompatibilityLevel();
+  }
+
+  RETURN_IF_ERROR(value->VerifyTypeIs(Value::INTEGER));
+  CompatibilityLevel level(value->int_value());
+
+  if (level.level_ < 0) {
+    return Err(*value, "Invalid compatibility_level " +
+                           base::Int64ToString(level.level_) +
+                           " (must be >= 0).");
+  }
+
+  if (level.supports(CompatibilityLevel::kNext)) {
+    return Err(*value,
+               "Unsupported compatibility_level " +
+                   base::Int64ToString(level.level_) + ".",
+               "This version of GN only supports compatibility levels up to " +
+                   base::Int64ToString(CompatibilityLevel::kCurrent) +
+                   ". Please update GN.");
+  }
+
+  if (!level.supports(CompatibilityLevel::kMin)) {
+    std::string help = "The minimum supported compatibility_level is " +
+                       base::Int64ToString(CompatibilityLevel::kMin) +
+                       " (currently requested " +
+                       base::Int64ToString(level.level_) +
+                       ").\nChanges required to upgrade:\n";
+    for (int64_t i = level.level_; i < CompatibilityLevel::kMin; ++i) {
+      help += "  Level " + base::Int64ToString(i) + " -> " +
+              base::Int64ToString(i + 1) + ": " +
+              std::string(kCompatibilityLevels[i]) + "\n";
+    }
+    return Err(*value,
+               "compatibility_level " + base::Int64ToString(level.level_) +
+                   " is no longer supported.",
+               help);
+  }
+
+  return level;
+}
diff --git a/src/gn/compatibility_level.h b/src/gn/compatibility_level.h
new file mode 100644
index 0000000..18d5b9d
--- /dev/null
+++ b/src/gn/compatibility_level.h
@@ -0,0 +1,97 @@
+// Copyright 2026 The GN Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef TOOLS_GN_COMPATIBILITY_LEVEL_H_
+#define TOOLS_GN_COMPATIBILITY_LEVEL_H_
+
+#include <stdint.h>
+
+#include <array>
+#include <cstddef>
+#include <string_view>
+
+#include "gn/err.h"
+
+class Value;
+
+// Represents a GN backwards-compatibility level configured via `.gn`.
+//
+// Process for making backwards-incompatible changes:
+// - File a tracking bug at https://gn.g-issues.chromium.org/issues/new for
+//   deprecating the old compatibility level, and use bugjuggler to assign it
+//   to yourself after the deprecation window has passed (at least 1 month,
+//   longer for large changes).
+// - Add a new enum value (e.g. `kNewLevel`) to `CompatibilityLevel::Level`
+//   immediately before `kNext`.
+// - Gate the backwards-incompatible behavior on
+//   `build_settings->SupportsCompatibilityLevel(CompatibilityLevel::kNewLevel)`,
+//   keeping the previous behavior for older levels.
+// - Add an entry to `kCompatibilityLevels` describing the changes from the
+//   previous level (including the tracking bug URL).
+//
+// Process for removing old compatibility levels / flags (after the deprecation
+// window):
+// - Check the tracking bug for any requests to extend the deprecation deadline.
+// - Delete the oldest enumerator(s) from `CompatibilityLevel::Level` (must be
+//   removed in order).
+// - Add the number of deleted items to `kLastUnsupported`.
+// - Keep old entries in `kCompatibilityLevels` so indices remain aligned with
+//   `Level` values.
+// - Replace `build_settings->SupportsCompatibilityLevel(kRemovedFlag)` with
+//   `true` and simplify code paths.
+class CompatibilityLevel {
+ public:
+  enum Level : int64_t {
+    // The minimum supported level - 1.
+    // This must be incremented when deleting enum entries, and enum entries
+    // must be deleted in order.
+    kLastUnsupported = -1,
+
+    kInitial,
+
+    kNext,
+  };
+
+  static constexpr Level kMin =
+      static_cast<Level>(static_cast<int64_t>(Level::kLastUnsupported) + 1);
+  static constexpr Level kCurrent =
+      static_cast<Level>(static_cast<int64_t>(Level::kNext) - 1);
+
+  constexpr CompatibilityLevel() = default;
+  constexpr CompatibilityLevel(Level level) : level_(level) {}
+
+  // Extracts and validates `compatibility_level` against `[kMin, kCurrent]`.
+  static Result<CompatibilityLevel> Parse(const Value* value);
+
+  constexpr bool supports(CompatibilityLevel other) const {
+    return level_ >= other.level_;
+  }
+
+ private:
+  constexpr explicit CompatibilityLevel(int64_t level)
+      : level_(static_cast<Level>(level)) {}
+
+  // By defaulting to kCurrent, we ensure that any project that does not
+  // explicitly specify `compatibility_level` is pinned to the latest.
+  Level level_ = kCurrent;
+};
+
+// Descriptions of breaking changes between adjacent compatibility levels.
+// Entry `i` describes the changes between compatibility level `i` and `i + 1`.
+inline constexpr std::array<std::string_view,
+                            static_cast<size_t>(CompatibilityLevel::kCurrent)>
+    kCompatibilityLevels = {};
+
+// If we're missing an entry, it will try to default-initialize it. We don't
+// want that.
+static_assert([]() {
+  for (std::string_view desc : kCompatibilityLevels) {
+    if (desc.empty()) {
+      return false;
+    }
+  }
+  return true;
+}());
+
+#endif  // TOOLS_GN_COMPATIBILITY_LEVEL_H_
diff --git a/src/gn/compatibility_level_unittest.cc b/src/gn/compatibility_level_unittest.cc
new file mode 100644
index 0000000..ebfb18d
--- /dev/null
+++ b/src/gn/compatibility_level_unittest.cc
@@ -0,0 +1,76 @@
+// Copyright 2026 The GN Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "gn/compatibility_level.h"
+
+#include <stdint.h>
+
+#include <string>
+
+#include "gn/value.h"
+#include "util/test/test.h"
+
+TEST(CompatibilityLevelTest, ParseDefault) {
+  Result<CompatibilityLevel> result = CompatibilityLevel::Parse(nullptr);
+  ASSERT_TRUE(result.has_value());
+  EXPECT_TRUE(result->supports(CompatibilityLevel::kCurrent));
+  EXPECT_FALSE(result->supports(CompatibilityLevel::kNext));
+}
+
+TEST(CompatibilityLevelTest, ParseInvalidType) {
+  Value value(nullptr, "0");
+  Result<CompatibilityLevel> result = CompatibilityLevel::Parse(&value);
+  ASSERT_TRUE(result.has_error());
+  EXPECT_EQ("This is not a integer.", result.message());
+}
+
+TEST(CompatibilityLevelTest, ParseNegative) {
+  Value value(nullptr, int64_t{-5});
+  Result<CompatibilityLevel> result = CompatibilityLevel::Parse(&value);
+  ASSERT_TRUE(result.has_error());
+  EXPECT_EQ("Invalid compatibility_level -5 (must be >= 0).", result.message());
+}
+
+TEST(CompatibilityLevelTest, ParseLastUnsupported) {
+  Value value(nullptr, CompatibilityLevel::kLastUnsupported);
+  Result<CompatibilityLevel> result = CompatibilityLevel::Parse(&value);
+  ASSERT_TRUE(result.has_error());
+  if (CompatibilityLevel::kLastUnsupported < 0) {
+    EXPECT_EQ("Invalid compatibility_level " +
+                  std::to_string(CompatibilityLevel::kLastUnsupported) +
+                  " (must be >= 0).",
+              result.message());
+  } else {
+    EXPECT_EQ("compatibility_level " +
+                  std::to_string(CompatibilityLevel::kLastUnsupported) +
+                  " is no longer supported.",
+              result.message());
+  }
+}
+
+TEST(CompatibilityLevelTest, ParseMin) {
+  Value value(nullptr, static_cast<int64_t>(CompatibilityLevel::kMin));
+  Result<CompatibilityLevel> result = CompatibilityLevel::Parse(&value);
+  ASSERT_TRUE(result.has_value());
+  EXPECT_TRUE(result->supports(CompatibilityLevel::kMin));
+  EXPECT_FALSE(result->supports(CompatibilityLevel(
+      static_cast<CompatibilityLevel::Level>(CompatibilityLevel::kMin + 1))));
+}
+
+TEST(CompatibilityLevelTest, ParseCurrent) {
+  Value value(nullptr, static_cast<int64_t>(CompatibilityLevel::kCurrent));
+  Result<CompatibilityLevel> result = CompatibilityLevel::Parse(&value);
+  ASSERT_TRUE(result.has_value());
+  EXPECT_TRUE(result->supports(CompatibilityLevel::kCurrent));
+  EXPECT_FALSE(result->supports(CompatibilityLevel::kNext));
+}
+
+TEST(CompatibilityLevelTest, ParseNext) {
+  Value value(nullptr, CompatibilityLevel::kNext);
+  Result<CompatibilityLevel> result = CompatibilityLevel::Parse(&value);
+  ASSERT_TRUE(result.has_error());
+  EXPECT_EQ("Unsupported compatibility_level " +
+                std::to_string(CompatibilityLevel::kNext) + ".",
+            result.message());
+}
diff --git a/src/gn/setup.cc b/src/gn/setup.cc
index f87c82b..9f5dfd6 100644
--- a/src/gn/setup.cc
+++ b/src/gn/setup.cc
@@ -23,6 +23,7 @@
 #include "gn/check_includes_strict_exceptions.h"
 #include "gn/command_format.h"
 #include "gn/commands.h"
+#include "gn/compatibility_level.h"
 #include "gn/exec_process.h"
 #include "gn/filesystem_utils.h"
 #include "gn/input_file.h"
@@ -290,6 +291,18 @@
       rules instead of stamp files whenever possible. This results in smaller
       Ninja build plans, but requires at least Ninja 1.11.
 
+  compatibility_level [optional]
+      An integer specifying the backwards-compatibility level for this project.
+      When GN introduces a backwards-incompatible change, it is gated behind a
+      new compatibility level so projects can opt out until their codebase is
+      updated.
+
+      If not explicitly set, we assume the latest compatibility level.
+
+      Unless we have requests to extend this deadline for a particular
+      compatibility level, GN will generally support old levels for at least 1
+      month (longer for large changes).
+
   experimental_collect_validations_metadata [optional]
       NOTE: This flag is experimental and will be removed in the future.
 
@@ -1080,6 +1093,13 @@
 }
 
 bool Setup::FillOtherConfig(const base::CommandLine& cmdline, Err* err) {
+  // Set the compatibility level as early as possible in the code, so we can
+  // gate other things in the setup on the compatibility level if we choose to.
+  ASSIGN_OR_RETURN_PTR(CompatibilityLevel compatibility_level, err,
+                       CompatibilityLevel::Parse(dotfile_scope_.GetValue(
+                           "compatibility_level", true)));
+  build_settings_.set_compatibility_level(compatibility_level);
+
   SourceDir current_dir("//");
   Label root_target_label(current_dir, "");
   std::vector<LabelPattern> root_patterns;
diff --git a/src/gn/setup_unittest.cc b/src/gn/setup_unittest.cc
index 3df05a0..0a4d26b 100644
--- a/src/gn/setup_unittest.cc
+++ b/src/gn/setup_unittest.cc
@@ -13,6 +13,7 @@
 #include "base/test/scoped_command_line.h"
 #include "gn/builder_record.h"
 #include "gn/commands.h"
+#include "gn/compatibility_level.h"
 #include "gn/filesystem_utils.h"
 #include "gn/switches.h"
 #include "gn/test_with_scheduler.h"
@@ -1145,3 +1146,37 @@
   EXPECT_TRUE(toolchain_ninja.contains("command = python3 -s "));
 }
 #endif  // !defined(OS_WIN)
+
+TEST_F(SetupTest, CompatibilityLevelInDotfile) {
+  base::CommandLine cmdline(base::CommandLine::NO_PROGRAM);
+
+  base::ScopedTempDir in_temp_dir;
+  base::FilePath in_path =
+      CreateSourceRoot(&in_temp_dir,
+                       "buildconfig = \"//BUILDCONFIG.gn\"\n"
+                       "compatibility_level = " +
+                           std::to_string(CompatibilityLevel::kCurrent) + "\n");
+  cmdline.AppendSwitchPath(switches::kRoot, in_path);
+
+  base::ScopedTempDir build_temp_dir;
+  ASSERT_TRUE(build_temp_dir.CreateUniqueTempDir());
+
+  Setup setup;
+  Err err;
+  EXPECT_TRUE(setup.DoSetupWithErr(FilePathToUTF8(build_temp_dir.GetPath()),
+                                   true, cmdline, &err));
+  EXPECT_FALSE(err.has_error());
+  EXPECT_TRUE(setup.build_settings().SupportsCompatibilityLevel(
+      CompatibilityLevel::kCurrent));
+}
+
+TEST_F(SetupTest, InvalidCompatibilityLevelInDotfile) {
+  RunDotfileErrorTest(
+      "buildconfig = \"//BUILDCONFIG.gn\"\n"
+      "compatibility_level = \"x\"\n",
+      "This is not a integer.");
+  RunDotfileErrorTest(
+      "buildconfig = \"//BUILDCONFIG.gn\"\n"
+      "compatibility_level = -1\n",
+      "Invalid compatibility_level -1 (must be >= 0).");
+}