ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
lib/stats/stats.c
Go to the documentation of this file.
1#include <ascii-chat/common.h>
4#include <libplatform/atomic.h>
5#include <libplatform/mutex.h>
6#include <libplatform/thread.h>
7#include <stdatomic.h>
8#include <string.h>
9
10// Each duration recorder owns a shard. Readers use sequence checks to copy a
11// complete observation without making capture, conversion, and output contend.
12#define STATS_DURATION_SHARDS 16
13
20
33
54
73
74static atomic_t next_scope_id = {0};
75
77 stats_scope_t **out_scope) {
78 if (!out_scope)
79 return SET_ERRNO(ERROR_INVALID_PARAM, "Missing stats scope output");
80 *out_scope = NULL;
81 if (!capabilities)
82 return SET_ERRNO(ERROR_INVALID_PARAM, "Missing stats capabilities");
83 stats_scope_t *scope = SAFE_CALLOC(1, sizeof(*scope), stats_scope_t *);
84 if (!scope)
85 return SET_ERRNO(ERROR_MEMORY, "Cannot allocate stats scope");
86 if (mutex_init(&scope->snapshot_mutex, "stats_snapshot") != 0) {
87 SAFE_FREE(scope);
88 return SET_ERRNO(ERROR_THREAD, "Cannot initialize stats snapshot mutex");
89 }
90 if (mutex_init(&scope->duration_mutex, "stats_duration") != 0) {
91 mutex_destroy(&scope->snapshot_mutex);
92 SAFE_FREE(scope);
93 return SET_ERRNO(ERROR_THREAD, "Cannot initialize stats duration mutex");
94 }
95 scope->capabilities = *capabilities;
96 // Bypass debug atomic instrumentation so recording never recursively collects
97 // or allocates.
98 scope->id = atomic_fetch_add_u64_impl(&next_scope_id, 1) + 1;
99 scope->started_ns = time_get_ns();
100 *out_scope = scope;
101 return ASCIICHAT_OK;
102}
103
105 if (!scope)
106 return;
107 mutex_destroy(&scope->duration_mutex);
108 mutex_destroy(&scope->snapshot_mutex);
109 SAFE_FREE(scope);
110}
111
113 void *context) {
114 if (scope) {
115 scope->observer = observer;
116 scope->observer_context = context;
117 }
118}
119
121 uint64_t amount) {
122 if (scope && (unsigned)id < STATS_COUNTER_COUNT &&
123 scope->capabilities.counters[id]) {
124 atomic_fetch_add_u64_impl(&scope->counters[id], amount);
125 if (scope->observer)
126 scope->observer(STATS_RECORD_COUNTER, id, amount,
127 scope->observer_context);
128 }
129}
130
132 uint64_t value) {
133 if (scope && (unsigned)id < STATS_GAUGE_COUNT &&
134 scope->capabilities.gauges[id]) {
135 atomic_store_u64_impl(&scope->gauges[id], value);
136 if (scope->observer)
137 scope->observer(STATS_RECORD_GAUGE, id, value, scope->observer_context);
138 }
139}
140
141static uint64_t duration_add(uint64_t a, uint64_t b) {
142 return a > UINT64_MAX - b ? b - (UINT64_MAX - a) - 1 : a + b;
143}
144
145static stats_duration_shard_t *duration_shard(stats_scope_t *scope) {
146 static _Thread_local uint64_t cached_scope_id;
147 static _Thread_local stats_duration_shard_t *cached_shard;
148 if (cached_scope_id == scope->id)
149 return cached_shard;
150 uint64_t owner = thread_current_id();
151 cached_scope_id = scope->id;
152 cached_shard = NULL;
153 for (size_t i = 0; i < STATS_DURATION_SHARDS; ++i) {
154 uint64_t expected = 0;
155 if (atomic_load(&scope->shards[i].owner) == owner ||
156 atomic_compare_exchange_strong(&scope->shards[i].owner, &expected,
157 owner)) {
158 cached_shard = &scope->shards[i];
159 break;
160 }
161 }
162 return cached_shard;
163}
164
166 uint64_t elapsed_ns) {
167 if (!scope || (unsigned)id >= STATS_DURATION_COUNT ||
168 !scope->capabilities.durations[id])
169 return;
170 stats_duration_shard_t *shard = duration_shard(scope);
171 if (shard) {
172 stats_duration_cell_t *cell = &shard->durations[id];
173 uint64_t sequence = atomic_load(&cell->sequence);
174 atomic_store(&cell->sequence, duration_add(sequence, 1));
175 uint64_t observations = atomic_load(&cell->observations);
176 if (!observations || elapsed_ns < atomic_load(&cell->min_ns))
177 atomic_store(&cell->min_ns, elapsed_ns);
178 if (elapsed_ns > atomic_load(&cell->max_ns))
179 atomic_store(&cell->max_ns, elapsed_ns);
180 atomic_store(&cell->last_ns, elapsed_ns);
181 atomic_store(&cell->recorded_ns, time_get_ns());
182 atomic_store(&cell->observations, duration_add(observations, 1));
183 atomic_store(&cell->total_ns,
184 duration_add(atomic_load(&cell->total_ns), elapsed_ns));
185 atomic_store(&cell->sequence, duration_add(sequence, 2));
186 if (scope->observer)
187 scope->observer(STATS_RECORD_DURATION, id, elapsed_ns,
188 scope->observer_context);
189 return;
190 }
191 // Unusually many lifetime producers retain the bounded, coherent fallback.
192 if (mutex_lock(&scope->duration_mutex) != 0)
193 return;
194 stats_duration_snapshot_t *duration = &scope->durations[id];
195 duration->last_ns = elapsed_ns;
196 scope->duration_recorded_ns[id] = time_get_ns();
197 if (!duration->observations || elapsed_ns < duration->min_ns)
198 duration->min_ns = elapsed_ns;
199 if (elapsed_ns > duration->max_ns)
200 duration->max_ns = elapsed_ns;
201 duration->observations =
202 duration->observations == UINT64_MAX ? 0 : duration->observations + 1;
203 // Unsigned wrap is intentional; an observed decrease causes samplers to
204 // rebaseline.
205 duration->total_ns = duration->total_ns > UINT64_MAX - elapsed_ns
206 ? elapsed_ns - (UINT64_MAX - duration->total_ns) - 1
207 : duration->total_ns + elapsed_ns;
208 mutex_unlock(&scope->duration_mutex);
209 if (scope->observer)
210 scope->observer(STATS_RECORD_DURATION, id, elapsed_ns,
211 scope->observer_context);
212}
213
216 if (!scope || !out)
218 "Missing stats scope or snapshot output");
219 // Logical constness: collection is unchanged; only snapshot synchronization
220 // is mutable.
221 stats_scope_t *mutable_scope = (stats_scope_t *)scope;
222 if (mutex_lock(&mutable_scope->snapshot_mutex) != 0)
223 return SET_ERRNO(ERROR_THREAD, "Cannot lock stats snapshot");
224 memset(out, 0, sizeof(*out));
225 out->scope_id = scope->id;
226 out->started_ns = scope->started_ns;
227 out->capabilities = scope->capabilities;
228 for (size_t i = 0; i < STATS_COUNTER_COUNT; ++i)
229 out->counters[i] = atomic_load_u64_impl(&scope->counters[i]);
230 for (size_t i = 0; i < STATS_GAUGE_COUNT; ++i)
231 out->gauges[i] = atomic_load_u64_impl(&scope->gauges[i]);
232 if (mutex_lock(&mutable_scope->duration_mutex) != 0) {
233 mutex_unlock(&mutable_scope->snapshot_mutex);
234 return SET_ERRNO(ERROR_THREAD, "Cannot lock stats durations");
235 }
236 memcpy(out->durations, scope->durations, sizeof(out->durations));
237 uint64_t recorded_ns[STATS_DURATION_COUNT];
238 memcpy(recorded_ns, scope->duration_recorded_ns, sizeof(recorded_ns));
239 mutex_unlock(&mutable_scope->duration_mutex);
240 for (size_t i = 0; i < STATS_DURATION_SHARDS; ++i) {
241 if (!atomic_load(&scope->shards[i].owner))
242 continue;
243 for (size_t id = 0; id < STATS_DURATION_COUNT; ++id) {
244 const stats_duration_cell_t *cell = &scope->shards[i].durations[id];
246 uint64_t stamp, before;
247 for (;;) {
248 before = atomic_load(&cell->sequence);
249 if (before & 1)
250 continue;
251 sample.observations = atomic_load(&cell->observations);
252 sample.total_ns = atomic_load(&cell->total_ns);
253 sample.min_ns = atomic_load(&cell->min_ns);
254 sample.max_ns = atomic_load(&cell->max_ns);
255 sample.last_ns = atomic_load(&cell->last_ns);
256 stamp = atomic_load(&cell->recorded_ns);
257 if (before == atomic_load(&cell->sequence))
258 break;
259 }
260 if (!sample.observations)
261 continue;
262 stats_duration_snapshot_t *total = &out->durations[id];
263 if (!total->observations || sample.min_ns < total->min_ns)
264 total->min_ns = sample.min_ns;
265 if (sample.max_ns > total->max_ns)
266 total->max_ns = sample.max_ns;
267 if (stamp >= recorded_ns[id]) {
268 recorded_ns[id] = stamp;
269 total->last_ns = sample.last_ns;
270 }
271 total->observations =
272 duration_add(total->observations, sample.observations);
273 total->total_ns = duration_add(total->total_ns, sample.total_ns);
274 }
275 }
276 out->sampled_ns = time_get_ns();
277 mutex_unlock(&mutable_scope->snapshot_mutex);
278 return ASCIICHAT_OK;
279}
280
282 stats_sampler_t **out_sampler) {
283 if (!out_sampler)
284 return SET_ERRNO(ERROR_INVALID_PARAM, "Missing stats sampler output");
285 *out_sampler = NULL;
286 if (!config || !config->resolution_ns ||
287 config->window_ns < config->resolution_ns)
288 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid stats sampling interval");
289 uint64_t slots = config->window_ns / config->resolution_ns +
290 (config->window_ns % config->resolution_ns != 0);
291 if (slots > 4096)
293 "Stats sampler exceeds 4096 history intervals");
294 stats_sampler_t *sampler =
295 SAFE_CALLOC(1, sizeof(*sampler), stats_sampler_t *);
296 if (!sampler)
297 return SET_ERRNO(ERROR_MEMORY, "Cannot allocate stats sampler");
298 sampler->capacity = (size_t)slots + 2;
299 sampler->history = SAFE_CALLOC(sampler->capacity, sizeof(*sampler->history),
301 if (!sampler->history) {
302 SAFE_FREE(sampler);
303 return SET_ERRNO(ERROR_MEMORY, "Cannot allocate stats history");
304 }
305 sampler->config = *config;
306 *out_sampler = sampler;
307 return ASCIICHAT_OK;
308}
309
310static bool stats_baseline_changed(const stats_snapshot_t *old,
311 const stats_snapshot_t *current) {
312 if (old->scope_id != current->scope_id ||
313 current->sampled_ns <= old->sampled_ns)
314 return true;
315 for (size_t i = 0; i < STATS_COUNTER_COUNT; ++i)
316 if (old->capabilities.counters[i] != current->capabilities.counters[i] ||
317 current->counters[i] < old->counters[i])
318 return true;
319 for (size_t i = 0; i < STATS_GAUGE_COUNT; ++i)
320 if (old->capabilities.gauges[i] != current->capabilities.gauges[i])
321 return true;
322 for (size_t i = 0; i < STATS_DURATION_COUNT; ++i)
323 if (old->capabilities.durations[i] != current->capabilities.durations[i] ||
324 current->durations[i].observations < old->durations[i].observations ||
325 current->durations[i].total_ns < old->durations[i].total_ns)
326 return true;
327 return false;
328}
329
331 const stats_snapshot_t *snapshot,
332 stats_rates_t *out_rates) {
333 if (!sampler || !snapshot || !out_rates)
335 "Missing stats sampler, snapshot, or rates output");
336 memset(out_rates, 0, sizeof(*out_rates));
337 if (!sampler->count || stats_baseline_changed(&sampler->latest, snapshot)) {
338 sampler->head = 0;
339 sampler->count = 1;
340 sampler->history[0] = *snapshot;
341 sampler->latest = *snapshot;
342 return ASCIICHAT_OK;
343 }
344 uint64_t cutoff = snapshot->sampled_ns > sampler->config.window_ns
345 ? snapshot->sampled_ns - sampler->config.window_ns
346 : 0;
347 while (sampler->count > 1) {
348 size_t next = (sampler->head + 1) % sampler->capacity;
349 if (sampler->history[next].sampled_ns > cutoff)
350 break;
351 sampler->head = next;
352 sampler->count--;
353 }
354 const stats_snapshot_t *baseline = &sampler->history[sampler->head];
355 out_rates->elapsed_ns = snapshot->sampled_ns - baseline->sampled_ns;
356 out_rates->ready = true;
357 for (size_t i = 0; i < STATS_COUNTER_COUNT; ++i)
358 if (snapshot->capabilities.counters[i])
359 out_rates->counters_per_second[i] =
360 (double)(snapshot->counters[i] - baseline->counters[i]) * 1e9 /
361 (double)out_rates->elapsed_ns;
362 for (size_t i = 0; i < STATS_DURATION_COUNT; ++i) {
363 uint64_t observations = snapshot->durations[i].observations -
364 baseline->durations[i].observations;
365 if (snapshot->capabilities.durations[i] && observations) {
366 out_rates->duration_valid[i] = true;
367 out_rates->duration_mean_ns[i] =
368 (double)(snapshot->durations[i].total_ns -
369 baseline->durations[i].total_ns) /
370 (double)observations;
371 }
372 }
373 size_t tail = (sampler->head + sampler->count - 1) % sampler->capacity;
374 if (snapshot->sampled_ns - sampler->history[tail].sampled_ns >=
375 sampler->config.resolution_ns) {
376 size_t next = (tail + 1) % sampler->capacity;
377 sampler->history[next] = *snapshot;
378 if (sampler->count == sampler->capacity)
379 sampler->head = (sampler->head + 1) % sampler->capacity;
380 else
381 sampler->count++;
382 }
383 sampler->latest = *snapshot;
384 return ASCIICHAT_OK;
385}
386
388 if (!sampler)
389 return;
390 SAFE_FREE(sampler->history);
391 SAFE_FREE(sampler);
392}
#define SET_ERRNO(code,...)
void atomic_store_u64_impl(atomic_t *a, uint64_t value)
uint64_t atomic_load_u64_impl(const atomic_t *a)
uint64_t atomic_fetch_add_u64_impl(atomic_t *a, uint64_t delta)
#define SAFE_FREE(ptr)
#define SAFE_CALLOC(count, size, cast)
unsigned long long uint64_t
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_PARAM
@ ERROR_THREAD
⚙️ Common definitions, error codes, macros, and types shared throughout the application
void(* stats_observer_fn)(stats_record_kind_t kind, unsigned id, uint64_t value, void *context)
struct stats_sampler stats_sampler_t
struct stats_scope stats_scope_t
void stats_scope_destroy(stats_scope_t *scope)
void stats_scope_set_observer(stats_scope_t *scope, stats_observer_fn observer, void *context)
void stats_counter_add(stats_scope_t *scope, stats_counter_id_t id, uint64_t amount)
void stats_duration_record(stats_scope_t *scope, stats_duration_id_t id, uint64_t elapsed_ns)
void stats_sampler_destroy(stats_sampler_t *sampler)
asciichat_error_t stats_scope_snapshot(const stats_scope_t *scope, stats_snapshot_t *out)
stats sampler config keeps the values that move through the subsystem: window_ns, resolution_ns....
#define STATS_DURATION_SHARDS
asciichat_error_t stats_scope_create(const stats_capabilities_t *capabilities, stats_scope_t **out_scope)
asciichat_error_t stats_sampler_update(stats_sampler_t *sampler, const stats_snapshot_t *snapshot, stats_rates_t *out_rates)
void stats_gauge_set(stats_scope_t *scope, stats_gauge_id_t id, uint64_t value)
asciichat_error_t stats_sampler_create(const stats_sampler_config_t *config, stats_sampler_t **out_sampler)
static bool size_t gotel_query_t * out
Definition queries.h:10
🔤 String Manipulation and Shell Escaping Utilities
Atomic value wrapper for integral/boolean types.
Definition atomic.h:80
stats descriptor is intentionally a small, concrete record. Fields such as name, unit,...
bool counters[STATS_COUNTER_COUNT]
bool durations[STATS_DURATION_COUNT]
_Atomic uint64_t min_ns
_Atomic uint64_t recorded_ns
_Atomic uint64_t max_ns
_Atomic uint64_t last_ns
_Atomic uint64_t observations
_Atomic uint64_t total_ns
_Atomic uint64_t sequence
For stats duration cell, this is the live record that ties sequence, observations,...
stats_duration_cell_t durations[STATS_DURATION_COUNT]
_Atomic uint64_t owner
double duration_mean_ns[STATS_DURATION_COUNT]
bool duration_valid[STATS_DURATION_COUNT]
double counters_per_second[STATS_COUNTER_COUNT]
This is the handoff point for stats scope. Callers fill observer, observer_context,...
stats_snapshot_t latest
stats_sampler_config_t config
stats_snapshot_t * history
stats duration shard keeps the values that move through the subsystem: owner. Some members are pointe...
stats_duration_shard_t shards[16]
mutex_t duration_mutex
mutex_t snapshot_mutex
uint64_t started_ns
atomic_t counters[STATS_COUNTER_COUNT]
stats_capabilities_t capabilities
stats_observer_fn observer
stats_duration_snapshot_t durations[STATS_DURATION_COUNT]
atomic_t gauges[STATS_GAUGE_COUNT]
void * observer_context
uint64_t duration_recorded_ns[STATS_DURATION_COUNT]
stats_capabilities_t capabilities
uint64_t counters[STATS_COUNTER_COUNT]
stats_duration_snapshot_t durations[STATS_DURATION_COUNT]
⏱️ High-precision timing utilities using sokol_time.h and uthash