[llvm] 29fd868 - [llvm/CAS] Improve layering and decouple `UnifiedOnDiskCache` from the builtin hash implementation (#177280)

via llvm-commits llvm-commits at lists.llvm.org
Mon Jan 26 09:48:36 PST 2026


Author: Argyrios Kyrtzidis
Date: 2026-01-26T09:48:32-08:00
New Revision: 29fd8686914d8de51851e776606003464790e938

URL: https://github.com/llvm/llvm-project/commit/29fd8686914d8de51851e776606003464790e938
DIFF: https://github.com/llvm/llvm-project/commit/29fd8686914d8de51851e776606003464790e938.diff

LOG: [llvm/CAS] Improve layering and decouple `UnifiedOnDiskCache` from the builtin hash implementation (#177280)

Added: 
    llvm/include/llvm/CAS/ValidationResult.h

Modified: 
    llvm/include/llvm/CAS/BuiltinUnifiedCASDatabases.h
    llvm/include/llvm/CAS/OnDiskGraphDB.h
    llvm/include/llvm/CAS/UnifiedOnDiskCache.h
    llvm/lib/CAS/ActionCaches.cpp
    llvm/lib/CAS/BuiltinCAS.cpp
    llvm/lib/CAS/BuiltinCAS.h
    llvm/lib/CAS/BuiltinUnifiedCASDatabases.cpp
    llvm/lib/CAS/OnDiskCAS.cpp
    llvm/lib/CAS/OnDiskGraphDB.cpp
    llvm/lib/CAS/UnifiedOnDiskCache.cpp
    llvm/unittests/CAS/ActionCacheTest.cpp
    llvm/unittests/CAS/BuiltinUnifiedCASDatabasesTest.cpp
    llvm/unittests/CAS/CASTestConfig.cpp
    llvm/unittests/CAS/CASTestConfig.h
    llvm/unittests/CAS/ObjectStoreTest.cpp
    llvm/unittests/CAS/UnifiedOnDiskCacheTest.cpp

Removed: 
    


################################################################################
diff  --git a/llvm/include/llvm/CAS/BuiltinUnifiedCASDatabases.h b/llvm/include/llvm/CAS/BuiltinUnifiedCASDatabases.h
index 0ac9386f1cda1..e95e50b46e863 100644
--- a/llvm/include/llvm/CAS/BuiltinUnifiedCASDatabases.h
+++ b/llvm/include/llvm/CAS/BuiltinUnifiedCASDatabases.h
@@ -9,6 +9,7 @@
 #ifndef LLVM_CAS_BUILTINUNIFIEDCASDATABASES_H
 #define LLVM_CAS_BUILTINUNIFIEDCASDATABASES_H
 
+#include "llvm/CAS/ValidationResult.h"
 #include "llvm/Support/Error.h"
 
 namespace llvm::cas {
@@ -22,19 +23,6 @@ LLVM_ABI
 Expected<std::pair<std::unique_ptr<ObjectStore>, std::unique_ptr<ActionCache>>>
 createOnDiskUnifiedCASDatabases(StringRef Path);
 
-/// Represents the result of validating the contents using
-/// \c validateOnDiskUnifiedCASDatabasesIfNeeded.
-///
-/// Note: invalid results are handled as an \c Error.
-enum class ValidationResult {
-  /// The data is already valid.
-  Valid,
-  /// The data was invalid, but was recovered.
-  Recovered,
-  /// Validation was skipped, as it was not needed.
-  Skipped,
-};
-
 /// Validate the data in \p Path, if needed to ensure correctness.
 ///
 /// \param Path directory for the on-disk database.

diff  --git a/llvm/include/llvm/CAS/OnDiskGraphDB.h b/llvm/include/llvm/CAS/OnDiskGraphDB.h
index 52e56ddba1243..64ad83440bc9c 100644
--- a/llvm/include/llvm/CAS/OnDiskGraphDB.h
+++ b/llvm/include/llvm/CAS/OnDiskGraphDB.h
@@ -342,7 +342,7 @@ class OnDiskGraphDB {
 
   /// Checks that \p ID exists in the index. It is allowed to not have data
   /// associated with it.
-  LLVM_ABI_FOR_TEST Error validateObjectID(ObjectID ID);
+  LLVM_ABI_FOR_TEST Error validateObjectID(ObjectID ID) const;
 
   /// How to fault-in nodes if an upstream database is used.
   enum class FaultInPolicy {

diff  --git a/llvm/include/llvm/CAS/UnifiedOnDiskCache.h b/llvm/include/llvm/CAS/UnifiedOnDiskCache.h
index c03733a28fc99..54dd8c0571735 100644
--- a/llvm/include/llvm/CAS/UnifiedOnDiskCache.h
+++ b/llvm/include/llvm/CAS/UnifiedOnDiskCache.h
@@ -9,8 +9,8 @@
 #ifndef LLVM_CAS_UNIFIEDONDISKCACHE_H
 #define LLVM_CAS_UNIFIEDONDISKCACHE_H
 
-#include "llvm/CAS/BuiltinUnifiedCASDatabases.h"
 #include "llvm/CAS/OnDiskGraphDB.h"
+#include "llvm/CAS/ValidationResult.h"
 #include <atomic>
 
 namespace llvm::cas::ondisk {
@@ -43,9 +43,15 @@ class UnifiedOnDiskCache {
   /// The \p OnDiskGraphDB instance for the open directory.
   OnDiskGraphDB &getGraphDB() { return *PrimaryGraphDB; }
 
+  /// The \p OnDiskGraphDB instance for the open directory.
+  const OnDiskGraphDB &getGraphDB() const { return *PrimaryGraphDB; }
+
   /// The \p OnDiskGraphDB instance for the open directory.
   OnDiskKeyValueDB &getKeyValueDB() { return *PrimaryKVDB; }
 
+  /// The \p OnDiskGraphDB instance for the open directory.
+  const OnDiskKeyValueDB &getKeyValueDB() const { return *PrimaryKVDB; }
+
   /// Open a \p UnifiedOnDiskCache instance for a directory.
   ///
   /// \param Path directory for the on-disk database. The directory will be
@@ -89,9 +95,13 @@ class UnifiedOnDiskCache {
   /// in an invalid state because \p AllowRecovery is false.
   static Expected<ValidationResult>
   validateIfNeeded(StringRef Path, StringRef HashName, unsigned HashByteSize,
-                   bool CheckHash, bool AllowRecovery, bool ForceValidation,
+                   bool CheckHash, OnDiskGraphDB::HashingFuncT HashFn,
+                   bool AllowRecovery, bool ForceValidation,
                    std::optional<StringRef> LLVMCasBinary);
 
+  /// Validate the action cache only.
+  LLVM_ABI_FOR_TEST Error validateActionCache() const;
+
   /// This is called implicitly at destruction time, so it is not required for a
   /// client to call this. After calling \p close the only method that is valid
   /// to call is \p needsGarbageCollection.

diff  --git a/llvm/include/llvm/CAS/ValidationResult.h b/llvm/include/llvm/CAS/ValidationResult.h
new file mode 100644
index 0000000000000..bd3d2999bda9e
--- /dev/null
+++ b/llvm/include/llvm/CAS/ValidationResult.h
@@ -0,0 +1,29 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CAS_VALIDATIONRESULT_H
+#define LLVM_CAS_VALIDATIONRESULT_H
+
+namespace llvm::cas {
+
+/// Represents the result of validating the contents using
+/// \c validateOnDiskUnifiedCASDatabasesIfNeeded.
+///
+/// Note: invalid results are handled as an \c Error.
+enum class ValidationResult {
+  /// The data is already valid.
+  Valid,
+  /// The data was invalid, but was recovered.
+  Recovered,
+  /// Validation was skipped, as it was not needed.
+  Skipped,
+};
+
+} // namespace llvm::cas
+
+#endif // LLVM_CAS_VALIDATIONRESULT_H

diff  --git a/llvm/lib/CAS/ActionCaches.cpp b/llvm/lib/CAS/ActionCaches.cpp
index 31b841f16ceba..89cdd481e185a 100644
--- a/llvm/lib/CAS/ActionCaches.cpp
+++ b/llvm/lib/CAS/ActionCaches.cpp
@@ -242,20 +242,7 @@ Error UnifiedOnDiskActionCache::putImpl(ArrayRef<uint8_t> Key,
 }
 
 Error UnifiedOnDiskActionCache::validate() const {
-  auto ValidateRef = [this](FileOffset Offset, ArrayRef<char> Value) -> Error {
-    auto ID = ondisk::UnifiedOnDiskCache::getObjectIDFromValue(Value);
-    auto formatError = [&](Twine Msg) {
-      return createStringError(
-          llvm::errc::illegal_byte_sequence,
-          "bad record at 0x" +
-              utohexstr((unsigned)Offset.get(), /*LowerCase=*/true) + ": " +
-              Msg.str());
-    };
-    if (Error E = UniDB->getGraphDB().validateObjectID(ID))
-      return formatError(llvm::toString(std::move(E)));
-    return Error::success();
-  };
-  return UniDB->getKeyValueDB().validate(ValidateRef);
+  return UniDB->validateActionCache();
 }
 
 Expected<std::unique_ptr<ActionCache>>

diff  --git a/llvm/lib/CAS/BuiltinCAS.cpp b/llvm/lib/CAS/BuiltinCAS.cpp
index e9bc6d8beed4e..173456665b054 100644
--- a/llvm/lib/CAS/BuiltinCAS.cpp
+++ b/llvm/lib/CAS/BuiltinCAS.cpp
@@ -104,3 +104,11 @@ cas::builtin::createBuiltinUnifiedOnDiskCache(StringRef Path) {
   return createStringError(inconvertibleErrorCode(), "OnDiskCache is disabled");
 #endif
 }
+
+void cas::builtin::hashingFunc(ArrayRef<ArrayRef<uint8_t>> Refs,
+                               ArrayRef<char> Data,
+                               SmallVectorImpl<uint8_t> &Result) {
+  auto Hash =
+      BuiltinObjectHasher<llvm::cas::builtin::HasherT>::hashObject(Refs, Data);
+  Result.assign(Hash.begin(), Hash.end());
+}

diff  --git a/llvm/lib/CAS/BuiltinCAS.h b/llvm/lib/CAS/BuiltinCAS.h
index 4d2de66cf636f..7b45a59a883e3 100644
--- a/llvm/lib/CAS/BuiltinCAS.h
+++ b/llvm/lib/CAS/BuiltinCAS.h
@@ -85,6 +85,10 @@ std::unique_ptr<ObjectStore> createObjectStoreFromUnifiedOnDiskCache(
 std::unique_ptr<ActionCache> createActionCacheFromUnifiedOnDiskCache(
     std::shared_ptr<ondisk::UnifiedOnDiskCache> UniDB);
 
+/// Convenience wrapper for \c BuiltinObjectHasher.
+void hashingFunc(ArrayRef<ArrayRef<uint8_t>> Refs, ArrayRef<char> Data,
+                 SmallVectorImpl<uint8_t> &Result);
+
 // FIXME: Proxy not portable. Maybe also error-prone?
 constexpr StringLiteral DefaultDirProxy = "/^llvm::cas::builtin::default";
 constexpr StringLiteral DefaultDir = "llvm.cas.builtin.default";

diff  --git a/llvm/lib/CAS/BuiltinUnifiedCASDatabases.cpp b/llvm/lib/CAS/BuiltinUnifiedCASDatabases.cpp
index f3f6fa043bc52..8283e981b1099 100644
--- a/llvm/lib/CAS/BuiltinUnifiedCASDatabases.cpp
+++ b/llvm/lib/CAS/BuiltinUnifiedCASDatabases.cpp
@@ -30,8 +30,8 @@ Expected<ValidationResult> cas::validateOnDiskUnifiedCASDatabasesIfNeeded(
 #if LLVM_ENABLE_ONDISK_CAS
   return ondisk::UnifiedOnDiskCache::validateIfNeeded(
       Path, builtin::BuiltinCASContext::getHashName(),
-      sizeof(builtin::HashType), CheckHash, AllowRecovery, ForceValidation,
-      LLVMCasBinary);
+      sizeof(builtin::HashType), CheckHash, builtin::hashingFunc, AllowRecovery,
+      ForceValidation, LLVMCasBinary);
 #else
   return createStringError(inconvertibleErrorCode(), "OnDiskCache is disabled");
 #endif

diff  --git a/llvm/lib/CAS/OnDiskCAS.cpp b/llvm/lib/CAS/OnDiskCAS.cpp
index 1f0f84556d153..cb3b7d92fa965 100644
--- a/llvm/lib/CAS/OnDiskCAS.cpp
+++ b/llvm/lib/CAS/OnDiskCAS.cpp
@@ -8,7 +8,6 @@
 
 #include "BuiltinCAS.h"
 #include "llvm/CAS/BuiltinCASContext.h"
-#include "llvm/CAS/BuiltinObjectHasher.h"
 #include "llvm/CAS/OnDiskCASLogger.h"
 #include "llvm/CAS/OnDiskGraphDB.h"
 #include "llvm/CAS/UnifiedOnDiskCache.h"
@@ -91,14 +90,7 @@ class OnDiskCAS : public BuiltinCAS {
 
 void OnDiskCAS::print(raw_ostream &OS) const { DB->print(OS); }
 Error OnDiskCAS::validate(bool CheckHash) const {
-  auto Hasher = [](ArrayRef<ArrayRef<uint8_t>> Refs, ArrayRef<char> Data,
-                   SmallVectorImpl<uint8_t> &Result) {
-    auto Hash = BuiltinObjectHasher<llvm::cas::builtin::HasherT>::hashObject(
-        Refs, Data);
-    Result.assign(Hash.begin(), Hash.end());
-  };
-
-  if (auto E = DB->validate(CheckHash, Hasher))
+  if (auto E = DB->validate(CheckHash, builtin::hashingFunc))
     return E;
 
   return Error::success();

diff  --git a/llvm/lib/CAS/OnDiskGraphDB.cpp b/llvm/lib/CAS/OnDiskGraphDB.cpp
index 36f779c119b12..2aaec22b10701 100644
--- a/llvm/lib/CAS/OnDiskGraphDB.cpp
+++ b/llvm/lib/CAS/OnDiskGraphDB.cpp
@@ -1029,7 +1029,7 @@ Error OnDiskGraphDB::validate(bool Deep, HashingFuncT Hasher) const {
   });
 }
 
-Error OnDiskGraphDB::validateObjectID(ObjectID ExternalRef) {
+Error OnDiskGraphDB::validateObjectID(ObjectID ExternalRef) const {
   auto formatError = [&](Twine Msg) {
     return createStringError(
         llvm::errc::illegal_byte_sequence,

diff  --git a/llvm/lib/CAS/UnifiedOnDiskCache.cpp b/llvm/lib/CAS/UnifiedOnDiskCache.cpp
index 80da30644d20f..ac3552c4f6330 100644
--- a/llvm/lib/CAS/UnifiedOnDiskCache.cpp
+++ b/llvm/lib/CAS/UnifiedOnDiskCache.cpp
@@ -66,7 +66,6 @@
 //===----------------------------------------------------------------------===//
 
 #include "llvm/CAS/UnifiedOnDiskCache.h"
-#include "BuiltinCAS.h"
 #include "OnDiskCommon.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/ScopeExit.h"
@@ -74,7 +73,6 @@
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringExtras.h"
 #include "llvm/ADT/StringRef.h"
-#include "llvm/CAS/ActionCache.h"
 #include "llvm/CAS/OnDiskCASLogger.h"
 #include "llvm/CAS/OnDiskGraphDB.h"
 #include "llvm/CAS/OnDiskKeyValueDB.h"
@@ -253,26 +251,42 @@ static Error validateOutOfProcess(StringRef LLVMCasBinary, StringRef RootPath,
   return Error::success();
 }
 
+Error UnifiedOnDiskCache::validateActionCache() const {
+  auto ValidateRef = [this](FileOffset Offset, ArrayRef<char> Value) -> Error {
+    auto ID = ondisk::UnifiedOnDiskCache::getObjectIDFromValue(Value);
+    auto formatError = [&](Twine Msg) {
+      return createStringError(
+          llvm::errc::illegal_byte_sequence,
+          "bad record at 0x" +
+              utohexstr((unsigned)Offset.get(), /*LowerCase=*/true) + ": " +
+              Msg.str());
+    };
+    if (Error E = this->getGraphDB().validateObjectID(ID))
+      return formatError(llvm::toString(std::move(E)));
+    return Error::success();
+  };
+  return getKeyValueDB().validate(ValidateRef);
+}
+
 static Error validateInProcess(StringRef RootPath, StringRef HashName,
-                               unsigned HashByteSize, bool CheckHash) {
+                               unsigned HashByteSize, bool CheckHash,
+                               OnDiskGraphDB::HashingFuncT HashFn) {
   std::shared_ptr<UnifiedOnDiskCache> UniDB;
   if (Error E = UnifiedOnDiskCache::open(RootPath, std::nullopt, HashName,
                                          HashByteSize)
                     .moveInto(UniDB))
     return E;
-  auto CAS = builtin::createObjectStoreFromUnifiedOnDiskCache(UniDB);
-  if (Error E = CAS->validate(CheckHash))
+  if (Error E = UniDB->getGraphDB().validate(CheckHash, HashFn))
     return E;
-  auto Cache = builtin::createActionCacheFromUnifiedOnDiskCache(UniDB);
-  if (Error E = Cache->validate())
+  if (Error E = UniDB->validateActionCache())
     return E;
   return Error::success();
 }
 
 Expected<ValidationResult> UnifiedOnDiskCache::validateIfNeeded(
     StringRef RootPath, StringRef HashName, unsigned HashByteSize,
-    bool CheckHash, bool AllowRecovery, bool ForceValidation,
-    std::optional<StringRef> LLVMCasBinaryPath) {
+    bool CheckHash, OnDiskGraphDB::HashingFuncT HashFn, bool AllowRecovery,
+    bool ForceValidation, std::optional<StringRef> LLVMCasBinaryPath) {
   if (std::error_code EC = sys::fs::create_directories(RootPath))
     return createFileError(RootPath, EC);
 
@@ -333,10 +347,10 @@ Expected<ValidationResult> UnifiedOnDiskCache::validateIfNeeded(
 
   // Validate!
   bool NeedsRecovery = false;
-  Error E =
-      LLVMCasBinaryPath
-          ? validateOutOfProcess(*LLVMCasBinaryPath, RootPath, CheckHash)
-          : validateInProcess(RootPath, HashName, HashByteSize, CheckHash);
+  Error E = LLVMCasBinaryPath
+                ? validateOutOfProcess(*LLVMCasBinaryPath, RootPath, CheckHash)
+                : validateInProcess(RootPath, HashName, HashByteSize, CheckHash,
+                                    HashFn);
   if (E) {
     if (Logger)
       LogValidationError = toStringWithoutConsuming(E);

diff  --git a/llvm/unittests/CAS/ActionCacheTest.cpp b/llvm/unittests/CAS/ActionCacheTest.cpp
index 692da230b6e09..b925aa4b55f66 100644
--- a/llvm/unittests/CAS/ActionCacheTest.cpp
+++ b/llvm/unittests/CAS/ActionCacheTest.cpp
@@ -19,6 +19,7 @@
 
 using namespace llvm;
 using namespace llvm::cas;
+using namespace llvm::unittest::cas;
 
 TEST_P(CASTest, ActionCacheHit) {
   std::unique_ptr<ObjectStore> CAS = createObjectStore();

diff  --git a/llvm/unittests/CAS/BuiltinUnifiedCASDatabasesTest.cpp b/llvm/unittests/CAS/BuiltinUnifiedCASDatabasesTest.cpp
index 19522e9372d85..ed659edf4d842 100644
--- a/llvm/unittests/CAS/BuiltinUnifiedCASDatabasesTest.cpp
+++ b/llvm/unittests/CAS/BuiltinUnifiedCASDatabasesTest.cpp
@@ -16,6 +16,7 @@
 
 using namespace llvm;
 using namespace llvm::cas;
+using namespace llvm::unittest::cas;
 
 TEST_F(OnDiskCASTest, UnifiedCASMaterializationCheckPreventsGarbageCollection) {
   unittest::TempDir Temp("on-disk-unified-cas", /*Unique=*/true);

diff  --git a/llvm/unittests/CAS/CASTestConfig.cpp b/llvm/unittests/CAS/CASTestConfig.cpp
index 08cbf1daf727d..364f8eb1d2ee8 100644
--- a/llvm/unittests/CAS/CASTestConfig.cpp
+++ b/llvm/unittests/CAS/CASTestConfig.cpp
@@ -7,13 +7,50 @@
 //===----------------------------------------------------------------------===//
 
 #include "CASTestConfig.h"
+#include "OnDiskCommonUtils.h"
 #include "llvm/CAS/ObjectStore.h"
+#include "llvm/Support/SHA1.h"
 #include "llvm/Testing/Support/Error.h"
 #include "gtest/gtest.h"
 #include <mutex>
 
 using namespace llvm;
 using namespace llvm::cas;
+using namespace llvm::unittest::cas;
+
+Expected<ObjectID> CustomHasherOnDiskCASTest::store(OnDiskGraphDB &DB,
+                                                    StringRef Data,
+                                                    ArrayRef<ObjectID> Refs) {
+  ObjectID ID = digest(DB, Data, Refs);
+  if (Error E = DB.store(ID, Refs, arrayRefFromStringRef<char>(Data)))
+    return std::move(E);
+  return ID;
+}
+
+CustomHasherOnDiskCASTest::HashType
+CustomHasherOnDiskCASTest::digest(StringRef Data,
+                                  ArrayRef<ArrayRef<uint8_t>> RefHashes) {
+  HashType Digest;
+  auto HashFn = GetParam().HashFn;
+  HashFn(RefHashes, arrayRefFromStringRef<char>(Data), Digest);
+  return Digest;
+}
+
+ObjectID CustomHasherOnDiskCASTest::digest(OnDiskGraphDB &DB, StringRef Data,
+                                           ArrayRef<ObjectID> Refs) {
+  SmallVector<ArrayRef<uint8_t>, 8> RefHashes;
+  for (ObjectID Ref : Refs)
+    RefHashes.push_back(DB.getDigest(Ref));
+  HashType Digest = digest(Data, RefHashes);
+  std::optional<ObjectID> ID;
+  EXPECT_THAT_ERROR(DB.getReference(Digest).moveInto(ID), Succeeded());
+  return *ID;
+}
+
+CustomHasherOnDiskCASTest::HashType
+CustomHasherOnDiskCASTest::digest(StringRef Data) {
+  return digest(Data, {});
+}
 
 static CASTestingEnv createInMemory(int I) {
   return CASTestingEnv{createInMemoryCAS(), createInMemoryActionCache(),
@@ -28,7 +65,7 @@ namespace llvm::cas::ondisk {
 void setMaxMappingSize(uint64_t Size);
 } // namespace llvm::cas::ondisk
 
-void setMaxOnDiskCASMappingSize() {
+void unittest::cas::setMaxOnDiskCASMappingSize() {
   static std::once_flag Flag;
   std::call_once(
       Flag, [] { llvm::cas::ondisk::setMaxMappingSize(100 * 1024 * 1024); });
@@ -44,6 +81,31 @@ static CASTestingEnv createOnDisk(int I) {
   return CASTestingEnv{std::move(CAS), std::move(Cache), std::move(Temp)};
 }
 INSTANTIATE_TEST_SUITE_P(OnDiskCAS, CASTest, ::testing::Values(createOnDisk));
+
+static void builtinDigest(ArrayRef<ArrayRef<uint8_t>> Refs, ArrayRef<char> Data,
+                          SmallVectorImpl<uint8_t> &Result) {
+  llvm::unittest::cas::HashType Digest =
+      llvm::unittest::cas::digest(toStringRef(Data), Refs);
+  Result.assign(Digest.begin(), Digest.end());
+}
+
+INSTANTIATE_TEST_SUITE_P(Builtin, CustomHasherOnDiskCASTest,
+                         ::testing::Values(CustomHasherParam{
+                             builtinDigest, "builtin",
+                             sizeof(llvm::unittest::cas::HashType)}));
+
+using SHA1HashType = decltype(SHA1::hash(std::declval<ArrayRef<uint8_t> &>()));
+
+static void sha1Digest(ArrayRef<ArrayRef<uint8_t>> Refs, ArrayRef<char> Data,
+                       SmallVectorImpl<uint8_t> &Result) {
+  SHA1HashType Digest = BuiltinObjectHasher<SHA1>::hashObject(Refs, Data);
+  Result.assign(Digest.begin(), Digest.end());
+}
+
+INSTANTIATE_TEST_SUITE_P(SHA1, CustomHasherOnDiskCASTest,
+                         ::testing::Values(CustomHasherParam{
+                             sha1Digest, "SHA1", sizeof(SHA1HashType)}));
+
 #else
 void setMaxOnDiskCASMappingSize() {}
 #endif /* LLVM_ENABLE_ONDISK_CAS */

diff  --git a/llvm/unittests/CAS/CASTestConfig.h b/llvm/unittests/CAS/CASTestConfig.h
index e3139c931ddd6..7b36ad9690565 100644
--- a/llvm/unittests/CAS/CASTestConfig.h
+++ b/llvm/unittests/CAS/CASTestConfig.h
@@ -20,14 +20,21 @@
 #include "llvm/Support/Windows/WindowsSupport.h"
 #endif
 
+namespace llvm::cas::ondisk {
+class ObjectID;
+class OnDiskGraphDB;
+} // namespace llvm::cas::ondisk
+
 namespace llvm::unittest::cas {
+
+using namespace llvm::cas::ondisk;
+
 class MockEnv {
   void anchor();
 
 public:
   virtual ~MockEnv();
 };
-} // namespace llvm::unittest::cas
 
 struct CASTestingEnv {
   std::unique_ptr<llvm::cas::ObjectStore> CAS;
@@ -49,6 +56,36 @@ class OnDiskCASTest : public ::testing::Test {
   }
 };
 
+struct CustomHasherParam {
+  std::function<void(ArrayRef<ArrayRef<uint8_t>>, ArrayRef<char>,
+                     SmallVectorImpl<uint8_t> &)>
+      HashFn;
+  std::string HashName;
+  size_t HashSize;
+};
+
+// Test fixture for on-disk data base tests with custom hasher.
+class CustomHasherOnDiskCASTest
+    : public ::testing::TestWithParam<CustomHasherParam> {
+protected:
+  void SetUp() override {
+#if !LLVM_ENABLE_ONDISK_CAS
+    GTEST_SKIP() << "OnDiskCAS is not enabled";
+#endif
+    // Use a smaller database size for testing to conserve disk space.
+    setMaxOnDiskCASMappingSize();
+  }
+
+  using HashType = SmallVector<uint8_t, 32>;
+
+  Expected<ObjectID> store(OnDiskGraphDB &DB, StringRef Data,
+                           ArrayRef<ObjectID> Refs);
+
+  ObjectID digest(OnDiskGraphDB &DB, StringRef Data, ArrayRef<ObjectID> Refs);
+  HashType digest(StringRef Data, ArrayRef<ArrayRef<uint8_t>> RefHashes);
+  HashType digest(StringRef Data);
+};
+
 // Parametered test fixture for ObjectStore and ActionCache tests.
 class CASTest
     : public testing::TestWithParam<std::function<CASTestingEnv(int)>> {
@@ -89,4 +126,6 @@ class CASTest
   }
 };
 
+} // namespace llvm::unittest::cas
+
 #endif

diff  --git a/llvm/unittests/CAS/ObjectStoreTest.cpp b/llvm/unittests/CAS/ObjectStoreTest.cpp
index b43ae33d74127..d7c059566a457 100644
--- a/llvm/unittests/CAS/ObjectStoreTest.cpp
+++ b/llvm/unittests/CAS/ObjectStoreTest.cpp
@@ -18,6 +18,7 @@
 
 using namespace llvm;
 using namespace llvm::cas;
+using namespace llvm::unittest::cas;
 
 TEST_P(CASTest, PrintIDs) {
   std::unique_ptr<ObjectStore> CAS = createObjectStore();

diff  --git a/llvm/unittests/CAS/UnifiedOnDiskCacheTest.cpp b/llvm/unittests/CAS/UnifiedOnDiskCacheTest.cpp
index 09aebc2d4bc19..084a61d90e879 100644
--- a/llvm/unittests/CAS/UnifiedOnDiskCacheTest.cpp
+++ b/llvm/unittests/CAS/UnifiedOnDiskCacheTest.cpp
@@ -42,25 +42,29 @@ static Expected<size_t> countFileSizes(StringRef Path) {
   return TotalSize;
 }
 
-TEST_F(OnDiskCASTest, UnifiedOnDiskCacheTest) {
+TEST_P(CustomHasherOnDiskCASTest, UnifiedOnDiskCacheTest) {
+  auto HashFn = GetParam().HashFn;
+  StringRef HashName = GetParam().HashName;
+  size_t HashSize = GetParam().HashSize;
+
   unittest::TempDir Temp("ondisk-unified", /*Unique=*/true);
   std::unique_ptr<UnifiedOnDiskCache> UniDB;
 
   const uint64_t SizeLimit = 1024ull * 64;
   auto reopenDB = [&]() {
     UniDB.reset();
-    ASSERT_THAT_ERROR(UnifiedOnDiskCache::open(Temp.path(), SizeLimit, "blake3",
-                                               sizeof(HashType))
-                          .moveInto(UniDB),
-                      Succeeded());
+    ASSERT_THAT_ERROR(
+        UnifiedOnDiskCache::open(Temp.path(), SizeLimit, HashName, HashSize)
+            .moveInto(UniDB),
+        Succeeded());
   };
 
   reopenDB();
 
-  HashType RootHash;
-  HashType OtherHash;
-  HashType Key1Hash;
-  HashType Key2Hash;
+  HashType RootHash(HashSize);
+  HashType OtherHash(HashSize);
+  HashType Key1Hash(HashSize);
+  HashType Key2Hash(HashSize);
   {
     OnDiskGraphDB &DB = UniDB->getGraphDB();
     std::optional<ObjectID> ID1;
@@ -126,6 +130,17 @@ TEST_F(OnDiskCASTest, UnifiedOnDiskCacheTest) {
   checkKey(Key1Hash, "root");
   checkKey(Key2Hash, "1");
 
+  ASSERT_THAT_ERROR(UniDB->validateActionCache(), Succeeded());
+  std::optional<ValidationResult> ValidationRes;
+  ASSERT_THAT_ERROR(UnifiedOnDiskCache::validateIfNeeded(
+                        Temp.path(), HashName, HashSize, /*CheckHash=*/true,
+                        HashFn, /*AllowRecovery=*/false,
+                        /*ForceValidation=*/true,
+                        /*LLVMCasBinary=*/std::nullopt)
+                        .moveInto(ValidationRes),
+                    Succeeded());
+  ASSERT_EQ(ValidationRes, ValidationResult::Valid);
+
   auto storeBigObject = [&](unsigned Index) {
     SmallString<1000> Buf;
     Buf.append(970, 'a');


        


More information about the llvm-commits mailing list