From f133d81a05224cd4d292d6e43fb40207a0a82ed2 Mon Sep 17 00:00:00 2001 From: Jabber Developer Date: Fri, 1 May 2026 18:24:57 +0000 Subject: [PATCH] fix(ai): use atomic operations for refcounting Replace plain ref_count++/-- with g_atomic_int_inc and g_atomic_int_dec_and_test for both AIProvider and AISession refcounts. Prevents data races when ref/unref is called from worker threads. --- src/ai/ai_client.c | 12 ++++++------ src/ai/ai_client.h | 4 ++-- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/ai/ai_client.c b/src/ai/ai_client.c index 97701a95..ea2f89e8 100644 --- a/src/ai/ai_client.c +++ b/src/ai/ai_client.c @@ -192,7 +192,7 @@ static AIProvider* ai_provider_ref(AIProvider* provider) { if (provider) { - provider->ref_count++; + g_atomic_int_inc(&provider->ref_count); } return provider; } @@ -203,9 +203,9 @@ ai_provider_unref(AIProvider* provider) if (!provider) return; - provider->ref_count--; - if (provider->ref_count > 0) + if (!g_atomic_int_dec_and_test(&provider->ref_count)) { return; + } g_free(provider->name); g_free(provider->api_url); @@ -451,7 +451,7 @@ AISession* ai_session_ref(AISession* session) { if (session) { - session->ref_count++; + g_atomic_int_inc(&session->ref_count); } return session; } @@ -462,9 +462,9 @@ ai_session_unref(AISession* session) if (!session) return; - session->ref_count--; - if (session->ref_count > 0) + if (!g_atomic_int_dec_and_test(&session->ref_count)) { return; + } g_free(session->provider_name); ai_provider_unref(session->provider); diff --git a/src/ai/ai_client.h b/src/ai/ai_client.h index 17083c39..030b55c7 100644 --- a/src/ai/ai_client.h +++ b/src/ai/ai_client.h @@ -22,7 +22,7 @@ typedef struct ai_provider_t gchar* org_id; /* Optional organization ID */ gchar* project_id; /* Optional project ID (for some providers) */ GList* models; /* List of available models (gchar*) */ - guint ref_count; /* Reference count */ + gint32 ref_count; /* Reference count (atomic) */ } AIProvider; /** @@ -35,7 +35,7 @@ typedef struct ai_session_t gchar* model; /* Model identifier (e.g., "gpt-4", "sonar") */ gchar* api_key; /* API key for this session */ GList* history; /* Conversation history (GList of AIMessage*) */ - guint ref_count; /* Reference count */ + gint32 ref_count; /* Reference count (atomic) */ } AISession; /* ========================================================================