| 125 | } |
| 126 | |
| 127 | static void write_diagnostics(void) { |
| 128 | /* Collect mimalloc stats */ |
| 129 | size_t elapsed_ms = 0; |
| 130 | size_t user_ms = 0; |
| 131 | size_t sys_ms = 0; |
| 132 | size_t current_rss = 0; |
| 133 | size_t peak_rss = 0; |
| 134 | size_t current_commit = 0; |
| 135 | size_t peak_commit = 0; |
| 136 | size_t page_faults = 0; |
| 137 | mi_process_info(&elapsed_ms, &user_ms, &sys_ms, ¤t_rss, &peak_rss, ¤t_commit, |
| 138 | &peak_commit, &page_faults); |
| 139 | |
| 140 | /* Fallback RSS for ASan builds */ |
| 141 | if (current_rss == 0) { |
| 142 | current_rss = cbm_mem_rss(); |
| 143 | } |
| 144 | |
| 145 | int fds = count_open_fds(); |
| 146 | time_t now = time(NULL); |
| 147 | long uptime = (long)(now - g_start_time); |
| 148 | |
| 149 | int qcount = atomic_load(&g_query_stats.count); |
| 150 | int qerrors = atomic_load(&g_query_stats.errors); |
| 151 | long long qtime = atomic_load(&g_query_stats.time_us); |
| 152 | long long qmax = atomic_load(&g_query_stats.max_us); |
| 153 | long long qavg = qcount > 0 ? qtime / qcount : 0; |
| 154 | |
| 155 | /* Write to .tmp then rename (atomic) */ |
| 156 | char tmp_path[sizeof(g_diag_path) + DIAG_PATH_EXTRA]; |
| 157 | snprintf(tmp_path, sizeof(tmp_path), "%s.tmp", g_diag_path); |
| 158 | |
| 159 | FILE *f = fopen(tmp_path, "w"); |
| 160 | if (!f) { |
| 161 | return; |
| 162 | } |
| 163 | |
| 164 | if (fprintf(f, |
| 165 | "{\n" |
| 166 | " \"uptime_s\": %ld,\n" |
| 167 | " \"rss_bytes\": %zu,\n" |
| 168 | " \"peak_rss_bytes\": %zu,\n" |
| 169 | " \"heap_committed_bytes\": %zu,\n" |
| 170 | " \"peak_committed_bytes\": %zu,\n" |
| 171 | " \"page_faults\": %zu,\n" |
| 172 | " \"fd_count\": %d,\n" |
| 173 | " \"query_count\": %d,\n" |
| 174 | " \"query_errors\": %d,\n" |
| 175 | " \"query_total_us\": %lld,\n" |
| 176 | " \"query_avg_us\": %lld,\n" |
| 177 | " \"query_max_us\": %lld,\n" |
| 178 | " \"pid\": %d\n" |
| 179 | "}\n", |
| 180 | uptime, current_rss, peak_rss, current_commit, peak_commit, page_faults, fds, |
| 181 | qcount, qerrors, qtime, qavg, qmax, (int)getpid()) < 0) { |
| 182 | (void)fclose(f); |
| 183 | return; |
| 184 | } |
no test coverage detected