diff --git a/.github/workflows/validate_wrapper.yml b/.github/workflows/validate_wrapper.yml index 3ced051..aa57eb4 100644 --- a/.github/workflows/validate_wrapper.yml +++ b/.github/workflows/validate_wrapper.yml @@ -521,7 +521,7 @@ jobs: run: >- cmake --build build/wrapper-contract --target llamadart_owner_api_test llamadart_owner_reentrancy_test - llamadart_model_fd_test llamadart_threadpool_test + llamadart_file_sha256_test llamadart_model_fd_test llamadart_threadpool_test llamadart_grammar_top_k_test llamadart_f16_dot_accumulation_test llamadart_speculative_api_test @@ -657,7 +657,7 @@ jobs: cmake --build --preset windows-x64-full --target llamadart_barrier_test llamadart_owner_api_test llamadart_owner_reentrancy_test - llamadart_model_fd_test + llamadart_file_sha256_test llamadart_model_fd_test llamadart_build_identity_test llamadart_upstream_abi_test llamadart_cancel_flag_test llamadart_exit_teardown_test @@ -676,7 +676,7 @@ jobs: $wrapperDir = (Resolve-Path build/wx64).Path $upstreamDir = (Resolve-Path build/wx64/bin).Path $env:PATH = "$wrapperDir;$upstreamDir;$env:PATH" - ctest --test-dir build/wx64 -R "owner_api|owner_reentrant|model_fd|barrier|build_identity|upstream_abi|cancel_flag|vocabulary|reasoning-budget|vulkan_device_info|device_memory|fit_api|tts_api|tts_types|asr_stream|tts_stream|image_token_limit" --timeout 120 --output-on-failure + ctest --test-dir build/wx64 -R "owner_api|owner_reentrant|file_sha256|model_fd|barrier|build_identity|upstream_abi|cancel_flag|vocabulary|reasoning-budget|vulkan_device_info|device_memory|fit_api|tts_api|tts_types|asr_stream|tts_stream|image_token_limit" --timeout 120 --output-on-failure - name: Validate wrapper exports shell: pwsh run: | @@ -734,7 +734,7 @@ jobs: - name: Build the exit teardown test run: >- cmake --build ${{ matrix.build_dir }} --target - llamadart_owner_api_test llamadart_owner_reentrancy_test llamadart_model_fd_test llamadart_threadpool_test llamadart_exit_teardown_test llamadart_image_token_limit_test llamadart_fit_api_test llamadart_device_memory_test + llamadart_owner_api_test llamadart_owner_reentrancy_test llamadart_file_sha256_test llamadart_model_fd_test llamadart_threadpool_test llamadart_exit_teardown_test llamadart_image_token_limit_test llamadart_fit_api_test llamadart_device_memory_test llamadart_grammar_top_k_test llamadart_build_identity_test llamadart_cancel_flag_test llamadart_f16_dot_accumulation_test @@ -750,7 +750,7 @@ jobs: # the Metal library, which takes most of a minute. - name: Run the exit teardown scenarios run: >- - ctest --test-dir ${{ matrix.build_dir }} -R "owner_|model_fd|threadpool|exit_teardown|grammar_top_k|image_token_limit|fit_api|device_memory|build_identity|cancel_flag|f16_dot_accumulation|f16_residual_kernels|upstream_abi|mtmd_compat|asr_stream" + ctest --test-dir ${{ matrix.build_dir }} -R "owner_|file_sha256|model_fd|threadpool|exit_teardown|grammar_top_k|image_token_limit|fit_api|device_memory|build_identity|cancel_flag|f16_dot_accumulation|f16_residual_kernels|upstream_abi|mtmd_compat|asr_stream" --timeout 300 --output-on-failure # Apple CPUs have FHM, so the shipped build takes the FMLAL branch of # patch 0005. ARMv8.2-A with FP16 compiles its conversion branch, as on diff --git a/CMakeLists.txt b/CMakeLists.txt index e6a00d6..dc2df5b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -318,6 +318,7 @@ endif() add_library(llamadart_lib SHARED "src/llama_dart_wrapper.cpp" "src/llama_dart_build_identity.cpp" + "src/llama_dart_file_sha256.cpp" "src/llama_dart_image_token_limit.cpp" "src/llama_dart_device_memory.cpp" "src/llama_dart_vulkan_device_info.cpp") @@ -338,6 +339,7 @@ if (NOT EXISTS "${LLAMADART_VULKAN_HEADERS_INCLUDE}/vulkan/vulkan_core.h") message(FATAL_ERROR "Missing submodule: third_party/Vulkan-Headers. Run: git submodule update --init --recursive") endif() target_include_directories(llamadart_lib SYSTEM PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}/third_party/llama.cpp/vendor/hash" "${LLAMADART_VULKAN_HEADERS_INCLUDE}") target_link_libraries(llamadart_lib PRIVATE ${CMAKE_DL_LIBS}) if (MSVC) @@ -651,6 +653,14 @@ if (LLAMADART_BUILD_TESTS) add_test(NAME llamadart_cancel_flag_flag COMMAND llamadart_cancel_flag_test flag) + add_executable(llamadart_file_sha256_test tests/file_sha256_test.cpp) + target_compile_features(llamadart_file_sha256_test PRIVATE cxx_std_17) + target_compile_definitions(llamadart_file_sha256_test PRIVATE LLAMADART_TESTING=1) + target_include_directories(llamadart_file_sha256_test PRIVATE src) + target_link_libraries(llamadart_file_sha256_test PRIVATE llamadart_lib Threads::Threads) + add_test(NAME llamadart_file_sha256_contract COMMAND llamadart_file_sha256_test) + set_tests_properties(llamadart_file_sha256_contract PROPERTIES TIMEOUT 30) + add_executable(llamadart_model_fd_test tests/model_fd_test.cpp) target_compile_features(llamadart_model_fd_test PRIVATE cxx_std_17) target_link_libraries(llamadart_model_fd_test PRIVATE llamadart_lib) @@ -993,7 +1003,7 @@ if (LLAMADART_BUILD_TESTS) llamadart_build_identity_test llamadart_upstream_abi_test llamadart_cancel_flag_test llamadart_tts_eval_test llamadart_tts_seed_test llamadart_tts_batch_test llamadart_tts_sampler_test llamadart_exit_teardown_test llamadart_model_fd_test llamadart_threadpool_test - llamadart_grammar_top_k_test + llamadart_grammar_top_k_test llamadart_file_sha256_test llamadart_mtmd_compat_test llamadart_vulkan_device_info_test llamadart_barrier_test llamadart_image_token_limit_test llamadart_fit_api_test llamadart_device_memory_test) diff --git a/README.md b/README.md index 989fd19..a674104 100644 --- a/README.md +++ b/README.md @@ -294,6 +294,23 @@ Generic MTP initialization requires empty target memory and checks rollback support before accepting the session. See [the MTP rollback contract and local component checks](docs/speculative_mtp_rollback.md). +## File SHA-256 + +Bindings can look up `llama_dart_file_sha256_api_version` and require version +1 to hash a downloaded model before initializing a backend. On older bundles +the symbol may be absent. Call `llama_dart_file_sha256` on a worker thread +with a stable regular file, a 32-byte output and an optional cancel byte. +Compare the raw digest with the expected checksum only on status zero. The +[public header](src/llama_dart_wrapper.h) defines the status codes. A directory +returns open failure (2) on Windows and read error (3) on POSIX. + +The wrapper reads 256 KiB at a time and checks for I/O errors and size changes +through EOF. Android and Linux arm64 select SHA-2 instructions when the CPU +advertises them. Apple arm64 uses the same instructions. Other targets use +llama.cpp's vendored public-domain SHA-256 implementation. To measure a +1 GiB file with a Release test build, run +`llamadart_file_sha256_test --benchmark`. + ## Exit Teardown ggml-metal aborts in its static destructor diff --git a/src/llama_dart_file_sha256.cpp b/src/llama_dart_file_sha256.cpp new file mode 100644 index 0000000..09da341 --- /dev/null +++ b/src/llama_dart_file_sha256.cpp @@ -0,0 +1,184 @@ +#include "llama_dart_wrapper.h" +#include "llama_dart_cancel_eval_internal.h" +#include "llama_dart_file_sha256_test_hooks.h" + +#include +#include +#include +#include +#include +#include + +#if defined(_WIN32) +#include +#else +#include +#include +#endif + +#if defined(__aarch64__) && defined(__AARCH64EL__) && (defined(__linux__) || defined(__APPLE__)) +#include +#if defined(__linux__) +#include +#include +#endif +#define LLAMADART_ARM_SHA2 1 +#endif + +namespace { +// Keep the upstream public-domain implementation private to the wrapper. +// Its constants, state and padding are shared by both compression paths. +#include "sha256/sha256.c" + +constexpr size_t chunk_size = 256 * 1024; + +#if defined(LLAMADART_ARM_SHA2) +bool has_arm_sha2() { +#if defined(__linux__) + return (getauxval(AT_HWCAP) & HWCAP_SHA2) != 0; +#else + return true; // SHA-256 instructions are baseline on Apple arm64. +#endif +} + +__attribute__((target("+crypto"), noinline)) void hash_blocks(sha256_t &ctx, const uint8_t *bytes, + size_t size) { + uint32x4_t abcd = vld1q_u32(ctx.state); + uint32x4_t efgh = vld1q_u32(ctx.state + 4); + for (size_t offset = 0; offset < size; offset += 64) { + const auto initial_abcd = abcd; + const auto initial_efgh = efgh; + uint32x4_t words[4]; + for (unsigned i = 0; i < 4; ++i) { + words[i] = vreinterpretq_u32_u8(vrev32q_u8(vld1q_u8(bytes + offset + 16 * i))); + } + // Constant indices keep the four message vectors in registers. +#if defined(__clang__) +#pragma clang loop unroll(full) +#else +#pragma GCC unroll 16 +#endif + for (unsigned group = 0; group < 16; ++group) { + const unsigned i = group % 4; + const auto rounds = vaddq_u32(words[i], vld1q_u32(K + 4 * group)); + if (group < 12) { + words[i] = vsha256su1q_u32(vsha256su0q_u32(words[i], words[(i + 1) % 4]), + words[(i + 2) % 4], words[(i + 3) % 4]); + } + const auto old_abcd = abcd; + abcd = vsha256hq_u32(abcd, efgh, rounds); + efgh = vsha256h2q_u32(efgh, old_abcd, rounds); + } + abcd = vaddq_u32(abcd, initial_abcd); + efgh = vaddq_u32(efgh, initial_efgh); + } + vst1q_u32(ctx.state, abcd); + vst1q_u32(ctx.state + 4, efgh); + ctx.count += size; +} +#endif + +llama_dart_file_sha256_status hash_stream(FILE *file, uint64_t remaining, uint8_t digest[32], + const int8_t *cancel_flag) { + std::unique_ptr buffer( + static_cast(std::malloc(chunk_size)), std::free); + if (!buffer) + return LLAMA_DART_FILE_SHA256_OUT_OF_MEMORY; + + sha256_t ctx; + sha256_init(&ctx); +#if defined(LLAMADART_ARM_SHA2) + const bool accelerated = has_arm_sha2(); +#endif + while (remaining > 0) { + if (llama_dart_cancel_flag_set(cancel_flag)) + return LLAMA_DART_FILE_SHA256_CANCELLED; + const size_t wanted = static_cast(std::min(remaining, chunk_size)); + const size_t n = std::fread(buffer.get(), 1, wanted, file); + if (std::ferror(file)) + return LLAMA_DART_FILE_SHA256_READ_ERROR; + if (n != wanted) + return LLAMA_DART_FILE_SHA256_SHORT_READ; + size_t blocks = 0; +#if defined(LLAMADART_ARM_SHA2) + if (accelerated) { + blocks = n - n % 64; + hash_blocks(ctx, buffer.get(), blocks); + } +#endif + sha256_update(&ctx, buffer.get() + blocks, n - blocks); + remaining -= n; + } + if (std::fgetc(file) != EOF) + return LLAMA_DART_FILE_SHA256_FILE_GREW; + if (std::ferror(file)) + return LLAMA_DART_FILE_SHA256_READ_ERROR; + if (llama_dart_cancel_flag_set(cancel_flag)) + return LLAMA_DART_FILE_SHA256_CANCELLED; + sha256_final(&ctx, digest); + return LLAMA_DART_FILE_SHA256_OK; +} + +FILE *open_file(const char *path) { +#ifdef _WIN32 + return ggml_fopen(path, "rb"); +#else + // Inspect the opened object without blocking on a FIFO with no writer. + const int fd = open(path, O_RDONLY | O_CLOEXEC | O_NONBLOCK); + if (fd < 0) + return nullptr; + FILE *file = fdopen(fd, "rb"); + if (!file) + close(fd); + return file; +#endif +} + +int64_t file_size(FILE *file) { +#ifdef _WIN32 + struct _stat64 info; + if (_fstat64(_fileno(file), &info) != 0 || (info.st_mode & _S_IFMT) != _S_IFREG) + return -1; +#else + struct stat info; + if (fstat(fileno(file), &info) != 0 || !S_ISREG(info.st_mode)) + return -1; +#endif + return info.st_size; +} + +llama_dart_file_sha256_status hash_and_close(FILE *file, int64_t size, uint8_t out_digest[32], + const int8_t *cancel_flag) { + uint8_t digest[32]; + auto status = size < 0 ? LLAMA_DART_FILE_SHA256_READ_ERROR + : hash_stream(file, static_cast(size), digest, cancel_flag); + if (std::fclose(file) != 0 && status == LLAMA_DART_FILE_SHA256_OK) { + return LLAMA_DART_FILE_SHA256_READ_ERROR; + } + if (status == LLAMA_DART_FILE_SHA256_OK) + std::memcpy(out_digest, digest, sizeof(digest)); + return status; +} +} // namespace + +uint32_t llama_dart_file_sha256_api_version(void) { return 1; } + +llama_dart_file_sha256_status llama_dart_file_sha256(const char *path, uint8_t out_digest[32], + const int8_t *cancel_flag) { + if (!path || !*path || !out_digest) + return LLAMA_DART_FILE_SHA256_INVALID_ARGUMENT; + if (llama_dart_cancel_flag_set(cancel_flag)) + return LLAMA_DART_FILE_SHA256_CANCELLED; + FILE *file = open_file(path); + if (!file) + return LLAMA_DART_FILE_SHA256_OPEN_FAILED; + return hash_and_close(file, file_size(file), out_digest, cancel_flag); +} + +#if defined(LLAMADART_TESTING) && !defined(_WIN32) +llama_dart_file_sha256_status llama_dart_test_sha256_and_close(FILE *file, int64_t size, + uint8_t digest[32], + const int8_t *cancel_flag) { + return hash_and_close(file, size, digest, cancel_flag); +} +#endif diff --git a/src/llama_dart_file_sha256_test_hooks.h b/src/llama_dart_file_sha256_test_hooks.h new file mode 100644 index 0000000..f4b7d03 --- /dev/null +++ b/src/llama_dart_file_sha256_test_hooks.h @@ -0,0 +1,10 @@ +#pragma once + +#if defined(LLAMADART_TESTING) && !defined(_WIN32) +#include "llama_dart_wrapper.h" +#include + +extern "C" LLAMADART_API enum llama_dart_file_sha256_status +llama_dart_test_sha256_and_close(FILE *file, int64_t size, uint8_t digest[32], + const int8_t *cancel_flag); +#endif diff --git a/src/llama_dart_wrapper.h b/src/llama_dart_wrapper.h index e19e56c..2ff3f48 100644 --- a/src/llama_dart_wrapper.h +++ b/src/llama_dart_wrapper.h @@ -260,7 +260,7 @@ LLAMADART_API void llama_dart_set_log_level(int level); // llama_dart_clear_last_error first to learn whether a free threw. // // The functions without a barrier are llama_dart_build_identity, -// llama_dart_last_error, llama_dart_clear_last_error, +// the llama_dart_file_sha256 functions, llama_dart_last_error, llama_dart_clear_last_error, // llama_dart_set_log_level, the // llama_dart_exit_ functions other than llama_dart_exit_track and // llama_dart_exit_free, the draft context getter and @@ -536,6 +536,30 @@ LLAMADART_API struct llama_model * llama_dart_model_load_from_file( const char * path_model, struct llama_model_params params); +// Optional full-file SHA-256 API. Resolve this probe and require version 1. +LLAMADART_API uint32_t llama_dart_file_sha256_api_version(void); + +enum llama_dart_file_sha256_status { + LLAMA_DART_FILE_SHA256_OK = 0, + LLAMA_DART_FILE_SHA256_INVALID_ARGUMENT = 1, + LLAMA_DART_FILE_SHA256_OPEN_FAILED = 2, + LLAMA_DART_FILE_SHA256_READ_ERROR = 3, + LLAMA_DART_FILE_SHA256_SHORT_READ = 4, + LLAMA_DART_FILE_SHA256_CANCELLED = 5, + LLAMA_DART_FILE_SHA256_FILE_GREW = 6, + LLAMA_DART_FILE_SHA256_OUT_OF_MEMORY = 7, +}; + +// Hash a stable regular file at a NUL-terminated UTF-8 path, on any thread, +// without initializing a model or backend. Only OK writes the 32 digest bytes. +// OPEN_FAILED includes a directory rejected by the Windows file open. +// READ_ERROR includes a failed size query or an opened non-regular file. SHORT_READ +// and FILE_GREW compare the bytes read with the opened file's initial size. +// cancel_flag may be NULL. Otherwise keep it live until return and set it +// atomically to a nonzero byte to cancel between reads. +LLAMADART_API enum llama_dart_file_sha256_status llama_dart_file_sha256( + const char * path, uint8_t out_digest[32], const int8_t * cancel_flag); + // Model load from a caller-owned file descriptor, API v1. See // docs/model_load_from_fd.md. Returns 0 where the platform has no descriptor // loader (Windows) and 1 elsewhere; check it before use. diff --git a/tests/file_sha256_test.cpp b/tests/file_sha256_test.cpp new file mode 100644 index 0000000..cdef28d --- /dev/null +++ b/tests/file_sha256_test.cpp @@ -0,0 +1,242 @@ +#ifdef NDEBUG +#error "Wrapper contract tests require active assertions in every configuration" +#endif + +#include "llama_dart_file_sha256_test_hooks.h" +#include "llama_dart_wrapper.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef _WIN32 +#include +#include +#include +#endif + +namespace fs = std::filesystem; +using Digest = std::array; + +static std::string hex(const Digest &bytes) { + const char digits[] = "0123456789abcdef"; + std::string result; + for (auto byte : bytes) { + result += digits[byte >> 4]; + result += digits[byte & 15]; + } + return result; +} + +static void verify(const fs::path &path, const char *expected) { + Digest digest; + assert(llama_dart_file_sha256(path.u8string().c_str(), digest.data(), nullptr) == + LLAMA_DART_FILE_SHA256_OK); + assert(hex(digest) == expected); +} + +static void write_pattern(const fs::path &path, size_t size) { + std::array block; + for (size_t i = 0; i < block.size(); ++i) + block[i] = static_cast(i % 251); + std::ofstream file(path, std::ios::binary); + while (size) { + const size_t count = std::min(size, block.size()); + file.write(block.data(), count); + size -= count; + } + file.close(); + assert(file); +} + +#if defined(__APPLE__) || defined(__linux__) +enum class FaultAt { read, chunk_cancel, eof_cancel, close }; + +struct Fault { + size_t remaining; + FaultAt at; + std::atomic cancel{0}; +}; + +#if defined(__APPLE__) +using ReadCount = int; +using ReadResult = int; +#else +using ReadCount = size_t; +using ReadResult = ssize_t; +#endif + +static ReadResult read_until_fault(void *data, char *buffer, ReadCount size) { + auto &fault = *static_cast(data); + if (fault.remaining == 0) { + if (fault.at == FaultAt::read) { + errno = EIO; + return -1; + } + if (fault.at == FaultAt::eof_cancel) + fault.cancel.store(1); + return 0; + } + const size_t count = std::min(fault.remaining, static_cast(size)); + std::memset(buffer, 'a', count); + fault.remaining -= count; + if (fault.remaining == 0 && fault.at == FaultAt::chunk_cancel) + fault.cancel.store(1); + return static_cast(count); +} + +static int close_cookie(void *data) { + if (static_cast(data)->at == FaultAt::close) { + errno = EIO; + return -1; + } + return 0; +} + +static void check_fault(int64_t reported_size, FaultAt at, llama_dart_file_sha256_status expected) { + Fault fault{256 * 1024, at}; +#if defined(__APPLE__) + FILE *file = funopen(&fault, read_until_fault, nullptr, nullptr, close_cookie); +#else + cookie_io_functions_t io{}; + io.read = read_until_fault; + io.close = close_cookie; + FILE *file = fopencookie(&fault, "r", io); +#endif + assert(file); + Digest digest; + digest.fill(0xa5); + const Digest original = digest; + const auto status = llama_dart_test_sha256_and_close( + file, reported_size, digest.data(), reinterpret_cast(&fault.cancel)); + assert(status == expected); + assert(digest == original); +} +#endif + +static void check_errors(const fs::path &path) { + Digest digest; + digest.fill(0xa5); + const Digest original = digest; + const auto name = path.u8string(); + assert(llama_dart_file_sha256(nullptr, digest.data(), nullptr) == + LLAMA_DART_FILE_SHA256_INVALID_ARGUMENT); + assert(llama_dart_file_sha256("", digest.data(), nullptr) == + LLAMA_DART_FILE_SHA256_INVALID_ARGUMENT); + assert(llama_dart_file_sha256(name.c_str(), nullptr, nullptr) == + LLAMA_DART_FILE_SHA256_INVALID_ARGUMENT); + std::atomic flag{1}; + assert(llama_dart_file_sha256(name.c_str(), digest.data(), + reinterpret_cast(&flag)) == + LLAMA_DART_FILE_SHA256_CANCELLED); + assert(llama_dart_file_sha256(name.c_str(), digest.data(), nullptr) == + LLAMA_DART_FILE_SHA256_OPEN_FAILED); + assert(digest == original); +#ifdef _WIN32 + assert(llama_dart_file_sha256(path.parent_path().u8string().c_str(), digest.data(), nullptr) == + LLAMA_DART_FILE_SHA256_OPEN_FAILED); +#else + const auto reject_non_regular = [&](const fs::path &input) { + assert(llama_dart_file_sha256(input.c_str(), digest.data(), nullptr) == + LLAMA_DART_FILE_SHA256_READ_ERROR); + assert(digest == original); + }; + reject_non_regular(path.parent_path()); + reject_non_regular("/dev/null"); + const auto fifo = path.parent_path() / "fifo"; + assert(mkfifo(fifo.c_str(), 0600) == 0); + reject_non_regular(fifo); + const int reader = open(fifo.c_str(), O_RDONLY | O_NONBLOCK); + assert(reader >= 0); + const int writer = open(fifo.c_str(), O_WRONLY | O_NONBLOCK); + assert(writer >= 0); + assert(write(writer, "x", 1) == 1); + reject_non_regular(fifo); + assert(close(writer) == 0); + assert(close(reader) == 0); + fs::remove(fifo); + + const auto check_size = [&](int64_t size, llama_dart_file_sha256_status expected) { + FILE *file = std::tmpfile(); + assert(file); + assert(std::fputs("abc", file) >= 0); + std::rewind(file); + assert(llama_dart_test_sha256_and_close(file, size, digest.data(), nullptr) == expected); + assert(digest == original); + }; + check_size(4, LLAMA_DART_FILE_SHA256_SHORT_READ); + check_size(2, LLAMA_DART_FILE_SHA256_FILE_GREW); +#endif + assert(digest == original); +#if defined(__APPLE__) || defined(__linux__) + constexpr int64_t chunk = 256 * 1024; + check_fault(chunk, FaultAt::read, LLAMA_DART_FILE_SHA256_READ_ERROR); + check_fault(chunk + 17, FaultAt::read, LLAMA_DART_FILE_SHA256_READ_ERROR); + check_fault(2 * chunk, FaultAt::chunk_cancel, LLAMA_DART_FILE_SHA256_CANCELLED); + check_fault(chunk, FaultAt::eof_cancel, LLAMA_DART_FILE_SHA256_CANCELLED); + check_fault(chunk, FaultAt::close, LLAMA_DART_FILE_SHA256_READ_ERROR); +#endif +} + +static void contract(const fs::path &path) { + assert(llama_dart_file_sha256_api_version() == 1); + check_errors(path); + std::ofstream(path, std::ios::binary).close(); + verify(path, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); + std::ofstream(path, std::ios::binary) << "abc"; + verify(path, "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"); + std::ofstream(path, std::ios::binary) << std::string(1000000, 'a'); + verify(path, "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0"); + const struct { + size_t size; + const char *digest; + } cases[] = { + {55, "463eb28e72f82e0a96c0a4cc53690c571281131f672aa229e0d45ae59b598b59"}, + {56, "da2ae4d6b36748f2a318f23e7ab1dfdf45acdc9d049bd80e59de82a60895f562"}, + {64, "fdeab9acf3710362bd2658cdc9a29e8f9c757fcf9811603a8c447cd1d9151108"}, + {262143, "196dccc11397ed99dd89ef516d2d483ef6a972d0a7e6e68568c33c79e965264d"}, + {262144, "3ff95170f300cd932540858091f015f83bc14a1fb755b28e45b22e1659191a52"}, + {262145, "bf01c537a991ad17343aca67cbd5c1c727caa8cfce4d50fd579806ae49b72b94"}, + {524295, "ec986e5be8467d8ecdfb24ff8883cef45fbc8b355c2e00f8511a054715f9268a"}, + }; + for (const auto &item : cases) { + write_pattern(path, item.size); + verify(path, item.digest); + } + std::ofstream(path, std::ios::binary).seekp(32 * 1024 * 1024).put('z'); + const char *expected = "20b63966fbf19b73cbf9f9d2103adafa06b8b22063dd8bef9edd3ab95219905a"; + std::thread worker(verify, path, expected); + verify(path, expected); + worker.join(); +} + +int main(int argc, char **argv) { + using clock = std::chrono::steady_clock; + const auto dir = fs::temp_directory_path() / + ("llamadart-sha256-" + std::to_string(clock::now().time_since_epoch().count())); + assert(fs::create_directory(dir)); + const auto path = dir / fs::u8path(u8"mod\u00e8le.bin"); + if (argc == 2 && std::strcmp(argv[1], "--benchmark") == 0) { + constexpr size_t size = 1ULL << 30; + write_pattern(path, size); + for (int i = 0; i < 3; ++i) { + const auto start = clock::now(); + verify(path, "acf95004a24ae06e1d9f80ae37e1cbe3491a20ba839c5926ff7937f81ccd1083"); + const double seconds = std::chrono::duration(clock::now() - start).count(); + std::printf("%.4f s, %.2f MB/s\n", seconds, size / seconds / 1e6); + } + } else { + contract(path); + } + fs::remove(path); + fs::remove(dir); +} diff --git a/tests/test_validate_exports.py b/tests/test_validate_exports.py index ec0a1d2..110a425 100644 --- a/tests/test_validate_exports.py +++ b/tests/test_validate_exports.py @@ -56,8 +56,8 @@ def test_speculative_retirement_inventory_retains_nextn_query(self): self.assertEqual(len(retiring), 15) required = set(validate_exports.DEFAULT_REQUIRED_SYMBOLS) self.assertFalse(required & retiring) - self.assertEqual(len(validate_exports.DEFAULT_REQUIRED_SYMBOLS), 120) - self.assertEqual(len(required), 120) + self.assertEqual(len(validate_exports.DEFAULT_REQUIRED_SYMBOLS), 122) + self.assertEqual(len(required), 122) self.assertIn('llama_dart_speculative_need_embd_nextn', required) self.assertEqual(len(validate_exports.RETIRED_SPECULATIVE_SYMBOLS), 15) self.assertEqual(set(validate_exports.RETIRED_SPECULATIVE_SYMBOLS), retiring) @@ -88,7 +88,15 @@ def test_full_surviving_export_inventory_is_accepted(self): result, diagnostics = self.validate_synthetic_exports( validate_exports.DEFAULT_REQUIRED_SYMBOLS) self.assertEqual(result, 0, diagnostics) - self.assertIn('Validated 120 required export(s)', diagnostics) + self.assertIn('Validated 122 required export(s)', diagnostics) + + def test_file_hash_requires_both_version_and_operation(self): + for name in ('llama_dart_file_sha256', 'llama_dart_file_sha256_api_version'): + with self.subTest(symbol=name): + result, diagnostics = self.validate_synthetic_exports( + s for s in validate_exports.DEFAULT_REQUIRED_SYMBOLS if s != name) + self.assertEqual(result, 1, diagnostics) + self.assertIn(f' - {name}\n', diagnostics) def test_missing_grammar_top_k_constructor_fails_with_other_required_exports(self): constructor = 'llama_dart_sampler_init_grammar_top_k' diff --git a/tools/validate_exports.py b/tools/validate_exports.py index 507cec3..e6db416 100644 --- a/tools/validate_exports.py +++ b/tools/validate_exports.py @@ -13,6 +13,8 @@ DEFAULT_REQUIRED_SYMBOLS = [ "llama_dart_build_identity", + "llama_dart_file_sha256_api_version", + "llama_dart_file_sha256", "llama_dart_last_error", "llama_dart_clear_last_error", "llama_dart_vulkan_get_device_count",