Local code intelligence for developers and AI agents. Connect code, docs and infrastructure in a persistent graph, with CBM Lens, MCP tools, agent integrations and change-aware test selection.
C aiderastclaude-codecode-analysiscode-intelligencecodexcursorcypherdeveloper-toolsgemini-cligraph-visualizationkilocodeknowledge-graphmcpmcp-servermodel-context-protocolopencodesqlitetree-sitterwindsurf
fix(daemon): make request completion transactional and EOF drain-safe
Martin Vogel5e23839f870e
diff --git a/src/daemon/frontend.c b/src/daemon/frontend.cindex 146a1f8b3..8d97adbe7 100644--- a/src/daemon/frontend.c+++ b/src/daemon/frontend.c@@ -27,12 +27,18 @@ enum {* close stdin before the worker is scheduled. Give already-accepted input* a short FIFO drain window so EOF cannot silently discard it. A genuinely* active long operation is still cancelled at this deadline. */- FRONTEND_EOF_DRAIN_MS = 1000,FRONTEND_WAIT_US = 1000,/* An idle thin frontend owns no work and only needs to notice the next* queue item promptly. Ten milliseconds avoids a 1 kHz wake-up loop per* connected coding-agent session without perceptible request latency. */FRONTEND_IDLE_WAIT_US = 10 * 1000,+ /* EOF-drain progress window. Sized to cover a cold daemon spawn plus one+ * request round-trip on the slowest platform (several seconds on Windows+ * under CI load): the drain aborts only after this long with NO item+ * completing, so batch clients that close stdin after writing keep+ * receiving every response while a genuinely stuck request still gets+ * cancelled and the frontend exits cleanly. */+ FRONTEND_EOF_DRAIN_MS = 15000,FRONTEND_MAINTENANCE_POLL_MS = 10,/* The owner thread may be draining a supervised process tree. Preserve the* supervisor's complete graceful + forced-settle window before the monitor@@ -71,6 +77,10 @@ typedef struct {const char *active_id_str;cbm_daemon_runtime_application_token_t active_request_token;bool failed;+ /* Monotonic count of fully processed queue items (responses written or+ * cancellations acknowledged). The EOF drain below watches it to tell a+ * batch that is still making progress from a genuinely stuck request. */+ atomic_uint_fast64_t completed_items;} frontend_state_t;typedef struct {@@ -190,7 +200,15 @@ static void frontend_item_free(frontend_item_t *item) {static bool frontend_should_stop(frontend_state_t *state) {cbm_mutex_lock(&state->mutex);- bool stopping = state->stopping || (state->input_closed && state->count == 0);+ /* The input-closed leg must also require that no item is IN FLIGHT: the+ * worker consults this while deciding whether a request failure was an+ * expected shutdown, and the final queued item after EOF has count == 0+ * precisely while its own forward is outstanding. Without the in_request+ * term, any daemon-side failure of that last item was classified as an+ * expected stop and its response silently dropped with a success exit —+ * an unanswerable failure mode for the client. */+ bool stopping =+ state->stopping || (state->input_closed && state->count == 0 && !state->in_request);cbm_mutex_unlock(&state->mutex);return stopping;}@@ -438,6 +456,7 @@ static void *frontend_worker(void *opaque) {bool expected_stop = failed && frontend_should_stop(state);frontend_end_request(state, failed && !expected_stop);frontend_item_free(&item);+ atomic_fetch_add_explicit(&state->completed_items, 1, memory_order_release);if (failed) {if (!expected_stop) {/* A failed daemon transport cannot wake a thread blocked in@@ -540,6 +559,7 @@ int cbm_daemon_frontend_mcp_run(cbm_daemon_runtime_client_t *client,.out = out,};cbm_mutex_init(&state.mutex);+ atomic_init(&state.completed_items, 0);cbm_daemon_maintenance_monitor_t *maintenance_monitor = cbm_daemon_maintenance_monitor_start(cohort_manager, frontend_cancel_for_maintenance, &state, EXIT_SUCCESS, "MCP frontend");if (!maintenance_monitor) {@@ -598,11 +618,28 @@ int cbm_daemon_frontend_mcp_run(cbm_daemon_runtime_client_t *client,if (clean_eof && !close_begun) {frontend_input_closed(&state);- uint64_t now = cbm_now_ms();- uint64_t drain_deadline =- now > UINT64_MAX - FRONTEND_EOF_DRAIN_MS ? UINT64_MAX : now + FRONTEND_EOF_DRAIN_MS;+ /* EOF ends INPUT, not accepted work: as long as queued items keep+ * completing, every already-enqueued request still receives its+ * response, exactly like the pre-daemon stdio server, which+ * processed the whole stream before exiting. The window resets on+ * each completed item, so it bounds STUCKNESS, not batch length: a+ * request making no progress for the full window is cancelled by the+ * stop path below and the frontend still exits cleanly. The previous+ * fixed 1s total window abandoned queued requests whenever the+ * daemon cold spawn plus the first request outlasted it (several+ * seconds on Windows), so batch clients that close stdin right after+ * writing — file redirects, piped harnesses, hook one-shots —+ * intermittently lost their tail responses. */+ uint64_t drained = atomic_load_explicit(&state.completed_items, memory_order_acquire);+ uint64_t drain_deadline = cbm_now_ms() + FRONTEND_EOF_DRAIN_MS;while (!frontend_worker_is_done(&state) && cbm_now_ms() < drain_deadline) {cbm_usleep(FRONTEND_WAIT_US);+ uint64_t now_drained =+ atomic_load_explicit(&state.completed_items, memory_order_acquire);+ if (now_drained != drained) {+ drained = now_drained;+ drain_deadline = cbm_now_ms() + FRONTEND_EOF_DRAIN_MS;+ }}}if (!close_begun) {diff --git a/src/daemon/host.c b/src/daemon/host.cindex f5d433bfe..efd865e67 100644--- a/src/daemon/host.c+++ b/src/daemon/host.c@@ -679,11 +679,11 @@ static bool host_background_start(host_state_t *host) {static bool host_wait_for_lifetime(cbm_daemon_runtime_service_t *service,atomic_int *stop_requested, host_state_t *host) {uint64_t initial_deadline = cbm_now_ms() + HOST_INITIAL_CLIENT_TIMEOUT_MS;- bool admitted = false;uint64_t stopping_deadline = 0;for (;;) {cbm_daemon_runtime_service_state_t state = cbm_daemon_runtime_service_state(service);if (state == CBM_DAEMON_RUNTIME_SERVICE_EXITED) {+ cbm_log_info("daemon.lifetime_end", "reason", "runtime_exited");return true;}if (state == CBM_DAEMON_RUNTIME_SERVICE_STOPPING) {@@ -696,11 +696,16 @@ static bool host_wait_for_lifetime(cbm_daemon_runtime_service_t *service,(void)cbm_daemon_runtime_service_wait_exited(service, HOST_WAIT_TICK_MS);continue;}- if (cbm_daemon_runtime_service_active_clients(service) > 0) {- admitted = true;- }+ /* The nobody-ever-connected window latches on the monotonic admission+ * total, not the live client count: a short first session can begin+ * and end entirely between two polls of this loop, and a sampled+ * count then reads zero forever — stopping a daemon whose client is+ * mid-conversation between per-request connections. */+ bool admitted = cbm_daemon_runtime_service_clients_admitted_total(service) > 0;bool stop = stop_requested && atomic_load(stop_requested);if (stop || (!admitted && cbm_now_ms() >= initial_deadline)) {+ cbm_log_info("daemon.lifetime_end", "reason",+ stop ? "stop_requested" : "initial_window_expired");return cbm_daemon_runtime_service_stop(service, HOST_RUNTIME_SHUTDOWN_MS);}host_http_reconcile_at(host, cbm_now_ms(), false);diff --git a/src/daemon/runtime.c b/src/daemon/runtime.cindex 7f08448de..48686864b 100644--- a/src/daemon/runtime.c+++ b/src/daemon/runtime.c@@ -142,6 +142,12 @@ struct cbm_daemon_runtime_service {size_t worker_mutexes_initialized;size_t active_connections;size_t committed_clients;+ /* Monotonic count of every admission since service start. The host's+ * nobody-ever-connected window latches on this instead of sampling the+ * live client count: a short-lived first session can begin and end+ * entirely between two host polls, and a sampled count then reads zero+ * forever, stopping a daemon whose client is mid-conversation. */+ uint64_t admitted_total;cbm_thread_t accept_thread;bool accept_thread_started;@@ -1019,10 +1025,16 @@ static void runtime_result_rejected(cbm_daemon_runtime_connect_result_t *result,}static void runtime_service_begin_stopping_locked(cbm_daemon_runtime_service_t *service,- uint64_t deadline, bool emergency) {+ uint64_t deadline, bool emergency,+ const char *reason) {if (service->state == CBM_DAEMON_RUNTIME_SERVICE_RUNNING) {service->state = CBM_DAEMON_RUNTIME_SERVICE_STOPPING;service->stop_deadline_ms = deadline;+ /* The generation's fate is decided here by one of several owners+ * (last-client exit, coordinator stop, activation drain, external+ * stop). Sessions dropped by the losing side of a race are+ * undiagnosable without naming which owner pulled the trigger. */+ cbm_log_info("daemon.runtime_stopping", "reason", reason ? reason : "unspecified");} else if (service->state == CBM_DAEMON_RUNTIME_SERVICE_STOPPING &&(service->stop_deadline_ms == 0 || deadline < service->stop_deadline_ms)) {service->stop_deadline_ms = deadline;@@ -1033,10 +1045,11 @@ static void runtime_service_begin_stopping_locked(cbm_daemon_runtime_service_t *}static void runtime_service_begin_stopping(cbm_daemon_runtime_service_t *service,- uint32_t timeout_ms, bool emergency) {+ uint32_t timeout_ms, bool emergency,+ const char *reason) {uint64_t deadline = runtime_deadline_after(timeout_ms);cbm_mutex_lock(&service->mutex);- runtime_service_begin_stopping_locked(service, deadline, emergency);+ runtime_service_begin_stopping_locked(service, deadline, emergency, reason);cbm_mutex_unlock(&service->mutex);}@@ -1084,7 +1097,8 @@ static void runtime_worker_disconnect(cbm_daemon_runtime_worker_t *worker) {/* A HELLO whose application session is still opening is only a* provisional coordinator client. It cannot keep the generation* alive after the final fully committed frontend disconnects. */- runtime_service_begin_stopping_locked(service, shutdown_deadline, false);+ runtime_service_begin_stopping_locked(service, shutdown_deadline, false,+ "last_committed_client_disconnected");}}cbm_mutex_unlock(&service->mutex);@@ -1098,7 +1112,8 @@ static void runtime_worker_disconnect(cbm_daemon_runtime_worker_t *worker) {worker->application_session);}if (cbm_daemon_coordinator_state(service->coordinator) == CBM_DAEMON_COORDINATOR_STOPPING) {- runtime_service_begin_stopping(service, service->shutdown_timeout_ms, false);+ runtime_service_begin_stopping(service, service->shutdown_timeout_ms, false,+ "coordinator_stopping");}}@@ -1121,6 +1136,7 @@ static bool runtime_worker_admit(cbm_daemon_runtime_worker_t *worker,worker->client_id = client_id;worker->admitted = true;worker->admission_committed = false;+ service->admitted_total++;}}cbm_mutex_unlock(&service->mutex);@@ -1202,13 +1218,23 @@ static void *runtime_application_worker(void *opaque) {status = CBM_DAEMON_RUNTIME_APPLICATION_HANDLER_ERROR;}+ /* Completion must be one atomic transition from the client's point of+ * view: publish the done flag BEFORE the response bytes leave, so by the+ * time any client can react to the response, admission already observes+ * this slot as reusable. With the store after the send, a client that+ * pipelines its next request the moment it sees a response raced this+ * thread's final instructions and was rejected BUSY — on loaded Windows+ * hosts roughly half of all back-to-back requests on one connection,+ * surfacing as the wandering Phase 5 session drops. The admission side+ * joins this thread after observing the flag, which safely absorbs the+ * tail of the send. */+ atomic_store_explicit(&worker->application_thread_done, true, memory_order_release);bool sent = runtime_worker_send_application_response(worker, worker->application_request_token,status, response, response_length, true);free(response);if (!sent && !atomic_load_explicit(&worker->disconnecting, memory_order_acquire)) {cbm_daemon_ipc_connection_interrupt(worker->connection);}- atomic_store_explicit(&worker->application_thread_done, true, memory_order_release);return NULL;}@@ -1383,7 +1409,7 @@ static void runtime_worker_handle_activation_shutdown(cbm_daemon_runtime_worker_result.active_connections =service->active_connections > 0 ? (uint64_t)(service->active_connections - 1U) : 0;if (service->state == CBM_DAEMON_RUNTIME_SERVICE_RUNNING) {- runtime_service_begin_stopping_locked(service, deadline, false);+ runtime_service_begin_stopping_locked(service, deadline, false, "activation_shutdown");service->activation_shutdown_requested = true;service->activation_response_inflight = true;worker->final_response_inflight = true;@@ -1569,6 +1595,15 @@ static void *runtime_connection_worker(void *opaque) {received = cbm_daemon_ipc_receive_frame(worker->connection, CBM_DAEMON_IPC_WAIT_FOREVER,&frame, &payload);if (received != 1 || frame.type != CBM_DAEMON_FRAME_REQUEST) {+ /* An admitted frontend disconnecting decides the daemon's fate+ * (last committed client ends the generation), so the transport+ * cause must be visible: 0 = orderly EOF, negative = transport+ * error. A silent break here previously made session-drop races+ * undiagnosable across three platforms. */+ char received_text[16];+ (void)snprintf(received_text, sizeof(received_text), "%d", received);+ cbm_log_info("daemon.connection_end", "received", received_text, "frame_type",+ received == 1 ? "non_request" : "none");break;}switch (frame.flags) {@@ -2026,6 +2061,16 @@ cbm_daemon_runtime_service_state_t cbm_daemon_runtime_service_state(return state;}+uint64_t cbm_daemon_runtime_service_clients_admitted_total(cbm_daemon_runtime_service_t *service) {+ if (!service) {+ return 0;+ }+ cbm_mutex_lock(&service->mutex);+ uint64_t total = service->admitted_total;+ cbm_mutex_unlock(&service->mutex);+ return total;+}+size_t cbm_daemon_runtime_service_active_clients(cbm_daemon_runtime_service_t *service) {if (!service) {return 0;@@ -2129,7 +2174,7 @@ bool cbm_daemon_runtime_service_stop(cbm_daemon_runtime_service_t *service, uintif (cbm_daemon_runtime_service_state(service) == CBM_DAEMON_RUNTIME_SERVICE_EXITED) {return cbm_daemon_runtime_service_wait_exited(service, timeout_ms);}- runtime_service_begin_stopping(service, timeout_ms, true);+ runtime_service_begin_stopping(service, timeout_ms, true, "service_stop");runtime_service_interrupt_connections(service);return cbm_daemon_runtime_service_wait_exited(service, timeout_ms);}diff --git a/src/daemon/runtime.h b/src/daemon/runtime.hindex 793c224b8..4647f99d2 100644--- a/src/daemon/runtime.h+++ b/src/daemon/runtime.h@@ -248,6 +248,10 @@ cbm_daemon_runtime_service_t *cbm_daemon_runtime_service_start_reserved(cbm_daemon_runtime_service_state_t cbm_daemon_runtime_service_state(cbm_daemon_runtime_service_t *service);size_t cbm_daemon_runtime_service_active_clients(cbm_daemon_runtime_service_t *service);+/* Monotonic count of every admission since service start; never decremented.+ * Use for "has any client ever connected" decisions — the live count above+ * can read zero between two short-lived sessions. */+uint64_t cbm_daemon_runtime_service_clients_admitted_total(cbm_daemon_runtime_service_t *service);/* Includes accepted connections still waiting for HELLO. Never exceeds the* configured max_clients; over-cap peers receive REJECTED before close. */size_t cbm_daemon_runtime_service_active_connections(cbm_daemon_runtime_service_t *service);