/* * krang -- the wall-clock budget. * * Copyright (c) 2026 Konrad Lother * License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree. * * The script transport is instant except for a tool that really sleeps. With * max_turn_seconds = 1 the turn must be cancelled and recorded as a timeout, * not reported as a normal answer. */ #include #include #include #include #include #include "krang.h" static int failures; #define CHECK(cond) do {\ if (!(cond)) {\ fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__,\ #cond);\ failures++;\ }\ } while (0) static int contains(const char *hay, const char *needle) { return hay != NULL && strstr(hay, needle) != NULL; } int main(void) { struct krang k; char tmpl[512], *dir, script[700], logpath[800], logbuf[65536]; struct sp_buf sp; FILE *f; int rc; dir = mkdtemp(strcpy(tmpl, "/tmp/krang-timeout-XXXXXX")); CHECK(dir != NULL); if (dir == NULL) return 1; (void)setenv("HOME", dir, 1); memset(&k, 0, sizeof(k)); k.log.fd = -1; pthread_mutex_init(&k.lock, NULL); pthread_cond_init(&k.cond, NULL); sp_buf_init(&k.err); kconfig_defaults(&k.cfg); snprintf(k.cfg.goal, sizeof(k.cfg.goal), "prove the wall clock"); snprintf(k.cfg.endpoint, sizeof(k.cfg.endpoint), "http://127.0.0.1:1/v1"); snprintf(k.cfg.model, sizeof(k.cfg.model), "test-model"); k.cfg.max_turn_seconds = 1; snprintf(k.session_dir, sizeof(k.session_dir), "%s/sessions", dir); (void)mkdir(k.session_dir, 0700); snprintf(logpath, sizeof(logpath), "%s/events.jsonl", dir); CHECK(klog_open(&k.log, logpath, k.last_error, sizeof(k.last_error)) == 0); sp_buf_init(&sp); k_system_prompt(&k, &sp); snprintf(k.system_prompt, sizeof(k.system_prompt), "%s", sp.p != NULL ? sp.p : ""); sp_buf_free(&sp); snprintf(script, sizeof(script), "%s/script.txt", dir); f = fopen(script, "w"); CHECK(f != NULL); if (f == NULL) return 1; fprintf(f, "tool run {\"command\":\"sleep 2\"}\n"); fprintf(f, "answer too-late\n"); fclose(f); CHECK(kengine_open(&k, script, k.last_error, sizeof(k.last_error)) == 0); if (k.eng == NULL) return 1; rc = krun_turn(&k, "take longer than the budget", "test", NULL); CHECK(rc != 0); CHECK(contains(k.st.last_error, "max_turn_seconds")); CHECK(!contains(k.st.last_outcome, "too-late")); { FILE *lf = fopen(logpath, "r"); size_t n = 0; if (lf != NULL) { n = fread(logbuf, 1, sizeof(logbuf) - 1, lf); logbuf[n] = '\0'; fclose(lf); } else { logbuf[0] = '\0'; } } CHECK(contains(logbuf, "\"kind\":\"turn_timeout\"")); CHECK(contains(logbuf, "\"kind\":\"turn_end\"")); kengine_close(&k); klog_close(&k.log); pthread_mutex_destroy(&k.lock); pthread_cond_destroy(&k.cond); sp_buf_free(&k.err); if (failures != 0) { fprintf(stderr, "%d test(s) failed\n", failures); return 1; } printf("test_timeout: ok\n"); return 0; }