From 18028c720e87a6f9f19b281dd92ad20076431163 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=97=D0=B0=D1=80=D1=83=D0=B1=D0=B8=D0=BD=20=D0=A4=D0=B8?= =?UTF-8?q?=D0=BB=D0=B8=D0=BF=D0=BF?= <289370046+zarubinphil@users.noreply.github.com> Date: Thu, 18 Jun 2026 00:07:55 +0300 Subject: [PATCH] Limit Graphify API concurrency --- scripts/graphify-extract-limited.py | 38 ++++++++++++++++++++++ scripts/mnemazine-refresh-graphify.mjs | 44 ++++++++++++++++++++++---- scripts/mnemazine-release-check.mjs | 3 ++ 3 files changed, 78 insertions(+), 7 deletions(-) create mode 100644 scripts/graphify-extract-limited.py diff --git a/scripts/graphify-extract-limited.py b/scripts/graphify-extract-limited.py new file mode 100644 index 0000000..117b7ae --- /dev/null +++ b/scripts/graphify-extract-limited.py @@ -0,0 +1,38 @@ +#!/usr/bin/env python3 +"""Run `graphify extract` with a controllable LLM concurrency limit. + +Graphify's public CLI currently does not expose `max_concurrency`, while some +API providers enforce low organization concurrency. This wrapper keeps the CLI +surface intact and only patches graphify.llm.extract_corpus_parallel in-process. +""" + +import os +import runpy +import sys + +import graphify.llm as graphify_llm + + +def main() -> None: + raw = os.environ.get("GRAPHIFY_LLM_MAX_CONCURRENCY", "").strip() + if raw: + try: + max_concurrency = max(1, int(raw)) + except ValueError: + print("GRAPHIFY_LLM_MAX_CONCURRENCY must be an integer", file=sys.stderr) + sys.exit(2) + + original = graphify_llm.extract_corpus_parallel + + def limited_extract_corpus_parallel(*args, **kwargs): + kwargs["max_concurrency"] = max_concurrency + return original(*args, **kwargs) + + graphify_llm.extract_corpus_parallel = limited_extract_corpus_parallel + + sys.argv = ["graphify", *sys.argv[1:]] + runpy.run_module("graphify.__main__", run_name="__main__") + + +if __name__ == "__main__": + main() diff --git a/scripts/mnemazine-refresh-graphify.mjs b/scripts/mnemazine-refresh-graphify.mjs index c61802e..6970efd 100644 --- a/scripts/mnemazine-refresh-graphify.mjs +++ b/scripts/mnemazine-refresh-graphify.mjs @@ -37,6 +37,7 @@ const MODEL_LADDER = (arg('models', process.env.MNEMAZINE_GRAPHIFY_MODELS || (BA const TIMEOUT_MS = Number(arg('timeout-seconds', String(CONFIG.timeout_seconds || '900'))) * 1000 const SMOKE_TIMEOUT_MS = Number(arg('smoke-timeout-seconds', String(CONFIG.smoke_timeout_seconds || '120'))) * 1000 const SHRINK_THRESHOLD = Number(arg('shrink-threshold', String(CONFIG.shrink_threshold || '0.85'))) +const MAX_CONCURRENCY = arg('max-concurrency', process.env.MNEMAZINE_GRAPHIFY_MAX_CONCURRENCY || String(CONFIG.max_concurrency || (BACKEND === 'kimi' ? '3' : ''))) const JSON_OUT = hasFlag('json') const GRAPHIFY_OUT = path.join(VAULT, 'graphify-out') const GRAPH_PATH = path.join(GRAPHIFY_OUT, 'graph.json') @@ -124,6 +125,14 @@ function stripCodeFence(text) { return match ? match[1].trim() : value } +function hasInvalidJsonWarning(text) { + return /invalid\s+JSON/i.test(String(text || '')) +} + +function hasRateLimitWarning(text) { + return /rate[_ -]?limit|reached max organization concurrency|429/i.test(String(text || '')) +} + function runCommand(cmd, args, { env = {}, cwd = ROOT, timeoutMs = TIMEOUT_MS } = {}) { return new Promise(resolve => { const child = spawn(cmd, args, { @@ -256,7 +265,7 @@ Return stable JSON graph fragments for document notes. }) const graphPath = path.join(tempRoot, 'graphify-out', 'graph.json') const summary = await graphSummary(graphPath).catch(() => ({ exists: false, nodes: 0, edges: 0, communities: 0, mtimeMs: 0 })) - const invalidJson = /invalid JSON/i.test(`${extract.stdout}\n${extract.stderr}`) + const invalidJson = hasInvalidJsonWarning(`${extract.stdout}\n${extract.stderr}`) await removeIfExists(tempRoot) if (extract.code !== 0 || extract.timedOut || invalidJson || !summary.exists || summary.nodes === 0) { return { @@ -283,6 +292,18 @@ function graphifyExtractArgs(target, backend, model) { return args } +function graphifyExtractCommand(target, backend, model) { + const args = graphifyExtractArgs(target, backend, model) + if (MAX_CONCURRENCY) { + return { + command: 'python3', + args: [path.join(ROOT, 'scripts/graphify-extract-limited.py'), ...args], + env: { GRAPHIFY_LLM_MAX_CONCURRENCY: MAX_CONCURRENCY } + } + } + return { command: 'graphify', args, env: {} } +} + function apiKeyStatus(backend) { if (backend === 'ollama') return { ok: true, required_env: [] } const required = API_KEY_ENV_BY_BACKEND[backend] @@ -310,13 +331,15 @@ Mnemazine must reject API/backend configs that cannot build a valid graph. - local smoke fixture `, 'utf8') - const extract = await runCommand('graphify', graphifyExtractArgs(tempRoot, backend, model), { + const command = graphifyExtractCommand(tempRoot, backend, model) + const extract = await runCommand(command.command, command.args, { cwd: ROOT, + env: command.env, timeoutMs: SMOKE_TIMEOUT_MS }) const graphPath = path.join(tempRoot, 'graphify-out', 'graph.json') const summary = await graphSummary(graphPath).catch(() => ({ exists: false, nodes: 0, edges: 0, communities: 0, mtimeMs: 0 })) - const invalidJson = /invalid JSON/i.test(`${extract.stdout}\n${extract.stderr}`) + const invalidJson = hasInvalidJsonWarning(`${extract.stdout}\n${extract.stderr}`) await removeIfExists(tempRoot) if (extract.code !== 0 || extract.timedOut || invalidJson || !summary.exists || summary.nodes === 0) { return { @@ -433,9 +456,10 @@ async function semanticRefresh({ baseline }) { } : {} const semanticOut = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-graphify-semantic-')) - const extract = await runCommand('graphify', [...graphifyExtractArgs(VAULT, BACKEND, chosenModel), '--out', semanticOut], { + const command = graphifyExtractCommand(VAULT, BACKEND, chosenModel) + const extract = await runCommand(command.command, [...command.args, '--out', semanticOut], { cwd: ROOT, - env + env: { ...env, ...command.env } }) const semanticGraphPath = path.join(semanticOut, 'graphify-out', 'graph.json') @@ -447,7 +471,9 @@ async function semanticRefresh({ baseline }) { const reportRefresh = existsSync(GRAPH_PATH) && merge.ok ? await realignReport() : { ok: false, code: 1, timedOut: false, stdout_tail: '', stderr_tail: merge.stderr_tail || 'graph missing after merge' } await removeIfExists(semanticOut) - const invalidJson = /invalid JSON/i.test(`${extract.stdout}\n${extract.stderr}`) + const combinedOutput = `${extract.stdout}\n${extract.stderr}` + const invalidJson = hasInvalidJsonWarning(combinedOutput) + const rateLimited = hasRateLimitWarning(combinedOutput) const severeShrink = baseline.nodes > 0 && summary.nodes < Math.floor(baseline.nodes * SHRINK_THRESHOLD) const success = extract.code === 0 && !extract.timedOut && @@ -458,6 +484,7 @@ async function semanticRefresh({ baseline }) { summary.nodes > 0 && summary.edges > 0 && !invalidJson && + !rateLimited && !severeShrink && reportRefresh.ok @@ -469,7 +496,7 @@ async function semanticRefresh({ baseline }) { await writeNeedsUpdate() return { ok: false, - status: extract.timedOut ? 'timeout' : invalidJson ? 'invalid_json' : severeShrink ? 'unsafe_shrink' : 'extract_failed', + status: extract.timedOut ? 'timeout' : invalidJson ? 'invalid_json' : rateLimited ? 'rate_limited_partial' : severeShrink ? 'unsafe_shrink' : 'extract_failed', backup_dir: backupDir, selected, chosen_model: chosenModel, @@ -479,6 +506,7 @@ async function semanticRefresh({ baseline }) { extract_stderr_tail: truncate(extract.stderr, 1800), semantic_graph: semanticSummary, merge, + rate_limited: rateLimited, attempted_graph: summary, baseline, report_refresh: reportRefresh @@ -495,6 +523,7 @@ async function semanticRefresh({ baseline }) { chosen_model: chosenModel, semantic_graph: semanticSummary, merge, + rate_limited: rateLimited, graph: summary, extract_stdout_tail: truncate(extract.stdout, 1800), extract_stderr_tail: truncate(extract.stderr, 1800), @@ -519,6 +548,7 @@ async function main() { model: MODEL, model_ladder: unique(MODEL_LADDER), api_key_env: API_KEY_ENV_BY_BACKEND[BACKEND] || null, + max_concurrency: MAX_CONCURRENCY || null, ollama_base_url: BACKEND === 'ollama' ? OLLAMA_BASE_URL : null, before: initialBefore, code_refresh: null, diff --git a/scripts/mnemazine-release-check.mjs b/scripts/mnemazine-release-check.mjs index 9b345f8..806df4e 100644 --- a/scripts/mnemazine-release-check.mjs +++ b/scripts/mnemazine-release-check.mjs @@ -59,6 +59,9 @@ async function checkSyntax() { for (const script of scripts) { if (existsSync(path.join(ROOT, script))) await must(`syntax:${script}`, process.execPath, ['--check', script]) } + if (existsSync(path.join(ROOT, 'scripts/graphify-extract-limited.py'))) { + await must('syntax:scripts/graphify-extract-limited.py', 'python3', ['-m', 'py_compile', 'scripts/graphify-extract-limited.py']) + } } async function demoSmoke() {