Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
12 changes: 12 additions & 0 deletions src/compile/diagnostic.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,18 @@ bool DiagnosticID::is_unused() const {
return source == DiagnosticSource::Clang && unused_diags.contains(value);
}

bool DiagnosticID::is_deserialization_error() const {
// Category membership rather than an ID list: the family is large
// (DiagnosticSerializationKinds) and grows across clang versions,
// while the category is stable. Resolved through a member of the
// family instead of a hard-coded category number.
const static unsigned category =
clang::DiagnosticIDs::getCategoryNumberForDiag(clang::diag::err_fe_ast_file_malformed);
return source == DiagnosticSource::Clang &&
(level == DiagnosticLevel::Error || level == DiagnosticLevel::Fatal) &&
clang::DiagnosticIDs::getCategoryNumberForDiag(value) == category;
}

bool is_note(clang::DiagnosticsEngine::Level level) {
return level == clang::DiagnosticsEngine::Note || level == clang::DiagnosticsEngine::Remark;
}
Expand Down
8 changes: 8 additions & 0 deletions src/compile/diagnostic.h
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,14 @@ struct DiagnosticID {

/// Whether this diagnostic represents an unused diagnostic.
bool is_unused() const;

/// Whether this diagnostic reports a failure to read a prebuilt
/// artifact (PCH/PCM) — clang's "AST Deserialization Issue" category.
/// Messages in this family do not reliably carry the artifact path
/// (e.g. "malformed or corrupted precompiled file: 'Blob ends too
/// soon'"), so consumers that must blame a specific artifact combine
/// this with a path match over the inputs they passed.
bool is_deserialization_error() const;
};

struct Diagnostic {
Expand Down
91 changes: 89 additions & 2 deletions src/server/compiler/compiler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -414,6 +414,19 @@ static bool may_write_pch_key(const Session& session,
return session.generation == launch_generation && session.dirty_epoch == launch_epoch;
}

void Compiler::invalidate_pch(llvm::StringRef pch_key) {
if(workspace.store) {
workspace.store->invalidate("pch", pch_key);
}
Comment thread
16bit-ykiko marked this conversation as resolved.
Resolved
// An in-flight rebuild owns the entry (BuildingGuard); its commit will
// republish fresh blobs over the retracted pair, so only a settled
// entry is dropped here.
if(auto it = workspace.pch_cache.find(pch_key);
it != workspace.pch_cache.end() && !it->second.building) {
workspace.pch_cache.erase(it);
}
}

kota::task<bool> Compiler::ensure_pch(Session& session,
std::uint64_t launch_generation,
std::uint64_t launch_epoch,
Expand Down Expand Up @@ -868,6 +881,7 @@ kota::task<> Compiler::run_compile(std::shared_ptr<Session> session) {
// without a prefix first; if the diagnostics indicate missing includer
// context, the second round re-compiles with a synthesized prefix.
// The trial's diagnostics are never published.
bool artifact_retried = false;
for(int attempt = 0; attempt < 2; ++attempt) {
worker::CompileParams params;
params.path = file_path;
Expand Down Expand Up @@ -936,8 +950,7 @@ kota::task<> Compiler::run_compile(std::shared_ptr<Session> session) {
std::vector<std::uint32_t> pch_inactive;
std::shared_ptr<index::PreambleState> preamble_state;
if(session->pch_key.has_value()) {
auto it = workspace.pch_cache.find(*session->pch_key);
preamble_state = it != workspace.pch_cache.end() ? it->second.load_state() : nullptr;
preamble_state = workspace.preamble_state(*session->pch_key);
}
if(preamble_state) {
auto regions = preamble_state->inactive_regions();
Expand Down Expand Up @@ -1000,6 +1013,23 @@ kota::task<> Compiler::run_compile(std::shared_ptr<Session> session) {
uri_str,
result.error().message);
}
// A death while consuming a prebuilt pair may be the pair's
// fault: deep corruption aborts the AST reader
// (report_fatal_error in the bitstream reader) before any
// diagnostic can anchor, so the attributable shapes above
// never get a say. Retract the pair — a corrupt artifact then
// heals on the next compile, while a genuinely poisonous
// document keeps crashing and its own quarantine budget still
// contains it (the extra rebuilds stay bounded by that
// budget).
if(result.error().code == worker::dispatch_errc::worker_crashed &&
session->pch_key.has_value() && !params.pch.first.empty()) {
LOG_WARN("Compile crashed consuming PCH pair {} for {}; retracting the pair",
*session->pch_key,
uri_str);
invalidate_pch(*session->pch_key);
session->pch_key.reset();
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
// A quarantined document announces itself instead of hiding
// behind the empty list; the clear path publishes empty
// diagnostics without a version and no inactive regions.
Expand All @@ -1018,6 +1048,63 @@ kota::task<> Compiler::run_compile(std::shared_ptr<Session> session) {
co_return;
}

// The artifact quality gate: a failed parse whose diagnostics name
// the consumed PCH (worker-side pch_suspect — setup failure and
// fatal error alike). ensure_pch validated the pair fresh via its
// deps, yet the frontend could not read it — the bytes on disk
// are the suspect. Retract the pair (store + cache) and rerun the
// round once; ensure_pch misses and rebuilds both halves. Without
// this write-back a corrupt blob is trusted for the life of the
// store and the file stays broken on every restart. A setup
// failure whose diagnostics do NOT name the blob (bad invocation,
// broken module input) deliberately falls through to the non-Done
// path below: retracting a healthy shared PCH over someone else's
// failure would rebuild it on every request for as long as that
// failure persists.
if(result.value().pch_suspect && session->pch_key.has_value() &&
!params.pch.first.empty() && !artifact_retried) {
artifact_retried = true;
LOG_WARN("Compile blamed PCH pair {} for {}; retracting the pair and rebuilding",
*session->pch_key,
uri_str);
invalidate_pch(*session->pch_key);
session->pch_key.reset();
// Rerun the same attempt so the trial semantics are untouched
// (the loop counter is about probe rounds, not artifact
// retries).
--attempt;
continue;
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

// A non-Done reply past the gate is a non-result: settling it
// would freeze the document on a product that never existed —
// empty diagnostics, no index, an empty deps snapshot nothing can
// invalidate. Superseded rounds were already discarded at the
// generation gate above, so this round's inputs are broken in a
// way a PCH rebuild cannot fix.
if(result.value().status != worker::CompileStatus::Done) {
LOG_WARN("Compile produced no result for {} (status={})",
uri_str,
static_cast<int>(result.value().status));
// ast_dirty stays set: the next request recompiles instead of
// trusting the phantom product. Publish the honest gap like
// the dispatch-failure path above — versionless empty
// diagnostics rather than a stale list posing as current.
if(session->quarantine.active()) {
publish_quarantined(session, source, suffix_line_limit);
} else {
session->output = CompileOutput{
.version = std::nullopt,
.source = source,
.diagnostics = kota::codec::RawValue{},
.line_limit = suffix_line_limit,
.inactive_regions = std::nullopt,
};
on_output.emit(session);
}
co_return;
}

// A probe invalidated mid-flight is discarded whole: its verdict is
// a conditional write like the dirty flag (dispatch reset trial_done
// and the header mode for the recompile to re-earn), and its
Expand Down
6 changes: 6 additions & 0 deletions src/server/compiler/compiler.h
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,12 @@ class Compiler {
bool is_stale(Session& session);
void record_deps(Session& session, llvm::ArrayRef<DepFile> deps, std::int64_t build_at);

/// Retract a PCH pair the frontend could not consume: remove both
/// blobs from the store and drop the settled cache entry, so the next
/// ensure_pch misses and rebuilds instead of trusting corrupt bytes
/// for the life of the store.
void invalidate_pch(llvm::StringRef pch_key);

kota::event_loop& loop;
Workspace& workspace;
ContextResolver& contexts;
Expand Down
27 changes: 27 additions & 0 deletions src/server/protocol/worker.h
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,34 @@ struct CompileParams {
std::vector<std::uint8_t> open_conditionals;
};

/// Outcome of a stateful compile. Anything but `Done` is a non-result: the
/// master must not settle the session, record dependencies, or publish the
/// (empty) diagnostics as current — doing so freezes the document on a
/// product that never existed.
enum class CompileStatus : uint8_t {
/// The parse produced a usable product — a complete AST, or a fatal
/// error whose diagnostics describe the user's code.
Done,
/// The parse was interrupted by CancelCompile (superseded round).
Cancelled,
/// The frontend failed before parsing began: bad invocation, or a
/// prebuilt input (PCH/PCM) clang could not read. Whether the consumed
/// PCH is to blame is a separate signal (pch_suspect).
SetupFail,
};

struct CompileResult {
CompileStatus status = CompileStatus::Done;

/// The parse failed and its diagnostics blame the consumed PCH — they
/// name the blob's path, or they are AST-deserialization errors naming
/// no other prebuilt input. Holds whether the reader rejected the blob
/// at setup or hit a fatal error past it (a Done status with real,
/// publishable diagnostics). Either way the artifact is the culprit:
/// the master should retract the pair and rebuild instead of trusting
/// the corrupt bytes until the preamble changes.
bool pch_suspect = false;

int version;
/// Diagnostics serialized as JSON (RawValue) to avoid bincode/serde annotation conflicts.
kota::codec::RawValue diagnostics;
Expand Down
5 changes: 1 addition & 4 deletions src/server/service/feature_router.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,7 @@ static kota::ipc::Error item_not_resolved(llvm::StringRef kind) {
std::vector<feature::DocumentLink> FeatureRouter::find_preamble_links(const Session& session) {
if(!session.pch_key)
return {};
auto it = workspace.pch_cache.find(*session.pch_key);
if(it == workspace.pch_cache.end())
return {};
auto& state = it->second.load_state();
auto state = workspace.preamble_state(*session.pch_key);
if(!state)
return {};
// Link offsets are buffer coordinates as of the PCH build; serve them
Expand Down
10 changes: 3 additions & 7 deletions src/server/service/query.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,9 @@ std::shared_ptr<index::PreambleState> IndexQuery::overlay_of(const Session& sess
if(!session.pch_key) {
return nullptr;
}
auto it = workspace.pch_cache.find(*session.pch_key);
if(it == workspace.pch_cache.end()) {
return nullptr;
}
// Return the shared_ptr by value: consumers run synchronously, but a
// reference into the map value would not survive a rehash.
return it->second.load_state();
// Returned by value: consumers run synchronously, but a reference into
// the map value would not survive a rehash.
return workspace.preamble_state(*session.pch_key);
}

void IndexQuery::visit_overlays(
Expand Down
21 changes: 21 additions & 0 deletions src/server/state/workspace.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,27 @@ const std::shared_ptr<index::PreambleState>& PCHState::load_state() {
return state;
}

std::shared_ptr<index::PreambleState> Workspace::preamble_state(llvm::StringRef pch_key) {
auto it = pch_cache.find(pch_key);
if(it == pch_cache.end()) {
return nullptr;
}

auto& st = it->second;
bool had_blob = !st.index_path.empty();
auto state = st.load_state();
if(!state && had_blob && store) {
// The blob was just found unreadable (load_state cleared the
// path): a pair that looks complete on disk but cannot be opened
// would be served to every session for the rest of the store's
// life. Retract it now; the entry itself stays until ensure_pch
// re-checks the store and rebuilds the pair.
LOG_WARN("Retracting PCH pair {} with unreadable PreambleState blob", pch_key);
store->invalidate("pch", pch_key);
}
return state;
}

void Workspace::load_cache(ContextResolver& contexts) {
if(!store)
return;
Expand Down
8 changes: 8 additions & 0 deletions src/server/state/workspace.h
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,14 @@ struct Workspace {
/// is a module unit so dependents can be re-evaluated on next compile.
void on_file_closed(std::uint32_t path_id);

/// Open the PreambleState blob of a cached PCH. The single consumption
/// gate for `.pch.idx` blobs: when the blob turns out unreadable, the
/// on-disk pair is retracted from the store as well — otherwise every
/// later session re-adopts the corrupt pair from cache.json and
/// silently degrades again. With the pair gone the next ensure_pch is
/// a miss and rebuilds both halves.
std::shared_ptr<index::PreambleState> preamble_state(llvm::StringRef pch_key);

/// Load PCH/PCM validity metadata plus the context resolver's slices
/// from cache.json (under the store's versioned root); entries whose
/// blob is gone from the store are dropped.
Expand Down
36 changes: 35 additions & 1 deletion src/server/worker/stateful_worker.cpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#include "server/worker/stateful_worker.h"

#include <algorithm>
#include <atomic>
#include <cstdint>
#include <list>
Expand Down Expand Up @@ -246,6 +247,34 @@ void StatefulWorker::register_handlers() {

worker::CompileResult result;
result.version = doc->version;

// A failed parse that blames the consumed PCH: either a
// diagnostic names the blob's path outright, or it is an
// AST-deserialization error naming no other prebuilt input
// (that family's messages do not reliably carry the path —
// "malformed or corrupted precompiled file: 'Blob ends too
// soon'"). User-code failures (missing include, modified
// header, bad flags) match neither, so the master never
// rebuilds an innocent shared PCH over a failure it did
// not cause. An anonymous read error with PCMs in play is
// ambiguous; blaming the PCH costs at most one retracted
// pair per round and self-corrects on the retry.
if(!doc->unit.completed() && !doc->pch.first.empty()) {
result.pch_suspect =
std::ranges::any_of(doc->unit.diagnostics(), [&](auto& diag) {
llvm::StringRef message = diag.message;
if(message.contains(doc->pch.first)) {
return true;
}
if(!diag.id.is_deserialization_error()) {
return false;
}
return std::ranges::none_of(doc->pcms, [&](auto& entry) {
return message.contains(entry.getValue());
});
});
}

if(doc->unit.completed() || doc->unit.fatal_error()) {
auto diags = feature::diagnostics(doc->unit);
auto json = kota::codec::json::to_json<kota::ipc::lsp_config>(diags);
Expand All @@ -256,8 +285,13 @@ void StatefulWorker::register_handlers() {
diags.size(),
doc->unit.fatal_error());
} else {
result.status = doc->unit.setup_fail() ? worker::CompileStatus::SetupFail
: worker::CompileStatus::Cancelled;
result.diagnostics = kota::codec::RawValue{"[]"};
LOG_WARN("Compile incomplete: path={}, {}ms", params.path, timer.ms());
LOG_WARN("Compile incomplete: path={}, {}ms, setup_fail={}",
params.path,
timer.ms(),
doc->unit.setup_fail());
}
result.memory_usage = 0; // TODO: query actual memory
if(doc->unit.completed() && !stop->load(std::memory_order_relaxed)) {
Expand Down
Loading
Loading