2 Commits

Author SHA1 Message Date
ykiko
42a3d20971 fix(server): make shutdown sanitizer-clean 2026-06-01 10:09:26 +08:00
ykiko
dfeda4dc6f fix(server): make shutdown sanitizer-clean 2026-06-01 00:08:12 +08:00
22 changed files with 243 additions and 366 deletions

3
.gitignore vendored
View File

@@ -68,7 +68,8 @@ tests/unit/Local/
.pixi/*
!.pixi/config.toml
.codex
.codex/
.claude/*
!.claude/CLAUDE.md
!.claude/commands/
openspec/

View File

@@ -124,31 +124,8 @@ if(CLICE_CI_ENVIRONMENT)
target_compile_definitions(clice_options INTERFACE CLICE_CI_ENVIRONMENT=1)
endif()
set(CLICE_CLANG_TIDY_MODULE_LIBRARIES)
set(CLICE_MISSING_CLANG_TIDY_MODULES)
foreach(module IN LISTS CLICE_CLANG_TIDY_MODULE_COMPONENTS)
find_library(CLICE_${module}_LIBRARY
NAMES "${module}"
PATHS "${LLVM_INSTALL_PATH}/lib"
NO_DEFAULT_PATH
)
if(CLICE_${module}_LIBRARY)
list(APPEND CLICE_CLANG_TIDY_MODULE_LIBRARIES "${CLICE_${module}_LIBRARY}")
else()
list(APPEND CLICE_MISSING_CLANG_TIDY_MODULES "${module}")
endif()
endforeach()
if(CLICE_MISSING_CLANG_TIDY_MODULES)
message(STATUS "Clang-tidy module libraries not available: ${CLICE_MISSING_CLANG_TIDY_MODULES}")
else()
target_compile_definitions(clice_options INTERFACE CLICE_HAS_CLANG_TIDY_MODULES=1)
endif()
set(FBS_SCHEMA_FILE "${PROJECT_SOURCE_DIR}/src/index/schema.fbs")
set(GENERATED_HEADER "${PROJECT_BINARY_DIR}/generated/schema_generated.h")
set(CLANG_TIDY_CONFIG_SOURCE_FILE "${PROJECT_SOURCE_DIR}/config/clang-tidy-config.h")
set(CLANG_TIDY_CONFIG_GENERATED_FILE "${PROJECT_BINARY_DIR}/generated/clang-tidy-config.h")
if(CMAKE_CROSSCOMPILING)
find_program(FLATC_EXECUTABLE flatc REQUIRED)
@@ -166,21 +143,10 @@ add_custom_command(
add_custom_target(generate_flatbuffers_schema DEPENDS "${GENERATED_HEADER}")
add_custom_command(
OUTPUT "${CLANG_TIDY_CONFIG_GENERATED_FILE}"
COMMAND ${CMAKE_COMMAND} -E copy_if_different
"${CLANG_TIDY_CONFIG_SOURCE_FILE}"
"${CLANG_TIDY_CONFIG_GENERATED_FILE}"
DEPENDS "${CLANG_TIDY_CONFIG_SOURCE_FILE}"
COMMENT "Generating C++ header from ${CLANG_TIDY_CONFIG_SOURCE_FILE}"
)
add_custom_target(generate_clang_tidy_config DEPENDS "${CLANG_TIDY_CONFIG_GENERATED_FILE}")
file(GLOB_RECURSE CLICE_CORE_SOURCES CONFIGURE_DEPENDS "${PROJECT_SOURCE_DIR}/src/*.cpp")
add_library(clice-core STATIC ${CLICE_CORE_SOURCES})
add_library(clice::core ALIAS clice-core)
add_dependencies(clice-core generate_flatbuffers_schema generate_clang_tidy_config)
add_dependencies(clice-core generate_flatbuffers_schema)
target_include_directories(clice-core PUBLIC
"${PROJECT_SOURCE_DIR}/src"
@@ -196,9 +162,6 @@ target_link_libraries(clice-core PUBLIC
kota::codec::toml
simdjson::simdjson
)
if(CLICE_CLANG_TIDY_MODULE_LIBRARIES)
target_link_libraries(clice-core PUBLIC ${CLICE_CLANG_TIDY_MODULE_LIBRARIES})
endif()
add_executable(clice "${PROJECT_SOURCE_DIR}/src/clice.cc")
target_link_libraries(clice PRIVATE clice::core kota::deco)

View File

@@ -1,34 +1,5 @@
include_guard()
set(CLICE_CLANG_TIDY_MODULE_COMPONENTS
# Keep this in sync with scripts/llvm-components.json and the old
# ALL_CLANG_TIDY_CHECKS list. MPIModule is intentionally excluded because
# clice disables static analyzer checks in ClangTidyForceLinker.h.
clangTidyAndroidModule
clangTidyAbseilModule
clangTidyAlteraModule
clangTidyBoostModule
clangTidyBugproneModule
clangTidyCERTModule
clangTidyConcurrencyModule
clangTidyCppCoreGuidelinesModule
clangTidyDarwinModule
clangTidyFuchsiaModule
clangTidyGoogleModule
clangTidyHICPPModule
clangTidyLinuxKernelModule
clangTidyLLVMModule
clangTidyLLVMLibcModule
clangTidyMiscModule
clangTidyModernizeModule
clangTidyObjCModule
clangTidyOpenMPModule
clangTidyPerformanceModule
clangTidyPortabilityModule
clangTidyReadabilityModule
clangTidyZirconModule
)
function(setup_llvm LLVM_VERSION)
find_package(Python3 COMPONENTS Interpreter REQUIRED)
@@ -116,6 +87,29 @@ function(setup_llvm LLVM_VERSION)
clangSerialization
clangTidy
clangTidyUtils
clangTidyAndroidModule
clangTidyAbseilModule
clangTidyAlteraModule
clangTidyBoostModule
clangTidyBugproneModule
clangTidyCERTModule
clangTidyConcurrencyModule
clangTidyCppCoreGuidelinesModule
clangTidyDarwinModule
clangTidyFuchsiaModule
clangTidyGoogleModule
clangTidyHICPPModule
clangTidyLinuxKernelModule
clangTidyLLVMModule
clangTidyLLVMLibcModule
clangTidyMiscModule
clangTidyModernizeModule
clangTidyObjCModule
clangTidyOpenMPModule
clangTidyPerformanceModule
clangTidyPortabilityModule
clangTidyReadabilityModule
clangTidyZirconModule
clangTooling
clangToolingCore
clangToolingInclusions

View File

@@ -16,10 +16,7 @@ import subprocess
import time
from datetime import datetime, timezone
from pathlib import Path
from typing import Iterable, List, Optional, Set
LLVM_COMPONENTS_FILE = Path(__file__).with_name("llvm-components.json")
from typing import Iterable, List, Optional
def parse_args() -> argparse.Namespace:
@@ -105,33 +102,12 @@ def run_build(build_dir: Path) -> bool:
return False
def protected_library_names() -> Set[str]:
data = json.loads(LLVM_COMPONENTS_FILE.read_text())
components = data.get("components", [])
if not isinstance(components, list):
raise ValueError(f"{LLVM_COMPONENTS_FILE} missing 'components' list")
names: Set[str] = set()
for component in components:
if not isinstance(component, str):
continue
if not (component.startswith("clangTidy") and component.endswith("Module")):
continue
names.add(f"lib{component}.a")
names.add(f"{component}.lib")
return names
def candidate_files(install_dir: Path) -> Iterable[Path]:
if not install_dir.is_dir():
raise FileNotFoundError(f"lib dir not found: {install_dir}")
protected = protected_library_names()
for path in sorted(install_dir.iterdir()):
if not path.is_file():
continue
if path.name in protected:
print(f"Keeping protected clang-tidy module library: {path.name}")
continue
if path.suffix.lower() in {".a", ".lib"}:
yield path
else:
@@ -180,11 +156,7 @@ def apply_manifest(manifest: Path, install_dir: Path) -> None:
removed = data.get("removed", [])
if not isinstance(removed, list):
raise ValueError("Manifest missing 'removed' list")
protected = protected_library_names()
for name in removed:
if name in protected:
print(f"Keeping protected clang-tidy module library from manifest: {name}")
continue
target = install_dir / name
if target.exists():
print(f"Deleting {target}")

View File

@@ -53,7 +53,7 @@ struct Options {
help =
"Agentic method (compileCommand, symbolSearch, definition, references, "
"documentSymbols, readSymbol, callGraph, typeHierarchy, projectFiles, "
"lint, fileDeps, impactAnalysis, status, shutdown)",
"fileDeps, impactAnalysis, status, shutdown)",
required = false)
<std::string> method;

View File

@@ -418,8 +418,6 @@ CompilationUnit compile(CompilationParams& params, PCMInfo& out) {
}
CompilationUnit complete(CompilationParams& params, clang::CodeCompleteConsumer* consumer) {
params.kind = CompilationKind::Completion;
auto& [file, offset] = params.completion;
/// The location of clang is 1-1 based.

View File

@@ -65,7 +65,7 @@ struct PCMInfo : ModuleInfo {
struct CompilationParams {
/// The kind of this compilation.
CompilationKind kind = CompilationKind::Content;
CompilationKind kind;
/// Whether to run clang-tidy.
bool clang_tidy = false;

View File

@@ -12,10 +12,6 @@
#include "clang-tidy/ClangTidyDiagnosticConsumer.h"
#include "clang-tidy/ClangTidyModuleRegistry.h"
#include "clang-tidy/ClangTidyOptions.h"
#ifdef CLICE_HAS_CLANG_TIDY_MODULES
#define CLANG_TIDY_DISABLE_STATIC_ANALYZER_CHECKS
#include "clang-tidy/ClangTidyForceLinker.h"
#endif
namespace clice::tidy {

View File

@@ -34,34 +34,6 @@ bool is_dependent(const clang::Decl* D) {
return isa<clang::UnresolvedUsingValueDecl>(D);
}
/// Whether a declaration name is backed by source text that should be highlighted.
bool can_highlight_name(clang::DeclarationName name) {
switch(name.getNameKind()) {
case clang::DeclarationName::Identifier: {
auto* info = name.getAsIdentifierInfo();
return info && !info->getName().empty();
}
case clang::DeclarationName::CXXConstructorName:
case clang::DeclarationName::CXXDestructorName: {
return true;
}
case clang::DeclarationName::CXXConversionFunctionName:
case clang::DeclarationName::CXXOperatorName:
case clang::DeclarationName::CXXDeductionGuideName:
case clang::DeclarationName::CXXLiteralOperatorName:
case clang::DeclarationName::CXXUsingDirective:
case clang::DeclarationName::ObjCZeroArgSelector:
case clang::DeclarationName::ObjCOneArgSelector:
case clang::DeclarationName::ObjCMultiArgSelector: {
return false;
}
}
std::unreachable();
}
/// Returns true if `decl` is considered to be from a default/system library.
/// This currently checks the systemness of the file by include type, although
/// different heuristics may be used in the future (e.g. sysroot paths).
@@ -199,10 +171,6 @@ public:
void handleDeclOccurrence(const clang::NamedDecl* decl,
RelationKind relation,
clang::SourceLocation location) {
if(relation.isReference() && !can_highlight_name(decl->getDeclName())) {
return;
}
std::uint32_t modifiers = 0;
if(relation.is_one_of(RelationKind::Definition)) {
// todo: clangd add both Declaration and Definition modifiers for definitions.

View File

@@ -669,7 +669,6 @@ kota::task<> Compiler::run_compile(std::uint32_t pid, std::shared_ptr<Session::P
params.path = file_path;
params.version = sess->version;
params.text = sess->text;
params.clang_tidy = workspace.config.project.clang_tidy.value;
if(!fill_compile_args(file_path, params.directory, params.arguments, sess)) {
finish_compile();
co_return;

View File

@@ -5,7 +5,6 @@
#include <string>
#include <vector>
#include "kota/ipc/lsp/protocol.h"
#include "kota/ipc/protocol.h"
namespace clice::agentic {
@@ -203,13 +202,6 @@ struct TypeHierarchyResult {
std::vector<TypeHierarchyEntry> subtypes;
};
struct LintParams {
std::string path;
std::optional<int> line;
};
using LintResult = std::vector<kota::ipc::protocol::Diagnostic>;
struct StatusParams {};
struct StatusResult {
@@ -291,12 +283,6 @@ struct RequestTraits<clice::agentic::TypeHierarchyParams> {
constexpr inline static std::string_view method = "agentic/typeHierarchy";
};
template <>
struct RequestTraits<clice::agentic::LintParams> {
using Result = clice::agentic::LintResult;
constexpr inline static std::string_view method = "agentic/lint";
};
template <>
struct RequestTraits<clice::agentic::StatusParams> {
using Result = clice::agentic::StatusResult;

View File

@@ -43,7 +43,6 @@ struct CompileParams {
std::string text;
std::string directory;
std::vector<std::string> arguments;
bool clang_tidy = false;
std::pair<std::string, uint32_t> pch;
std::unordered_map<std::string, std::string> pcms;
};

View File

@@ -6,14 +6,11 @@
#include <string>
#include <vector>
#include "compile/compilation.h"
#include "feature/feature.h"
#include "server/protocol/agentic.h"
#include "server/service/master_server.h"
#include "support/filesystem.h"
#include "support/logging.h"
#include "kota/async/async.h"
#include "kota/ipc/lsp/uri.h"
#include "kota/meta/enum.h"
#include "llvm/ADT/DenseSet.h"
@@ -772,36 +769,6 @@ AgentClient::AgentClient(MasterServer& server, kota::ipc::JsonPeer& peer) :
co_return result;
});
peer.on_request([&srv](RequestContext&, const LintParams& params) -> RequestResult<LintParams> {
std::string directory;
std::vector<std::string> arguments;
if(!srv.compiler.fill_compile_args(params.path, directory, arguments)) {
co_return kota::outcome_error(
kota::ipc::Error{std::format("no compile command found for {}", params.path)});
}
auto result = co_await kota::queue([path = params.path,
directory = std::move(directory),
arguments = std::move(arguments)]() mutable {
CompilationParams cp;
cp.kind = CompilationKind::Content;
cp.clang_tidy = true;
cp.directory = std::move(directory);
for(auto& arg: arguments) {
cp.arguments.push_back(arg.c_str());
}
auto unit = compile(cp);
if(!unit.completed() && !unit.fatal_error()) {
LOG_WARN("Lint compilation failed: {}", path);
return LintResult{};
}
return feature::diagnostics(unit);
});
co_return result.value();
});
peer.on_request([&srv](RequestContext&, const StatusParams&) -> RequestResult<StatusParams> {
StatusResult result;
result.idle = srv.indexer.is_idle();
@@ -811,9 +778,10 @@ AgentClient::AgentClient(MasterServer& server, kota::ipc::JsonPeer& peer) :
co_return result;
});
peer.on_notification([&srv](const ShutdownParams&) {
peer.on_notification([this, &srv](const ShutdownParams&) {
LOG_INFO("agentic/shutdown received, shutting down");
srv.schedule_shutdown();
this->peer.close();
});
}

View File

@@ -85,9 +85,6 @@ static kota::task<> agentic_request(kota::ipc::JsonPeer& peer,
.line = line,
.direction = dir,
});
} else if(opts.method == "lint") {
auto line = opts.line > 0 ? std::optional(opts.line) : std::nullopt;
ok = co_await send_and_print(peer, agentic::LintParams{.path = opts.path, .line = line});
} else if(opts.method == "fileDeps") {
auto dir = opts.direction.empty() ? std::nullopt : std::optional(opts.direction);
ok = co_await send_and_print(peer,

View File

@@ -156,6 +156,7 @@ LSPClient::LSPClient(MasterServer& server, kota::ipc::JsonPeer& peer) : server(s
peer.on_notification([this]([[maybe_unused]] const protocol::ExitParams& params) {
LOG_INFO("Exit notification received");
this->server.schedule_shutdown();
this->peer.close();
});
peer.on_notification([this](const protocol::DidOpenTextDocumentParams& params) {

View File

@@ -110,14 +110,14 @@ void MasterServer::start_file_watcher() {
if(workspace_root.empty())
return;
loop.schedule([this]() -> kota::task<> {
auto watcher = kota::fs_event::create(workspace_root, {}, loop);
loop.schedule([](MasterServer& server) -> kota::task<> {
auto watcher = kota::fs_event::create(server.workspace_root, {}, server.loop);
if(!watcher) {
LOG_WARN("Failed to start file watcher for {}", workspace_root);
LOG_WARN("Failed to start file watcher for {}", server.workspace_root);
co_return;
}
LOG_INFO("File watcher started for {}", workspace_root);
LOG_INFO("File watcher started for {}", server.workspace_root);
while(true) {
auto changes = co_await watcher->next();
@@ -132,19 +132,19 @@ void MasterServer::start_file_watcher() {
llvm::StringRef file(change.path);
if(file.ends_with("compile_commands.json")) {
LOG_INFO("CDB changed, reloading workspace");
load_workspace();
server.load_workspace();
continue;
}
if(file.ends_with(".cpp") || file.ends_with(".cc") || file.ends_with(".cxx") ||
file.ends_with(".c") || file.ends_with(".h") || file.ends_with(".hpp") ||
file.ends_with(".hxx") || file.ends_with(".cppm") || file.ends_with(".ixx")) {
auto path_id = workspace.path_pool.intern(file);
on_file_saved(path_id);
auto path_id = server.workspace.path_pool.intern(file);
server.on_file_saved(path_id);
}
}
}
}());
}(*this));
}
Session* MasterServer::find_session(std::uint32_t path_id) {
@@ -212,10 +212,10 @@ void MasterServer::schedule_shutdown() {
workspace.save_cache();
shutdown_event.set();
loop.schedule([this]() -> kota::task<> {
co_await kota::when_all(indexer.stop(), compiler.stop(), pool.stop());
loop.stop();
}());
loop.schedule([](MasterServer& server) -> kota::task<> {
co_await kota::when_all(server.indexer.stop(), server.compiler.stop(), server.pool.stop());
server.loop.stop();
}(*this));
}
void MasterServer::load_workspace() {
@@ -355,35 +355,53 @@ static kota::task<> accept_connections(MasterServer& server,
std::list<Connection>& connections) {
auto& loop = kota::event_loop::current();
kota::task_group<> connection_group(loop);
bool lsp_registered = false;
while(true) {
auto conn = co_await acceptor.accept();
if(!conn.has_value())
break;
co_await kota::when_all(
[](MasterServer& server,
kota::tcp::acceptor& acceptor,
bool register_lsp,
std::list<Connection>& connections,
kota::task_group<>& connection_group) -> kota::task<> {
auto& loop = kota::event_loop::current();
bool lsp_registered = false;
LOG_INFO("Client connected");
while(true) {
auto conn = co_await acceptor.accept();
if(!conn.has_value())
break;
auto transport = std::make_unique<kota::ipc::StreamTransport>(std::move(*conn));
auto peer = std::make_unique<kota::ipc::JsonPeer>(loop, std::move(transport));
LOG_INFO("Client connected");
std::unique_ptr<LSPClient> lsp;
if(register_lsp && !lsp_registered) {
lsp = std::make_unique<LSPClient>(server, *peer);
lsp_registered = true;
}
auto agent = std::make_unique<AgentClient>(server, *peer);
auto transport = std::make_unique<kota::ipc::StreamTransport>(std::move(*conn));
auto peer = std::make_unique<kota::ipc::JsonPeer>(loop, std::move(transport));
auto* peer_ptr = peer.get();
auto it = connections.emplace(connections.end(),
Connection{
.peer = std::move(peer),
.lsp_client = std::move(lsp),
.agent_client = std::move(agent),
});
std::unique_ptr<LSPClient> lsp;
if(register_lsp && !lsp_registered) {
lsp = std::make_unique<LSPClient>(server, *peer);
lsp_registered = true;
}
auto agent = std::make_unique<AgentClient>(server, *peer);
connection_group.spawn(run_connection(peer_ptr, connections, it));
}
auto* peer_ptr = peer.get();
auto it = connections.emplace(connections.end(),
Connection{
.peer = std::move(peer),
.lsp_client = std::move(lsp),
.agent_client = std::move(agent),
});
connection_group.spawn(run_connection(peer_ptr, connections, it));
}
}(server, acceptor, register_lsp, connections, connection_group),
[](MasterServer& server,
kota::tcp::acceptor& acceptor,
std::list<Connection>& connections) -> kota::task<> {
co_await server.get_shutdown_event().wait();
acceptor.stop();
for(auto& conn: connections) {
conn.peer->close();
}
}(server, acceptor, connections));
co_await connection_group.join();
}
@@ -411,18 +429,50 @@ int run_server_mode(const ServerOptions& opts) {
kota::ipc::JsonPeer lsp_peer(loop, std::move(final_transport));
LSPClient lsp_client(server, lsp_peer);
loop.schedule([](MasterServer& server, kota::ipc::JsonPeer& peer) -> kota::task<> {
co_await server.get_shutdown_event().wait();
peer.close();
}(server, lsp_peer));
kota::tcp::acceptor agent_acceptor;
bool has_agent_acceptor = false;
if(opts.port > 0) {
auto acceptor = kota::tcp::listen(opts.host, opts.port, {}, loop);
if(acceptor) {
LOG_INFO("Agentic protocol listening on {}:{}", opts.host, opts.port);
loop.schedule(accept_connections(server, std::move(*acceptor), false, connections));
agent_acceptor = std::move(*acceptor);
has_agent_acceptor = true;
} else {
LOG_WARN("Failed to start agentic listener on {}:{}", opts.host, opts.port);
}
}
loop.schedule(lsp_peer.run());
loop.schedule([](MasterServer& server,
kota::ipc::JsonPeer& peer,
std::list<Connection>& connections,
kota::tcp::acceptor acceptor,
bool has_acceptor) -> kota::task<> {
auto run_peer = [](MasterServer& server, kota::ipc::JsonPeer& peer) -> kota::task<> {
co_await peer.run();
server.schedule_shutdown();
};
auto close_peer_on_shutdown = [](MasterServer& server,
kota::ipc::JsonPeer& peer) -> kota::task<> {
co_await server.get_shutdown_event().wait();
peer.close();
};
if(has_acceptor) {
co_await kota::when_all(
run_peer(server, peer),
close_peer_on_shutdown(server, peer),
accept_connections(server, std::move(acceptor), false, connections));
} else {
co_await kota::when_all(run_peer(server, peer),
close_peer_on_shutdown(server, peer));
}
}(server, lsp_peer, connections, std::move(agent_acceptor), has_agent_acceptor));
loop.run();
return 0;
}
@@ -463,7 +513,12 @@ static kota::task<> daemon_main(MasterServer& server, kota::pipe::acceptor accep
kota::task_group<> connection_group(loop);
co_await kota::when_all(
[&]() -> kota::task<> {
[](MasterServer& server,
kota::pipe::acceptor& acceptor,
std::list<DaemonConnection>& connections,
kota::task_group<>& connection_group) -> kota::task<> {
auto& loop = kota::event_loop::current();
while(true) {
auto conn = co_await acceptor.accept();
if(!conn.has_value())
@@ -484,14 +539,16 @@ static kota::task<> daemon_main(MasterServer& server, kota::pipe::acceptor accep
connection_group.spawn(run_daemon_connection(peer_ptr, connections, it));
}
}(),
[&]() -> kota::task<> {
}(server, acceptor, connections, connection_group),
[](MasterServer& server,
kota::pipe::acceptor& acceptor,
std::list<DaemonConnection>& connections) -> kota::task<> {
co_await server.get_shutdown_event().wait();
acceptor.stop();
for(auto& conn: connections) {
conn.peer->close();
}
}());
}(server, acceptor, connections));
co_await connection_group.join();
}

View File

@@ -152,7 +152,6 @@ void StatefulWorker::register_handlers() {
CompilationParams cp;
cp.kind = CompilationKind::Content;
cp.clang_tidy = params.clang_tidy;
fill_args(cp, doc->directory, doc->arguments);
if(!doc->pch.first.empty()) {
cp.pch = doc->pch;

View File

@@ -116,6 +116,9 @@ bool WorkerPool::start(const WorkerPoolOptions& options) {
options_ = options;
log_dir_ = options.log_dir;
stateless_workers.reserve(options.stateless_count);
stateful_workers.reserve(options.stateful_count);
for(std::uint32_t i = 0; i < options.stateless_count; ++i) {
if(!spawn_worker(options.self_path, false, 0)) {
return false;
@@ -229,10 +232,10 @@ void WorkerPool::clear_owner(std::size_t worker_index) {
kota::task<> WorkerPool::monitor_worker(std::size_t index, bool stateful) {
auto& workers = stateful ? stateful_workers : stateless_workers;
auto& w = workers[index];
auto name = std::string(stateful ? "SF-" : "SL-") + std::to_string(index);
auto result = co_await w.proc.wait();
auto result = co_await workers[index].proc.wait();
auto& w = workers[index];
w.alive = false;
if(shutting_down_)

View File

@@ -185,44 +185,94 @@ async def make_client(executable: Path, workspace: Path) -> CliceClient:
return c
SANITIZER_MARKERS = (
"AddressSanitizer",
"LeakSanitizer",
"MemorySanitizer",
"ThreadSanitizer",
"UndefinedBehaviorSanitizer",
"==ERROR:",
"runtime error:",
)
def _server_stderr_excerpt(stderr_text: str) -> str:
interesting = [
line
for line in stderr_text.splitlines()
if "[warn]" in line
or "[error]" in line
or "Sanitizer" in line
or "==ERROR:" in line
or "runtime error:" in line
]
return "\n".join(interesting[-80:])
async def assert_server_exited_cleanly(server, timeout: float = 3.0) -> None:
failures: list[str] = []
if server is None:
return
if server.returncode is None:
try:
await asyncio.wait_for(server.wait(), timeout=timeout)
except asyncio.TimeoutError:
server.kill()
await server.wait()
failures.append(f"server did not exit within {timeout:g}s after shutdown")
print(f"[server] exit code: {server.returncode}", flush=True)
stderr_text = ""
if server.stderr:
try:
stderr_data = await asyncio.wait_for(server.stderr.read(), timeout=2.0)
stderr_text = stderr_data.decode("utf-8", errors="replace")
except Exception as exc:
failures.append(f"failed to collect server stderr: {exc!r}")
for line in _server_stderr_excerpt(stderr_text).splitlines():
print(f"[server] {line}", flush=True)
if server.returncode != 0:
failures.append(f"server exited with code {server.returncode}")
if any(marker in stderr_text for marker in SANITIZER_MARKERS):
failures.append("server stderr contains sanitizer/runtime error output")
if failures:
excerpt = _server_stderr_excerpt(stderr_text)
if excerpt:
failures.append("server stderr excerpt:\n" + excerpt)
pytest.fail("\n".join(failures))
async def _shutdown_client(c: CliceClient) -> None:
"""Gracefully shut down a client, force-kill if needed."""
server = getattr(c, "_server", None)
try:
await asyncio.wait_for(c.shutdown_async(None), timeout=3.0)
except Exception:
pass
try:
c.exit(None)
except Exception:
pass
await asyncio.sleep(0.3)
if hasattr(c, "_server") and c._server is not None and c._server.returncode is None:
c._server.kill()
try:
server = getattr(c, "_server", None)
if server:
if server.returncode is not None:
print(f"[server] exit code: {server.returncode}", flush=True)
if server.stderr:
stderr_data = await asyncio.wait_for(server.stderr.read(), timeout=2.0)
if stderr_data:
for line in stderr_data.decode(
"utf-8", errors="replace"
).splitlines():
if "[warn]" in line or "[error]" in line or "Sanitizer" in line:
print(f"[server] {line}", flush=True)
except Exception:
pass
try:
c._stop_event.set()
for task in c._async_tasks:
task.cancel()
await asyncio.sleep(0.1)
except Exception:
pass
await assert_server_exited_cleanly(server)
finally:
try:
c._stop_event.set()
for task in c._async_tasks:
task.cancel()
await asyncio.sleep(0.1)
except Exception:
pass
shutdown_client = _shutdown_client # Public alias for multi-session tests

View File

@@ -530,7 +530,7 @@ async def test_rpc_impact_analysis_unknown(indexed_agentic, workspace):
async def test_shutdown_during_indexing(executable, tmp_path):
"""Shutdown during active background indexing must exit cleanly."""
from tests.integration.utils.client import CliceClient
from tests.conftest import _find_free_port
from tests.conftest import _find_free_port, assert_server_exited_cleanly
workspace = tmp_path / "ws"
workspace.mkdir()
@@ -560,33 +560,38 @@ async def test_shutdown_during_indexing(executable, tmp_path):
c = CliceClient()
await c.start_io(*cmd)
init_options = {
"project": {
"cache_dir": str(workspace / ".clice"),
"idle_timeout_ms": 0,
}
}
await c.initialize(workspace, initialization_options=init_options)
# Give indexing a moment to start, then send shutdown
await asyncio.sleep(0.5)
rpc = AgenticRpcClient(host, port)
body = json.dumps({"jsonrpc": "2.0", "method": "agentic/shutdown", "params": {}})
rpc.sock.sendall(f"Content-Length: {len(body)}\r\n\r\n{body}".encode())
rpc.sock.settimeout(5)
try:
rpc.sock.recv(4096)
except (socket.timeout, OSError):
pass
rpc.sock.close()
init_options = {
"project": {
"cache_dir": str(workspace / ".clice"),
"idle_timeout_ms": 0,
}
}
try:
await c.initialize(workspace, initialization_options=init_options)
except Exception:
if c._server.returncode is not None:
await assert_server_exited_cleanly(c._server, timeout=15.0)
raise
for _ in range(30):
if c._server.returncode is not None:
break
# Give indexing a moment to start, then send shutdown
await asyncio.sleep(0.5)
assert c._server.returncode is not None, "Server did not exit after shutdown"
assert c._server.returncode >= 0, (
f"Server crashed with signal {-c._server.returncode}"
)
rpc = AgenticRpcClient(host, port)
body = json.dumps(
{"jsonrpc": "2.0", "method": "agentic/shutdown", "params": {}}
)
rpc.sock.sendall(f"Content-Length: {len(body)}\r\n\r\n{body}".encode())
rpc.sock.settimeout(5)
try:
rpc.sock.recv(4096)
except (socket.timeout, OSError):
pass
rpc.sock.close()
await assert_server_exited_cleanly(c._server, timeout=15.0)
finally:
c._stop_event.set()
for task in c._async_tasks:
task.cancel()
await asyncio.sleep(0.1)

View File

@@ -1,6 +1,5 @@
#include "test/test.h"
#include "compile/compilation.h"
#include "compile/implement.h"
namespace clice::testing {
namespace {
@@ -8,10 +7,6 @@ namespace {
TEST_SUITE(ClangTidy) {
TEST_CASE(FastCheck) {
#ifdef CLICE_HAS_CLANG_TIDY_MODULES
ASSERT_TRUE(tidy::is_registered_tidy_check("bugprone-integer-division"));
#endif
// ASSERT_TRUE(tidy::is_fast_tidy_check("readability-misleading-indentation"));
// ASSERT_TRUE(tidy::is_fast_tidy_check("bugprone-unused-return-value"));
//
@@ -27,7 +22,6 @@ TEST_CASE(Tidy) {
std::string main_path = TestVFS::path("main.cpp");
CompilationParams params;
params.kind = CompilationKind::Content;
params.clang_tidy = true;
params.vfs = vfs;
params.arguments = {"clang++", "-ffreestanding", "-Xclang", "-undef", main_path.c_str()};
@@ -36,37 +30,6 @@ TEST_CASE(Tidy) {
ASSERT_FALSE(unit.diagnostics().empty());
}
#ifdef CLICE_HAS_CLANG_TIDY_MODULES
TEST_CASE(BugproneIntegerDivision) {
auto vfs = llvm::makeIntrusiveRefCnt<TestVFS>();
vfs->add("main.cpp",
"int main() {"
" double d;"
" int i = 42;"
" d = 32 * 8 / (2 + i);"
" return static_cast<int>(d);"
"}");
std::string main_path = TestVFS::path("main.cpp");
CompilationParams params;
params.kind = CompilationKind::Content;
params.clang_tidy = true;
params.vfs = vfs;
params.arguments = {"clang++", "-ffreestanding", "-Xclang", "-undef", main_path.c_str()};
auto unit = compile(params);
ASSERT_TRUE(unit.completed());
bool found = false;
for(auto& diagnostic: unit.diagnostics()) {
if(llvm::StringRef(diagnostic.message).contains("integer division")) {
found = true;
break;
}
}
ASSERT_TRUE(found);
}
#endif
}; // TEST_SUITE(ClangTidy)
} // namespace
} // namespace clice::testing

View File

@@ -140,10 +140,6 @@ void EXPECT_TOKEN(llvm::StringRef name,
ASSERT_EQ(token->modifiers, expected_modifiers);
}
void EXPECT_NO_TOKEN(llvm::StringRef name) {
ASSERT_TRUE(find_by_range(name) == nullptr);
}
TEST_CASE(BasicLexicalKinds) {
run_utf8(R"cpp(
@d1[#define] @m0[FOO]
@@ -270,44 +266,6 @@ int main() {
EXPECT_TOKEN("x3", SymbolKind::Variable, 0);
}
TEST_CASE(IneligibleOperatorReferenceIsSuppressed) {
run_utf8(R"cpp(
struct S {};
S operator+(S lhs, S rhs);
void use(S lhs, S rhs) {
(void)(lhs @plus[+] rhs);
}
)cpp");
EXPECT_NO_TOKEN("plus");
}
TEST_CASE(ConstructorAndDestructorNamesRemainHighlighted) {
run_utf8(R"cpp(
struct S {
@ctor_decl[S]();
@dtor_decl[~]S();
};
S::@ctor_def[S]() {}
void use(S* value) {
value->@dtor_ref[~]S();
}
)cpp");
auto declaration = modifier_mask({SymbolModifiers::Declaration});
auto definition = modifier_mask({SymbolModifiers::Definition});
auto special_member = modifier_mask({SymbolModifiers::ConstructorOrDestructor});
EXPECT_TOKEN("ctor_decl", SymbolKind::Method, declaration | special_member);
EXPECT_TOKEN("dtor_decl", SymbolKind::Method, declaration | special_member);
EXPECT_TOKEN("ctor_def", SymbolKind::Method, definition | special_member);
EXPECT_TOKEN("dtor_ref", SymbolKind::Method, special_member);
}
TEST_CASE(LegacyVarDeclTemplates) {
run_utf8(R"cpp(
extern int @x1[x];