Files
profanity/tests/bench/bench_common.c
Jabber Developer 3f36c303c2 feat(history): flat-file backend with bidirectional SQLite migration
A flat-file alternative to the SQLite chatlog backend with runtime
switching, full migration tooling, integrity verification, and a
synthetic load harness. SQLite remains the default; both backends share
one dispatch layer (db_backend_t vtable) so callers don't change.

Storage layout
- Per-contact append-only `flatlog/<account>/<contact>/history.log`
  under XDG_DATA_HOME, one line per message
- Single-line file header with embedded format-version marker
  (FLATFILE_FORMAT_VERSION); reader warns on missing or mismatched
  marker, writer and checker stay in sync via preprocessor
  stringification
- Deterministic key=value metadata (`id`, `aid`, `corrects`, `to`,
  `to_res`, `read`) plus escaped body \u2014 `\|`, `\]`, `\\`, `\n`, `\r`
  literals prevent log injection
- Sparse byte-offset index (FF_INDEX_STEP=500) per contact for
  O(log n) time-range lookups; rebuilt on inode / size / mtime
  change, extended in-place when the file just grew
- Per-contact GHashTable caches for archive_id presence and
  stanza_id \u2192 from_jid mapping (O(1) MAM dedup, O(1) LMC sender
  validation)

Hardening
- Path-traversal protection: JID directory name normalisation
  (`@` \u2192 `_at_`, slashes and `..` rejected at construction); every
  per-contact path is anchored under the account's flatlog/
  directory and validated before open
- Symlink-attack protection: every fopen / open uses O_NOFOLLOW; on
  ELOOP the operation aborts with an error rather than following
- Filesystem permissions: log files created with mode 0600,
  directories with mode 0700; both enforced at creation, verified
  on each open and reported on drift by `/history verify`
- Atomic crash-safe export: write to a temp file via mkstemp (mode
  0600, random suffix, no name collisions between concurrent
  exports), fsync, then rename \u2014 partial state never replaces the
  live file
- Concurrency: advisory flock(LOCK_EX) held for the duration of
  every write, including append from live messages and full rewrite
  from export, so two profanity processes can't interleave bytes
  on the same log
- DoS / abuse guards:
    * FF_MAX_LINE_LEN = 10 MB \u2014 lines longer than this are rejected
      at read with a warning; the parser will not allocate
      unbounded memory for a single record
    * FF_MAX_LMC_DEPTH = 100 \u2014 `corrects:` chain walk stops at this
      depth and emits a warning, preventing a malicious correction
      cycle from spinning the apply pass
    * FF_VERSION_SCAN_MAX = 16 \u2014 header version probe never reads
      past 16 leading comment lines, even on garbage input
    * Empty / inverted byte-range early-return in page-up read path
      so a malformed time filter cannot cause an unbounded scan
    * Zero-entry index guard so a file whose every line failed to
      parse cannot cause a NULL deref on later page-up
- LMC sender validation: an incoming correction whose sender does
  not match the original message's sender is rejected at write
  time and surfaced via cons_show_error; a cycle in the apply pass
  is broken via a visited-set
- jid_create_from_bare_and_resource treats NULL, empty string, and
  the literal "(null)" as no resource and returns a bare jid;
  similar normalisation for barejid eliminates the legacy
  "user@host/(null)" artefact that leaked into stored fulljids
  whenever g_strdup_printf("%s", NULL) ran inside create_fulljid

Commands
- `/history switch sqlite|flatfile` \u2014 runtime backend swap, closes
  the old backend and opens the new one without reconnecting
- `/history export [<jid>]` \u2014 SQLite -> flat-file, merging with any
  existing flatlog (dedup keyed on a SHA-256 hash mixing stanza_id,
  timestamp, from_jid, body \u2014 robust against id reuse by older
  clients)
- `/history import [<jid>]` \u2014 flat-file -> SQLite, same merge
  semantics, runs inside a single SQLite transaction with rollback
  on per-contact failure
- `/history verify [<jid>]` \u2014 integrity check; emits a structured
  list of issues (ERROR / WARNING / INFO) per file:
    * file-level: missing log, wrong permissions (\u2260 0600), UTF-8
      BOM present, CRLF line endings, empty file
    * line-level: invalid UTF-8 (with byte offset), embedded
      control characters, unparsable lines, timestamps out of
      order, duplicate `id:` and `aid:` (tracked separately so a
      stanza/archive id collision isn't double-reported)
    * cross-line: broken `corrects:` references whose target id is
      not present in the file
- `/history backend` \u2014 show currently active backend
- Active backend indicator `[sqlite]` / `[flatfile]` in the status
  bar next to the JID
- Roster-JID autocomplete for verify / export / import
- export and import open a SQLite handle on demand when the
  flatfile backend is currently active, so migration works
  regardless of which backend is live

Tests
- Unit: database_export (parser round-trip, escape/unescape, dedup
  key stability, JID normalisation), database_stress (14 cases
  exercising rapid writes, large messages, deep LMC chains, MAM
  dedup, concurrent contacts)
- Functional: history persistence across reconnects, export /
  import round-trip with content equality, MUC migration,
  timestamp normalisation across timezones
- Bench harness P1\u2013P5 (synthetic load: bulk insert, time-range
  read, page-up scroll, MAM ingest, mixed workload) and failure
  modes F1\u2013F17 (page-up cursor and forward-iteration symmetry,
  oversized lines, MAM dedup, LMC depth and cycles, BOM/CRLF,
  missing log, empty file, mtime+inode flip, broken corrects, etc.)
- All bench tests integrate with the existing make targets and
  emit CSV rows for baseline comparison

Author: jabber.developer2 <jabber.developer2@jabber.space>
Reviewed-by: jabber.developer <jabber.developer@jabber.space>
2026-05-05 19:26:07 +00:00

136 lines
3.1 KiB
C

// SPDX-License-Identifier: GPL-3.0-or-later
//
// This file is part of CProof.
// See LICENSE for the full GPLv3 text and the special OpenSSL linking exception.
#include "bench_common.h"
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/statvfs.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>
double
bench_now_ms(void)
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (double)ts.tv_sec * 1000.0 + (double)ts.tv_nsec / 1.0e6;
}
char*
bench_fmt_bytes(uint64_t bytes)
{
static const char* units[] = { "B", "KB", "MB", "GB", "TB" };
int u = 0;
double v = (double)bytes;
while (v >= 1024.0 && u < 4) {
v /= 1024.0;
u++;
}
if (u == 0)
return g_strdup_printf("%" G_GUINT64_FORMAT " %s", bytes, units[u]);
return g_strdup_printf("%.2f %s", v, units[u]);
}
char*
bench_fmt_ms(double ms)
{
if (ms < 1.0)
return g_strdup_printf("%.0f us", ms * 1000.0);
if (ms < 1000.0)
return g_strdup_printf("%.1f ms", ms);
if (ms < 60000.0)
return g_strdup_printf("%.2f s", ms / 1000.0);
return g_strdup_printf("%.1f min", ms / 60000.0);
}
bench_volume_t
bench_volume_from_env(void)
{
const char* v = getenv("BENCH_VOLUME");
if (!v || !v[0])
return BENCH_VOLUME_MEDIUM;
if (g_ascii_strcasecmp(v, "small") == 0)
return BENCH_VOLUME_SMALL;
if (g_ascii_strcasecmp(v, "medium") == 0)
return BENCH_VOLUME_MEDIUM;
if (g_ascii_strcasecmp(v, "max") == 0)
return BENCH_VOLUME_MAX;
fprintf(stderr, "WARN: unknown BENCH_VOLUME='%s', defaulting to medium\n", v);
return BENCH_VOLUME_MEDIUM;
}
const char*
bench_volume_name(bench_volume_t v)
{
switch (v) {
case BENCH_VOLUME_SMALL:
return "small";
case BENCH_VOLUME_MEDIUM:
return "medium";
case BENCH_VOLUME_MAX:
return "max";
}
return "?";
}
gboolean
bench_drop_page_cache(const char* path)
{
int fd = open(path, O_RDONLY);
if (fd < 0)
return FALSE;
#ifdef POSIX_FADV_DONTNEED
// Best-effort: kernel may ignore but typically honours.
posix_fadvise(fd, 0, 0, POSIX_FADV_DONTNEED);
#endif
close(fd);
return TRUE;
}
int64_t
bench_fs_free_bytes(const char* path)
{
struct statvfs vfs;
if (statvfs(path, &vfs) != 0)
return -1;
return (int64_t)vfs.f_bavail * (int64_t)vfs.f_frsize;
}
long
bench_peak_rss_kb(void)
{
struct rusage ru;
if (getrusage(RUSAGE_SELF, &ru) != 0)
return -1;
return ru.ru_maxrss; // already KB on Linux
}
double
bench_run_best_of(int runs, bench_fn_t fn, void* arg, long* peak_rss_kb)
{
if (runs < 1)
runs = 1;
double best = 0.0;
long max_rss = 0;
for (int i = 0; i < runs; i++) {
double t0 = bench_now_ms();
fn(arg);
double dt = bench_now_ms() - t0;
if (i == 0 || dt < best)
best = dt;
long rss = bench_peak_rss_kb();
if (rss > max_rss)
max_rss = rss;
}
if (peak_rss_kb)
*peak_rss_kb = max_rss;
return best;
}