No public description

PiperOrigin-RevId: 1018756182
diff --git a/centipede/BUILD b/centipede/BUILD
index e7c3faf..69e0501 100644
--- a/centipede/BUILD
+++ b/centipede/BUILD
@@ -583,6 +583,36 @@
 )
 
 cc_library(
+    name = "input_metadata_store",
+    srcs = ["input_metadata_store.cc"],
+    hdrs = ["input_metadata_store.h"],
+    deps = [
+        ":environment",
+        ":runner_result",
+        "@abseil-cpp//absl/types:span",
+        "@com_google_fuzztest//common:defs",
+        "@com_google_fuzztest//common:hash",
+        "@com_google_fuzztest//common:logging",
+        "@com_google_fuzztest//common:remote_file",
+    ],
+)
+
+cc_test(
+    name = "input_metadata_store_test",
+    srcs = ["input_metadata_store_test.cc"],
+    deps = [
+        ":environment",
+        ":input_metadata_store",
+        ":runner_result",
+        "@com_google_fuzztest//common:defs",
+        "@com_google_fuzztest//common:hash",
+        "@com_google_fuzztest//common:remote_file",
+        "@com_google_fuzztest//common:test_util",
+        "@googletest//:gtest_main",
+    ],
+)
+
+cc_library(
     name = "centipede_callbacks",
     srcs = ["centipede_callbacks.cc"],
     hdrs = ["centipede_callbacks.h"],
@@ -593,6 +623,7 @@
         ":control_flow",
         ":environment",
         ":fuzztest_mutator",
+        ":input_metadata_store",
         ":mutation_data",
         ":runner_request",
         ":runner_result",
@@ -1567,6 +1598,17 @@
 )
 
 cc_test(
+    name = "runner_request_test",
+    srcs = ["runner_request_test.cc"],
+    deps = [
+        ":runner_request",
+        ":shared_memory_blob_sequence",
+        "@com_google_fuzztest//common:defs",
+        "@googletest//:gtest_main",
+    ],
+)
+
+cc_test(
     name = "runner_result_test",
     srcs = ["runner_result_test.cc"],
     deps = [
@@ -1958,6 +2000,7 @@
         ":stop",
         ":util",
         ":workdir",
+        "@abseil-cpp//absl/container:flat_hash_map",
         "@abseil-cpp//absl/container:flat_hash_set",
         "@abseil-cpp//absl/strings",
         "@abseil-cpp//absl/time",
diff --git a/centipede/centipede.cc b/centipede/centipede.cc
index 0057787..5509a52 100644
--- a/centipede/centipede.cc
+++ b/centipede/centipede.cc
@@ -496,6 +496,69 @@
   bool success = ExecuteAndReportCrash(env_.binary, inputs, batch_result);
   FUZZTEST_CHECK_EQ(mutants.size(), batch_result.results().size());
 
+  const size_t initial_read =
+      std::min(batch_result.num_outputs_read(), inputs.size());
+  size_t total_outputs_read = initial_read;
+  uint64_t batch_peak_rss_mb =
+      initial_read > 0
+          ? batch_result.results()[initial_read - 1].stats().peak_rss_mb
+          : 0;
+
+  // When replaying and continuing after crashes, re-run the inputs after a
+  // single-input failure or a truncated batch, so that one failing input does
+  // not prevent the rest of the batch from being executed.
+  if (env_.fuzztest_only_replay && !env_.exit_on_crash) {
+    // Returns the offset, within a (sub-)batch of `sub_size` inputs, of the
+    // first input that still needs to be executed, or `sub_size` if there is
+    // none.
+    const auto next_tail_offset = [](bool sub_success,
+                                     const BatchResult& sub_result,
+                                     size_t sub_size) -> size_t {
+      const size_t read = sub_result.num_outputs_read();
+      if (!sub_success) {
+        // Skip the failing input. Failures that are not attributable to a
+        // single input (e.g. per-batch timeouts) end the batch.
+        const bool is_single_input_failure =
+            sub_result.IsInputFailure() && sub_result.failure_description() !=
+                                               kExecutionFailurePerBatchTimeout;
+        return is_single_input_failure && read + 1 < sub_size ? read + 1
+                                                              : sub_size;
+      }
+      if (sub_result.exit_code() == EXIT_SUCCESS && read < sub_size) {
+        if (read == 0) {
+          // No progress: give up instead of looping forever.
+          FUZZTEST_LOG(WARNING)
+              << "Batch execution produced no outputs; skipping the remaining "
+              << sub_size << " inputs of the batch";
+          return sub_size;
+        }
+        return read;
+      }
+      return sub_size;
+    };
+
+    for (size_t next = next_tail_offset(success, batch_result, inputs.size());
+         next < inputs.size() && !stop_condition_.ShouldStop();) {
+      const auto sub_inputs = absl::MakeConstSpan(inputs).subspan(next);
+      BatchResult tail_result;
+      const bool tail_success =
+          ExecuteAndReportCrash(env_.binary, sub_inputs, tail_result);
+      success = success && tail_success;
+      const size_t tail_read =
+          std::min(tail_result.num_outputs_read(), sub_inputs.size());
+      total_outputs_read += tail_read;
+      if (tail_read > 0) {
+        batch_peak_rss_mb =
+            std::max(batch_peak_rss_mb,
+                     tail_result.results()[tail_read - 1].stats().peak_rss_mb);
+      }
+      for (size_t j = 0; j < tail_read; ++j) {
+        batch_result.results()[next + j] = std::move(tail_result.results()[j]);
+      }
+      next += next_tail_offset(tail_success, tail_result, sub_inputs.size());
+    }
+  }
+
   for (const auto &extra_binary : env_.extra_binaries) {
     if (stop_condition_.ShouldStop()) break;
     BatchResult extra_batch_result;
@@ -570,16 +633,8 @@
       }
     }
   }
-  num_runs_ += batch_result.num_outputs_read();
-  if (batch_result.num_outputs_read() > 0) {
-    // The reported values increase monotonically within a batch. So it suffices
-    // to look at the last value.
-    execution_peak_rss_mb_ =
-        std::max(execution_peak_rss_mb_,
-                 batch_result.results()[batch_result.num_outputs_read() - 1]
-                     .stats()
-                     .peak_rss_mb);
-  }
+  num_runs_ += total_outputs_read;
+  execution_peak_rss_mb_ = std::max(execution_peak_rss_mb_, batch_peak_rss_mb);
   corpus_.UpdateWeights(fs_, coverage_frontier_, env_.exec_time_weight_scaling);
   return batch_gained_new_coverage;
 }
diff --git a/centipede/centipede_callbacks.cc b/centipede/centipede_callbacks.cc
index 1a79da2..9ceeb28 100644
--- a/centipede/centipede_callbacks.cc
+++ b/centipede/centipede_callbacks.cc
@@ -550,11 +550,25 @@
   outputs_blobseq_.Reset();
 
   size_t num_inputs_written = 0;
+  // The persistent input metadata is exchanged with the primary binary only,
+  // and needs the inputs to be passed via shared memory.
+  const bool use_input_metadata_store = input_metadata_store_.enabled() &&
+                                        binary == env_.binary &&
+                                        !env_.has_input_wildcards;
 
   if (env_.has_input_wildcards) {
     FUZZTEST_CHECK_EQ(inputs.size(), 1);
     WriteToLocalFile(temp_input_file_path_, inputs[0]);
     num_inputs_written = 1;
+  } else if (use_input_metadata_store) {
+    // Feed the inputs, each preceded by its stored persistent metadata (if
+    // any), to inputs_blobseq_.
+    const std::vector<ByteArray> stored_metadata =
+        input_metadata_store_.Load(inputs);
+    const std::vector<ByteSpan> persistent_metadata(stored_metadata.begin(),
+                                                    stored_metadata.end());
+    num_inputs_written =
+        RequestExecution(inputs, persistent_metadata, inputs_blobseq_);
   } else {
     // Feed the inputs to inputs_blobseq_.
     num_inputs_written = RequestExecution(inputs, inputs_blobseq_);
@@ -579,6 +593,11 @@
   const bool read_success = batch_result.Read(outputs_blobseq_);
   FUZZTEST_LOG_IF(ERROR, !read_success) << "Failed to read batch result!";
   outputs_blobseq_.ReleaseSharedMemory();  // Outputs are already consumed.
+  if (use_input_metadata_store) {
+    // Store the persistent metadata of the executed inputs, including those
+    // executed before a failure.
+    input_metadata_store_.Save(inputs.first(num_inputs_written), batch_result);
+  }
 
   // We may have fewer feature blobs than inputs if
   // * some inputs were not written (i.e. num_inputs_written < inputs.size).
diff --git a/centipede/centipede_callbacks.h b/centipede/centipede_callbacks.h
index 38d6bc3..3fc908c 100644
--- a/centipede/centipede_callbacks.h
+++ b/centipede/centipede_callbacks.h
@@ -31,6 +31,7 @@
 #include "./centipede/command.h"
 #include "./centipede/environment.h"
 #include "./centipede/fuzztest_mutator.h"
+#include "./centipede/input_metadata_store.h"
 #include "./centipede/mutation_data.h"
 #include "./centipede/runner_result.h"
 #include "./centipede/shared_memory_blob_sequence.h"
@@ -168,6 +169,9 @@
   StopCondition& stop_condition_;
   ByteArrayMutator byte_array_mutator_;
   FuzzTestMutator fuzztest_mutator_;
+  // Storage of the persistent input metadata of the test. Disabled unless
+  // `env_.fuzztest_persistent_metadata_root` is set.
+  InputMetadataStore input_metadata_store_{env_};
 
  private:
   class PersistentModeServer;
diff --git a/centipede/centipede_flags.inc b/centipede/centipede_flags.inc
index a335b6e..af85197 100644
--- a/centipede/centipede_flags.inc
+++ b/centipede/centipede_flags.inc
@@ -515,6 +515,12 @@
                "The root directory for Centipede workdirs for working on the "
                "corpus database.")
 CENTIPEDE_FLAG(
+    std::string, fuzztest_persistent_metadata_root, "",
+    "If set to non-empty, the root directory for storing the persistent input "
+    "metadata that tests attach to their inputs. The metadata of an input is "
+    "stored under <root>/<fuzztest_binary_identifier>/<test_name>/ and is "
+    "passed back to the test before the next execution of the same input.")
+CENTIPEDE_FLAG(
     std::vector<std::string>, fuzztest_seed_corpus_databases, {},
     "A comma-separated list of read-only corpus databases. When fuzzing with "
     "the corpus database, the coverage inputs of the test in these databases "
diff --git a/centipede/centipede_test.cc b/centipede/centipede_test.cc
index d7fe79a..530ba81 100644
--- a/centipede/centipede_test.cc
+++ b/centipede/centipede_test.cc
@@ -29,6 +29,7 @@
 
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
+#include "absl/container/flat_hash_map.h"
 #include "absl/container/flat_hash_set.h"
 #include "absl/strings/str_cat.h"
 #include "absl/time/clock.h"
@@ -63,7 +64,9 @@
 using ::testing::IsSupersetOf;
 using ::testing::Le;
 using ::testing::Not;
+using ::testing::Pair;
 using ::testing::SizeIs;
+using ::testing::UnorderedElementsAre;
 
 inline std::vector<ByteSpan> AsByteSpans(const std::vector<ByteArray>& inputs) {
   std::vector<ByteSpan> results;
@@ -1280,6 +1283,169 @@
   EXPECT_EQ(batch_result.failure_description(), "stack-limit-exceeded");
 }
 
+// Fails the batch at every input whose only byte is in `crashing_values` (or
+// truncates cleanly after `max_inputs_per_call` inputs when > 0), and counts
+// the successful executions of every input value.
+class FakeTailRerunCallbacks : public CentipedeCallbacks {
+ public:
+  FakeTailRerunCallbacks(const Environment& env,
+                         absl::flat_hash_set<uint8_t> crashing,
+                         size_t max_inputs_per_call = 0,
+                         std::string failure_description = "crash")
+      : CentipedeCallbacks(env, internal_stop_condition_),
+        crashing_values_(std::move(crashing)),
+        max_inputs_per_call_(max_inputs_per_call),
+        failure_description_(std::move(failure_description)) {}
+
+  bool Execute(std::string_view binary, absl::Span<const ByteSpan> inputs,
+               BatchResult& batch_result) override {
+    ++execute_calls_;
+    batch_result.ClearAndResize(inputs.size());
+    const size_t limit = max_inputs_per_call_ > 0
+                             ? std::min(inputs.size(), max_inputs_per_call_)
+                             : inputs.size();
+    for (size_t i = 0; i < limit; ++i) {
+      FUZZTEST_CHECK_EQ(inputs[i].size(), 1);
+      if (crashing_values_.contains(inputs[i][0])) {
+        batch_result.num_outputs_read() = i;
+        batch_result.exit_code() = EXIT_FAILURE;
+        batch_result.failure_description() = failure_description_;
+        return false;
+      }
+      ++num_executions_[inputs[i][0]];
+    }
+    batch_result.num_outputs_read() = limit;
+    return true;
+  }
+
+  // Generates the 1-byte mutants 100, 101, ... (distinct from the seed {0}).
+  std::vector<Mutant> Mutate(absl::Span<const MutationInputRef> inputs,
+                             size_t num_mutants) override {
+    std::vector<Mutant> mutants;
+    mutants.reserve(num_mutants);
+    for (size_t i = 0; i < num_mutants; ++i) {
+      mutants.push_back({/*data=*/{static_cast<uint8_t>(next_value_++)},
+                         Mutant::kOriginNone});
+    }
+    return mutants;
+  }
+
+  const absl::flat_hash_map<uint8_t, int>& num_executions() const {
+    return num_executions_;
+  }
+  int execute_calls() const { return execute_calls_; }
+
+ private:
+  absl::flat_hash_set<uint8_t> crashing_values_;
+  size_t max_inputs_per_call_;
+  std::string failure_description_;
+  absl::flat_hash_map<uint8_t, int> num_executions_;
+  int execute_calls_ = 0;
+  size_t next_value_ = 100;
+  StopCondition internal_stop_condition_;
+};
+
+Environment TailRerunEnv(std::string_view workdir) {
+  Environment env;
+  env.log_level = 0;
+  env.workdir = workdir;
+  env.batch_size = 10;
+  // Seed {0} runs before `num_runs_` is reset, so `num_runs = 10` runs exactly
+  // one mutant batch of 10 inputs (100..109).
+  env.num_runs = 10;
+  env.require_pc_table = false;
+  env.exit_on_crash = false;
+  env.fuzztest_only_replay = true;
+  // Only re-execute the suspect when reporting a crash, so that the counts
+  // below reflect the batch executions.
+  env.batch_triage_suspect_only = true;
+  return env;
+}
+
+TEST(Centipede, ReplayReRunsTheTailOfAFailedBatch) {
+  TempDir temp_dir{test_info_->name()};
+  Environment env = TailRerunEnv(temp_dir.path().string());
+  FakeTailRerunCallbacks fake(env, /*crashing=*/{103, 106});
+  NonOwningCallbacksFactory factory(fake);
+  EXPECT_EQ(CentipedeMain(env, factory), EXIT_SUCCESS);
+  // Seed {0} plus all 8 non-crashing inputs of the mutant batch (100..109 \
+  // {103, 106}).
+  EXPECT_THAT(fake.num_executions(),
+              UnorderedElementsAre(Pair(0, 1), Pair(100, 1), Pair(101, 1),
+                                   Pair(102, 1), Pair(104, 1), Pair(105, 1),
+                                   Pair(107, 1), Pair(108, 1), Pair(109, 1)));
+}
+
+TEST(Centipede, ReplayCrashOnFinalElementDoesNotIssueEmptyTailBatch) {
+  TempDir temp_dir{test_info_->name()};
+  Environment env = TailRerunEnv(temp_dir.path().string());
+  FakeTailRerunCallbacks fake(env, /*crashing=*/{109});
+  NonOwningCallbacksFactory factory(fake);
+  EXPECT_EQ(CentipedeMain(env, factory), EXIT_SUCCESS);
+  // 1 seed batch ({0}) + 1 mutant batch (100..109) + 1 suspect triage ({109}) =
+  // 3 Execute calls (no empty subspan tail call after 109).
+  EXPECT_EQ(fake.execute_calls(), 3);
+  EXPECT_THAT(
+      fake.num_executions(),
+      UnorderedElementsAre(Pair(0, 1), Pair(100, 1), Pair(101, 1), Pair(102, 1),
+                           Pair(103, 1), Pair(104, 1), Pair(105, 1),
+                           Pair(106, 1), Pair(107, 1), Pair(108, 1)));
+}
+
+TEST(Centipede, ReplayReRunsTruncatedSubBatches) {
+  TempDir temp_dir{test_info_->name()};
+  Environment env = TailRerunEnv(temp_dir.path().string());
+  FakeTailRerunCallbacks fake(env, /*crashing=*/{},
+                              /*max_inputs_per_call=*/4);
+  NonOwningCallbacksFactory factory(fake);
+  EXPECT_EQ(CentipedeMain(env, factory), EXIT_SUCCESS);
+  // 1 seed batch ({0}) + 3 sub-batches (4 + 4 + 2) for 100..109 = 4 calls.
+  EXPECT_EQ(fake.execute_calls(), 4);
+  EXPECT_THAT(fake.num_executions(),
+              UnorderedElementsAre(Pair(0, 1), Pair(100, 1), Pair(101, 1),
+                                   Pair(102, 1), Pair(103, 1), Pair(104, 1),
+                                   Pair(105, 1), Pair(106, 1), Pair(107, 1),
+                                   Pair(108, 1), Pair(109, 1)));
+}
+
+TEST(Centipede, ReplayDoesNotReRunTailOnPerBatchTimeout) {
+  TempDir temp_dir{test_info_->name()};
+  Environment env = TailRerunEnv(temp_dir.path().string());
+  FakeTailRerunCallbacks fake(env, /*crashing=*/{102},
+                              /*max_inputs_per_call=*/0,
+                              std::string(kExecutionFailurePerBatchTimeout));
+  NonOwningCallbacksFactory factory(fake);
+  EXPECT_EQ(CentipedeMain(env, factory), EXIT_SUCCESS);
+  // Seed {0} + inputs 100, 101 ran; inputs 103..109 in the batch were NOT
+  // re-run because per-batch timeout is not a single-input failure.
+  EXPECT_THAT(fake.num_executions(),
+              UnorderedElementsAre(Pair(0, 1), Pair(100, 1), Pair(101, 1)));
+}
+
+TEST(Centipede, ReplayDoesNotReRunTailWithExitOnCrash) {
+  TempDir temp_dir{test_info_->name()};
+  Environment env = TailRerunEnv(temp_dir.path().string());
+  env.exit_on_crash = true;
+  FakeTailRerunCallbacks fake(env, /*crashing=*/{103, 106});
+  NonOwningCallbacksFactory factory(fake);
+  EXPECT_EQ(CentipedeMain(env, factory), EXIT_FAILURE);
+  EXPECT_THAT(fake.num_executions(),
+              UnorderedElementsAre(Pair(0, 1), Pair(100, 1), Pair(101, 1),
+                                   Pair(102, 1)));
+}
+
+TEST(Centipede, FuzzingDoesNotReRunTheTailOfAFailedBatch) {
+  TempDir temp_dir{test_info_->name()};
+  Environment env = TailRerunEnv(temp_dir.path().string());
+  env.fuzztest_only_replay = false;
+  FakeTailRerunCallbacks fake(env, /*crashing=*/{103, 106});
+  NonOwningCallbacksFactory factory(fake);
+  EXPECT_EQ(CentipedeMain(env, factory), EXIT_SUCCESS);
+  EXPECT_THAT(fake.num_executions(),
+              UnorderedElementsAre(Pair(0, 1), Pair(100, 1), Pair(101, 1),
+                                   Pair(102, 1)));
+}
+
 class SetupFailureCallbacks : public CentipedeCallbacks {
  public:
   explicit SetupFailureCallbacks(const Environment& env)
diff --git a/centipede/engine_abi.h b/centipede/engine_abi.h
index a139500..4cce087 100644
--- a/centipede/engine_abi.h
+++ b/centipede/engine_abi.h
@@ -75,6 +75,35 @@
   void (*Emit)(FuzzTestBytesSinkCtx* ctx, const FuzzTestBytesView* view);
 } FuzzTestBytesSink;
 
+// Types of input metadata. The engine handles each type differently, and the
+// content of every type is opaque to the engine.
+typedef enum {
+  // Hints for mutating the input (e.g. the operands of comparisons seen when
+  // executing it). Kept in memory only, and passed back to the adapter for the
+  // origin inputs of mutations.
+  kFuzzTestInputMetadataMutationHints = 0,
+  // Metadata that the engine may store for the input and pass back to the
+  // adapter before a later execution of the same input.
+  kFuzzTestInputMetadataPersistent = 1,
+} FuzzTestInputMetadataType;
+
+// A piece of input metadata of a given type.
+typedef struct {
+  FuzzTestInputMetadataType type;
+  FuzzTestBytesView bytes;
+} FuzzTestInputMetadataView;
+
+// Sink for input metadata.
+typedef struct FuzzTestInputMetadataSinkCtx FuzzTestInputMetadataSinkCtx;
+typedef struct {
+  FuzzTestInputMetadataSinkCtx* ctx;
+
+  // Emits a piece of input metadata. Multiple emissions of the same type are
+  // concatenated. A type that is never emitted is treated as absent.
+  void (*Emit)(FuzzTestInputMetadataSinkCtx* ctx,
+               const FuzzTestInputMetadataView* metadata);
+} FuzzTestInputMetadataSink;
+
 // Sink for seed inputs.
 typedef struct FuzzTestInputSinkCtx FuzzTestInputSinkCtx;
 typedef struct {
@@ -215,14 +244,18 @@
                                   const FuzzTestBytesView* content,
                                   const FuzzTestInputSink* sink);
 
-  // [Optional] Serializes the test `input` metadata into bytes using `sink`.
+  // [Optional] Serializes the test `input` metadata, of any type, using
+  // `sink`.
   void (*SerializeInputMetadata)(FuzzTestAdapterCtx* ctx,
                                  FuzzTestInputHandle input,
-                                 const FuzzTestBytesSink* sink);
+                                 const FuzzTestInputMetadataSink* sink);
 
-  // [Optional] Updates the test `input` metadata from serialized `metadata`.
+  // [Optional] Updates the test `input` metadata of type `metadata->type` from
+  // the serialized `metadata->bytes`. Called with the mutation hints of
+  // mutation origins before `Mutate`/`CrossOver`, and with the persistent
+  // metadata stored for `input` (if any) before `Execute`.
   void (*UpdateInputMetadata)(FuzzTestAdapterCtx* ctx,
-                              const FuzzTestBytesView* metadata,
+                              const FuzzTestInputMetadataView* metadata,
                               FuzzTestInputHandle input);
 
   // Callback to run when the engine is done with `input`.
diff --git a/centipede/engine_worker.cc b/centipede/engine_worker.cc
index 464931e..6a0356d 100644
--- a/centipede/engine_worker.cc
+++ b/centipede/engine_worker.cc
@@ -398,6 +398,39 @@
       }};
 }
 
+// The serialized input metadata collected from an adapter, by type.
+struct SerializedInputMetadata {
+  std::vector<uint8_t> mutation_hints;
+  std::vector<uint8_t> persistent;
+
+  void clear() {
+    mutation_hints.clear();
+    persistent.clear();
+  }
+};
+
+FuzzTestInputMetadataSink GetInputMetadataSinkTo(
+    SerializedInputMetadata& metadata) {
+  return {/*ctx=*/reinterpret_cast<FuzzTestInputMetadataSinkCtx*>(&metadata),
+          /*Emit=*/[](FuzzTestInputMetadataSinkCtx* ctx,
+                      const FuzzTestInputMetadataView* view) {
+            auto* output = reinterpret_cast<SerializedInputMetadata*>(ctx);
+            std::vector<uint8_t>* bytes = nullptr;
+            switch (view->type) {
+              case kFuzzTestInputMetadataMutationHints:
+                bytes = &output->mutation_hints;
+                break;
+              case kFuzzTestInputMetadataPersistent:
+                bytes = &output->persistent;
+                break;
+            }
+            // Ignore metadata of unknown types.
+            if (bytes == nullptr) return;
+            bytes->insert(bytes->end(), view->bytes.data,
+                          view->bytes.data + view->bytes.size);
+          }};
+}
+
 FuzzTestInputSink GetInputSinkTo(std::vector<FuzzTestInputHandle>& inputs) {
   return {/*ctx=*/reinterpret_cast<FuzzTestInputSinkCtx*>(&inputs),
           /*Emit=*/[](FuzzTestInputSinkCtx* ctx, FuzzTestInputHandle input) {
@@ -512,8 +545,9 @@
     if (!IsDataInput(blob)) break;
     emitted_inputs.clear();
     auto input_content = FuzzTestBytesView{blob.data, blob.size};
-    auto input_metadata =
-        FuzzTestBytesView{metadata.cmp_data.data(), metadata.cmp_data.size()};
+    const auto input_metadata = FuzzTestInputMetadataView{
+        kFuzzTestInputMetadataMutationHints,
+        {metadata.cmp_data.data(), metadata.cmp_data.size()}};
     adapter.DeserializeInputContent(adapter.ctx, &input_content, &input_sink);
     WORKER_CHECK_FOR_ERROR();
     WorkerCheck(emitted_inputs.size() == 1,
@@ -655,7 +689,8 @@
 
   // In-loop variables declared outside to save allocations.
   std::vector<uint64_t> features;
-  std::vector<uint8_t> serialized_metadata;
+  SerializedInputMetadata serialized_metadata;
+  const auto metadata_sink = GetInputMetadataSinkTo(serialized_metadata);
   std::vector<FuzzTestInputHandle> emitted_inputs;
   const auto input_sink = GetInputSinkTo(emitted_inputs);
 
@@ -670,8 +705,19 @@
     // TODO(xinhaoyuan): Consider improving it. E.g. let user override stats.
     ExecutionResult::Stats stats = {};
     (void)timer.UsecSinceLast();
-    auto blob = inputs_blobseq->Read();
-    if (!blob.IsValid()) return;  // no more blobs to read.
+    const auto first_blob = inputs_blobseq->Read();
+    if (!first_blob.IsValid()) return;  // no more blobs to read.
+    // The data input may be preceded by its persistent metadata, which is
+    // passed to the adapter before `Execute`.
+    const bool has_persistent_metadata = IsPersistentMetadata(first_blob);
+    const auto persistent_metadata = FuzzTestInputMetadataView{
+        kFuzzTestInputMetadataPersistent,
+        {has_persistent_metadata ? first_blob.data : nullptr,
+         has_persistent_metadata ? first_blob.size : 0}};
+    const auto blob =
+        has_persistent_metadata ? inputs_blobseq->Read() : first_blob;
+    // The inputs blob sequence may have overflown between the two blobs.
+    if (!blob.IsValid()) return;
     WorkerCheck(IsDataInput(blob), "Must read data input");
 
     if (!BatchResult::WriteInputBegin(*outputs_blobseq)) {
@@ -686,6 +732,10 @@
     WorkerCheck(emitted_inputs.size() == 1,
                 "Deserialize must emit exactly one input");
     auto input = emitted_inputs[0];
+    if (has_persistent_metadata && adapter.UpdateInputMetadata != nullptr) {
+      adapter.UpdateInputMetadata(adapter.ctx, &persistent_metadata, input);
+      WORKER_CHECK_FOR_ERROR();
+    }
 
     features.clear();
     FuzzTestFeedbackSink feedback_sink = {
@@ -706,7 +756,6 @@
 
     serialized_metadata.clear();
     if (adapter.SerializeInputMetadata != nullptr) {
-      const auto metadata_sink = GetBytesSinkTo(serialized_metadata);
       adapter.SerializeInputMetadata(adapter.ctx, input, &metadata_sink);
     }
     adapter.FreeInput(adapter.ctx, input);
@@ -746,7 +795,10 @@
       WorkerLog("failed to write feedback");
       break;
     }
-    if (!BatchResult::WriteMetadata(serialized_metadata, *outputs_blobseq)) {
+    if (!BatchResult::WriteMetadata(serialized_metadata.mutation_hints,
+                                    *outputs_blobseq) ||
+        !BatchResult::WritePersistentMetadata(serialized_metadata.persistent,
+                                              *outputs_blobseq)) {
       WorkerLog("failed to write input metadata");
       break;
     }
diff --git a/centipede/environment.cc b/centipede/environment.cc
index 8fb2a35..6ff21de 100644
--- a/centipede/environment.cc
+++ b/centipede/environment.cc
@@ -245,6 +245,7 @@
   fuzztest_binary_identifier = config.binary_identifier;
   fuzztest_stats_root = config.stats_root;
   fuzztest_workdir_root = config.workdir_root;
+  fuzztest_persistent_metadata_root = config.persistent_metadata_root;
   fuzztest_seed_corpus_databases = config.seed_corpus_databases;
   fuzztest_only_replay = config.only_replay;
   fuzztest_update_corpus_database = config.update_corpus_database;
diff --git a/centipede/environment_test.cc b/centipede/environment_test.cc
index 4b93216..3900dab 100644
--- a/centipede/environment_test.cc
+++ b/centipede/environment_test.cc
@@ -194,6 +194,7 @@
   config.binary_identifier = "bin";
   config.stats_root = "stats";
   config.workdir_root = "workdir";
+  config.persistent_metadata_root = "metadata";
   config.seed_corpus_databases = {"seed_db1", "seed_db2"};
   config.only_replay = true;
   config.execution_id = "exec";
@@ -207,6 +208,7 @@
   EXPECT_EQ(env.fuzztest_binary_identifier, "bin");
   EXPECT_EQ(env.fuzztest_stats_root, "stats");
   EXPECT_EQ(env.fuzztest_workdir_root, "workdir");
+  EXPECT_EQ(env.fuzztest_persistent_metadata_root, "metadata");
   EXPECT_EQ(env.fuzztest_seed_corpus_databases,
             (std::vector<std::string>{"seed_db1", "seed_db2"}));
   EXPECT_TRUE(env.fuzztest_only_replay);
diff --git a/centipede/in_process_centipede_callbacks.cc b/centipede/in_process_centipede_callbacks.cc
index 59539d9..0bb931d 100644
--- a/centipede/in_process_centipede_callbacks.cc
+++ b/centipede/in_process_centipede_callbacks.cc
@@ -81,6 +81,32 @@
   };
 }
 
+// Returns a sink that appends the emitted input metadata to the field of
+// `metadata` that corresponds to its type.
+FuzzTestInputMetadataSink GetInputMetadataSinkTo(ExecutionMetadata& metadata) {
+  return {
+      /*ctx=*/reinterpret_cast<FuzzTestInputMetadataSinkCtx*>(&metadata),
+      /*Emit=*/
+      [](FuzzTestInputMetadataSinkCtx* ctx,
+         const FuzzTestInputMetadataView* view) {
+        auto* output = reinterpret_cast<ExecutionMetadata*>(ctx);
+        ByteArray* bytes = nullptr;
+        switch (view->type) {
+          case kFuzzTestInputMetadataMutationHints:
+            bytes = &output->cmp_data;
+            break;
+          case kFuzzTestInputMetadataPersistent:
+            bytes = &output->persistent_data;
+            break;
+        }
+        // Ignore metadata of unknown types.
+        if (bytes == nullptr) return;
+        bytes->insert(bytes->end(), view->bytes.data,
+                      view->bytes.data + view->bytes.size);
+      },
+  };
+}
+
 FuzzTestInputSink GetInputSinkTo(std::vector<FuzzTestInputHandle>& inputs) {
   return {
       /*ctx=*/reinterpret_cast<FuzzTestInputSinkCtx*>(&inputs),
@@ -476,8 +502,9 @@
     FUZZTEST_CHECK_EQ(emitted_inputs.size(), 1)
         << "DeserializeInputContent must emit exactly one input";
     if (adapter_.UpdateInputMetadata != nullptr && input.metadata != nullptr) {
-      const FuzzTestBytesView input_metadata{input.metadata->cmp_data.data(),
-                                             input.metadata->cmp_data.size()};
+      const FuzzTestInputMetadataView input_metadata{
+          kFuzzTestInputMetadataMutationHints,
+          {input.metadata->cmp_data.data(), input.metadata->cmp_data.size()}};
       adapter_.UpdateInputMetadata(adapter_.ctx, &input_metadata,
                                    emitted_inputs[0]);
       if (CheckError()) {
@@ -561,6 +588,21 @@
   };
   const auto input_sink = GetInputSinkTo(emitted_inputs);
 
+  // The persistent input metadata is exchanged with the primary binary only.
+  const bool use_input_metadata_store =
+      input_metadata_store_.enabled() && binary == env_.binary;
+  // Empty if the store is not used.
+  const std::vector<ByteArray> stored_metadata =
+      use_input_metadata_store ? input_metadata_store_.Load(inputs)
+                               : std::vector<ByteArray>();
+  // Stores the persistent metadata of the executed inputs on all return paths,
+  // including those executed before a failure.
+  absl::Cleanup save_persistent_metadata = [&] {
+    if (use_input_metadata_store) {
+      input_metadata_store_.Save(inputs, batch_result);
+    }
+  };
+
   for (size_t i = 0; i < inputs.size(); ++i) {
     if (stop_condition_.ShouldStop()) {
       return true;
@@ -578,6 +620,17 @@
     FUZZTEST_CHECK_EQ(emitted_inputs.size(), 1)
         << "DeserializeInputContent must emit exactly one input";
     const FuzzTestInputHandle input = emitted_inputs[0];
+    if (i < stored_metadata.size() && !stored_metadata[i].empty() &&
+        adapter_.UpdateInputMetadata != nullptr) {
+      const FuzzTestInputMetadataView persistent_metadata{
+          kFuzzTestInputMetadataPersistent,
+          {stored_metadata[i].data(), stored_metadata[i].size()}};
+      adapter_.UpdateInputMetadata(adapter_.ctx, &persistent_metadata, input);
+      if (CheckError()) {
+        CopyErrorOrMoveFindingToBatchResult(batch_result);
+        return false;
+      }
+    }
 
     features.clear();
     FuzzTestFeedbackSink feedback_sink = {
@@ -609,8 +662,7 @@
 
     ExecutionResult& exec_result = batch_result.results()[i];
     if (adapter_.SerializeInputMetadata != nullptr) {
-      const auto metadata_sink =
-          GetBytesSinkTo(exec_result.metadata().cmp_data);
+      const auto metadata_sink = GetInputMetadataSinkTo(exec_result.metadata());
       adapter_.SerializeInputMetadata(adapter_.ctx, input, &metadata_sink);
     }
     // Frees `input`, the only emitted input.
diff --git a/centipede/in_process_centipede_callbacks_test.cc b/centipede/in_process_centipede_callbacks_test.cc
index 1b40572..108ed30 100644
--- a/centipede/in_process_centipede_callbacks_test.cc
+++ b/centipede/in_process_centipede_callbacks_test.cc
@@ -80,7 +80,11 @@
 
 struct FakeInput {
   std::string content;
+  // Mutation hints.
   std::string metadata;
+  // Persistent metadata: what the engine passed before `Execute` (if any),
+  // and what the adapter emits afterwards.
+  std::string persistent_metadata;
 };
 
 struct FakeAdapterState {
@@ -304,6 +308,12 @@
     // = 44.
     features.push_back(MakeEngineFeature(1, 10, 0xB0));
     input_obj->metadata = "recorded_cmp_meta";
+  } else if (input_obj->content == "with_persistent_meta") {
+    features.push_back(MakeEngineFeature(0, 8, 0));
+    // Echo what the engine passed (if anything), so that tests can observe
+    // both directions.
+    input_obj->persistent_metadata =
+        absl::StrCat("persisted(", input_obj->persistent_metadata, ")");
   }
 
   const FuzzTestUint64sView features_view{features.data(), features.size()};
@@ -334,18 +344,31 @@
 
 void FakeSerializeInputMetadata(FuzzTestAdapterCtx* ctx,
                                 FuzzTestInputHandle input,
-                                const FuzzTestBytesSink* sink) {
+                                const FuzzTestInputMetadataSink* sink) {
   const auto* input_obj = reinterpret_cast<FakeInput*>(input);
-  const FuzzTestBytesView bytes = ToBytesView(input_obj->metadata);
-  sink->Emit(sink->ctx, &bytes);
+  const FuzzTestInputMetadataView metadata = {
+      kFuzzTestInputMetadataMutationHints, ToBytesView(input_obj->metadata)};
+  sink->Emit(sink->ctx, &metadata);
+  if (input_obj->persistent_metadata.empty()) return;
+  const FuzzTestInputMetadataView persistent_metadata = {
+      kFuzzTestInputMetadataPersistent,
+      ToBytesView(input_obj->persistent_metadata)};
+  sink->Emit(sink->ctx, &persistent_metadata);
 }
 
 void FakeUpdateInputMetadata(FuzzTestAdapterCtx* ctx,
-                             const FuzzTestBytesView* metadata,
+                             const FuzzTestInputMetadataView* metadata,
                              FuzzTestInputHandle input) {
   auto* input_obj = reinterpret_cast<FakeInput*>(input);
-  input_obj->metadata.assign(reinterpret_cast<const char*>(metadata->data),
-                             metadata->size);
+  if (metadata->type == kFuzzTestInputMetadataMutationHints) {
+    input_obj->metadata.assign(
+        reinterpret_cast<const char*>(metadata->bytes.data),
+        metadata->bytes.size);
+  } else if (metadata->type == kFuzzTestInputMetadataPersistent) {
+    input_obj->persistent_metadata.assign(
+        reinterpret_cast<const char*>(metadata->bytes.data),
+        metadata->bytes.size);
+  }
   MaybeEmitDiagnostic(reinterpret_cast<FakeAdapterState*>(ctx),
                       "UpdateInputMetadata");
 }
@@ -726,10 +749,89 @@
                               expected_counter_feature_id)));
   EXPECT_EQ(ToString(batch_result.results()[1].metadata().cmp_data),
             "recorded_cmp_meta");
+  EXPECT_THAT(batch_result.results()[1].metadata().persistent_data, IsEmpty());
   EXPECT_EQ(state.active_inputs, 0);
 }
 
 TEST(InProcessCentipedeCallbacksTest,
+     ExecuteSeparatesPersistentMetadataFromMutationHints) {
+  FakeAdapterState state;
+  const FuzzTestAdapterManager manager = MakeFakeAdapterManager(&state);
+
+  Environment env;
+  StopCondition stop_condition;
+  InProcessCentipedeCallbacks callbacks(env, stop_condition, &manager);
+
+  const ByteArray input = ToByteArray("with_persistent_meta");
+  BatchResult batch_result;
+  EXPECT_TRUE(callbacks.Execute("binary", {input}, batch_result));
+  ASSERT_EQ(batch_result.num_outputs_read(), 1);
+
+  const ExecutionMetadata& metadata = batch_result.results()[0].metadata();
+  EXPECT_THAT(metadata.cmp_data, IsEmpty());
+  EXPECT_EQ(ToString(metadata.persistent_data), "persisted()");
+  EXPECT_EQ(state.active_inputs, 0);
+}
+
+TEST(InProcessCentipedeCallbacksTest,
+     ExecutePassesBackTheStoredPersistentMetadata) {
+  TempDir temp_dir{test_info_->name()};
+  FakeAdapterState state;
+  const FuzzTestAdapterManager manager = MakeFakeAdapterManager(&state);
+
+  Environment env;
+  env.binary = "binary";
+  env.fuzztest_persistent_metadata_root = temp_dir.path().string();
+  env.fuzztest_binary_identifier = "binary_id";
+  StopCondition stop_condition;
+  InProcessCentipedeCallbacks callbacks(env, stop_condition, &manager);
+
+  const ByteArray input = ToByteArray("with_persistent_meta");
+  // An input that emits no persistent metadata.
+  const ByteArray other_input = ToByteArray("random_seed");
+  BatchResult batch_result;
+
+  // Nothing is stored for the first execution.
+  EXPECT_TRUE(callbacks.Execute("binary", {other_input, input}, batch_result));
+  ASSERT_EQ(batch_result.num_outputs_read(), 2);
+  EXPECT_THAT(batch_result.results()[0].metadata().persistent_data, IsEmpty());
+  EXPECT_EQ(ToString(batch_result.results()[1].metadata().persistent_data),
+            "persisted()");
+
+  // The second execution gets what the first one emitted, for the same input
+  // only.
+  EXPECT_TRUE(callbacks.Execute("binary", {input, other_input}, batch_result));
+  ASSERT_EQ(batch_result.num_outputs_read(), 2);
+  EXPECT_EQ(ToString(batch_result.results()[0].metadata().persistent_data),
+            "persisted(persisted())");
+  EXPECT_THAT(batch_result.results()[1].metadata().persistent_data, IsEmpty());
+  EXPECT_EQ(state.active_inputs, 0);
+}
+
+TEST(InProcessCentipedeCallbacksTest,
+     ExecuteDoesNotExchangePersistentMetadataWithOtherBinaries) {
+  TempDir temp_dir{test_info_->name()};
+  FakeAdapterState state;
+  const FuzzTestAdapterManager manager = MakeFakeAdapterManager(&state);
+
+  Environment env;
+  env.binary = "binary";
+  env.fuzztest_persistent_metadata_root = temp_dir.path().string();
+  StopCondition stop_condition;
+  InProcessCentipedeCallbacks callbacks(env, stop_condition, &manager);
+
+  const ByteArray input = ToByteArray("with_persistent_meta");
+  BatchResult batch_result;
+  EXPECT_TRUE(callbacks.Execute("extra_binary", {input}, batch_result));
+  EXPECT_TRUE(callbacks.Execute("extra_binary", {input}, batch_result));
+
+  // Nothing was stored by the first execution.
+  ASSERT_EQ(batch_result.num_outputs_read(), 1);
+  EXPECT_EQ(ToString(batch_result.results()[0].metadata().persistent_data),
+            "persisted()");
+}
+
+TEST(InProcessCentipedeCallbacksTest,
      ExecuteReportsFindingAndResetsOnNextBatch) {
   FakeAdapterState state;
   const FuzzTestAdapterManager manager = MakeFakeAdapterManager(&state);
diff --git a/centipede/input_metadata_store.cc b/centipede/input_metadata_store.cc
new file mode 100644
index 0000000..ae949b5
--- /dev/null
+++ b/centipede/input_metadata_store.cc
@@ -0,0 +1,86 @@
+// Copyright 2026 The Centipede Authors.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "./centipede/input_metadata_store.h"
+
+#include <algorithm>
+#include <cstddef>
+#include <filesystem>  // NOLINT
+#include <string>
+#include <string_view>
+#include <vector>
+
+#include "absl/types/span.h"
+#include "./centipede/environment.h"
+#include "./centipede/runner_result.h"
+#include "./common/defs.h"
+#include "./common/hash.h"
+#include "./common/logging.h"
+#include "./common/remote_file.h"
+
+namespace fuzztest::internal {
+namespace {
+
+std::string MetadataDir(const Environment& env) {
+  if (env.fuzztest_persistent_metadata_root.empty()) return "";
+  return (std::filesystem::path(env.fuzztest_persistent_metadata_root) /
+          env.fuzztest_binary_identifier / env.test_name)
+      .string();
+}
+
+std::string MetadataPath(std::string_view dir, ByteSpan input) {
+  return (std::filesystem::path(dir) / Hash(input)).string();
+}
+
+}  // namespace
+
+InputMetadataStore::InputMetadataStore(const Environment& env)
+    : dir_(MetadataDir(env)) {}
+
+std::vector<ByteArray> InputMetadataStore::Load(
+    absl::Span<const ByteSpan> inputs) const {
+  if (!enabled()) return {};
+  std::vector<ByteArray> metadata(inputs.size());
+  for (size_t i = 0; i < inputs.size(); ++i) {
+    const std::string path = MetadataPath(dir_, inputs[i]);
+    if (!RemotePathExists(path)) continue;
+    FUZZTEST_CHECK_OK(RemoteFileGetContents(path, metadata[i]))
+        << "Failed to read the persistent input metadata from " << path;
+  }
+  return metadata;
+}
+
+void InputMetadataStore::Save(absl::Span<const ByteSpan> inputs,
+                              const BatchResult& batch_result) {
+  if (!enabled()) return;
+  const size_t num_results =
+      std::min({inputs.size(), batch_result.num_outputs_read(),
+                batch_result.results().size()});
+  for (size_t i = 0; i < num_results; ++i) {
+    const ByteArray& metadata =
+        batch_result.results()[i].metadata().persistent_data;
+    if (metadata.empty()) continue;
+    if (!dir_created_) {
+      FUZZTEST_CHECK_OK(RemoteMkdir(dir_))
+          << "Failed to create the persistent input metadata directory "
+          << dir_;
+      dir_created_ = true;
+    }
+    const std::string path = MetadataPath(dir_, inputs[i]);
+    FUZZTEST_CHECK_OK(RemoteFileSetContents(path, metadata))
+        << "Failed to write the persistent input metadata to " << path;
+  }
+}
+
+}  // namespace fuzztest::internal
diff --git a/centipede/input_metadata_store.h b/centipede/input_metadata_store.h
new file mode 100644
index 0000000..2ac53e6
--- /dev/null
+++ b/centipede/input_metadata_store.h
@@ -0,0 +1,72 @@
+// Copyright 2026 The Centipede Authors.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Controller-side storage of persistent input metadata.
+//
+// Persistent input metadata is opaque data that the test attaches to an input
+// when executing it (see `ExecutionMetadata::persistent_data`). The engine
+// stores it per input and passes it back to the test before the next execution
+// of the same input. The engine never interprets it.
+//
+// The metadata of an input is stored in the file
+//
+//   <fuzztest_persistent_metadata_root>/<fuzztest_binary_identifier>/
+//       <test_name>/<hash>
+//
+// where <hash> is `Hash()` of the input bytes.
+
+#ifndef FUZZTEST_CENTIPEDE_INPUT_METADATA_STORE_H_
+#define FUZZTEST_CENTIPEDE_INPUT_METADATA_STORE_H_
+
+#include <string>
+#include <vector>
+
+#include "absl/types/span.h"
+#include "./centipede/environment.h"
+#include "./centipede/runner_result.h"
+#include "./common/defs.h"
+
+namespace fuzztest::internal {
+
+class InputMetadataStore {
+ public:
+  // The store is enabled iff `env.fuzztest_persistent_metadata_root` is
+  // non-empty.
+  explicit InputMetadataStore(const Environment& env);
+
+  bool enabled() const { return !dir_.empty(); }
+
+  // Returns the directory with the metadata files, or empty if disabled.
+  const std::string& dir() const { return dir_; }
+
+  // Returns the stored metadata of each of `inputs`, in the same order. The
+  // metadata of an input without stored metadata is empty. Returns an empty
+  // vector if the store is disabled. Crashes on I/O errors.
+  std::vector<ByteArray> Load(absl::Span<const ByteSpan> inputs) const;
+
+  // Stores the persistent metadata in the results of `batch_result` that were
+  // read after executing `inputs`. Results without persistent metadata leave
+  // the stored metadata of their inputs unchanged. No-op if the store is
+  // disabled. Crashes on I/O errors.
+  void Save(absl::Span<const ByteSpan> inputs, const BatchResult& batch_result);
+
+ private:
+  // Empty if the store is disabled.
+  const std::string dir_;
+  bool dir_created_ = false;
+};
+
+}  // namespace fuzztest::internal
+
+#endif  // FUZZTEST_CENTIPEDE_INPUT_METADATA_STORE_H_
diff --git a/centipede/input_metadata_store_test.cc b/centipede/input_metadata_store_test.cc
new file mode 100644
index 0000000..a605f4f
--- /dev/null
+++ b/centipede/input_metadata_store_test.cc
@@ -0,0 +1,155 @@
+// Copyright 2026 The Centipede Authors.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "./centipede/input_metadata_store.h"
+
+#include <cstddef>
+#include <filesystem>  // NOLINT
+#include <string>
+#include <vector>
+
+#include "gmock/gmock.h"
+#include "gtest/gtest.h"
+#include "./centipede/environment.h"
+#include "./centipede/runner_result.h"
+#include "./common/defs.h"
+#include "./common/hash.h"
+#include "./common/remote_file.h"
+#include "./common/test_util.h"
+
+namespace fuzztest::internal {
+namespace {
+
+using ::testing::ElementsAre;
+using ::testing::IsEmpty;
+
+Environment EnvWithRoot(const std::string& root) {
+  Environment env;
+  env.fuzztest_persistent_metadata_root = root;
+  env.fuzztest_binary_identifier = "some/binary";
+  env.test_name = "Suite.Test";
+  return env;
+}
+
+// Saves to `store` the results of executing `inputs`, with `metadata[i]` as the
+// persistent metadata of the result of `inputs[i]`. Only the first
+// `num_outputs_read` results count as read.
+void SaveResults(InputMetadataStore& store, const std::vector<ByteSpan>& inputs,
+                 const std::vector<ByteArray>& metadata,
+                 size_t num_outputs_read) {
+  BatchResult batch_result;
+  batch_result.ClearAndResize(metadata.size());
+  for (size_t i = 0; i < metadata.size(); ++i) {
+    batch_result.results()[i].metadata().persistent_data = metadata[i];
+  }
+  batch_result.num_outputs_read() = num_outputs_read;
+  store.Save(inputs, batch_result);
+}
+
+void SaveResults(InputMetadataStore& store, const std::vector<ByteSpan>& inputs,
+                 const std::vector<ByteArray>& metadata) {
+  SaveResults(store, inputs, metadata, metadata.size());
+}
+
+TEST(InputMetadataStore, IsDisabledWithoutARoot) {
+  const Environment env = EnvWithRoot("");
+  InputMetadataStore store(env);
+  const ByteArray input = {1};
+
+  EXPECT_FALSE(store.enabled());
+  EXPECT_THAT(store.Load({input}), IsEmpty());
+  // Must not crash or write anything.
+  SaveResults(store, {input}, {{7}});
+}
+
+TEST(InputMetadataStore, UsesAPerBinaryAndPerTestDirectory) {
+  const Environment env = EnvWithRoot("/root");
+  InputMetadataStore store(env);
+
+  EXPECT_TRUE(store.enabled());
+  EXPECT_EQ(store.dir(), "/root/some/binary/Suite.Test");
+}
+
+TEST(InputMetadataStore, LoadsWhatWasSavedForTheSameInputBytes) {
+  TempDir temp_dir{test_info_->name()};
+  const Environment env = EnvWithRoot(temp_dir.path().string());
+  const ByteArray in0 = {1, 2};
+  const ByteArray in1 = {3};
+  const ByteArray in2 = {4, 5, 6};
+  const ByteArray metadata0 = {'a', 0, 'b'};
+  const ByteArray metadata2 = {'c'};
+
+  {
+    InputMetadataStore store(env);
+    // Nothing is stored yet.
+    EXPECT_THAT(store.Load({in0, in1, in2}),
+                ElementsAre(IsEmpty(), IsEmpty(), IsEmpty()));
+    // Input 1 returns no persistent metadata.
+    SaveResults(store, {in0, in1, in2}, {metadata0, {}, metadata2});
+  }
+
+  // A new store (e.g. of a later run) sees the stored metadata, keyed by the
+  // input bytes and regardless of the order.
+  InputMetadataStore store(env);
+  EXPECT_THAT(store.Load({in2, in1, in0}),
+              ElementsAre(metadata2, IsEmpty(), metadata0));
+  EXPECT_TRUE(RemotePathExists(
+      (std::filesystem::path(store.dir()) / Hash(in0)).string()));
+  EXPECT_FALSE(RemotePathExists(
+      (std::filesystem::path(store.dir()) / Hash(in1)).string()));
+}
+
+TEST(InputMetadataStore, KeepsStoredMetadataWhenAResultHasNone) {
+  TempDir temp_dir{test_info_->name()};
+  const Environment env = EnvWithRoot(temp_dir.path().string());
+  InputMetadataStore store(env);
+  const ByteArray input = {1, 2};
+  const ByteArray metadata = {'a'};
+
+  SaveResults(store, {input}, {metadata});
+  SaveResults(store, {input}, {{}});
+
+  EXPECT_THAT(store.Load({input}), ElementsAre(metadata));
+}
+
+TEST(InputMetadataStore, OverwritesStoredMetadataWithNewMetadata) {
+  TempDir temp_dir{test_info_->name()};
+  const Environment env = EnvWithRoot(temp_dir.path().string());
+  InputMetadataStore store(env);
+  const ByteArray input = {1, 2};
+  const ByteArray new_metadata = {'n', 'e', 'w'};
+
+  SaveResults(store, {input}, {{'o', 'l', 'd'}});
+  SaveResults(store, {input}, {new_metadata});
+
+  EXPECT_THAT(store.Load({input}), ElementsAre(new_metadata));
+}
+
+TEST(InputMetadataStore, SavesOnlyTheResultsThatWereRead) {
+  TempDir temp_dir{test_info_->name()};
+  const Environment env = EnvWithRoot(temp_dir.path().string());
+  InputMetadataStore store(env);
+  const ByteArray in0 = {1};
+  const ByteArray in1 = {2};
+  const ByteArray metadata0 = {'a'};
+
+  // The second input was not executed (e.g. the first one crashed after its
+  // result was written), so its result slot must be ignored.
+  SaveResults(store, {in0, in1}, {metadata0, {'x'}}, /*num_outputs_read=*/1);
+
+  EXPECT_THAT(store.Load({in0, in1}), ElementsAre(metadata0, IsEmpty()));
+}
+
+}  // namespace
+}  // namespace fuzztest::internal
diff --git a/centipede/runner.cc b/centipede/runner.cc
index 57147d7..e588dc5 100644
--- a/centipede/runner.cc
+++ b/centipede/runner.cc
@@ -374,6 +374,10 @@
   return DeserializeInput({0});
 }
 
+void RunnerCallbacks::SetPersistentMetadata(void* input, ByteSpan metadata) {}
+
+ByteArray RunnerCallbacks::TakePersistentMetadata(void* input) { return {}; }
+
 void* RunnerCallbacks::CrossOver(void* origin,
                                  const ExecutionMetadata& origin_metadata,
                                  void* other,
@@ -805,6 +809,8 @@
   const int old_traced = CentipedeSetCurrentThreadTraced(/*traced=*/1);
   RunOneInput(input->content, runner_ctx->callbacks);
   CentipedeSetCurrentThreadTraced(old_traced);
+  ByteArray persistent_metadata =
+      runner_ctx->callbacks.TakePersistentMetadata(input->content);
   {
     LockGuard lock(state->execution_result_override_mu);
     bool has_overridden_execution_result = false;
@@ -824,11 +830,13 @@
       };
       sink->EmitCoverageFeatures(sink->ctx, &features);
       input->metadata = result.metadata();
+      input->metadata.persistent_data = std::move(persistent_metadata);
       return;
     }
   }
   SanCovRuntimeEmitFeatures(sink);
   input->metadata = SanCovRuntimeGetExecutionMetadata();
+  input->metadata.persistent_data = std::move(persistent_metadata);
 }
 
 void DeserializeInputContent(FuzzTestAdapterCtx* ctx,
@@ -843,10 +851,22 @@
   sink->Emit(sink->ctx, reinterpret_cast<FuzzTestInputHandle>(input));
 }
 
-void UpdateInputMetadata(FuzzTestAdapterCtx* ctx, const FuzzTestBytesView* view,
+void UpdateInputMetadata(FuzzTestAdapterCtx* ctx,
+                         const FuzzTestInputMetadataView* view,
                          FuzzTestInputHandle handle) {
   auto* input = reinterpret_cast<Input*>(handle);
-  input->metadata.cmp_data = {view->data, view->data + view->size};
+  switch (view->type) {
+    case kFuzzTestInputMetadataMutationHints:
+      input->metadata.cmp_data.assign(view->bytes.data,
+                                      view->bytes.data + view->bytes.size);
+      break;
+    case kFuzzTestInputMetadataPersistent: {
+      auto* runner_ctx = reinterpret_cast<RunnerAdapterCtx*>(ctx);
+      runner_ctx->callbacks.SetPersistentMetadata(
+          input->content, ByteSpan{view->bytes.data, view->bytes.size});
+      break;
+    }
+  }
 }
 
 void SerializeInputContent(FuzzTestAdapterCtx* ctx, FuzzTestInputHandle handle,
@@ -863,13 +883,20 @@
 }
 
 void SerializeInputMetadata(FuzzTestAdapterCtx* ctx, FuzzTestInputHandle handle,
-                            const FuzzTestBytesSink* sink) {
+                            const FuzzTestInputMetadataSink* sink) {
   auto* input = reinterpret_cast<Input*>(handle);
-  const auto input_bytes = FuzzTestBytesView{
-      reinterpret_cast<const uint8_t*>(input->metadata.cmp_data.data()),
-      input->metadata.cmp_data.size(),
+  const auto mutation_hints = FuzzTestInputMetadataView{
+      kFuzzTestInputMetadataMutationHints,
+      {input->metadata.cmp_data.data(), input->metadata.cmp_data.size()},
   };
-  sink->Emit(sink->ctx, &input_bytes);
+  sink->Emit(sink->ctx, &mutation_hints);
+  if (input->metadata.persistent_data.empty()) return;
+  const auto persistent = FuzzTestInputMetadataView{
+      kFuzzTestInputMetadataPersistent,
+      {input->metadata.persistent_data.data(),
+       input->metadata.persistent_data.size()},
+  };
+  sink->Emit(sink->ctx, &persistent);
 }
 
 void FreeInput(FuzzTestAdapterCtx* ctx, FuzzTestInputHandle handle) {
diff --git a/centipede/runner_interface.h b/centipede/runner_interface.h
index 4a22b2d..bdfd954 100644
--- a/centipede/runner_interface.h
+++ b/centipede/runner_interface.h
@@ -189,6 +189,14 @@
   virtual void* DeserializeInput(ByteSpan bytes) = 0;
   // Called when the runner is done with `input`.
   virtual void FreeInput(void* input) = 0;
+  // Called before `Execute(input)` with the persistent metadata that the
+  // engine has stored for `input`, if any. `metadata` does not outlive the
+  // call. The default implementation ignores it.
+  virtual void SetPersistentMetadata(void* input, ByteSpan metadata);
+  // Called after `Execute(input)`. Returns the persistent metadata for the
+  // engine to store for `input`, or empty to store nothing. The default
+  // implementation returns empty.
+  virtual ByteArray TakePersistentMetadata(void* input);
   virtual ~RunnerCallbacks() = default;
 };
 
diff --git a/centipede/runner_request.cc b/centipede/runner_request.cc
index 9ce49ce..48a0779 100644
--- a/centipede/runner_request.cc
+++ b/centipede/runner_request.cc
@@ -34,16 +34,25 @@
   kTagNumMutants,
   kTagExecutionMetadata,
   kTagDataInput,
+  kTagPersistentMetadata,
 };
 
 // Writes `inputs` to `blobseq`, returns the number of inputs written.
+// `persistent_metadata` is either empty or has the same size as `inputs`; a
+// non-empty `persistent_metadata[i]` is written before `inputs[i]`.
 static size_t WriteInputs(absl::Span<const ByteSpan> inputs,
+                          absl::Span<const ByteSpan> persistent_metadata,
                           BlobSequence& blobseq) {
   size_t num_inputs = inputs.size();
   if (!blobseq.Write(kTagNumInputs, num_inputs)) return 0;
   size_t result = 0;
-  for (const auto &input : inputs) {
-    if (!blobseq.Write({kTagDataInput, input.size(), input.data()}))
+  for (size_t i = 0; i < inputs.size(); ++i) {
+    if (i < persistent_metadata.size() && !persistent_metadata[i].empty() &&
+        !blobseq.Write({kTagPersistentMetadata, persistent_metadata[i].size(),
+                        persistent_metadata[i].data()})) {
+      return result;
+    }
+    if (!blobseq.Write({kTagDataInput, inputs[i].size(), inputs[i].data()}))
       return result;
     ++result;
   }
@@ -78,8 +87,18 @@
 
 size_t RequestExecution(absl::Span<const ByteSpan> inputs,
                         BlobSequence& blobseq) {
+  return RequestExecution(inputs, /*persistent_metadata=*/{}, blobseq);
+}
+
+size_t RequestExecution(absl::Span<const ByteSpan> inputs,
+                        absl::Span<const ByteSpan> persistent_metadata,
+                        BlobSequence& blobseq) {
+  if (!persistent_metadata.empty() &&
+      persistent_metadata.size() != inputs.size()) {
+    return 0;
+  }
   if (!blobseq.Write({kTagExecution, 0, nullptr})) return 0;
-  return WriteInputs(inputs, blobseq);
+  return WriteInputs(inputs, persistent_metadata, blobseq);
 }
 
 size_t RequestMutation(size_t num_mutants,
@@ -114,6 +133,10 @@
   return true;
 }
 
+bool IsPersistentMetadata(Blob blob) {
+  return blob.tag == kTagPersistentMetadata;
+}
+
 bool IsDataInput(Blob blob) { return blob.tag == kTagDataInput; }
 
 }  // namespace fuzztest::internal
diff --git a/centipede/runner_request.h b/centipede/runner_request.h
index 01132c4..590d29b 100644
--- a/centipede/runner_request.h
+++ b/centipede/runner_request.h
@@ -39,6 +39,16 @@
 size_t RequestExecution(absl::Span<const ByteSpan> inputs,
                         BlobSequence& blobseq);
 
+// Same as above, but also sends the persistent input metadata of the inputs:
+// a non-empty `persistent_metadata[i]` is sent as a separate blob immediately
+// before `inputs[i]`. `persistent_metadata` must be empty or have the same
+// size as `inputs`. Without any non-empty persistent metadata, the request is
+// byte-identical to the one sent by the overload above.
+// Returns the number of sent inputs.
+size_t RequestExecution(absl::Span<const ByteSpan> inputs,
+                        absl::Span<const ByteSpan> persistent_metadata,
+                        BlobSequence& blobseq);
+
 // Sends a request (via `blobseq`) to compute `num_mutants` mutants of `inputs`.
 // Returns the number of sent inputs, which would normally be inputs.size().
 size_t RequestMutation(size_t num_mutants,
@@ -63,6 +73,10 @@
 // execution metadata.
 bool IsExecutionMetadata(Blob blob, ExecutionMetadata &metadata);
 
+// Returns true iff `blob` indicates the persistent metadata of the data input
+// that follows it in an execution request.
+bool IsPersistentMetadata(Blob blob);
+
 // Returns true iff `blob` indicates a data input.
 bool IsDataInput(Blob blob);
 
diff --git a/centipede/runner_request_test.cc b/centipede/runner_request_test.cc
new file mode 100644
index 0000000..19a83d0
--- /dev/null
+++ b/centipede/runner_request_test.cc
@@ -0,0 +1,127 @@
+// Copyright 2026 The Centipede Authors.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      https://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "./centipede/runner_request.h"
+
+#include <cstddef>
+#include <cstdint>
+#include <vector>
+
+#include "gtest/gtest.h"
+#include "./centipede/shared_memory_blob_sequence.h"
+#include "./common/defs.h"
+
+namespace fuzztest::internal {
+namespace {
+
+ByteArray ToByteArray(Blob blob) {
+  return ByteArray(blob.data, blob.data + blob.size);
+}
+
+TEST(RequestExecution, WithoutPersistentMetadataIsByteIdentical) {
+  const ByteArray in0 = {10, 11};
+  const ByteArray in1 = {20};
+  const std::vector<ByteSpan> inputs = {in0, in1};
+
+  std::vector<uint8_t> plain(512, 0);
+  std::vector<uint8_t> no_metadata(512, 0);
+  std::vector<uint8_t> all_empty_metadata(512, 0);
+  BlobSequence plain_seq(plain.data(), plain.size());
+  BlobSequence no_metadata_seq(no_metadata.data(), no_metadata.size());
+  BlobSequence all_empty_metadata_seq(all_empty_metadata.data(),
+                                      all_empty_metadata.size());
+
+  ASSERT_EQ(RequestExecution(inputs, plain_seq), 2);
+  ASSERT_EQ(
+      RequestExecution(inputs, /*persistent_metadata=*/{}, no_metadata_seq), 2);
+  ASSERT_EQ(RequestExecution(inputs, std::vector<ByteSpan>{{}, {}},
+                             all_empty_metadata_seq),
+            2);
+
+  EXPECT_EQ(plain, no_metadata);
+  EXPECT_EQ(plain, all_empty_metadata);
+}
+
+TEST(RequestExecution, WritesPersistentMetadataBeforeItsInput) {
+  const ByteArray in0 = {10, 11};
+  const ByteArray in1 = {20};
+  const ByteArray in2 = {30, 31, 32};
+  const ByteArray metadata0 = {1, 2};
+  const ByteArray metadata2 = {3};
+  const std::vector<ByteSpan> inputs = {in0, in1, in2};
+  // Input 1 has no persistent metadata.
+  const std::vector<ByteSpan> persistent_metadata = {metadata0, {}, metadata2};
+
+  std::vector<uint8_t> buffer(1024, 0);
+  BlobSequence blobseq(buffer.data(), buffer.size());
+  ASSERT_EQ(RequestExecution(inputs, persistent_metadata, blobseq), 3);
+  blobseq.Reset();
+
+  EXPECT_TRUE(IsExecutionRequest(blobseq.Read()));
+  size_t num_inputs = 0;
+  ASSERT_TRUE(IsNumInputs(blobseq.Read(), num_inputs));
+  EXPECT_EQ(num_inputs, 3);
+
+  const Blob metadata0_blob = blobseq.Read();
+  ASSERT_TRUE(IsPersistentMetadata(metadata0_blob));
+  EXPECT_FALSE(IsDataInput(metadata0_blob));
+  EXPECT_EQ(ToByteArray(metadata0_blob), metadata0);
+  const Blob in0_blob = blobseq.Read();
+  ASSERT_TRUE(IsDataInput(in0_blob));
+  EXPECT_EQ(ToByteArray(in0_blob), in0);
+
+  const Blob in1_blob = blobseq.Read();
+  EXPECT_FALSE(IsPersistentMetadata(in1_blob));
+  ASSERT_TRUE(IsDataInput(in1_blob));
+  EXPECT_EQ(ToByteArray(in1_blob), in1);
+
+  const Blob metadata2_blob = blobseq.Read();
+  ASSERT_TRUE(IsPersistentMetadata(metadata2_blob));
+  EXPECT_EQ(ToByteArray(metadata2_blob), metadata2);
+  const Blob in2_blob = blobseq.Read();
+  ASSERT_TRUE(IsDataInput(in2_blob));
+  EXPECT_EQ(ToByteArray(in2_blob), in2);
+
+  EXPECT_FALSE(blobseq.Read().IsValid());
+}
+
+TEST(RequestExecution, RejectsPersistentMetadataOfMismatchedSize) {
+  const ByteArray in0 = {10, 11};
+  const ByteArray in1 = {20};
+  const ByteArray metadata0 = {1, 2};
+  std::vector<uint8_t> buffer(512, 0);
+  BlobSequence blobseq(buffer.data(), buffer.size());
+
+  EXPECT_EQ(RequestExecution({in0, in1}, {metadata0}, blobseq), 0);
+}
+
+TEST(RequestExecution, DoesNotCountAnInputWhoseDataDoesNotFit) {
+  const ByteArray in0 = {10, 11};
+  const ByteArray metadata0 = {1, 2};
+  // The size of a request with just the metadata and the input.
+  const size_t request_size = [&] {
+    std::vector<uint8_t> buffer(1024, 0);
+    BlobSequence blobseq(buffer.data(), buffer.size());
+    RequestExecution({in0}, {metadata0}, blobseq);
+    return blobseq.offset();
+  }();
+
+  // One byte short: the metadata fits, but the input does not.
+  std::vector<uint8_t> buffer(request_size - 1, 0);
+  BlobSequence blobseq(buffer.data(), buffer.size());
+  EXPECT_EQ(RequestExecution({in0}, {metadata0}, blobseq), 0);
+}
+
+}  // namespace
+}  // namespace fuzztest::internal
diff --git a/centipede/runner_result.cc b/centipede/runner_result.cc
index 0220d52..637c726 100644
--- a/centipede/runner_result.cc
+++ b/centipede/runner_result.cc
@@ -46,6 +46,9 @@
   kTagHasCustomMutator,
   kTagMutantOrigin,
   kTagMutant,
+
+  // Appended after the mutation result tags to keep the existing tag values.
+  kTagPersistentMetadata,
 };
 
 }  // namespace
@@ -72,13 +75,20 @@
 
 bool BatchResult::WriteMetadata(const ExecutionMetadata &metadata,
                                 BlobSequence &blobseq) {
-  return WriteMetadata(metadata.cmp_data, blobseq);
+  return WriteMetadata(metadata.cmp_data, blobseq) &&
+         WritePersistentMetadata(metadata.persistent_data, blobseq);
 }
 
 bool BatchResult::WriteMetadata(ByteSpan bytes, BlobSequence &blobseq) {
   return blobseq.Write({kTagMetadata, bytes.size(), bytes.data()});
 }
 
+bool BatchResult::WritePersistentMetadata(ByteSpan bytes,
+                                          BlobSequence& blobseq) {
+  if (bytes.empty()) return true;
+  return blobseq.Write({kTagPersistentMetadata, bytes.size(), bytes.data()});
+}
+
 // The sequence we expect to receive is
 // InputBegin, Features, Stats, InputEnd, InputBegin, ...
 // with a total of results().size() tuples (InputBegin ... InputEnd).
@@ -113,6 +123,12 @@
           blob.data, blob.data + blob.size);
       continue;
     }
+    if (blob.tag == kTagPersistentMetadata) {
+      if (current_execution_result == nullptr) return false;
+      current_execution_result->metadata().persistent_data.assign(
+          blob.data, blob.data + blob.size);
+      continue;
+    }
     if (blob.tag == kTagStats) {
       if (current_execution_result == nullptr) return false;
       if (blob.size != sizeof(ExecutionResult::Stats)) return false;
diff --git a/centipede/runner_result.h b/centipede/runner_result.h
index e113c12..5ff1be9 100644
--- a/centipede/runner_result.h
+++ b/centipede/runner_result.h
@@ -129,15 +129,22 @@
   // Writes unit execution stats.
   static bool WriteStats(const ExecutionResult::Stats& stats,
                          BlobSequence& blobseq);
-  // Writes the execution `metadata` to `blobseq`.
+  // Writes the execution `metadata` (the mutation hints and, if non-empty, the
+  // persistent metadata) to `blobseq`.
   // Returns true iff successful.
   static bool WriteMetadata(const ExecutionMetadata& metadata,
                             BlobSequence& blobseq);
 
-  // Writes the execution `metadata` to `blobseq` as raw bytes.
+  // Writes the mutation hints of the execution metadata to `blobseq` as raw
+  // bytes.
   // Returns true iff successful.
   static bool WriteMetadata(ByteSpan bytes, BlobSequence& blobseq);
 
+  // Writes the persistent input metadata to `blobseq` as raw bytes. Writes
+  // nothing if `bytes` is empty.
+  // Returns true iff successful.
+  static bool WritePersistentMetadata(ByteSpan bytes, BlobSequence& blobseq);
+
   // Reads everything written by the runner to `blobseq` into `this`.
   // Returns true iff successful.
   // When running N inputs, ClearAndResize(N) must be called before Read().
diff --git a/centipede/runner_result_test.cc b/centipede/runner_result_test.cc
index 38d6aa3..1857599 100644
--- a/centipede/runner_result_test.cc
+++ b/centipede/runner_result_test.cc
@@ -38,6 +38,7 @@
 namespace {
 
 using ::testing::ElementsAre;
+using ::testing::IsEmpty;
 
 TEST(ExecutionResult, WriteThenRead) {
   auto buffer = std::make_unique<uint8_t[]>(1000);
@@ -270,5 +271,50 @@
       [](ByteSpan, ByteSpan) {}));
 }
 
+TEST(ExecutionResult, ReadsPersistentMetadataSeparatelyFromMutationHints) {
+  auto buffer = std::make_unique<uint8_t[]>(1000);
+  BlobSequence blobseq(buffer.get(), 1000);
+
+  ExecutionMetadata metadata;
+  metadata.cmp_data = {2, 1, 2, 3, 4};
+  metadata.persistent_data = {'p', 0, 'q'};
+  const ByteArray hints_only = {5, 6};
+
+  // Input 0 has both types, input 1 has only mutation hints.
+  EXPECT_TRUE(BatchResult::WriteInputBegin(blobseq));
+  EXPECT_TRUE(BatchResult::WriteMetadata(metadata, blobseq));
+  EXPECT_TRUE(BatchResult::WriteInputEnd(blobseq));
+  EXPECT_TRUE(BatchResult::WriteInputBegin(blobseq));
+  EXPECT_TRUE(BatchResult::WriteMetadata(hints_only, blobseq));
+  EXPECT_TRUE(BatchResult::WritePersistentMetadata({}, blobseq));
+  EXPECT_TRUE(BatchResult::WriteInputEnd(blobseq));
+  blobseq.Reset();
+
+  BatchResult batch_result;
+  batch_result.ClearAndResize(2);
+  EXPECT_TRUE(batch_result.Read(blobseq));
+  ASSERT_EQ(batch_result.num_outputs_read(), 2);
+  EXPECT_EQ(batch_result.results()[0].metadata().cmp_data, metadata.cmp_data);
+  EXPECT_EQ(batch_result.results()[0].metadata().persistent_data,
+            metadata.persistent_data);
+  EXPECT_EQ(batch_result.results()[1].metadata().cmp_data, hints_only);
+  EXPECT_THAT(batch_result.results()[1].metadata().persistent_data, IsEmpty());
+}
+
+TEST(ExecutionResult, EmptyPersistentMetadataDoesNotChangeTheWrittenBytes) {
+  std::vector<uint8_t> without(256, 0);
+  std::vector<uint8_t> with_empty(256, 0);
+  BlobSequence without_seq(without.data(), without.size());
+  BlobSequence with_empty_seq(with_empty.data(), with_empty.size());
+  const ByteArray hints = {13, 14};
+
+  EXPECT_TRUE(BatchResult::WriteMetadata(hints, without_seq));
+  EXPECT_TRUE(BatchResult::WriteMetadata(hints, with_empty_seq));
+  EXPECT_TRUE(BatchResult::WritePersistentMetadata({}, with_empty_seq));
+
+  EXPECT_EQ(without_seq.offset(), with_empty_seq.offset());
+  EXPECT_EQ(without, with_empty);
+}
+
 }  // namespace
 }  // namespace fuzztest::internal
diff --git a/e2e_tests/functional_test.cc b/e2e_tests/functional_test.cc
index 13a2bfb..245bdfc 100644
--- a/e2e_tests/functional_test.cc
+++ b/e2e_tests/functional_test.cc
@@ -916,6 +916,67 @@
   EXPECT_THAT_LOG(std_err, HasSubstr("will not limit jobs"));
 }
 
+TEST_F(GenericCommandLineInterfaceTest, RejectsInvalidDurationFlagUsage) {
+  {
+    auto [status, std_out, std_err] =
+        RunWith(/*flags=*/{{"duration", "1s"}}, /*env=*/{},
+                /*timeout=*/absl::Seconds(10),
+                /*binary=*/"testdata/unit_test_and_fuzz_tests");
+    EXPECT_THAT(status, Ne(ExitCode(0)));
+    EXPECT_THAT_LOG(
+        std_err, AllOf(HasSubstr("duration requires one of"), HasSubstr("fuzz"),
+                       HasSubstr("replay_corpus")));
+  }
+  for (const auto& flags :
+       std::vector<absl::flat_hash_map<std::string, std::string>>{
+           {{"fuzz", "*"}, {"duration", "0s"}},
+           {{"replay_corpus", "*"}, {"duration", "-1s"}},
+       }) {
+    auto [status, std_out, std_err] =
+        RunWith(flags, /*env=*/{}, /*timeout=*/absl::Seconds(10),
+                /*binary=*/"testdata/unit_test_and_fuzz_tests");
+    EXPECT_THAT(status, Ne(ExitCode(0)));
+    EXPECT_THAT_LOG(std_err, HasSubstr("duration must be positive"));
+  }
+}
+
+TEST_F(GenericCommandLineInterfaceTest, RejectsMutuallyExclusiveModeFlags) {
+  for (const auto& flags :
+       std::vector<absl::flat_hash_map<std::string, std::string>>{
+           {{"fuzz", "*"}, {"replay_corpus", "*"}},
+           {{"fuzz_for", "1s"}, {"replay_corpus", "*"}},
+           {{"fuzz", "*"}, {"replay_corpus_for", "1s"}},
+           {{"fuzz_for", "1s"}, {"replay_corpus_for", "1s"}},
+       }) {
+    auto [status, std_out, std_err] =
+        RunWith(flags, /*env=*/{}, /*timeout=*/absl::Seconds(10),
+                /*binary=*/"testdata/unit_test_and_fuzz_tests");
+    EXPECT_THAT(status, Ne(ExitCode(0)));
+    EXPECT_THAT_LOG(std_err, HasSubstr("At most one of"));
+  }
+}
+
+TEST_F(GenericCommandLineInterfaceTest,
+       RejectsCombiningDurationFlagWithLegacyDurationFlags) {
+  for (const auto& flags :
+       std::vector<absl::flat_hash_map<std::string, std::string>>{
+           {{"fuzz", "*"}, {"duration", "1s"}, {"fuzz_for", "1s"}},
+           {{"fuzz", "*"}, {"duration", "1s"}, {"fuzz_for", "inf"}},
+           {{"replay_corpus", "*"},
+            {"duration", "1s"},
+            {"replay_corpus_for", "1s"}},
+           {{"replay_corpus", "*"},
+            {"duration", "1s"},
+            {"replay_corpus_for", "0s"}},
+       }) {
+    auto [status, std_out, std_err] =
+        RunWith(flags, /*env=*/{}, /*timeout=*/absl::Seconds(10),
+                /*binary=*/"testdata/unit_test_and_fuzz_tests");
+    EXPECT_THAT(status, Ne(ExitCode(0)));
+    EXPECT_THAT_LOG(std_err, HasSubstr("cannot be combined with"));
+  }
+}
+
 // Tests for the FuzzTest command line interface in fuzzing mode, which can only
 // run with coverage instrumentation enabled.
 class FuzzingModeCommandLineInterfaceTest
@@ -1465,6 +1526,56 @@
   EXPECT_THAT(status, Eq(ExitCode(0)));
 }
 
+TEST_F(FuzzingModeCommandLineInterfaceTest,
+       FuzzWildcardWithDurationRunsOnlyFuzzTestsAndRespectsFilter) {
+  {
+    auto [status, std_out, std_err] = RunWith(
+        {{"fuzz", "*"}, {"duration", "1s"}}, /*env=*/{},
+        /*timeout=*/absl::Seconds(15), "testdata/unit_test_and_fuzz_tests");
+    EXPECT_THAT_LOG(std_out,
+                    Not(HasSubstr("[ RUN      ] UnitTest.AlwaysPasses")));
+    EXPECT_THAT_LOG(std_out, HasSubstr("[ RUN      ] FuzzTest.AlwaysPasses"));
+    EXPECT_THAT_LOG(std_out,
+                    HasSubstr("[ RUN      ] FuzzTest.AlsoAlwaysPasses"));
+    EXPECT_THAT_LOG(std_out, HasSubstr("2 tests from 1 test suite ran."));
+    EXPECT_THAT(status, Eq(ExitCode(0)));
+  }
+  {
+    auto [status, std_out, std_err] = RunWith(
+        {{"fuzz", "*"}, {"duration", "1s"}}, /*env=*/{},
+        /*timeout=*/absl::Seconds(15), "testdata/unit_test_and_fuzz_tests",
+        {{GTEST_FLAG_PREFIX_ "filter",
+          "UnitTest.AlwaysPasses:FuzzTest.AlsoAlwaysPasses"}});
+    EXPECT_THAT_LOG(std_out,
+                    Not(HasSubstr("[ RUN      ] UnitTest.AlwaysPasses")));
+    EXPECT_THAT_LOG(std_out,
+                    Not(HasSubstr("[ RUN      ] FuzzTest.AlwaysPasses")));
+    EXPECT_THAT_LOG(std_out,
+                    HasSubstr("[ RUN      ] FuzzTest.AlsoAlwaysPasses"));
+    EXPECT_THAT_LOG(std_out, HasSubstr("1 test from 1 test suite ran."));
+    EXPECT_THAT(status, Eq(ExitCode(0)));
+  }
+}
+
+TEST_F(FuzzingModeCommandLineInterfaceTest,
+       ReplayCorpusWildcardWithDurationRunsOnlyFuzzTests) {
+  TempDir temp_dir;
+  const std::string corpus_database = temp_dir.path() / "corpus_database";
+  auto [status, std_out, std_err] = RunWith(
+      {{"replay_corpus", "*"},
+       {"duration", "1s"},
+       {"corpus_database", corpus_database}},
+      // Needed for the legacy runtime to skip fuzzing.
+      /*env=*/{{"FUZZTEST_FUZZ_FOR", "0s"}},
+      /*timeout=*/absl::Seconds(15), "testdata/unit_test_and_fuzz_tests");
+  EXPECT_THAT_LOG(std_out,
+                  Not(HasSubstr("[ RUN      ] UnitTest.AlwaysPasses")));
+  EXPECT_THAT_LOG(std_out, HasSubstr("[ RUN      ] FuzzTest.AlwaysPasses"));
+  EXPECT_THAT_LOG(std_out, HasSubstr("[ RUN      ] FuzzTest.AlsoAlwaysPasses"));
+  EXPECT_THAT_LOG(std_out, HasSubstr("2 tests from 1 test suite ran."));
+  EXPECT_THAT(status, Eq(ExitCode(0)));
+}
+
 // This tests both the command line interface and the fuzzing logic. It is under
 // FuzzingModeCommandLineInterfaceTest so it can specify the command line.
 TEST_F(FuzzingModeCommandLineInterfaceTest, CorpusDoesNotContainSkippedInputs) {
diff --git a/framework_shared/internal/execution_metadata.h b/framework_shared/internal/execution_metadata.h
index e7d860f..7fa7e09 100644
--- a/framework_shared/internal/execution_metadata.h
+++ b/framework_shared/internal/execution_metadata.h
@@ -13,7 +13,8 @@
 // limitations under the License.
 
 // Abstraction of metadata collected from executions that does not
-// contribute to coverage but can be useful in mutation.
+// contribute to coverage: hints that can be useful in mutation, and opaque
+// data that the engine persists per input for the test framework.
 //
 // This library is for both engine and runner.
 
@@ -42,6 +43,11 @@
   //  * `value0` (`size` bytes)
   //  * `value1` (`size` bytes)
   ByteArray cmp_data;
+
+  // Persistent input metadata: opaque bytes that the test framework attaches
+  // to an input, for the engine to store and pass back before a later
+  // execution of the same input. Empty if there is none.
+  ByteArray persistent_data;
 };
 
 }  // namespace fuzztest::internal
diff --git a/fuzztest/init_fuzztest.cc b/fuzztest/init_fuzztest.cc
index a1c9280..d29e0dc 100644
--- a/fuzztest/init_fuzztest.cc
+++ b/fuzztest/init_fuzztest.cc
@@ -55,20 +55,25 @@
 
 FUZZTEST_DEFINE_FLAG(
     std::string, fuzz, std::string(kUnspecified),
-    "Runs a single FUZZ_TEST in continuous fuzzing mode. E.g., "
-    "`--" FUZZTEST_FLAG_PREFIX
+    "Runs a single FUZZ_TEST, or all FUZZ_TESTs when set to `*`, in continuous "
+    "fuzzing mode. E.g., `--" FUZZTEST_FLAG_PREFIX
     "fuzz=MySuite.MyFuzzTest` runs the given FUZZ_TEST in fuzzing mode. You "
     "can also provide just a part of the name, e.g., "
     "`--" FUZZTEST_FLAG_PREFIX
     "fuzz=MyFuzz`, if it matches only a single FUZZ_TEST. If you have only one "
     "fuzz test in your binary, you can also use `--" FUZZTEST_FLAG_PREFIX
     "fuzz=` to run it in fuzzing mode (i.e., by setting the flag to empty "
-    "string). In fuzzing mode the selected test runs until a bug is found or "
-    "until manually stopped. Fuzzing mode uses coverage feedback to "
-    "iteratively build up a corpus of inputs that maximize coverage and to "
-    "reach deep bugs. Note that the binary must be compiled with "
-    "`--config=fuzztest` for this to work, as it needs coverage "
-    "instrumentation.");
+    "string). Setting `--" FUZZTEST_FLAG_PREFIX
+    "fuzz=*` runs all FUZZ_TESTs in the binary (or those matching "
+    "`--" GTEST_FLAG_PREFIX_
+    "filter`). Can be combined with "
+    "`--" FUZZTEST_FLAG_PREFIX
+    "duration=<duration>` to bound the fuzzing time; otherwise the selected "
+    "FUZZ_TEST(s) run until a bug is found or until manually stopped. Fuzzing "
+    "mode uses coverage feedback to iteratively build up a corpus of inputs "
+    "that maximize coverage and to reach deep bugs. Note that the binary must "
+    "be compiled with `--config=fuzztest` for this to work, as it needs "
+    "coverage instrumentation.");
 
 FUZZTEST_DEFINE_FLAG(
     absl::Duration, fuzz_for, absl::InfiniteDuration(),
@@ -105,8 +110,8 @@
 
 FUZZTEST_DEFINE_FLAG(
     std::string, replay_corpus, std::string(kUnspecified),
-    "Runs a single FUZZ_TEST in corpus replay mode. E.g., "
-    "`--" FUZZTEST_FLAG_PREFIX
+    "Runs a single FUZZ_TEST, or all FUZZ_TESTs when set to `*`, in corpus "
+    "replay mode. E.g., `--" FUZZTEST_FLAG_PREFIX
     "replay_corpus=MySuite.MyFuzzTest` replays the corpus from the corpus "
     "database for the given FUZZ_TEST. You can also provide just a part of the "
     "name, e.g., `--" FUZZTEST_FLAG_PREFIX
@@ -114,19 +119,25 @@
     "only one fuzz test in your binary, you can also use "
     "`--" FUZZTEST_FLAG_PREFIX
     "replay_corpus=` to run it in the corpus replay mode (i.e., by setting the "
-    "flag to empty string). In corpus replay mode the selected test replays "
-    "the inputs that exercise unique coverage (corpus) from the corpus "
-    "database. Note that this does not include crashing inputs (counterexample "
-    "findings). Replaying coverage (non-crashing) inputs is useful for "
-    "measuring the coverage of the corpus built up during previously ran "
-    "fuzzing sessions, or to catch newly introduced regressions at presubmit "
-    "time in CI.");
+    "flag to empty string). Setting `--" FUZZTEST_FLAG_PREFIX
+    "replay_corpus=*` replays all FUZZ_TESTs in the binary (or those matching "
+    "`--" GTEST_FLAG_PREFIX_
+    "filter`). Can be combined with "
+    "`--" FUZZTEST_FLAG_PREFIX
+    "duration=<duration>` to bound the replay time; otherwise the entire "
+    "corpus "
+    "is replayed. In corpus replay mode the selected test replays the inputs "
+    "exercise unique coverage (corpus) from the corpus database. Note that "
+    "this does not include crashing inputs (counterexample findings). "
+    "Replaying coverage (non-crashing) inputs is useful for measuring the "
+    "coverage of the corpus built up during previously ran fuzzing sessions, "
+    "or to catch newly introduced regressions at presubmit time in CI.");
 
 FUZZTEST_DEFINE_FLAG(
     absl::Duration, replay_corpus_for, absl::ZeroDuration(),
     "Runs all fuzz tests in corpus replay mode up to the specified duration. "
     "Can be combined with --" FUZZTEST_FLAG_PREFIX
-    "fuzz to select a single fuzz test, or with --" GTEST_FLAG_PREFIX_
+    "replay_corpus to select a single fuzz test, or with --" GTEST_FLAG_PREFIX_
     "filter to select a subset of fuzz tests. To replay the entire corpus for "
     "each FUZZ_TEST in the binary, set this flag to `inf` (infinite time "
     "budget). It's recommended to run the tests in the binary in parallel "
@@ -136,13 +147,22 @@
     "value of --" FUZZTEST_FLAG_PREFIX "time_budget_type.");
 
 FUZZTEST_DEFINE_FLAG(
+    std::optional<absl::Duration>, duration, std::nullopt,
+    "The maximum duration for `--" FUZZTEST_FLAG_PREFIX
+    "fuzz` or `--" FUZZTEST_FLAG_PREFIX
+    "replay_corpus`. Defaults to `inf` (infinite time budget) when omitted. "
+    "Whether the time budget applies per FUZZ_TEST or across all running "
+    "FUZZ_TESTs is controlled by `--" FUZZTEST_FLAG_PREFIX
+    "time_budget_type`.");
+
+FUZZTEST_DEFINE_FLAG(
     fuzztest::internal::TimeBudgetType, time_budget_type,
     fuzztest::internal::TimeBudgetType::kPerTest,
     "Determines whether the time budget specified by --" FUZZTEST_FLAG_PREFIX
-    "fuzz_for or --" FUZZTEST_FLAG_PREFIX
-    "replay_corpus_for is for each FUZZ_TEST or for all 'N' running FUZZ_TESTs "
-    ". In the latter case, each FUZZ_TEST will run for at most (1/N)th of the "
-    "time budget.");
+    "duration, --" FUZZTEST_FLAG_PREFIX "fuzz_for, or --" FUZZTEST_FLAG_PREFIX
+    "replay_corpus_for is for each FUZZ_TEST or for all 'N' running "
+    "FUZZ_TESTs. In the latter case, each FUZZ_TEST will run for at most "
+    "(1/N)th of the time budget.");
 
 FUZZTEST_DEFINE_FLAG(
     std::optional<bool>, update_corpus_database, std::nullopt,
@@ -241,7 +261,8 @@
     absl::InfiniteDuration(),
     "Internal-only flag - do not use directly. If --" FUZZTEST_FLAG_PREFIX
     "internal_override_fuzz_test is set, override the time limit set by "
-    "--" FUZZTEST_FLAG_PREFIX "fuzz_for / --" FUZZTEST_FLAG_PREFIX
+    "--" FUZZTEST_FLAG_PREFIX "duration / --" FUZZTEST_FLAG_PREFIX
+    "fuzz_for / --" FUZZTEST_FLAG_PREFIX
     "replay_corpus_for with --time_budget_type set to total.")
     .OnUpdate([] {
       FUZZTEST_PRECONDITION(
@@ -316,36 +337,74 @@
 namespace {
 
 std::optional<absl::Duration> GetFuzzingTime() {
+  const bool has_fuzz_target =
+      absl::GetFlag(FUZZTEST_FLAG(fuzz)) != kUnspecified;
+  if (const std::optional<absl::Duration> duration =
+          absl::GetFlag(FUZZTEST_FLAG(duration));
+      duration.has_value()) {
+    return has_fuzz_target ? duration : std::nullopt;
+  }
   absl::Duration fuzz_time_limit = absl::GetFlag(FUZZTEST_FLAG(fuzz_for));
   if (fuzz_time_limit <= absl::ZeroDuration()) {
     fuzz_time_limit = absl::InfiniteDuration();
   }
-  if (absl::GetFlag(FUZZTEST_FLAG(fuzz)) == kUnspecified &&
-      fuzz_time_limit == absl::InfiniteDuration()) {
+  if (!has_fuzz_target && fuzz_time_limit == absl::InfiniteDuration()) {
     return std::nullopt;
   }
   return fuzz_time_limit;
 }
 
 std::optional<absl::Duration> GetReplayCorpusTime() {
-  absl::Duration replay_corpus_time_limit =
-      absl::GetFlag(FUZZTEST_FLAG(replay_corpus_for));
-  if (absl::GetFlag(FUZZTEST_FLAG(replay_corpus)) == kUnspecified &&
-      replay_corpus_time_limit <= absl::ZeroDuration()) {
-    return std::nullopt;
+  const bool has_replay_target =
+      absl::GetFlag(FUZZTEST_FLAG(replay_corpus)) != kUnspecified;
+  if (const std::optional<absl::Duration> duration =
+          absl::GetFlag(FUZZTEST_FLAG(duration));
+      duration.has_value()) {
+    return has_replay_target ? duration : std::nullopt;
   }
-  if (absl::GetFlag(FUZZTEST_FLAG(replay_corpus)) != kUnspecified &&
-      replay_corpus_time_limit <= absl::ZeroDuration()) {
-    replay_corpus_time_limit = absl::InfiniteDuration();
+  const absl::Duration replay_corpus_time_limit =
+      absl::GetFlag(FUZZTEST_FLAG(replay_corpus_for));
+  if (replay_corpus_time_limit <= absl::ZeroDuration()) {
+    return has_replay_target
+               ? std::optional<absl::Duration>(absl::InfiniteDuration())
+               : std::nullopt;
   }
   return replay_corpus_time_limit;
 }
 
-bool GetDefaultUpdateCorpusDatabase() {
-  const std::string test_to_fuzz = absl::GetFlag(FUZZTEST_FLAG(fuzz));
-  const bool is_fuzzing =
-      test_to_fuzz != kUnspecified || GetFuzzingTime().has_value();
-  return is_fuzzing && !GetReplayCorpusTime().has_value();
+void ValidateModeAndDurationFlags() {
+  const bool has_fuzz_target =
+      absl::GetFlag(FUZZTEST_FLAG(fuzz)) != kUnspecified;
+  const bool has_replay_target =
+      absl::GetFlag(FUZZTEST_FLAG(replay_corpus)) != kUnspecified;
+  if (const std::optional<absl::Duration> duration =
+          absl::GetFlag(FUZZTEST_FLAG(duration));
+      duration.has_value()) {
+    FUZZTEST_CHECK(has_fuzz_target || has_replay_target)
+        << "--" FUZZTEST_FLAG_PREFIX "duration requires one of --"
+        << FUZZTEST_FLAG_PREFIX "fuzz or --" FUZZTEST_FLAG_PREFIX
+        << "replay_corpus.";
+    FUZZTEST_CHECK(*duration > absl::ZeroDuration())
+        << "--" FUZZTEST_FLAG_PREFIX "duration must be positive (got "
+        << absl::FormatDuration(*duration) << ").";
+    const bool legacy_fuzz_for_specified =
+        FUZZTEST_FLAG(fuzz_for).IsSpecifiedOnCommandLine() ||
+        absl::GetFlag(FUZZTEST_FLAG(fuzz_for)) != absl::InfiniteDuration();
+    const bool legacy_replay_for_specified =
+        FUZZTEST_FLAG(replay_corpus_for).IsSpecifiedOnCommandLine() ||
+        absl::GetFlag(FUZZTEST_FLAG(replay_corpus_for)) != absl::ZeroDuration();
+    FUZZTEST_CHECK(!legacy_fuzz_for_specified && !legacy_replay_for_specified)
+        << "--" FUZZTEST_FLAG_PREFIX "duration cannot be combined with --"
+        << FUZZTEST_FLAG_PREFIX "fuzz_for or --" FUZZTEST_FLAG_PREFIX
+        << "replay_corpus_for.";
+  }
+
+  FUZZTEST_CHECK(!GetFuzzingTime().has_value() ||
+                 !GetReplayCorpusTime().has_value())
+      << "At most one of --" FUZZTEST_FLAG_PREFIX "fuzz / --"
+      << FUZZTEST_FLAG_PREFIX "fuzz_for and --" FUZZTEST_FLAG_PREFIX
+      << "replay_corpus / --" FUZZTEST_FLAG_PREFIX
+      << "replay_corpus_for may be specified at the same time.";
 }
 
 // Expands a leading `~/` to $HOME and, when running under a test, makes a
@@ -365,6 +424,7 @@
 
 internal::Configuration CreateConfigurationsFromFlags(
     absl::string_view binary_identifier) {
+  ValidateModeAndDurationFlags();
   const bool reproduce_findings_as_separate_tests =
       absl::GetFlag(FUZZTEST_FLAG(reproduce_findings_as_separate_tests));
   const std::optional<absl::Duration> fuzzing_time_limit = GetFuzzingTime();
@@ -376,7 +436,8 @@
       fuzzing_time_limit.has_value() || replay_corpus_time_limit.has_value();
   const bool update_corpus_database =
       absl::GetFlag(FUZZTEST_FLAG(update_corpus_database))
-          .value_or(GetDefaultUpdateCorpusDatabase());
+          .value_or(fuzzing_time_limit.has_value() &&
+                    !replay_corpus_time_limit.has_value());
 
   const absl::Duration time_limit =
       override_fuzz_test.has_value()
@@ -464,28 +525,21 @@
     std::cout << std::flush;
     std::exit(0);
   }
+  ValidateModeAndDurationFlags();
   std::optional<absl::Duration> fuzzing_time_limit = GetFuzzingTime();
   std::optional<absl::Duration> replay_corpus_time_limit =
       GetReplayCorpusTime();
-  FUZZTEST_CHECK(!fuzzing_time_limit || !replay_corpus_time_limit)
-      << "Cannot run in fuzzing and corpus replay mode at the same time.";
-  const auto specified_test = []() -> std::optional<std::string> {
-    if (auto internal_selected_test =
-            absl::GetFlag(FUZZTEST_FLAG(internal_override_fuzz_test));
-        internal_selected_test.has_value()) {
-      return internal_selected_test;
+  std::optional<std::string> specified_test =
+      absl::GetFlag(FUZZTEST_FLAG(internal_override_fuzz_test));
+  if (!specified_test.has_value()) {
+    std::string target = absl::GetFlag(FUZZTEST_FLAG(fuzz));
+    if (target == kUnspecified) {
+      target = absl::GetFlag(FUZZTEST_FLAG(replay_corpus));
     }
-    if (auto test_to_fuzz = absl::GetFlag(FUZZTEST_FLAG(fuzz));
-        test_to_fuzz != kUnspecified) {
-      return test_to_fuzz;
+    if (target != kUnspecified && target != "*") {
+      specified_test = std::move(target);
     }
-    if (auto test_to_replay_corpus =
-            absl::GetFlag(FUZZTEST_FLAG(replay_corpus));
-        test_to_replay_corpus != kUnspecified) {
-      return test_to_replay_corpus;
-    }
-    return std::nullopt;
-  }();
+  }
   if (specified_test.has_value()) {
     const std::string matching_fuzz_test =
         GetMatchingFuzzTestOrExit(*specified_test);
diff --git a/fuzztest/internal/configuration.cc b/fuzztest/internal/configuration.cc
index 4ca302f..9d7dce6 100644
--- a/fuzztest/internal/configuration.cc
+++ b/fuzztest/internal/configuration.cc
@@ -218,7 +218,8 @@
       SpaceFor(time_limit_str) + SpaceFor(time_budget_type_str) +
       SpaceFor(jobs) + SpaceFor(centipede_command) +
       SpaceFor(crashing_input_to_reproduce) + SpaceFor(replay_crash_attempts) +
-      SpaceFor(reproduction_command_template));
+      SpaceFor(reproduction_command_template) +
+      SpaceFor(persistent_metadata_root));
   size_t offset = 0;
   offset = WriteString(out, offset, corpus_database);
   offset = WriteString(out, offset, stats_root);
@@ -246,6 +247,7 @@
   offset = WriteOptionalString(out, offset, crashing_input_to_reproduce);
   offset = WriteIntegral(out, offset, replay_crash_attempts);
   offset = WriteOptionalString(out, offset, reproduction_command_template);
+  offset = WriteString(out, offset, persistent_metadata_root);
   FUZZTEST_CHECK_EQ(offset, out.size());
   return out;
 }
@@ -283,6 +285,7 @@
     ASSIGN_OR_RETURN(replay_crash_attempts, Consume<size_t>(serialized));
     ASSIGN_OR_RETURN(reproduction_command_template,
                      ConsumeOptionalString(serialized));
+    ASSIGN_OR_RETURN(persistent_metadata_root, ConsumeString(serialized));
     if (!serialized.empty()) {
       return absl::InvalidArgumentError(
           "Buffer is not empty after consuming a serialized configuration.");
@@ -319,7 +322,8 @@
                          *std::move(centipede_command),
                          *std::move(crashing_input_to_reproduce),
                          *replay_crash_attempts,
-                         *std::move(reproduction_command_template)};
+                         *std::move(reproduction_command_template),
+                         *std::move(persistent_metadata_root)};
   }();
 }
 
diff --git a/fuzztest/internal/configuration.h b/fuzztest/internal/configuration.h
index 8f82196..6831386 100644
--- a/fuzztest/internal/configuration.h
+++ b/fuzztest/internal/configuration.h
@@ -122,6 +122,11 @@
   // - $TEST_FILTER: for replaying only a subset of the tests in a binary.
   std::optional<std::string> reproduction_command_template;
 
+  // If non-empty, the root directory where the engine stores the persistent
+  // input metadata that the test attaches to its inputs, and from where it
+  // passes the stored metadata back before executing the same inputs again.
+  std::string persistent_metadata_root;
+
   // Preprocessing step for reproducing crashing input.
   // Note: This field is not serialized and deserialized.
   // TODO(b/329709054): Consider eliminating the field.
diff --git a/fuzztest/internal/configuration_test.cc b/fuzztest/internal/configuration_test.cc
index 70f9e3a..de42a86 100644
--- a/fuzztest/internal/configuration_test.cc
+++ b/fuzztest/internal/configuration_test.cc
@@ -43,7 +43,8 @@
              other->crashing_input_to_reproduce &&
          config.replay_crash_attempts == other->replay_crash_attempts &&
          config.reproduction_command_template ==
-             other->reproduction_command_template;
+             other->reproduction_command_template &&
+         config.persistent_metadata_root == other->persistent_metadata_root;
 }
 
 TEST(ConfigurationTest,
@@ -106,7 +107,8 @@
                               "centipede_command",
                               "crashing_input_to_reproduce",
                               /*replay_crash_attempts=*/20,
-                              "reproduction_command_template"};
+                              "reproduction_command_template",
+                              "persistent_metadata_root"};
 
   EXPECT_THAT(Configuration::Deserialize(configuration.Serialize()),
               IsOkAndEquals(configuration));
diff --git a/rust/engine/src/engine_ffi.rs b/rust/engine/src/engine_ffi.rs
index e1c0f07..004e378 100644
--- a/rust/engine/src/engine_ffi.rs
+++ b/rust/engine/src/engine_ffi.rs
@@ -146,6 +146,56 @@
     >,
 }
 
+/// Types of input metadata. The engine handles each type differently, and the
+/// content of every type is opaque to the engine.
+///
+/// Represented as an integer rather than a Rust enum, since values received
+/// from the engine are not guaranteed to be one of the known constants.
+#[repr(transparent)]
+#[derive(Debug, Copy, Clone, PartialEq, Eq)]
+pub struct FuzzTestInputMetadataType(pub u32);
+
+impl FuzzTestInputMetadataType {
+    /// Hints for mutating the input (e.g. the operands of comparisons seen when
+    /// executing it). Kept in memory only, and passed back to the adapter for
+    /// the origin inputs of mutations.
+    pub const MUTATION_HINTS: Self = Self(0);
+    /// Metadata that the engine may store for the input and pass back to the
+    /// adapter before a later execution of the same input.
+    pub const PERSISTENT: Self = Self(1);
+}
+
+/// A piece of input metadata of a given type.
+#[repr(C)]
+#[derive(Debug, Copy, Clone)]
+pub struct FuzzTestInputMetadataView {
+    pub metadata_type: FuzzTestInputMetadataType,
+    pub bytes: FuzzTestBytesView,
+}
+
+#[repr(C)]
+pub struct FuzzTestInputMetadataSinkCtx {
+    _opaque: (),
+    _not_send_nor_sync: PhantomData<*mut ()>,
+    _not_unpin: PhantomPinned,
+}
+
+/// Sink for input metadata.
+#[repr(C)]
+#[derive(Copy, Clone)]
+pub struct FuzzTestInputMetadataSink {
+    pub ctx: *mut FuzzTestInputMetadataSinkCtx,
+
+    /// Emits a piece of input metadata. Multiple emissions of the same type are
+    /// concatenated. A type that is never emitted is treated as absent.
+    pub emit: Option<
+        unsafe extern "C" fn(
+            ctx: *mut FuzzTestInputMetadataSinkCtx,
+            metadata: *const FuzzTestInputMetadataView,
+        ),
+    >,
+}
+
 #[repr(C)]
 pub struct FuzzTestInputSinkCtx {
     _opaque: (),
@@ -376,20 +426,25 @@
         ),
     >,
 
-    /// [Optional] Serializes the test `input` metadata into bytes using `sink`.
+    /// [Optional] Serializes the test `input` metadata, of any type, using
+    /// `sink`.
     pub serialize_input_metadata: Option<
         unsafe extern "C" fn(
             ctx: *mut FuzzTestAdapterCtx,
             input: FuzzTestInputHandle,
-            sink: *const FuzzTestBytesSink,
+            sink: *const FuzzTestInputMetadataSink,
         ),
     >,
 
-    /// [Optional] Updates the test `input` metadata from serialized `metadata`.
+    /// [Optional] Updates the test `input` metadata of type
+    /// `metadata.metadata_type` from the serialized `metadata.bytes`. Called
+    /// with the mutation hints of mutation origins before
+    /// `Mutate`/`CrossOver`, and with the persistent metadata stored for
+    /// `input` (if any) before `Execute`.
     pub update_input_metadata: Option<
         unsafe extern "C" fn(
             ctx: *mut FuzzTestAdapterCtx,
-            metadata: *const FuzzTestBytesView,
+            metadata: *const FuzzTestInputMetadataView,
             input: FuzzTestInputHandle,
         ),
     >,