Skip to content
Merged
21 changes: 15 additions & 6 deletions projects/hrr/DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,10 +90,18 @@ atomically renamed), so a crash never leaves a partial final blob.
On the read side, `load_archive` is append-only-aware: a torn record can only be
the last one, so a partial header/payload at the tail is a recovery point — all
complete records are kept and `Archive::truncated` is set, rather than failing
the whole load. `Archive::complete` reflects whether the trailer was found.
`hrr-playback --info` reports both; `hrr-playback --repair` rewrites a truncated
archive (trimmed to the last complete record, trailer + manifest added) into a
clean one.
the whole load. The trailer ends the event stream. Records after it, which a
runtime older than the writer fix could leave from calls still in flight at
shutdown, are counted in `Archive::skipped_after_trailer`, reported once and
not replayed. `Archive::complete` is set when the trailer was found and its
`total_events` equals the number of records before it; a mismatch is reported
and leaves the archive incomplete without setting `truncated`. The trailer and
its count are kept in `Archive::trailer` and `Archive::trailer_events`, and
`hrr-playback --info` says which of these cases an archive is. `hrr-playback --repair` rewrites any
incomplete archive, whether its tail was torn, its trailer is missing or its
trailer miscounts, into a clean one: the complete records before the tail or
the trailer are kept, and a trailer that counts them and a manifest are
written.

### Per-Process Archive Layout

Expand Down Expand Up @@ -145,8 +153,9 @@ sub-archive in turn and then rebuilds the root `manifest.json` from the results.
This is the normal case for a multi-process serving stack, where the framework
force-kills its workers at shutdown — the ranks that did all the GPU work are
precisely the ones left without a trailer and absent from the root index, while
the parent that exited cleanly needs no repair. Sub-archives that already carry
a clean trailer are skipped without being read.
the parent that exited cleanly needs no repair. A sub-archive is skipped when
a walk of its record headers, which does not read the payloads, finds a
trailer at the end that counts the records before it.

### Archive Format (v7)
```
Expand Down
60 changes: 44 additions & 16 deletions projects/hrr/playback/hrr_playback.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
#include <algorithm>
#include <cassert>
#include <chrono>
#include <climits>
#include <cstdio>
#include <cstdlib>
#include <cstring>
Expand Down Expand Up @@ -302,11 +303,16 @@ static bool print_root_info(const std::string& archive_path) {
static void print_info(const hrr::Archive& archive, bool show_events) {
printf("HRR Archive: %s\n", archive.path.c_str());
printf("========================================\n");
printf("Complete: %s\n",
archive.complete ? "yes (clean shutdown)"
: (archive.truncated
? "NO (crash-truncated; trailing torn record discarded)"
: "NO (no shutdown trailer; capture likely crashed)"));
if (archive.trailer && !archive.complete)
printf("Complete: NO (shutdown trailer counts %llu events; %zu precede it)\n",
static_cast<unsigned long long>(archive.trailer_events),
archive.event_count);
else
printf("Complete: %s\n",
archive.complete ? "yes (clean shutdown)"
: (archive.truncated
? "NO (crash-truncated; trailing torn record discarded)"
: "NO (no shutdown trailer; capture likely crashed)"));
printf("Recovered: %zu events\n", archive.event_count);
printf("Events: %zu\n", archive.event_count);
printf("Kernels: %zu\n", archive.kernel_count);
Expand Down Expand Up @@ -1029,26 +1035,48 @@ static int repair_archive(const hrr::Archive& archive) {
}

// Cheap completeness probe: a cleanly finalized events.bin ends with the
// trailer record, so checking the last 44 bytes answers the question without
// parsing the file. Used only to skip work when repairing a root that is
// already clean — a false negative just costs a full load that repair_archive
// then no-ops on, so this can never turn a good archive into a rewritten one.
// trailer record, and the trailer counts the records before it. Walking the
// record headers and seeking over the payloads checks both, the same test
// load_archive applies, without reading the payloads. Used only to skip work
// when repairing a root that is already clean — a false negative just costs a
// full load that repair_archive then no-ops on, so this can never turn a good
// archive into a rewritten one.
static bool has_clean_trailer(const fs::path& archive_dir) {
const fs::path events_path = archive_dir / "events.bin";
std::error_code ec;
const auto size = fs::file_size(events_path, ec);
const uint64_t size = fs::file_size(events_path, ec);
if (ec || size < sizeof(hrr_file_header) + sizeof(hrr_eof_record)) return false;

FILE* f = fopen(events_path.string().c_str(), "rb");
if (!f) return false;
// The offset is tracked here rather than asked of ftell, whose long is 32
// bits on Windows; every seek is relative and at most one payload long.
uint64_t offset = sizeof(hrr_file_header);
uint64_t records = 0;
bool clean = false;
hrr_eof_record rec{};
const bool read_ok = fseek(f, -static_cast<long>(sizeof(rec)), SEEK_END) == 0 &&
fread(&rec, sizeof(rec), 1, f) == 1;
bool ok = fseek(f, static_cast<long>(offset), SEEK_SET) == 0;
while (ok && size - offset >= sizeof(rec.hdr) &&
fread(&rec.hdr, sizeof(rec.hdr), 1, f) == 1) {
const uint64_t total = rec.hdr.payload_length;
if (total < sizeof(rec.hdr) || total > size - offset ||
total - sizeof(rec.hdr) > static_cast<uint64_t>(LONG_MAX))
break;
if (rec.hdr.event_type == HRR_EOF_MARKER && total == sizeof(rec)) {
ok = fread(reinterpret_cast<char*>(&rec) + sizeof(rec.hdr),
sizeof(rec) - sizeof(rec.hdr), 1, f) == 1;
if (ok && rec.eof_magic == HRR_EOF_MAGIC) {
clean = offset + total == size && rec.total_events == records;
break;
}
} else {
ok = fseek(f, static_cast<long>(total - sizeof(rec.hdr)), SEEK_CUR) == 0;
}
offset += total;
++records;
}
fclose(f);

return read_ok && rec.hdr.event_type == HRR_EOF_MARKER &&
rec.hdr.payload_length == static_cast<uint16_t>(sizeof(hrr_eof_record)) &&
rec.eof_magic == HRR_EOF_MAGIC;
return clean;
}

// Rebuild the root index from the per-process manifests. Mirrors the schema the
Expand Down
40 changes: 34 additions & 6 deletions projects/hrr/playback/hrr_reader.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -324,9 +324,12 @@ bool load_archive(const std::string& path, Archive& archive) {
// Read events sequentially. read_raw_record handles the framing and the
// torn-tail recovery; a torn record means the capture was interrupted, and
// everything parsed before it is kept. The clean-shutdown trailer
// (hrr_eof_record) explicitly marks a whole archive.
// (hrr_eof_record) explicitly marks a whole archive, and it ends the event
// stream.
bool truncated = false;
bool complete = false;
bool trailer = false;
uint64_t trailer_count = 0;
const uint16_t hdr_size = static_cast<uint16_t>(sizeof(hrr_event_header));
while (true) {
Event ev;
Expand All @@ -349,8 +352,9 @@ bool load_archive(const std::string& path, Archive& archive) {
total == static_cast<uint32_t>(sizeof(hrr_eof_record))) {
const auto* er = reinterpret_cast<const hrr_eof_record*>(ev.raw_payload.data());
if (er->eof_magic == HRR_EOF_MAGIC) {
complete = true;
continue; // do not append trailer as a replay event
trailer = true;
trailer_count = er->total_events;
break; // the trailer is not a replay event, and nothing after it is
}
}

Expand Down Expand Up @@ -598,11 +602,35 @@ bool load_archive(const std::string& path, Archive& archive) {
archive.events.push_back(std::move(ev));
}

// A runtime older than the writer fix for it could append a few records
// after the trailer, from calls still in flight at shutdown. They are not in
// the trailer's count, so they are counted and left out of the replay.
if (trailer) {
std::vector<uint8_t> rest;
while (read_raw_record(f, rest) == RecordStatus::Ok)
++archive.skipped_after_trailer;
if (archive.skipped_after_trailer)
fprintf(stderr,
"[HRR] Ignored %zu records after the clean-shutdown trailer\n",
archive.skipped_after_trailer);
}

fclose(f);

archive.complete = complete;
archive.truncated = truncated;
if (!complete) {
if (trailer) {
complete = trailer_count == archive.events.size();
Comment thread
andraghetti marked this conversation as resolved.
Resolved
if (!complete)
fprintf(stderr,
"[HRR] Clean-shutdown trailer counts %llu events but %zu precede it; "
"the archive is not treated as complete\n",
static_cast<unsigned long long>(trailer_count), archive.events.size());
}

archive.complete = complete;
archive.truncated = truncated;
archive.trailer = trailer;
archive.trailer_events = trailer_count;
if (!trailer) {
fprintf(stderr,
"[HRR] Archive has no clean-shutdown trailer (capture likely crashed); "
"recovered %zu events%s\n",
Expand Down
12 changes: 10 additions & 2 deletions projects/hrr/playback/hrr_reader.h
Original file line number Diff line number Diff line change
Expand Up @@ -166,14 +166,22 @@ struct Archive {
std::vector<Event> events;

// Crash-resilience status, set by load_archive:
// complete — the clean-shutdown trailer (hrr_eof_record) was found, so the
// capturing process exited normally and the archive is whole.
// complete — the clean-shutdown trailer (hrr_eof_record) was found and
// counts the records before it, so the capturing process
// exited normally and the archive is whole.
Comment thread
andraghetti marked this conversation as resolved.
Resolved
// truncated — a torn trailing record was detected and discarded; all
// complete records before it were recovered. Replay still works.
// A capture interrupted by a crash typically has complete=false; it may also
// have truncated=true if the final record was only partially written.
bool complete = false;
bool truncated = false;
// The trailer was found and how many events it counts. trailer && !complete
// means the count disagrees with the records before it.
bool trailer = false;
uint64_t trailer_events = 0;
// Whole records found after the trailer. They are not replayed, and the
// trailer's event count must match the records before it for complete=true.
size_t skipped_after_trailer = 0;

// Content-addressed blobs: hash_hex -> file path
std::unordered_map<std::string, std::string> blobs;
Expand Down
93 changes: 91 additions & 2 deletions projects/hrr/tests/unit/hrr_recovery_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,10 @@ struct TmpRootArchive {

~TmpRootArchive() { fs::remove_all(root); }

// trailer_count < 0 makes the trailer count the records written.
fs::path add_process(uint64_t pid, uint64_t parent_pid, int records,
bool trailer = true, bool manifest = true) {
bool trailer = true, bool manifest = true,
int trailer_count = -1) {
fs::path proc = root / ("pid-" + std::to_string(pid));
fs::create_directories(proc / "blobs");
fs::create_directories(proc / "code_objects");
Expand All @@ -124,8 +126,9 @@ struct TmpRootArchive {
events.write(reinterpret_cast<const char*>(&h), sizeof(h));
}
if (trailer) {
const int counted = trailer_count < 0 ? records : trailer_count;
hrr_eof_record eof = hrr_make_eof_record(static_cast<uint64_t>(records),
static_cast<uint64_t>(records));
static_cast<uint64_t>(counted));
events.write(reinterpret_cast<const char*>(&eof), sizeof(eof));
}
events.close();
Expand Down Expand Up @@ -267,6 +270,64 @@ HRR_TEST_CASE(Unit_HRR_Recovery_NoTrailer) {
CHECK_FALSE(a.truncated);
}

/**
* Test Description
* ----------------
* - N records, a clean trailer that counts them, then two more records, as a
* runtime that kept writing after the trailer at shutdown could leave. The
* reader stops at the trailer: the archive is complete with exactly the N
* records, and the two after it are counted and not replayed.
*/
HRR_TEST_CASE(Unit_HRR_Recovery_RecordAfterTrailer) {
TmpArchive arc("after_trailer");
arc.write_records(5);
arc.write_trailer(5);
for (uint64_t seq : {100u, 101u}) {
hrr_event_header h = make_min_record(seq);
arc.write_bytes(&h, sizeof(h));
}
arc.finish();

hrr::Archive a;
REQUIRE(hrr::load_archive(arc.path(), a));
CHECK(a.events.size() == 5);
CHECK(a.complete);
CHECK_FALSE(a.truncated);
CHECK(a.skipped_after_trailer == 2);
for (const auto& ev : a.events) CHECK(ev.header().sequence_id < 100);
}

/**
* Test Description
* ----------------
* - N records followed by a trailer that claims a different count. The
* trailer still ends the stream, but the archive is not treated as a clean
* complete capture, so --repair rewrites it rather than trusting it.
* - The archive keeps the trailer and its count, and --info reports the
* mismatch instead of a missing trailer.
*/
HRR_TEST_CASE(Unit_HRR_Recovery_TrailerCountMismatch) {
TmpArchive arc("count_mismatch");
arc.write_records(5);
arc.write_trailer(4);
arc.finish();

hrr::Archive a;
REQUIRE(hrr::load_archive(arc.path(), a));
CHECK(a.events.size() == 5);
CHECK_FALSE(a.complete);
CHECK_FALSE(a.truncated);
CHECK(a.skipped_after_trailer == 0);
CHECK(a.trailer);
CHECK(a.trailer_events == 4);

auto [ret, out] = run_hrr_playback(arc.root, "--info");
INFO("hrr-playback --info stdout:\n" << out);
REQUIRE(ret == 0);
CHECK(out.find("trailer counts 4 events; 5 precede it") != std::string::npos);
CHECK(out.find("no shutdown trailer") == std::string::npos);
}

/**
* Test Description
* ----------------
Expand Down Expand Up @@ -312,6 +373,34 @@ HRR_TEST_CASE(Unit_HRR_Recovery_RepairWritesProcessManifest) {
CHECK(manifest.find("\"capture_mode\"") == std::string::npos);
}

/**
* Test Description
* ----------------
* - A root with two sub-archives, one clean and one whose trailer sits at the
* end of events.bin but counts one record too few.
* - hrr-playback --repair on the root must not take the miscounting trailer
* as clean: it rewrites that sub-archive, which then loads complete with a
* trailer that counts its records.
*/
HRR_TEST_CASE(Unit_HRR_Recovery_RepairRootRewritesMiscountedTrailer) {
TmpRootArchive root("repair_root_miscount");
root.add_process(/*pid=*/111, /*parent_pid=*/0, /*records=*/2);
fs::path bad = root.add_process(/*pid=*/222, /*parent_pid=*/111,
/*records=*/4, /*trailer=*/true,
/*manifest=*/true, /*trailer_count=*/3);

auto [ret, out] = run_hrr_playback(root.root, "--repair");
INFO("hrr-playback --repair stdout:\n" << out);
REQUIRE(ret == 0);
CHECK(out.find("1 repaired, 1 already complete, 0 failed") != std::string::npos);

hrr::Archive repaired;
REQUIRE(hrr::load_archive(bad.string(), repaired));
CHECK(repaired.complete);
CHECK(repaired.events.size() == 4);
CHECK(repaired.trailer_events == 4);
}

/**
* Test Description
* ----------------
Expand Down