Limit Graphify API concurrency

This commit is contained in:
Зарубин Филипп
2026-06-18 00:07:55 +03:00
parent 3f58c7f8b9
commit 18028c720e
3 changed files with 78 additions and 7 deletions
+38
View File
@@ -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()
+37 -7
View File
@@ -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 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 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 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 JSON_OUT = hasFlag('json')
const GRAPHIFY_OUT = path.join(VAULT, 'graphify-out') const GRAPHIFY_OUT = path.join(VAULT, 'graphify-out')
const GRAPH_PATH = path.join(GRAPHIFY_OUT, 'graph.json') const GRAPH_PATH = path.join(GRAPHIFY_OUT, 'graph.json')
@@ -124,6 +125,14 @@ function stripCodeFence(text) {
return match ? match[1].trim() : value 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 } = {}) { function runCommand(cmd, args, { env = {}, cwd = ROOT, timeoutMs = TIMEOUT_MS } = {}) {
return new Promise(resolve => { return new Promise(resolve => {
const child = spawn(cmd, args, { 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 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 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) await removeIfExists(tempRoot)
if (extract.code !== 0 || extract.timedOut || invalidJson || !summary.exists || summary.nodes === 0) { if (extract.code !== 0 || extract.timedOut || invalidJson || !summary.exists || summary.nodes === 0) {
return { return {
@@ -283,6 +292,18 @@ function graphifyExtractArgs(target, backend, model) {
return args 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) { function apiKeyStatus(backend) {
if (backend === 'ollama') return { ok: true, required_env: [] } if (backend === 'ollama') return { ok: true, required_env: [] }
const required = API_KEY_ENV_BY_BACKEND[backend] 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 - local smoke fixture
`, 'utf8') `, '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, cwd: ROOT,
env: command.env,
timeoutMs: SMOKE_TIMEOUT_MS timeoutMs: SMOKE_TIMEOUT_MS
}) })
const graphPath = path.join(tempRoot, 'graphify-out', 'graph.json') 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 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) await removeIfExists(tempRoot)
if (extract.code !== 0 || extract.timedOut || invalidJson || !summary.exists || summary.nodes === 0) { if (extract.code !== 0 || extract.timedOut || invalidJson || !summary.exists || summary.nodes === 0) {
return { return {
@@ -433,9 +456,10 @@ async function semanticRefresh({ baseline }) {
} }
: {} : {}
const semanticOut = await fs.mkdtemp(path.join(os.tmpdir(), 'mnemazine-graphify-semantic-')) 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, cwd: ROOT,
env env: { ...env, ...command.env }
}) })
const semanticGraphPath = path.join(semanticOut, 'graphify-out', 'graph.json') 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' } 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) 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 severeShrink = baseline.nodes > 0 && summary.nodes < Math.floor(baseline.nodes * SHRINK_THRESHOLD)
const success = extract.code === 0 && const success = extract.code === 0 &&
!extract.timedOut && !extract.timedOut &&
@@ -458,6 +484,7 @@ async function semanticRefresh({ baseline }) {
summary.nodes > 0 && summary.nodes > 0 &&
summary.edges > 0 && summary.edges > 0 &&
!invalidJson && !invalidJson &&
!rateLimited &&
!severeShrink && !severeShrink &&
reportRefresh.ok reportRefresh.ok
@@ -469,7 +496,7 @@ async function semanticRefresh({ baseline }) {
await writeNeedsUpdate() await writeNeedsUpdate()
return { return {
ok: false, 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, backup_dir: backupDir,
selected, selected,
chosen_model: chosenModel, chosen_model: chosenModel,
@@ -479,6 +506,7 @@ async function semanticRefresh({ baseline }) {
extract_stderr_tail: truncate(extract.stderr, 1800), extract_stderr_tail: truncate(extract.stderr, 1800),
semantic_graph: semanticSummary, semantic_graph: semanticSummary,
merge, merge,
rate_limited: rateLimited,
attempted_graph: summary, attempted_graph: summary,
baseline, baseline,
report_refresh: reportRefresh report_refresh: reportRefresh
@@ -495,6 +523,7 @@ async function semanticRefresh({ baseline }) {
chosen_model: chosenModel, chosen_model: chosenModel,
semantic_graph: semanticSummary, semantic_graph: semanticSummary,
merge, merge,
rate_limited: rateLimited,
graph: summary, graph: summary,
extract_stdout_tail: truncate(extract.stdout, 1800), extract_stdout_tail: truncate(extract.stdout, 1800),
extract_stderr_tail: truncate(extract.stderr, 1800), extract_stderr_tail: truncate(extract.stderr, 1800),
@@ -519,6 +548,7 @@ async function main() {
model: MODEL, model: MODEL,
model_ladder: unique(MODEL_LADDER), model_ladder: unique(MODEL_LADDER),
api_key_env: API_KEY_ENV_BY_BACKEND[BACKEND] || null, api_key_env: API_KEY_ENV_BY_BACKEND[BACKEND] || null,
max_concurrency: MAX_CONCURRENCY || null,
ollama_base_url: BACKEND === 'ollama' ? OLLAMA_BASE_URL : null, ollama_base_url: BACKEND === 'ollama' ? OLLAMA_BASE_URL : null,
before: initialBefore, before: initialBefore,
code_refresh: null, code_refresh: null,
+3
View File
@@ -59,6 +59,9 @@ async function checkSyntax() {
for (const script of scripts) { for (const script of scripts) {
if (existsSync(path.join(ROOT, script))) await must(`syntax:${script}`, process.execPath, ['--check', script]) 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() { async function demoSmoke() {