Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

Add reproducible Pi cache comparison and document current integration

Jeremiah Ritcheye0feb8530c07
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 9f05042a9..7631dbe7f 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -625,6 +625,8 @@ if(STRATA_BUILD_TESTS)
add_executable(draft_policy_test src/spec/draft_policy_test.cpp)
target_link_libraries(draft_policy_test PRIVATE strata_spec)
add_test(NAME draft_policy_test COMMAND draft_policy_test)
+endif()
+if(STRATA_BUILD_TESTS OR STRATA_BUILD_CONVERSATION_TESTS)
# the serve loop's conversation-cache retention policy (header-only, no library to link)
add_executable(conv_cache_test src/program/conv_cache_test.cpp)
target_include_directories(conv_cache_test PRIVATE include)
diff --git a/docs/DETAILS.md b/docs/DETAILS.md
index d8a7765db..5e97ffeee 100644
--- a/docs/DETAILS.md
+++ b/docs/DETAILS.md
@@ -377,6 +377,12 @@ in a bounded 8 GiB host-RAM cache. This preserves controller/worker histories wh
their requests alternate; it does not execute requests concurrently. No client session
ID is required: only exact token/image prefixes with matching steering mode are reused.
The default budget is 0 (disabled); `--prompt-cache 0` also disables parking.
+The initial shared-core integration supports a single session GPU: combining
+enabled parking with `--layer-split` is rejected before model loading. Ordinary
+upstream layer-split checkpoints remain available with parking disabled. FP16,
+INT8, Q4_0 and identity-layout K8V4 snapshots are supported; the K8V4 draft ring
+remains INT8, as in upstream. Windows/HIP and multi-GPU runtime coverage must be
+reported separately from Linux/CUDA evidence.
Snapshots contain running state, checkpoints, used K/V pages, and draft-layer K/V.
They add host RAM, not another model or VRAM allocation. The byte budget also counts
diff --git a/docs/plans/agent-cache-benchmark.md b/docs/plans/agent-cache-benchmark.md
new file mode 100644
index 000000000..ffd40d753
--- /dev/null
+++ b/docs/plans/agent-cache-benchmark.md
@@ -0,0 +1,50 @@
+# Controlled local Pi cache comparison
+
+`tools/agent_cache_benchmark.py` runs a bounded real coding task through the Pi
+SDK with parking disabled and enabled. It defaults to a dry run and never uses
+an existing server. `--run` requires an exclusive GPU window, the configured
+model assets, Node.js, and an installed `@earendil-works/pi-coding-agent` package.
+
+Both runs start from identical files and use the same working-directory path,
+prompts, model configuration and tool limits. Each loads a fresh private server.
+The workflow is controller A implementing a CSV-report library, worker B adding
+its CLI, then A returning to verify/fix the integration. This exercises real file
+edits and shell checks rather than replaying prerecorded model responses. The
+input corpus is generated public test data, not a user conversation.
+
+The task uses the Python standard library. Ten independent checks cover UTC
+date grouping, decimal sums, sorting, invalid input, last-valid duplicate IDs,
+quoted commas, file/stdin CLI behavior and missing-file status. These validators
+run outside the agent workspace after the workflow finishes. A model's assertion
+that the task succeeded is not accepted as validation.
+
+Each phase allows 12 executed tools, 16 model turns and 240 seconds. Bash calls
+are limited to 15 seconds and returned text to 16,000 characters per tool result.
+Requests use greedy sampling, disabled thinking, and at most 2,048 output tokens.
+No compaction, skills, discovered extensions, inherited context files or remote
+model catalogs are loaded. Generated event logs remain local; review them before
+publishing any benchmark artifact.
+
+Example (paths to the local model configuration and Pi installation are supplied
+by the operator):
+
+```sh
+python tools/agent_cache_benchmark.py \
+ --config /path/to/engine-config.json --engine build-validation/strata \
+ --pi-package /path/to/node_modules/@earendil-works/pi-coding-agent \
+ --output /path/to/new-results --run
+```
+
+Use a fixed expert allocation small enough that neither engine trims it for
+VRAM headroom. The harness rejects mismatched engine settings. `--order on,off`
+supports a reverse-order repetition; changing the order is not a substitute for
+reporting repeat variability.
+
+Results include task wall time (excluding model startup), per-phase/tool times,
+prompt/decode times, token reuse and generation volume, engine configuration,
+independent success status, generated files, and the engine's Linux kernel
+high-water RSS. RSS includes startup and model mappings; it is not a system-wide
+or GPU peak-memory measurement. Normal speculative inference can produce
+different tool paths, so report output/task differences and do not infer a
+general speedup from a single pair. This local workload does not reproduce the
+earlier remote Windows game-building workflow.
diff --git a/docs/plans/shared-conversation-snapshots.md b/docs/plans/shared-conversation-snapshots.md
index e692c3034..07e331775 100644
--- a/docs/plans/shared-conversation-snapshots.md
+++ b/docs/plans/shared-conversation-snapshots.md
@@ -1,9 +1,19 @@
# Shared conversation snapshots: convergence proposal
-Status: proposed interface and development work for issues/PRs #41, #52 and #57.
-This is not an agreed integration-owner assignment, a merged upstream feature,
-or a claim that the disk tier already uses this core. Development starts at
-upstream `b38c183` (0.1.18); the deployed/tested 0.1.15 branch remains separate.
+Status: shared-core development for issues/PRs #41, #52 and #57. In the issue's
+September 28 follow-up the maintainer asked @jeremiahritchey to own the unified
+PR, @midhatn to review Windows admission/acceptance, and @maedoc to layer optional
+NVMe persistence on the core. The September 29 follow-up permits the single-GPU
+core to land first. This is not a merged upstream feature or acceptance of the
+separate disk implementation.
+
+The original evidence targets upstream `b38c183` (0.1.18). Current integration
+is based on `8fc40dd` (0.1.25), fetched September 29 after main advanced beyond
+the requested 0.1.22. The earlier branches and their evidence remain separate.
+Parking rejects `--layer-split` while ordinary upstream multi-device checkpoint
+handling is retained. Checkpoint LRU stamps and system-prompt/root retention are
+preserved. K8V4 snapshots store separate INT8 K/scales and Q4 V payloads; hybrid
+streaming/ring layouts are rejected before calling upstream's block movers.
## Boundaries
diff --git a/src/core/conversation_snapshot_test.cpp b/src/core/conversation_snapshot_test.cpp
index 9a8c89a72..f6b8e6fbf 100644
--- a/src/core/conversation_snapshot_test.cpp
+++ b/src/core/conversation_snapshot_test.cpp
@@ -160,7 +160,7 @@ void full_session(int fmt, int mode, int experts) {
int main() {
int devices=0;
if (cudaGetDeviceCount(&devices)!=cudaSuccess || !devices) return 77;
- for (int fmt : {kKvF16,kKvInt8,kKvQ4,3}) for (int mode : {0,1,2}) {
+ for (int fmt : std::array<int,4>{kKvF16,kKvInt8,kKvQ4,3}) for (int mode : {0,1,2}) {
if (fmt==3 && mode!=0) continue;
Fixture f(fmt,mode);
if (fmt==3) {
diff --git a/tools/agent_cache_benchmark.py b/tools/agent_cache_benchmark.py
new file mode 100644
index 000000000..74fa38381
--- /dev/null
+++ b/tools/agent_cache_benchmark.py
@@ -0,0 +1,183 @@
+"""Controlled local Pi coding task with cache off/on; private server, dry-run by default.
+
+Requires an installed Pi SDK (--pi-package). Never contacts an existing server.
+Only --run creates files or loads a model. Retains generated code, private agent
+events, exact inputs, timings, engine metrics and independent validator results.
+"""
+import argparse
+import hashlib
+import json
+import os
+from pathlib import Path
+import shutil
+import signal
+import subprocess
+import sys
+import time
+import urllib.request
+
+ROOT = Path(__file__).resolve().parents[1]
+SPEC = '''Implement a Python 3 standard-library expense report.
+report.py exports summarize(text: str) -> list[dict]. Input is CSV with headers
+id,timestamp,team,amount. Strip surrounding whitespace in values. A valid row has
+a nonempty id and team, an ISO timestamp WITH timezone (Z or explicit offset),
+and a finite decimal amount with at most two fractional digits. Ignore invalid
+rows. Among valid rows with the same id, the last valid row wins (a later invalid
+row must not erase a valid row). Normalize timestamps to UTC and group by UTC
+date and team. Return groups sorted by (day, team), each with exactly the keys
+day (YYYY-MM-DD), team, count (int), total (decimal string with two places).
+Negative amounts and zero are valid. Use decimal arithmetic, not binary floats.
+Empty input and header-only input return []. Correctly parse quoted commas.
+cli.py accepts exactly one argument, a CSV filename or - for stdin. Print the
+JSON list and exit 0. An unreadable filename prints a concise message to stderr
+and exits 2 without a traceback. Do not add third-party dependencies.
+'''
+VALIDATOR = r'''
+import importlib.util, json, subprocess, sys
+from pathlib import Path
+root=Path(sys.argv[1]); spec=importlib.util.spec_from_file_location('report',root/'report.py')
+m=importlib.util.module_from_spec(spec); spec.loader.exec_module(m)
+header='id,timestamp,team,amount\n'
+cases=[('',[]),(header,[]),
+ (header+'a,2026-01-02T00:30:00+02:00,"Blue, East",0.10\nb,2026-01-01T12:00:00Z,"Blue, East",0.20\n',
+ [{'day':'2026-01-01','team':'Blue, East','count':2,'total':'0.30'}]),
+ (header+'a,2026-01-01T00:00:00Z,X,1.00\na,2026-01-02T00:00:00Z,Y,2.00\na,bad,X,9.00\n',
+ [{'day':'2026-01-02','team':'Y','count':1,'total':'2.00'}]),
+ (header+' a ,2026-01-01T00:00:00Z, X ,-2.10\nb,2026-01-01T00:00:00Z,X,0\n',
+ [{'day':'2026-01-01','team':'X','count':2,'total':'-2.10'}]),
+ (header+'a,2026-01-01T00:00:00,X,1\nb,2026-01-01T00:00:00Z,X,NaN\nc,2026-01-01T00:00:00Z,X,1.001\n,2026-01-01T00:00:00Z,X,2\nd,2026-01-01T00:00:00Z,,2\n',[]),
+ (header+'a,2026-01-02T00:00:00Z,B,1\nb,2026-01-01T00:00:00Z,Z,2\nc,2026-01-02T00:00:00Z,A,3\n',
+ [{'day':'2026-01-01','team':'Z','count':1,'total':'2.00'},
+ {'day':'2026-01-02','team':'A','count':1,'total':'3.00'},
+ {'day':'2026-01-02','team':'B','count':1,'total':'1.00'}])]
+checks=[]
+for i,(text,want) in enumerate(cases):
+ got=m.summarize(text); assert got==want,(i,got,want); checks.append('library-'+str(i))
+text,want=cases[2]
+p=subprocess.run([sys.executable,str(root/'cli.py'),'-'],input=text,text=True,capture_output=True,timeout=10)
+assert p.returncode==0 and json.loads(p.stdout)==want,p; checks.append('stdin')
+f=root/'validator-input.csv';f.write_text(text)
+p=subprocess.run([sys.executable,str(root/'cli.py'),str(f)],text=True,capture_output=True,timeout=10)
+assert p.returncode==0 and json.loads(p.stdout)==want,p;checks.append('file');f.unlink()
+p=subprocess.run([sys.executable,str(root/'cli.py'),str(root/'does-not-exist.csv')],text=True,capture_output=True,timeout=10)
+assert p.returncode==2 and p.stderr and 'Traceback' not in p.stderr,p;checks.append('missing-file')
+print(json.dumps({'passed':checks}))
+'''
+
+
+def get_json(url):
+ with urllib.request.urlopen(url, timeout=5) as response:
+ return json.load(response)
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__)
+ ap.add_argument('--config', type=Path, required=True)
+ ap.add_argument('--engine', type=Path, required=True)
+ ap.add_argument('--pi-package', type=Path, required=True)
+ ap.add_argument('--output', type=Path, required=True)
+ ap.add_argument('--port', type=int, default=11436)
+ ap.add_argument('--order', default='off,on', choices=('off,on', 'on,off'))
+ ap.add_argument('--run', action='store_true')
+ args = ap.parse_args()
+ if not args.run:
+ print('Dry run: private server, identical Pi A/B/A coding tasks, cache off/on, independent validators.')
+ return
+ args.output = args.output.resolve()
+ args.output.mkdir(parents=False, exist_ok=False)
+ cfg = json.loads(args.config.read_text())
+ cfg.update(exe=str(args.engine.resolve()), cwd=str(ROOT), host='127.0.0.1', port=args.port)
+ work = args.output / 'workspace'
+ agent = args.output / 'agent'
+ agent.mkdir()
+ model = cfg['model_name']
+ if model != 'qwen3.8-flash-next-iq3_s':
+ raise ValueError('This task is currently validated for qwen3.8-flash-next-iq3_s')
+ (agent/'models.json').write_text(json.dumps({'providers': {'strata-benchmark': {
+ 'baseUrl': f'http://127.0.0.1:{args.port}/v1', 'api': 'openai-completions', 'apiKey': 'local',
+ 'models': [{'id': model, 'reasoning': False, 'input': ['text'], 'contextWindow': 131072,
+ 'maxTokens': 2048, 'cost': {'input': 0, 'output': 0, 'cacheRead': 0, 'cacheWrite': 0}}],
+ 'compat': {'supportsStore': False, 'supportsDeveloperRole': False, 'supportsReasoningEffort': False}
+ }}}))
+ corpus = 'id,timestamp,team,amount\n' + ''.join(
+ f'r{i},2026-01-{i%28+1:02d}T12:00:00Z,Team{i%7},{i%100}.{i%97:02d}\n' for i in range(280))
+ initial = {'SPEC.md': SPEC, 'sample.csv': corpus,
+ 'report.py': 'def summarize(text):\n raise NotImplementedError\n', 'cli.py': ''}
+ manifest = {name: hashlib.sha256(text.encode()).hexdigest() for name, text in initial.items()}
+ (args.output/'inputs.json').write_text(json.dumps(initial, indent=2))
+ validator = args.output/'validate.py'
+ validator.write_text(VALIDATOR)
+ results = []
+ for label in args.order.split(','):
+ run = args.output/label
+ run.mkdir()
+ if work.exists():
+ shutil.rmtree(work) # only this harness's new, disposable task workspace
+ work.mkdir()
+ for name, text in initial.items():
+ (work/name).write_text(text)
+ run_cfg = dict(cfg, args=list(cfg['args']), log=str(run/'engine.log'))
+ run_cfg['args'] += ['--conversation-cache-mib', '8192' if label=='on' else '0']
+ config = run/'config.json'
+ config.write_text(json.dumps(run_cfg, indent=2))
+ config.with_name('config.shared-settings.json').write_text(json.dumps({
+ 'reasoning_effort': 'none', 'temperature': 0, 'max_tokens': 2048}))
+ record = {'mode': label, 'inputs_sha256': manifest}
+ with (run/'server.log').open('w') as log:
+ server = subprocess.Popen([sys.executable, '-m', 'serve.server', '--engine', 'strata',
+ '--config', str(config), '--host', '127.0.0.1', '--port', str(args.port)],
+ cwd=ROOT, stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
+ try:
+ base = f'http://127.0.0.1:{args.port}'
+ for _ in range(180):
+ if server.poll() is not None:
+ raise RuntimeError('Private server exited; inspect server.log')
+ try:
+ get_json(base+'/health')
+ break
+ except OSError:
+ time.sleep(1)
+ else:
+ raise TimeoutError('Private server did not become ready')
+ started = time.monotonic()
+ with (run/'agent.log').open('w') as agent_log:
+ task = subprocess.run(['node', str(ROOT/'tools/agent_cache_task.mjs'),
+ str(args.pi_package.resolve()), str(work), str(agent), str(run/'task.json')],
+ cwd=work, stdout=agent_log, stderr=subprocess.STDOUT, timeout=750,
+ env={**os.environ, 'PI_OFFLINE': '1'})
+ record.update(wall_s=time.monotonic()-started, agent_exit=task.returncode)
+ check = subprocess.run([sys.executable, str(validator), str(work)],
+ text=True, capture_output=True, timeout=30)
+ (run/'validation.txt').write_text(check.stdout+check.stderr)
+ record.update(validator_exit=check.returncode, success=task.returncode==check.returncode==0)
+ metrics = get_json(base+'/metrics?requests=all')
+ (run/'metrics.json').write_text(json.dumps(metrics, indent=2))
+ record.update(totals=metrics['totals'], engine=metrics['engine'])
+ # Kernel high-water RSS for the engine, unlike periodic request-end samples.
+ children = Path(f'/proc/{server.pid}/task/{server.pid}/children').read_text().split()
+ record['child_memory_kib'] = {}
+ for pid in children:
+ status = Path(f'/proc/{pid}/status').read_text().splitlines()
+ record['child_memory_kib'][pid] = {s.split(':')[0]: int(s.split()[1])
+ for s in status if s.startswith(('VmHWM:', 'VmRSS:'))}
+ shutil.copytree(work, run/'artifacts')
+ finally:
+ if server.poll() is None:
+ os.killpg(server.pid, signal.SIGINT)
+ try:
+ server.wait(timeout=30)
+ except subprocess.TimeoutExpired:
+ os.killpg(server.pid, signal.SIGTERM)
+ server.wait(timeout=10)
+ results.append(record)
+ (args.output/'results.json').write_text(json.dumps(results, indent=2)+'\n')
+ print(json.dumps(record), flush=True)
+ for key in ('expert_slots', 'context', 'kv', 'kv_resident', 'spec', 'mtp_max', 'lookup', 'pool_workers', 'pcie_frac'):
+ if results[0]['engine'][key] != results[1]['engine'][key]:
+ raise AssertionError(f'Unmatched engine configuration: {key}')
+ if not all(r['success'] for r in results):
+ raise SystemExit('Agent task or independent validation failed; no successful-task speedup claim')
+
+
+if __name__ == '__main__':
+ main()
diff --git a/tools/agent_cache_task.mjs b/tools/agent_cache_task.mjs
new file mode 100644
index 000000000..75d1690c7
--- /dev/null
+++ b/tools/agent_cache_task.mjs
@@ -0,0 +1,106 @@
+// Bounded real Pi A -> B -> A coding workflow, used by agent_cache_benchmark.py.
+import fs from 'node:fs';
+import path from 'node:path';
+import {pathToFileURL} from 'node:url';
+
+const [packageDir, cwd, agentDir, output] = process.argv.slice(2);
+const {createAgentSession, DefaultResourceLoader, ModelRuntime, SessionManager, SettingsManager} =
+ await import(pathToFileURL(path.join(packageDir, 'dist/index.js')));
+const runtime = await ModelRuntime.create({authPath: path.join(agentDir, 'auth.json'),
+ modelsPath: path.join(agentDir, 'models.json'), allowModelNetwork: false});
+const model = runtime.getModel('strata-benchmark', 'qwen3.8-flash-next-iq3_s');
+if (!model) throw new Error('Benchmark model unavailable');
+const events = fs.createWriteStream(output + '.events.jsonl');
+const sessions = [];
+const phases = [];
+const budgets = new WeakMap();
+const system = 'You are implementing a small Python standard-library project. Work only in the current directory. '
+ + 'Do not access the network, install dependencies, or read parent directories. Use at most 12 tool calls per task. '
+ + 'Keep tool outputs below 16000 characters and shell commands below 15 seconds. Implement the requested files, '
+ + 'run focused checks, then give a short result. Do not build unrelated features.';
+async function makeSession() {
+ const budget = {calls: 0, limited: false};
+ const settingsManager = SettingsManager.inMemory({compaction: {enabled: false}, retry: {enabled: false}});
+ const loader = new DefaultResourceLoader({cwd, agentDir, settingsManager, noExtensions: true,
+ noSkills: true, noPromptTemplates: true, noThemes: true, noContextFiles: true,
+ extensionFactories: [pi => {
+ pi.on('tool_call', event => {
+ if (++budget.calls > 12) {
+ budget.limited = true;
+ return {block: true, terminate: true, reason: 'Benchmark tool-call limit'};
+ }
+ if (event.toolName === 'bash') event.input.timeout = Math.min(event.input.timeout || 15, 15);
+ });
+ pi.on('tool_result', event => {
+ let left = 16000;
+ return {content: event.content.map(part => {
+ if (part.type !== 'text') return part;
+ const text = part.text.slice(0, left);
+ left -= text.length;
+ return {...part, text: text + (text.length < part.text.length ? '\n[benchmark output limit]' : '')};
+ })};
+ });
+ }],
+ systemPromptOverride: () => system});
+ await loader.reload();
+ const {session} = await createAgentSession({cwd, agentDir, model, modelRuntime: runtime,
+ thinkingLevel: 'off', tools: ['read', 'write', 'edit', 'bash'], resourceLoader: loader,
+ sessionManager: SessionManager.inMemory(), settingsManager});
+ sessions.push(session);
+ budgets.set(session, budget);
+ return session;
+}
+async function phase(session, name, prompt) {
+ const budget = budgets.get(session);
+ budget.calls = 0; budget.limited = false;
+ const record = {name, tool_calls: 0, tool_ms: 0, turns: 0, limited: false};
+ const activeTools = new Map();
+ const started = performance.now();
+ const unsubscribe = session.subscribe(event => {
+ events.write(JSON.stringify({phase: name, elapsed_ms: performance.now() - started, event}) + '\n');
+ if (event.type === 'turn_start') record.turns++;
+ if (event.type === 'tool_execution_start') {
+ record.tool_calls++;
+ activeTools.set(event.toolCallId, performance.now());
+ }
+ if (event.type === 'tool_execution_end') {
+ record.tool_ms += performance.now() - (activeTools.get(event.toolCallId) ?? performance.now());
+ }
+ if (record.tool_calls > 12 || record.turns > 16) {
+ record.limited = true;
+ void session.abort();
+ }
+ });
+ const timeout = setTimeout(() => { record.limited = true; void session.abort(); }, 240000);
+ try {
+ await session.prompt(prompt);
+ const last = session.messages.filter(m => m.role === 'assistant').at(-1);
+ if (record.limited || budget.limited || !last || ['error', 'aborted'].includes(last.stopReason)) {
+ throw new Error(`Phase ${name} failed: ${last?.errorMessage ?? last?.stopReason ?? 'limit'}`);
+ }
+ record.answer = last.content;
+ } finally {
+ clearTimeout(timeout); unsubscribe(); record.wall_ms = performance.now() - started;
+ phases.push(record);
+ fs.writeFileSync(output, JSON.stringify({phases}, null, 2) + '\n');
+ }
+}
+try {
+ const controller = await makeSession();
+ const worker = await makeSession();
+ await phase(controller, 'controller-implement',
+ 'Implement report.py summarize(text) using SPEC.md. Read the complete sample.csv (a realistic input corpus) '
+ + 'before implementing. Implement only the library for now; another developer will implement cli.py. '
+ + 'You may add small tests. Summarize what you implemented.');
+ await phase(worker, 'worker-cli',
+ 'You are responsible for cli.py. Read SPEC.md and report.py, implement the specified CLI, and verify both '
+ + 'file and stdin inputs. Do not modify report.py. Keep your answer brief.');
+ await phase(controller, 'controller-integrate',
+ 'The CLI developer has finished. Read cli.py and verify the integrated project against SPEC.md, especially '
+ + 'quoted commas, timezone-to-UTC day conversion, last-valid duplicate IDs, invalid rows, empty input, '
+ + 'Decimal totals, stdin, and missing-file exit status. Fix any problems in report.py or cli.py. '
+ + 'Run focused checks and report the result.');
+} finally {
+ for (const session of sessions) session.dispose();
+ events.end();
+}