Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions .github/workflows/build-wasm.yml
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,9 @@ jobs:
run: |
git clone https://github.com/emscripten-core/emsdk.git
cd emsdk
./emsdk install latest
./emsdk activate latest
EMSDK_VERSION=7.0.0
./emsdk install "$EMSDK_VERSION"
./emsdk activate "$EMSDK_VERSION"

- name: Fetch emdawnwebgpu
run: |
Expand Down
12 changes: 11 additions & 1 deletion include/llama.h
Original file line number Diff line number Diff line change
Expand Up @@ -973,7 +973,17 @@ extern "C" {
// `<path>.tmp` and a rename. read_file fills a persona made by llama_persona_init on a context of the same memory
// layout, for the owner and epoch her file names; file_mismatch (another owner, epoch, layout or size) and io_error
// leave her as she was. Bind her afterwards as after a save.
LLAMA_API int32_t llama_persona_write_file(const struct llama_persona * persona, const char * path);
enum llama_persona_file_stage {
LLAMA_PERSONA_FILE_NONE, LLAMA_PERSONA_FILE_OPEN, LLAMA_PERSONA_FILE_WRITE,
LLAMA_PERSONA_FILE_FLUSH, LLAMA_PERSONA_FILE_CLOSE, LLAMA_PERSONA_FILE_RENAME,
};
struct llama_persona_write_result {
int32_t status;
enum llama_persona_file_stage stage;
// errno, except for RENAME on Windows where this is GetLastError().
uint32_t os_error;
};
LLAMA_API struct llama_persona_write_result llama_persona_write_checkpoint(const struct llama_persona * persona, const char * path);
LLAMA_API int32_t llama_persona_read_file(struct llama_persona * persona, const char * path);

LLAMA_API const char * llama_persona_status_name(int32_t status);
Expand Down
64 changes: 50 additions & 14 deletions src/llama-persona-file.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
#include "llama.h"
#include "llama-persona.h"

#include <cerrno>
#include <cstdio>
#ifdef _WIN32
# ifndef WIN32_LEAN_AND_MEAN
Expand All @@ -22,6 +23,7 @@
# endif
# include <windows.h>
#endif
#include <algorithm>
#include <string>
#include <vector>

Expand All @@ -32,11 +34,16 @@ constexpr uint32_t VERSION = 1;

struct writer {
std::FILE * f;
bool ok = true;
template <typename T> void put(const T & v) { ok = ok && std::fwrite(&v, sizeof(T), 1, f) == 1; }
int error = 0;
void write(const void * data, size_t size) {
if (!error && size && std::fwrite(data, 1, size, f) != size) {
error = errno;
}
}
template <typename T> void put(const T & v) { write(&v, sizeof(v)); }
void bytes(const std::vector<uint8_t> & b) {
put<uint64_t>(b.size());
ok = ok && (b.empty() || std::fwrite(b.data(), 1, b.size(), f) == b.size());
write(b.data(), b.size());
}
void rows(const std::vector<std::vector<uint8_t>> & layers) {
put<uint32_t>((uint32_t) layers.size());
Expand Down Expand Up @@ -83,11 +90,27 @@ struct reader {

// Replace `path` with the finished `tmp` in one step. POSIX rename replaces an existing destination; the Windows CRT's
// refuses one (Codex on #155, UCRT on BigMama: -1 with the old body intact), so a second save to her fixed path failed.
bool replace_file(const std::string & tmp, const char * path) {
uint32_t replace_file(const std::string & tmp, const char * path) {
#ifdef _WIN32
return MoveFileExA(tmp.c_str(), path, MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH) != 0;
// A short-lived reader without FILE_SHARE_DELETE can hold the complete temporary
// file across fclose. Retry only the atomic rename, never the block write.
constexpr ULONGLONG sharing_deadline_ms = 2000;
const auto deadline = GetTickCount64() + sharing_deadline_ms;
DWORD delay_ms = 10;
for (;;) {
if (MoveFileExA(tmp.c_str(), path, MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) {
return 0;
}
const auto error = GetLastError();
const auto now = GetTickCount64();
if (error != ERROR_SHARING_VIOLATION || now >= deadline) {
return error;
}
Sleep(static_cast<DWORD>(std::min<ULONGLONG>(delay_ms, deadline - now)));
delay_ms = std::min<DWORD>(2 * delay_ms, 100);
}
#else
return std::rename(tmp.c_str(), path) == 0;
return std::rename(tmp.c_str(), path) == 0 ? 0 : errno;
#endif
}

Expand All @@ -98,15 +121,15 @@ struct closes {

} // namespace

int32_t llama_persona_write_file(const llama_persona * persona, const char * path) {
llama_persona_write_result llama_persona_write_checkpoint(const llama_persona * persona, const char * path) {
const auto & b = persona->blocks;
if (!b.owned) {
return (int32_t) llama_persona_move::file_mismatch; // never saved: these blocks hold nothing of hers to write
return {(int32_t) llama_persona_move::file_mismatch, LLAMA_PERSONA_FILE_NONE, 0}; // never saved: these blocks hold nothing of hers to write
}
const std::string tmp = std::string(path) + ".tmp";
std::FILE * f = std::fopen(tmp.c_str(), "wb");
if (f == nullptr) {
return (int32_t) llama_persona_move::io_error;
return {(int32_t) llama_persona_move::io_error, LLAMA_PERSONA_FILE_OPEN, (uint32_t) errno};
}
writer w { f };
w.put(MAGIC);
Expand Down Expand Up @@ -144,13 +167,26 @@ int32_t llama_persona_write_file(const llama_persona * persona, const char * pat
w.put<uint32_t>(b.rs.rs_idx);
w.rows(b.rs.r);
w.rows(b.rs.s);
const bool flushed = w.ok && std::fflush(f) == 0;
const bool closed = std::fclose(f) == 0;
if (!flushed || !closed || !replace_file(tmp, path)) {
llama_persona_write_result result {(int32_t) llama_persona_move::done, LLAMA_PERSONA_FILE_NONE, 0};
const auto io_error = (int32_t) llama_persona_move::io_error;
if (w.error) {
result = {io_error, LLAMA_PERSONA_FILE_WRITE, (uint32_t) w.error};
} else if (std::fflush(f) != 0) {
result = {io_error, LLAMA_PERSONA_FILE_FLUSH, (uint32_t) errno};
}
if (std::fclose(f) != 0 && result.status == 0) {
result = {io_error, LLAMA_PERSONA_FILE_CLOSE, (uint32_t) errno};
}
if (result.status == 0) {
const uint32_t error = replace_file(tmp, path);
if (error) {
result = {io_error, LLAMA_PERSONA_FILE_RENAME, error};
}
}
if (result.status != 0) {
std::remove(tmp.c_str());
return (int32_t) llama_persona_move::io_error;
}
return (int32_t) llama_persona_move::done;
return result;
}

int32_t llama_persona_read_file(llama_persona * persona, const char * path) {
Expand Down
50 changes: 45 additions & 5 deletions tests/test-persona-blocks.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,14 @@

#include "../src/llama-context.h"

#ifdef _WIN32
# include "../src/llama-persona.h"
# include <thread>
# ifndef NOMINMAX
# define NOMINMAX
# endif
# include <windows.h>
#endif
#include <algorithm>
#include <atomic>
#include <new>
Expand Down Expand Up @@ -260,9 +268,9 @@ int main(int argc, char ** argv) {
require_move(ctx.persona_load(0, 1 - occupied, bad, A), llama_persona_move::layout_mismatch, "a layout mismatch");
require(f.pos_max(0) < 0, "a refused load writes nothing");
if (a.rs.has_state) { // hybrid: a rollback index past the snapshot groups is refused before any write
llama_persona_blocks far = a;
far.rs.rs_idx = 1u << 20;
require_move(ctx.persona_load(0, 1 - occupied, far, A), llama_persona_move::invalid_rollback, "a rollback out of bounds");
llama_persona_blocks invalid_rollback = a;
invalid_rollback.rs.rs_idx = 1u << 20;
require_move(ctx.persona_load(0, 1 - occupied, invalid_rollback, A), llama_persona_move::invalid_rollback, "a rollback out of bounds");
require(f.pos_max(0) < 0, "a refused hybrid load writes neither half");
}

Expand Down Expand Up @@ -490,9 +498,41 @@ int main(int argc, char ** argv) {
llama_memory_clear(llama_get_memory(f.ctx), true);
f.prompt(0, 1);
require_move(st(llama_persona_save(f.ctx, 0, saved)), llama_persona_move::done, "a saved");
require_move(st(llama_persona_write_file(saved, path.c_str())), llama_persona_move::done, "a written to her file");
require_move(st(llama_persona_write_checkpoint(saved, path.c_str()).status), llama_persona_move::done, "a written to her file");
// a second save to her fixed path replaces the first (Windows CRT rename refuses an existing destination)
require_move(st(llama_persona_write_file(saved, path.c_str())), llama_persona_move::done, "a written again over her file");
require_move(st(llama_persona_write_checkpoint(saved, path.c_str()).status), llama_persona_move::done, "a written again over her file");
// The file already exists, so opening a temporary beneath it must fail.
const auto open_error = llama_persona_write_checkpoint(saved, (path + "/child").c_str());
require_move(st(open_error.status), llama_persona_move::io_error, "open failure is an IO refusal");
require(open_error.stage == LLAMA_PERSONA_FILE_OPEN && open_error.os_error != 0, "open refusal carries errno");
#ifdef _WIN32
// Keep a real reader on the temporary across the entire retry budget.
const std::string tmp = path + ".tmp";
HANDLE reader = CreateFileA(tmp.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
require(reader != INVALID_HANDLE_VALUE, "temporary reader opened");
// Keep serialization out of the deadline measurement, independent of the model under test.
llama_persona checkpoint_fixture{};
checkpoint_fixture.blocks.owned = true;
const auto start = GetTickCount64();
const auto rename_error = llama_persona_write_checkpoint(&checkpoint_fixture, path.c_str());
const auto elapsed = GetTickCount64() - start;
CloseHandle(reader);
std::remove(tmp.c_str());
require_move(st(rename_error.status), llama_persona_move::io_error, "held temporary refuses publication");
require(rename_error.stage == LLAMA_PERSONA_FILE_RENAME && rename_error.os_error == ERROR_SHARING_VIOLATION,
"rename refusal retains its Win32 cause across cleanup");
require(elapsed >= 2000 && elapsed < 5000, "persistent sharing conflict consumes the bounded retry budget");
const std::string transient = path + ".transient";
reader = CreateFileA((transient + ".tmp").c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
require(reader != INVALID_HANDLE_VALUE, "transient temporary reader opened");
std::thread release([reader] { Sleep(150); CloseHandle(reader); });
const auto published = llama_persona_write_checkpoint(&checkpoint_fixture, transient.c_str());
release.join();
require_move(st(published.status), llama_persona_move::done, "publication retries until the transient reader releases");
std::remove(transient.c_str());
#endif
llama_persona_free(saved);

llama_persona * other = llama_persona_init(f.ctx, 0xB, 1);
Expand Down