fix(server): plan 3j close-out — serialized audit-chain appends, atomic metadata and scheduler limits, rollback and race proofs for the plugin repositories

This commit is contained in:
jubnl
2026-09-24 04:52:18 +02:00
parent 6ff45be032
commit fe69a3b9a7
11 changed files with 525 additions and 57 deletions
@@ -68,4 +68,34 @@ export class PluginEntityMetadataRepository extends TrekRepository<PluginEntityM
const changed = await this.nativeDelete({ plugin_id: pluginId, entity_type: entityType, entity_id: entityId, key });
return changed > 0;
}
/**
* Plan 3j Task 7 fix wave, must-land 2 (task-7-review.md): MR2 (the
* pre-write existence check), MR3 (the `META_KEYS_MAX` count gate) and MR4
* (the upsert) made atomic. `meta.rpc.ts#set` used to run these as three
* separately-awaited calls — two concurrent `meta.set` calls for two
* DIFFERENT new keys on the same (plugin, entity) could both read
* `count < max` before either's write landed, so a 100-key cap let a live
* burst land 130 rows. Wrapped in `this.getEntityManager().transactional`
* — the same MikroORM API `UnitOfWork.transactional` itself calls (see
* that class's own docstring on why its default NESTED/savepoint
* propagation is safe even when a caller is already inside a transaction)
* — so `MetaRpc` needs no new constructor dependency: this fix wave found
* `tests/helpers/plugin-host.ts` (which hand-constructs `MetaRpc`) mid-edit
* by a concurrent Plan 4 task and could not touch its construction site,
* so the fix stays entirely inside the repository it already owns.
* Returns whether the write happened; `false` means a NEW key was blocked
* by the cap (the caller maps that to `BadParams`, same message as before).
*/
async upsertValueCapped(pluginId: string, entityType: string, entityId: number, key: string, value: string, maxKeys: number): Promise<boolean> {
return this.getEntityManager().transactional(async () => {
const exists = (await this.findValue(pluginId, entityType, entityId, key)) !== null;
if (!exists) {
const n = await this.countForEntity(pluginId, entityType, entityId);
if (n >= maxKeys) return false;
}
await this.upsertValue(pluginId, entityType, entityId, key, value);
return true;
});
}
}
@@ -113,4 +113,29 @@ export class PluginScheduledTasksRepository extends TrekRepository<PluginSchedul
const changed = await this.nativeDelete({ plugin_id: pluginId, name });
return changed > 0;
}
/**
* Plan 3j Task 7 fix wave, must-land 3 (task-7-review.md): HR5 (the
* pre-write existence check), HR6 (the `SCHED_MAX` count gate) and HR7
* (the upsert) made atomic — the SAME shape and SAME reason as
* `PluginEntityMetadataRepository.upsertValueCapped` (must-land 2): two
* concurrent `scheduler.set` calls for two different new task names on the
* same plugin could both read `count < max` before either's write landed
* (live: 130 rows on a 100 cap). `this.getEntityManager().transactional` —
* no new constructor dependency on `HostSurfaceRpc`, for the same
* `tests/helpers/plugin-host.ts` (dirty, mid-edit by a concurrent Plan 4
* task) reason `upsertValueCapped`'s docstring gives. Returns whether the
* write happened; `false` means a NEW task name was blocked by the cap.
*/
async upsertTaskCapped(input: PluginScheduledTaskUpsertInput, maxTasks: number): Promise<boolean> {
return this.getEntityManager().transactional(async () => {
const exists = await this.existsForPluginAndName(input.plugin_id, input.name);
if (!exists) {
const n = await this.countForPlugin(input.plugin_id);
if (n >= maxTasks) return false;
}
await this.upsertTask(input);
return true;
});
}
}
+68 -13
View File
@@ -82,6 +82,57 @@ const MAX_AUDIT_ROWS = envInt('TREK_PLUGIN_AUDIT_MAX_ROWS', 20_000);
const PRUNE_EVERY = 500; // amortise the COUNT/DELETE over this many appends per plugin
const appendsSincePrune = new Map<string, number>();
/**
* Plan 3j Task 7 fix wave, must-land 1 (task-7-review.md R-hash-chain): a
* per-plugin promise tail serializing `appendAudit`'s read-previous-hash +
* insert pair. Before this, two RPCs from the SAME plugin racing through
* `appendAudit` concurrently could both read the same `lastHash` before
* either's INSERT committed, forking the chain — a live 40-way burst left
* 108 of 120 rows unlinked. Queuing per plugin id (the SAME module-mutable-
* state shape `appendsSincePrune` above already uses for the amortised
* prune counter) fixes it: a plugin's Nth append always reads the (N-1)th's
* committed hash, while a DIFFERENT plugin's chain never waits on this one's.
*
* `uow.transactional` (wrapping `lastHash` + `insertRow` in a real SQLite
* transaction) was the fix brief's other option, but `isAuditable` covers
* EVERY core-data/broadcast method, so it runs on nearly every granted RPC
* call — wrapping each one in a transaction would serialize the app's single
* connection mutex (`unit-of-work.ts`'s own docstring: "an open transaction
* holds it for every other request") behind the audit write on every
* authorized plugin call, a far larger blast radius than queuing one
* plugin's own chain in JS. No DB transaction opens here, so rule 24 ("a
* transactional body awaits DB work only") is not engaged either way. The
* IPC answer-then-throw ruling (`rpc-host.ts#dispatch` computes the RPC
* answer FIRST, then `try { await this.deps.audit(...) } catch { /*
* auditing must never break a call * / }` afterward) is preserved unchanged:
* a queued append's rejection surfaces only to the dispatch() call that
* queued it, through that same swallow — never to an unrelated later call.
*/
const auditAppendTails = new Map<string, Promise<unknown>>();
/**
* Runs `run` after every earlier queued append for `pluginId` has settled,
* whether that one resolved or rejected — `.then(run, run)`, never a bare
* `.then(run)`, which would leave every later append for this plugin
* permanently queued behind one rejected promise. The stored tail is a
* swallowed copy (`.then(() => undefined, () => undefined)`) so a later
* call's own `auditAppendTails.get(pluginId)` read never itself rejects;
* the returned promise is the UNswallowed one, so the caller that queued
* THIS run still sees its own failure.
*/
function serializePerPlugin<T>(pluginId: string, run: () => Promise<T>): Promise<T> {
const prevTail = auditAppendTails.get(pluginId) ?? Promise.resolve();
const result = prevTail.then(run, run);
auditAppendTails.set(
pluginId,
result.then(
() => undefined,
() => undefined,
),
);
return result;
}
function envInt(name: string, def: number): number {
const raw = process.env[name];
if (raw === undefined || raw.trim() === '') return def;
@@ -110,19 +161,23 @@ export async function pruneAudit(audit: PluginCapabilityAuditRepository, pluginI
* handle.
*/
export async function appendAudit(audit: PluginCapabilityAuditRepository, e: AuditEntry): Promise<void> {
const prev = (await audit.lastHash(e.pluginId)) ?? '';
const ts = new Date().toISOString();
const row = JSON.stringify([e.pluginId, e.actingUserId ?? null, e.method, e.resource ?? null, e.code, ts]);
const hash = crypto.createHash('sha256').update(prev + row).digest('hex');
await audit.insertRow({
plugin_id: e.pluginId,
acting_user_id: e.actingUserId ?? null,
method: e.method,
resource: e.resource ?? null,
code: e.code,
ts,
prev_hash: prev || null,
hash,
// The read-previous-hash + insert pair, serialized per plugin — see
// `serializePerPlugin`'s docstring above (must-land 1).
await serializePerPlugin(e.pluginId, async () => {
const prev = (await audit.lastHash(e.pluginId)) ?? '';
const ts = new Date().toISOString();
const row = JSON.stringify([e.pluginId, e.actingUserId ?? null, e.method, e.resource ?? null, e.code, ts]);
const hash = crypto.createHash('sha256').update(prev + row).digest('hex');
await audit.insertRow({
plugin_id: e.pluginId,
acting_user_id: e.actingUserId ?? null,
method: e.method,
resource: e.resource ?? null,
code: e.code,
ts,
prev_hash: prev || null,
hash,
});
});
// Amortised retention: prune roughly every PRUNE_EVERY appends per plugin.
const n = (appendsSincePrune.get(e.pluginId) ?? 0) + 1;
@@ -37,6 +37,7 @@ export function closePluginDataDb(id: string): void {
dataDbs.get(id)?.close();
dataDbs.delete(id);
budgets.delete(id);
seedingBudgets.delete(id);
}
// Per-plugin daily broker budgets (ai/notify). Lazily created + seeded from the
@@ -45,23 +46,45 @@ export function closePluginDataDb(id: string): void {
// nothing persisted or phoned home.
const budgets = new Map<string, DailyBudget>();
export async function budgetFor(id: string, audit: PluginCapabilityAuditRepository): Promise<DailyBudget> {
let b = budgets.get(id);
if (!b) {
const now = Date.now();
const since = new Date(now).toISOString().slice(0, 10) + 'T00:00:00';
const rows = await audit.budgetSeed(id, since);
let ai = 0, notify = 0;
for (const r of rows) {
if (r.method === 'notify.send') notify += r.n;
else ai += r.n; // ai.complete + ai.extract
}
b = new DailyBudget(DEFAULT_DAILY_BUDGET, now, { ai, notify });
budgets.set(id, b);
// Plan 3j Task 7 fix wave, should-land 7 (task-7-review.md "budget seed race"):
// `budgetFor` used to check `budgets.get(id)` and, on a miss, `await
// audit.budgetSeed(...)` before setting the map — an `await` between the read
// and the write. Two concurrent first calls for the same plugin (e.g. a burst
// of `notify.send`/`ai.complete` RPCs right after activation) could both miss,
// both seed, and each end up with its OWN `DailyBudget` instance — one
// overwriting the other in `budgets`, so usage tracked against the discarded
// instance is invisible to the surviving one and the daily cap under-counts.
// Not reproduced live (task-7-review.md: a 20-way burst with a cap of 5 came
// back 5/5 on both sides) but real given the `await` gap, so fixed defensively:
// concurrent first callers now share the SAME in-flight seeding promise (and
// therefore the SAME `DailyBudget` instance) instead of racing to seed twice.
const seedingBudgets = new Map<string, Promise<DailyBudget>>();
async function seedBudget(id: string, audit: PluginCapabilityAuditRepository): Promise<DailyBudget> {
const now = Date.now();
const since = new Date(now).toISOString().slice(0, 10) + 'T00:00:00';
const rows = await audit.budgetSeed(id, since);
let ai = 0, notify = 0;
for (const r of rows) {
if (r.method === 'notify.send') notify += r.n;
else ai += r.n; // ai.complete + ai.extract
}
const b = new DailyBudget(DEFAULT_DAILY_BUDGET, now, { ai, notify });
budgets.set(id, b);
return b;
}
export async function budgetFor(id: string, audit: PluginCapabilityAuditRepository): Promise<DailyBudget> {
const existing = budgets.get(id);
if (existing) return existing;
let pending = seedingBudgets.get(id);
if (pending === undefined) {
pending = seedBudget(id, audit).finally(() => seedingBudgets.delete(id));
seedingBudgets.set(id, pending);
}
return pending;
}
/** Today's broker usage for one plugin (admin view). Seeds the counter if unseen. */
export async function pluginBudgetUsage(id: string, audit: PluginCapabilityAuditRepository): Promise<ReturnType<DailyBudget['used']>> {
return (await budgetFor(id, audit)).used(Date.now());
@@ -204,20 +204,14 @@ export class HostSurfaceRpc {
}
const json = JSON.stringify(params.payload ?? null);
if (json.length > SCHED_PAYLOAD_MAX) throw new BadParams(`scheduler payload too large (max ${SCHED_PAYLOAD_MAX} bytes)`);
const existing = await this.scheduledTasks.existsForPluginAndName(ctx.pluginId, name); // HR5 — Plan 3j
if (!existing) {
const n = await this.scheduledTasks.countForPlugin(ctx.pluginId); // HR6 — Plan 3j
if (n >= SCHED_MAX) throw new BadParams(`too many scheduled tasks (max ${SCHED_MAX})`);
}
// HR5/HR6/HR7 — Plan 3j Task 7 fix (must-land 3): one atomic call, not
// three separately-awaited ones (task-7-review.md's concurrent-cap-bypass).
// Upsert by (plugin, name): re-scheduling the same name replaces it.
await this.scheduledTasks.upsertTask({
// HR7 — Plan 3j
plugin_id: ctx.pluginId,
name,
due_at: Math.max(dueAt, Date.now()),
payload: json,
every_ms: everyMs ?? null,
});
const written = await this.scheduledTasks.upsertTaskCapped(
{ plugin_id: ctx.pluginId, name, due_at: Math.max(dueAt, Date.now()), payload: json, every_ms: everyMs ?? null },
SCHED_MAX,
);
if (!written) throw new BadParams(`too many scheduled tasks (max ${SCHED_MAX})`);
return { scheduled: true };
}
+4 -6
View File
@@ -78,12 +78,10 @@ export class MetaRpc {
if (key.length > META_KEY_MAX) throw new BadParams(`metadata key too long (>${META_KEY_MAX} chars)`);
const json = JSON.stringify(params.value ?? null);
if (json.length > META_VALUE_MAX) throw new BadParams(`metadata value too large (>${META_VALUE_MAX} bytes)`);
const exists = (await this.meta.findValue(ctx.pluginId, entityType, entityId, key)) !== null; // MR2 — Plan 3j
if (!exists) {
const n = await this.meta.countForEntity(ctx.pluginId, entityType, entityId); // MR3 — Plan 3j
if (n >= META_KEYS_MAX) throw new BadParams(`too many metadata keys on this ${entityType} (max ${META_KEYS_MAX})`);
}
await this.meta.upsertValue(ctx.pluginId, entityType, entityId, key, json); // MR4 — Plan 3j
// MR2/MR3/MR4 — Plan 3j Task 7 fix (must-land 2): one atomic call, not
// three separately-awaited ones (task-7-review.md's concurrent-cap-bypass).
const written = await this.meta.upsertValueCapped(ctx.pluginId, entityType, entityId, key, json, META_KEYS_MAX);
if (!written) throw new BadParams(`too many metadata keys on this ${entityType} (max ${META_KEYS_MAX})`);
return { key, value: params.value ?? null };
}
@@ -814,10 +814,13 @@ export class PluginRuntimeService implements OnApplicationBootstrap, OnModuleDes
if (!clean.includes(host)) clean.push(host);
}
if (!this.uow) throw new Error('UnitOfWork not provided — tests that set egress hosts must pass one');
// PR22/PR23, R-uninstall's ONE named transaction: the delete-then-insert-loop is now
// atomic (`PluginEgressHostsRepository.replaceAllForPlugin`) — a crash mid-write
// leaves the OLD host set intact instead of a plugin with zero egress hosts, a
// deliberate behavior change ("For the user" in the plan document), not silent parity.
// PR22/PR23: the delete-then-insert-loop is atomic (`PluginEgressHostsRepository
// .replaceAllForPlugin`) — a crash mid-write leaves the OLD host set intact instead
// of a plugin with zero egress hosts. Plan 3j Task 7 fix (should-land 6,
// task-7-review.md): this transaction is PARITY, not a new behaviour — the legacy
// code already wrapped this delete+insert in a transaction (base: line 679). It was
// wrongly reported as a deliberate deviation; corrected here, and the egress "For
// the user" item is dropped (no decision needed — nothing changed).
await this.uow.transactional(async () => {
await this.pluginEgressHosts.replaceAllForPlugin(id, clean);
});