Skip to content

Commit 513895a

Browse files
authored
fix(minimax-bot): 坏文件不再让插件起不来,账本写失败不再带走已经跑完的回合 (#110)
读不出来的状态文件改成改名留证、从默认值起,写盘在 rename 之前先 fsync;台账写 不进去时只记一条 warn,不再把已经跑完的回合、群里后面的成员和跑完的后台报告一 并带走。版本 0.7.24。
1 parent 1efe539 commit 513895a

10 files changed

Lines changed: 296 additions & 45 deletions

File tree

‎plugins/minimax-ai/minimax-bot/.minimax-plugin/plugin.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
"schemaVersion": 1,
33
"name": "minimax-bot",
44
"displayName": "MiniMax Bot",
5-
"version": "0.7.23",
5+
"version": "0.7.24",
66
"description": "Turn MiniMax Code into an always-on team of Bots. A Chief Bot helps you build the team; in group chats the admin answers and @mentions hand work to other members. Every Bot has its own octopus avatar and memory, with scheduled tasks and usage stats.",
77
"author": "MiniMax Code",
88
"icon": "icon.png",

‎plugins/minimax-ai/minimax-bot/README.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,11 @@ The usage ledger counts the time the model really ran. A retried turn waits betw
8080

8181
The hand-over between two Bots of a group carried the tail of the previous reply: the last thing one Bot said, not what the round had concluded — and a discussion concludes over several replies, not in the closing line of one of them. The hand-over now carries the conclusions of the round so far, one entry per hop and each with the Bot that said it, the way a seminar hands its conclusion to the next speaker instead of the last sentence that was said. A round with a single hop hands over exactly what it handed over before, byte for byte. The note setting does not change any of this: the hand-over reads the round itself, and a round is built whether or not the group keeps a note. The note stays what it always was, a record of the earlier rounds that lives in the standing brief of every Bot.
8282

83+
## 0.7.24 A file that cannot be read, and a ledger that cannot be written
84+
85+
- A `state.json` or a chat file that cannot be parsed no longer keeps the Mini App from starting. The unreadable file is kept as `*.corrupt-<time>` instead of being thrown away, and the store starts from the defaults: an unreadable chat starts empty, the other chats still load. The file was written with a rename, but nothing was flushed before it, so a power loss could leave an empty file behind; the bytes are flushed before the rename now, and the directory after it where the platform allows it.
86+
- A failed ledger write no longer fails the turn that already ran. The reply keeps its outcome, a group round goes on to the next member, and a finished background job still saves its status and delivers its report. The miss goes to the log.
87+
8388
## 0.7.10 Optional group notes
8489

8590
- A group can keep a note of what it said. After every round the group records the closing lines of the replies, and every Bot of the group gets that record in its standing brief.

‎plugins/minimax-ai/minimax-bot/miniapp/node/engine.mjs‎

Lines changed: 42 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -881,22 +881,28 @@ export class Engine {
881881
}
882882
} finally {
883883
// The model ran: the ledger must say so even when a later step of this turn fails.
884-
await this.store.recordUsage({
885-
ts: Date.now(),
886-
turnId: message.id,
887-
botId: bot.id,
888-
botName: bot.name,
889-
chatId,
890-
kind: input.kind,
891-
status,
892-
durationMs: message.durationMs,
893-
chars: finalText.length,
894-
tools,
895-
// One turn, but the model may have been called more than once to finish it.
896-
attempts: modelCalls,
897-
// The wait between two attempts is recorded on its own: it is not the model's time.
898-
sleptMs,
899-
});
884+
// The ledger is metering, not the turn's outcome: a failed write (a full disk) must
885+
// not take the turn that already ran down with it. The miss goes to the log.
886+
try {
887+
await this.store.recordUsage({
888+
ts: Date.now(),
889+
turnId: message.id,
890+
botId: bot.id,
891+
botName: bot.name,
892+
chatId,
893+
kind: input.kind,
894+
status,
895+
durationMs: message.durationMs,
896+
chars: finalText.length,
897+
tools,
898+
// One turn, but the model may have been called more than once to finish it.
899+
attempts: modelCalls,
900+
// The wait between two attempts is recorded on its own: it is not the model's time.
901+
sleptMs,
902+
});
903+
} catch (error) {
904+
this.logger.warn('minimax_bot.usage_write_failed', { chatId, code: error?.code ?? 'unknown' });
905+
}
900906
this.broadcast({ type: 'usage.changed' });
901907
}
902908
this.broadcast({ type: 'message.upsert', chatId, message });
@@ -1915,21 +1921,26 @@ export class Engine {
19151921
if (report) helper.report = report;
19161922
if (turnStartedAt) {
19171923
// A background job is an Agent turn like any other: meter it here, or the usage panel
1918-
// counts fewer turns than the model actually ran.
1919-
await this.store.recordUsage({
1920-
ts: Date.now(),
1921-
turnId: helper.id,
1922-
botId: helper.botId,
1923-
botName: turnBotName,
1924-
chatId: helper.chatId,
1925-
kind: 'helper-run',
1926-
status: helperTurnStatus(helper.status),
1927-
durationMs: turnMs,
1928-
chars: turnText.length,
1929-
tools: turnTools,
1930-
// A background job runs the model once; it has no retry loop of its own.
1931-
attempts: 1,
1932-
});
1924+
// counts fewer turns than the model actually ran. A failed write must not keep the
1925+
// finished job from saving its status and delivering its report.
1926+
try {
1927+
await this.store.recordUsage({
1928+
ts: Date.now(),
1929+
turnId: helper.id,
1930+
botId: helper.botId,
1931+
botName: turnBotName,
1932+
chatId: helper.chatId,
1933+
kind: 'helper-run',
1934+
status: helperTurnStatus(helper.status),
1935+
durationMs: turnMs,
1936+
chars: turnText.length,
1937+
tools: turnTools,
1938+
// A background job runs the model once; it has no retry loop of its own.
1939+
attempts: 1,
1940+
});
1941+
} catch (error) {
1942+
this.logger.warn('minimax_bot.usage_write_failed', { chatId: helper.chatId, code: error?.code ?? 'unknown' });
1943+
}
19331944
this.broadcast({ type: 'usage.changed' });
19341945
}
19351946
if (this.disposed) return;

‎plugins/minimax-ai/minimax-bot/miniapp/node/mcp.mjs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -662,7 +662,7 @@ export function createMcpHandler({ team, engine }) {
662662
result = {
663663
protocolVersion: PROTOCOL_VERSIONS.includes(requested) ? requested : PROTOCOL_VERSIONS[0],
664664
capabilities: { tools: { listChanged: false } },
665-
serverInfo: { name: 'minimax-bot', version: '0.7.23' },
665+
serverInfo: { name: 'minimax-bot', version: '0.7.24' },
666666
instructions: t('mcp.instructions'),
667667
};
668668
break;

‎plugins/minimax-ai/minimax-bot/miniapp/node/server.mjs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,8 @@ function chatReferences(messages, src) {
114114
*/
115115
export async function start(context) {
116116
const clientDir = join(context.pluginRoot, 'miniapp/client');
117-
const store = new Store(context.dataDir);
117+
// The store writes the ledger; when that write fails it says so through the host's log.
118+
const store = new Store(context.dataDir, context.logger);
118119
const memory = new MemoryStore(context.dataDir);
119120
await store.init();
120121
await memory.init();

‎plugins/minimax-ai/minimax-bot/miniapp/node/store.mjs‎

Lines changed: 56 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// @ts-check
22
import { randomUUID } from 'node:crypto';
3-
import { appendFile, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
4-
import { join } from 'node:path';
3+
import { appendFile, copyFile, mkdir, open, readFile, rename, rm } from 'node:fs/promises';
4+
import { basename, dirname, join } from 'node:path';
55
import { userReaction } from '../client/emoji-data.js';
66

77
import { resolveLocale, setLocale, t } from './i18n.mjs';
@@ -120,23 +120,50 @@ export function newId(prefix) {
120120
async function writeJsonAtomic(path, value) {
121121
const tmp = `${path}.${process.pid}.${Date.now()}.tmp`;
122122
try {
123-
await writeFile(tmp, JSON.stringify(value, null, 2), 'utf8');
123+
// Flush the bytes before the rename: a power loss after an unflushed rename is what
124+
// leaves a 0-byte file behind.
125+
const handle = await open(tmp, 'w');
126+
try {
127+
await handle.writeFile(JSON.stringify(value, null, 2), 'utf8');
128+
await handle.sync();
129+
} finally {
130+
await handle.close();
131+
}
124132
await rename(tmp, path);
133+
// Best effort: some platforms (Windows) cannot sync a directory handle.
134+
await open(dirname(path), 'r').then((dir) => dir.sync().finally(() => dir.close())).catch(() => {});
125135
} catch (error) {
126136
await rm(tmp, { force: true }).catch(() => {});
127137
throw error;
128138
}
129139
}
130140

131-
async function readJson(path, fallback) {
141+
async function readJson(path, fallback, logger) {
142+
let text;
132143
try {
133-
return JSON.parse(await readFile(path, 'utf8'));
144+
text = await readFile(path, 'utf8');
134145
} catch (error) {
135146
if (error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT') {
136147
return fallback;
137148
}
138149
throw error;
139150
}
151+
try {
152+
return JSON.parse(text);
153+
} catch {
154+
// Keep the unreadable bytes as evidence instead of deleting them; start from defaults.
155+
const kept = `${path}.corrupt-${Date.now()}`;
156+
try {
157+
await rename(path, kept);
158+
} catch {
159+
// The rename can fail (the file may be held open). A copy keeps the bytes even when the
160+
// name cannot change; the next save may write over the original, but the copy stays.
161+
await copyFile(path, kept).catch(() => {});
162+
}
163+
// A team that came back empty, or a chat that reads empty, is otherwise unexplainable.
164+
logger?.warn('minimax_bot.corrupt_file_quarantined', { file: basename(path) });
165+
return fallback;
166+
}
140167
}
141168

142169
function defaultState() {
@@ -213,9 +240,11 @@ function knownText(message) {
213240
}
214241

215242
export class Store {
216-
/** @param {string} dataDir */
217-
constructor(dataDir) {
243+
/** @param {string} dataDir @param {{ warn: (...args: any[]) => void }} [logger] */
244+
constructor(dataDir, logger) {
218245
this.dir = dataDir;
246+
/** The ledger must be able to say it lost a row; without a host logger it stays quiet. */
247+
this.logger = logger ?? { warn() {} };
219248
this.statePath = join(dataDir, 'state.json');
220249
this.messagesDir = join(dataDir, 'messages');
221250
this.usagePath = join(dataDir, 'usage.jsonl');
@@ -236,10 +265,20 @@ export class Store {
236265

237266
async init() {
238267
await mkdir(this.messagesDir, { recursive: true });
239-
this.state = { ...defaultState(), ...(await readJson(this.statePath, defaultState())) };
268+
this.state = { ...defaultState(), ...(await readJson(this.statePath, defaultState(), this.logger)) };
240269
this.state.settings = { ...defaultState().settings, ...(this.state.settings ?? {}) };
241270
setLocale(resolveLocale(this.state));
242271
let migrated = false;
272+
// The fields init walks must have the shape it walks: a wrong shape starts from defaults
273+
// rather than throwing half way through startup.
274+
for (const key of ['bots', 'groups', 'schedules']) {
275+
if (!Array.isArray(this.state[key])) { this.state[key] = []; migrated = true; }
276+
}
277+
const sessions = this.state.sessions;
278+
if (!sessions || typeof sessions !== 'object' || Array.isArray(sessions)) {
279+
this.state.sessions = {};
280+
migrated = true;
281+
}
243282
// A helper's Agent run does not survive the Mini App process; one left running was cut off.
244283
this.state.helpers = Array.isArray(this.state.helpers) ? this.state.helpers : [];
245284
for (const helper of this.state.helpers) {
@@ -410,7 +449,7 @@ export class Store {
410449
}
411450

412451
async loadMessages(chatId) {
413-
let list = await readJson(this.messagePath(chatId), []);
452+
let list = await readJson(this.messagePath(chatId), [], this.logger);
414453
// deleteChat() may have installed an empty list while the read was in flight; it wins.
415454
const installed = this.messageCache.get(chatId);
416455
if (installed) return installed;
@@ -620,7 +659,14 @@ export class Store {
620659
// ---------- usage ----------
621660
recordUsage(entry) {
622661
return this.enqueue(async () => {
623-
await appendFile(this.usagePath, `${JSON.stringify(entry)}\n`, 'utf8');
662+
// The ledger is metering: a failed append (a full disk) must not fail the caller's turn,
663+
// but the miss goes to the log. The id is added only on success, so a retry can still write.
664+
try {
665+
await appendFile(this.usagePath, `${JSON.stringify(entry)}\n`, 'utf8');
666+
} catch (error) {
667+
this.logger.warn('minimax_bot.usage_write_failed', { code: error?.code ?? 'unknown' });
668+
return;
669+
}
624670
if (entry.turnId) this.usageIds.add(entry.turnId);
625671
});
626672
}

‎plugins/minimax-ai/minimax-bot/package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "minimax-bot",
3-
"version": "0.7.23",
3+
"version": "0.7.24",
44
"private": true,
55
"type": "module",
66
"mcode": {
Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
import assert from 'node:assert/strict';
2+
import { test } from 'node:test';
3+
import { mkdtemp, readFile, rm } from 'node:fs/promises';
4+
import { tmpdir } from 'node:os';
5+
import { join } from 'node:path';
6+
import { Store } from '../miniapp/node/store.mjs';
7+
import { MemoryStore } from '../miniapp/node/memory.mjs';
8+
import { Engine } from '../miniapp/node/engine.mjs';
9+
import { setLocale } from '../miniapp/node/i18n.mjs';
10+
11+
// The ledger is metering, not the turn's outcome: a failed write (a full disk) must not fail a
12+
// turn that already ran, stop a group round, or keep a finished background job from reporting.
13+
14+
async function until(predicate) {
15+
for (let i = 0; i < 400; i += 1) {
16+
if (await predicate()) return;
17+
await new Promise((resolve) => setTimeout(resolve, 5));
18+
}
19+
throw new Error('The expected state did not arrive');
20+
}
21+
22+
async function fixture(t, { stub = true } = {}) {
23+
const dir = await mkdtemp(join(tmpdir(), 'bot-ledger-failure-'));
24+
const warnings = [];
25+
const logger = { warn: (...args) => warnings.push(args), info() {}, error() {} };
26+
const store = new Store(dir, logger);
27+
const memory = new MemoryStore(dir);
28+
await store.init();
29+
await memory.init();
30+
setLocale('en');
31+
const engine = new Engine({ store, memory, logger, broadcast() {}, retryDelaysMs: [] });
32+
t.after(async () => {
33+
engine.dispose();
34+
await until(() => engine.running.size === 0 && engine.helperRuns.size === 0 && engine.tickets.size === 0);
35+
await store.writeChain;
36+
await rm(dir, { recursive: true, force: true });
37+
});
38+
if (stub) {
39+
// The whole ledger write fails, exactly like a full disk; the guard must live at the call site.
40+
store.recordUsage = async () => { throw Object.assign(new Error('ENOSPC'), { code: 'ENOSPC' }); };
41+
}
42+
return { dir, store, engine, warnings };
43+
}
44+
45+
const loggedMiss = (warnings) => warnings.some(([event]) => event === 'minimax_bot.usage_write_failed');
46+
47+
test('a full ledger does not fail the turn that already ran', async (t) => {
48+
const { store, engine, warnings } = await fixture(t);
49+
const bot = { id: 'bot_a', name: 'Alice', role: 'Writer' };
50+
store.state.bots = [bot];
51+
engine.agent = { async run(input, options) {
52+
const ids = { sessionId: 's-ledger', turnId: 't-ledger' };
53+
options.onEvent({ type: 'turn.started', ...ids });
54+
return { ...ids, status: 'finished', text: 'All done' };
55+
} };
56+
const result = await engine.runBotTurn({ bot, chatId: `bot:${bot.id}`, text: 'hi', kind: 'private' });
57+
assert.equal(result.status, 'done', 'the reply keeps its outcome');
58+
const messages = await store.getMessages(`bot:${bot.id}`);
59+
assert.equal(messages.find((m) => m.id === result.messageId)?.status, 'done');
60+
assert.ok(loggedMiss(warnings), 'the miss goes to the log');
61+
});
62+
63+
test('a full ledger does not stop the group round before the next member', async (t) => {
64+
const { store, engine, warnings } = await fixture(t);
65+
const a = { id: 'bot_a', name: 'Alice', role: 'Writer' };
66+
const b = { id: 'bot_b', name: 'Bob', role: 'Reviewer' };
67+
const group = { id: 'grp_round', name: 'Round', adminId: a.id, memberIds: [a.id, b.id], replyMode: 'all' };
68+
store.state.bots = [a, b];
69+
store.state.groups = [group];
70+
const calls = [];
71+
engine.agent = { async run(input, options) {
72+
calls.push(input.text);
73+
const ids = { sessionId: `s-${calls.length}`, turnId: `t-${calls.length}` };
74+
options.onEvent({ type: 'turn.started', ...ids });
75+
return { ...ids, status: 'finished', text: `Reply ${calls.length}` };
76+
} };
77+
await engine.driveGroup(group, engine.groupQueue(group, 'hi'));
78+
assert.equal(calls.length, 2, 'the round continues with the next member');
79+
assert.ok(loggedMiss(warnings), 'the miss goes to the log');
80+
});
81+
82+
test('a full ledger does not keep a finished background job from saving and reporting', async (t) => {
83+
const { dir, store, engine, warnings } = await fixture(t);
84+
const bot = { id: 'bot_a', name: 'Alice', role: 'Writer' };
85+
store.state.bots = [bot];
86+
const chatId = `bot:${bot.id}`;
87+
const calls = [];
88+
engine.agent = { async run(input, options) {
89+
calls.push(input.text);
90+
const ids = { sessionId: `s-${calls.length}`, turnId: `t-${calls.length}` };
91+
options.onEvent({ type: 'turn.started', ...ids });
92+
if (input.text.startsWith('<minimax-bot-helper>')) return { ...ids, status: 'finished', text: 'BACKGROUND_ANSWER' };
93+
if (input.text.endsWith('START_BACKGROUND')) {
94+
await engine.startHelper(bot, { task: 'Look this up' });
95+
return { ...ids, status: 'finished', text: 'Started' };
96+
}
97+
return { ...ids, status: 'finished', text: 'Relay' };
98+
} };
99+
await engine.runBotTurn({ bot, chatId, text: 'START_BACKGROUND', kind: 'private' });
100+
await until(() => store.state.helpers[0]?.status === 'done');
101+
const messages = await store.getMessages(chatId);
102+
assert.ok(messages.some((m) => m.role === 'helper'), 'the finished job delivers its report');
103+
const onDisk = JSON.parse(await readFile(join(dir, 'state.json'), 'utf8'));
104+
assert.equal(onDisk.helpers.find((h) => h.id === store.state.helpers[0].id)?.status, 'done', 'the status is saved, not left running');
105+
assert.ok(loggedMiss(warnings), 'the miss goes to the log');
106+
});
107+
108+
test('a real failing ledger append is logged, not silently dropped', async (t) => {
109+
// No stub: the real Store.recordUsage must survive the failed append AND log the miss,
110+
// which is what the README promises for a full disk in production.
111+
const { dir, store, engine, warnings } = await fixture(t, { stub: false });
112+
const bot = { id: 'bot_a', name: 'Alice', role: 'Writer' };
113+
store.state.bots = [bot];
114+
// appendFile onto a directory fails (EISDIR) the way a full disk fails the append.
115+
store.usagePath = dir;
116+
engine.agent = { async run(input, options) {
117+
const ids = { sessionId: 's-real', turnId: 't-real' };
118+
options.onEvent({ type: 'turn.started', ...ids });
119+
return { ...ids, status: 'finished', text: 'All done' };
120+
} };
121+
const result = await engine.runBotTurn({ bot, chatId: `bot:${bot.id}`, text: 'hi', kind: 'private' });
122+
assert.equal(result.status, 'done', 'the reply keeps its outcome');
123+
const messages = await store.getMessages(`bot:${bot.id}`);
124+
assert.equal(messages.find((m) => m.id === result.messageId)?.status, 'done');
125+
assert.ok(loggedMiss(warnings), 'the real store path must log the lost row');
126+
assert.equal(store.usageIds.size, 0, 'a failed append must not claim the turn id, so a retry can still write');
127+
});

0 commit comments

Comments
 (0)