workbuddy 0.2.13: the free window's ledger read is linear in its rows, not their square
xmoon76 (Discord #feedback, 2026-11-02): with WorkBuddy on, the plugin host (magpie-bun run host-*.js) sat at 99% CPU, every session stalled, restarting magpie didn't help, and turning WorkBuddy off did. The cause: readLedgerTail called pinned(chain) after every row of the account it kept, and pinned walks the whole chain, so a chain with no edge in it (no readable refusal, no day-wide gap: an account a server spends on the free model all day) cost the square of its rows. Measured on mote (bun 1.4.2), a call a minute: 2,000 rows 187 ms, 4,000 771 ms, 8,000 3.1 s, 16,000 10.5 s. That ran on the host's one thread at every usage read, and the ledger changes with every call so the parse cache never held: a month of such use (~43,000 rows) is minutes per read. It reaches the China build since 0.2.12 read its window too, and WorkBuddy AI before that. pinning() now answers row by row in constant time what pinned answered for the rows read so far: the rows only grow at their oldest end and pinned was asked only while it said 0, so the one new thing a row brings is the first (newest) readable refusal or a gap between it and the oldest answered row before it. pinned stays as it was. Run at this head on mote (bun 1.4.2, HOME=$(mktemp -d)): - packages/workbuddy bun test: 313 pass, 0 fail. - whole repo bun test: 4793 pass, 14 skip, 0 fail. - bun scripts/check.mjs workbuddy: ok. - The same ledger after: 16,000 rows 14 ms, 64,000 45 ms, same window. On Linux (wsl-run, magpie-desktop): packages/workbuddy 313 pass, 0 fail; 16,000 rows 28 ms, 64,000 69 ms. Broken by hand: - the old per-row pinned(chain) put back: "a busy account's ledger is read in time linear in its rows" red, 18,009,000 Date.parse calls for 12,000 lines (bound 48,000). - pinning answering a gap with the newer row: "pinning answers as pinned does, row by row" and "a gap of a day or more pins the chain too" red. - pinning keeping the oldest refusal instead of the newest: the row-by-row test red. Not tried: the reporter's own ledger or a Docker install; their magpie and plugin versions are unknown, so that this was their spin is the best fit (it persists over restarts, stops with WorkBuddy off, and is CPU on the host's thread), not a confirmed one.
This commit is contained in:
@@ -670,3 +670,77 @@ test("a row whose time cannot be read is passed over", () => {
|
||||
// the same bound, not Infinity and not the 0 of a chain with no edge
|
||||
expect(_internal.pinned(holey, "me@example.com")).toBe(bound)
|
||||
})
|
||||
|
||||
// pinning answers each row as pinned would answer the rows handed so far, for
|
||||
// as long as readLedgerTail asks (pinned said 0, and the row is not a
|
||||
// refusal). Random chains of answered rows, failures, refusals with and
|
||||
// without a readable reset, unreadable times and day-wide gaps.
|
||||
test("pinning answers as pinned does, row by row", () => {
|
||||
let seed = 7
|
||||
const rand = () => ((seed = (seed * 1103515245 + 12345) % 2147483648) / 2147483648)
|
||||
const now = at("2026-10-22T12:00:00+08:00")
|
||||
const at8 = (ms) => `${new Date(ms + 8 * AN_HOUR).toISOString().slice(0, 19).replace("T", " ")} UTC+8`
|
||||
let edged = 0
|
||||
for (let k = 0; k < 400; k++) {
|
||||
let t = now
|
||||
const chain = []
|
||||
const edge = _internal.pinning()
|
||||
let reach = 0
|
||||
for (let i = 0; i < 60 && !reach; i++) {
|
||||
t -= rand() < 0.08 ? A_DAY + rand() * A_DAY : rand() * 3 * AN_HOUR
|
||||
const p = rand()
|
||||
const r =
|
||||
p < 0.05
|
||||
? row(new Date(t).toISOString(), { status: 429, err: `${TIMEOUT_BEFORE_RESET}${at8(t + rand() * A_DAY)}, alternatively, you can switch.` })
|
||||
: p < 0.08
|
||||
? row(new Date(t).toISOString(), { status: 429, err: "too many requests" })
|
||||
: p < 0.12
|
||||
? row(new Date(t).toISOString(), { status: 500 })
|
||||
: p < 0.14
|
||||
? row("not-a-time")
|
||||
: row(new Date(t).toISOString())
|
||||
chain.push(r)
|
||||
const got = edge(r)
|
||||
if (Number(r.status) === 429) {
|
||||
expect(got).toBe(0)
|
||||
continue
|
||||
}
|
||||
expect(got).toBe(_internal.pinned(chain, "me@example.com"))
|
||||
reach = got
|
||||
}
|
||||
if (reach) edged++
|
||||
}
|
||||
// most chains met an edge, so both of pinned's answers were compared
|
||||
expect(edged).toBeGreaterThan(200)
|
||||
})
|
||||
|
||||
// xmoon76 (Discord, 2026-11-02): with WorkBuddy on, the plugin host sat at
|
||||
// 99% CPU and every session through it stalled. readLedgerTail asked pinned
|
||||
// about its whole chain after every row, and a chain with no edge — an account
|
||||
// a server spends on the free model all day, no refusal and no day's gap —
|
||||
// cost the square of its rows: 10.5 s for 16,000 on mote, on the host's one
|
||||
// thread, at every usage read. The work is counted here, not timed: every
|
||||
// time is read with Date.parse, which a quadratic read calls millions of
|
||||
// times for these 6,000 rows and a linear one a few times per line.
|
||||
test("a busy account's ledger is read in time linear in its rows", () => {
|
||||
const now = at("2026-11-02T12:00:00+08:00")
|
||||
const lines = []
|
||||
for (let i = 6000; i >= 1; i--) {
|
||||
const t = new Date(now - i * 60_000).toISOString()
|
||||
lines.push(JSON.stringify(row(t, { in: 1000, out: 100, provider: "workbuddy" })))
|
||||
lines.push(JSON.stringify(row(t, { in: 1, provider: "zcode", account: "other" })))
|
||||
}
|
||||
const root = writeLedger(lines)
|
||||
const parse = Date.parse
|
||||
let calls = 0
|
||||
Date.parse = (s) => (calls++, parse(s))
|
||||
try {
|
||||
const path = join(root, "usage.jsonl")
|
||||
const got = _internal.readLedgerTail(path, statSync(path), now, undefined, "me@example.com", _internal.FREE_WINDOW_CN)
|
||||
expect(got.rows.length).toBe(6000)
|
||||
expect(calls).toBeLessThan(lines.length * 4)
|
||||
} finally {
|
||||
Date.parse = parse
|
||||
rmSync(root, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
@@ -2674,7 +2674,7 @@ function readLedgerTail(path, st, now, chunks, account, win = FREE_WINDOW_AI) {
|
||||
let carry = ""
|
||||
let firstPass = true
|
||||
let stop = false
|
||||
let chain = [] // this account's own rows read, latest first
|
||||
const edge = pinning() // where this account's own rows read so far say the chain is read from
|
||||
let reach = 0 // the row below which nothing is kept: 0 until an edge is found
|
||||
let answered = false // whether an answered free-model row of it is read
|
||||
|
||||
@@ -2717,9 +2717,8 @@ function readLedgerTail(path, st, now, chunks, account, win = FREE_WINDOW_AI) {
|
||||
}
|
||||
if (!ofAccount(row, account, win)) continue
|
||||
rev.push(row)
|
||||
chain.push(row)
|
||||
if (Number(row.status) === 200) answered = true
|
||||
if (!reach && Number(row.status) !== 429) reach = pinned(chain, account)
|
||||
if (!reach) reach = edge(row)
|
||||
}
|
||||
firstPass = false
|
||||
}
|
||||
@@ -2787,6 +2786,51 @@ function pinned(rows, account) {
|
||||
return 0
|
||||
}
|
||||
|
||||
// pinning is pinned read a row at a time: it is handed the account's own
|
||||
// rows latest first, as readLedgerTail reads them, and answers each with what
|
||||
// pinned would answer for every row handed so far — in constant time.
|
||||
//
|
||||
// readLedgerTail used to call pinned on its whole chain after each row, and
|
||||
// pinned walks the chain, so a chain with no edge in it cost the square of
|
||||
// its rows: 10.5 s for 16,000 rows on mote, a minute and more for an account
|
||||
// a server spends on all day (a call a minute is 43,000 rows in a month).
|
||||
// That ran on the plugin host's one thread at every usage read, and the
|
||||
// ledger changes with every call, so nothing held it over: the host sat at
|
||||
// 99% CPU and every session through it stalled (xmoon76 on Discord, the
|
||||
// China build's window being read since 0.2.12).
|
||||
//
|
||||
// It holds because the rows only ever grow at their oldest end, and pinned
|
||||
// was asked only while it answered 0 — no readable refusal and no day's gap
|
||||
// among the rows so far — so the one new thing a row can bring is:
|
||||
//
|
||||
// - a refusal with a readable reset: the newest such is the first read,
|
||||
// and pinned answers it whatever else the rows hold, once a row that is
|
||||
// not a refusal follows (readLedgerTail asked pinned for those alone);
|
||||
// - a day's gap between it and the oldest answered row before it, the only
|
||||
// pair of answered rows not already looked at. pinned answers that with
|
||||
// the older row of the pair, this one.
|
||||
function pinning() {
|
||||
let denied = null // the newest readable refusal's reset
|
||||
let oldest = null // the oldest answered row's time so far
|
||||
return (row) => {
|
||||
const status = Number(row?.status)
|
||||
if (status === 429) {
|
||||
if (denied === null) {
|
||||
const reset = windowReset(row.err)
|
||||
if (Number.isFinite(reset)) denied = reset
|
||||
}
|
||||
return 0
|
||||
}
|
||||
if (denied !== null) return denied - FREE_WINDOW_LEAD
|
||||
if (status !== 200) return 0
|
||||
const t = Date.parse(row?.t)
|
||||
if (!Number.isFinite(t)) return 0
|
||||
if (oldest !== null && oldest - t >= FREE_WINDOW_GAP) return t - FREE_WINDOW_LEAD
|
||||
oldest = t
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
// _internal is where these are handed to a test: magpie's host calls every
|
||||
// exported function of a plugin as one of its own factories (host.js,
|
||||
// servers()), so freeWindowRows et al. must not be exports of the plugin.
|
||||
@@ -3896,4 +3940,4 @@ export const WorkBuddyAuthPlugin = makePlugin(SITES.workbuddy)
|
||||
export const WorkBuddyAIAuthPlugin = makePlugin(SITES["workbuddy-ai"])
|
||||
|
||||
// for tests
|
||||
export const _internal = { planCodes, idFor, OFF_TAKEN, replyAfterToolsOn, withDefaultEffort, defaultEffortOf, gzipped, FREE_ONLY, PRICE_TTL, keyAccount, remoteConfig, cycleOf, typeUnions, systemAsUser, systemKey, DEFAULT_SYSTEM, EDGE_READS, fitShape, replyAfterTools, AFTER_TOOLS_REFUSED, enterpriseUsageOf, accountName, notDesktop, textOnly, runsOutOf, packagesOf, endOf, enterpriseHeaders, enterpriseOf, liveModels, browserSignIn, withSystem, asReasoning, normalizeToolChoice, fitTools, fitted, renamed, unsaid, FILTER_SAYS, unflagged, usageOf, desktopHeld, explained, REFUSED_HINT, RESTRICTED_HINT, EXHAUSTED_HINT, REFUSED_DOC, commaPaused, commaPausedOn, opened, freeCredits, creditsOf, priceOf, fresh, SITES, renewing, renewed, SESSION, attend, scopeOf, turnKey, conversationKey, signatureOf, isMessages, withoutUnsigned, withoutSignedThinking, prepared, answeredBefore, nativeOf, modelOf, configModels, freeWindowOf, tokensShort, freeWindowRows, freeWindowLedger, readLedgerTail, pinned, rowTime, rowAccount, ofAccount, windowOffset, windowReset, FREE_WINDOW_MODELS, FREE_WINDOW_CN, FREE_WINDOW_AI, FREE_WINDOW_SPAN, FREE_WINDOW_GAP, FREE_WINDOW_LEAD, checkinOf, API_MESSAGES: NPM_MESSAGES, API_CHAT: NPM }
|
||||
export const _internal = { planCodes, idFor, OFF_TAKEN, replyAfterToolsOn, withDefaultEffort, defaultEffortOf, gzipped, FREE_ONLY, PRICE_TTL, keyAccount, remoteConfig, cycleOf, typeUnions, systemAsUser, systemKey, DEFAULT_SYSTEM, EDGE_READS, fitShape, replyAfterTools, AFTER_TOOLS_REFUSED, enterpriseUsageOf, accountName, notDesktop, textOnly, runsOutOf, packagesOf, endOf, enterpriseHeaders, enterpriseOf, liveModels, browserSignIn, withSystem, asReasoning, normalizeToolChoice, fitTools, fitted, renamed, unsaid, FILTER_SAYS, unflagged, usageOf, desktopHeld, explained, REFUSED_HINT, RESTRICTED_HINT, EXHAUSTED_HINT, REFUSED_DOC, commaPaused, commaPausedOn, opened, freeCredits, creditsOf, priceOf, fresh, SITES, renewing, renewed, SESSION, attend, scopeOf, turnKey, conversationKey, signatureOf, isMessages, withoutUnsigned, withoutSignedThinking, prepared, answeredBefore, nativeOf, modelOf, configModels, freeWindowOf, tokensShort, freeWindowRows, freeWindowLedger, readLedgerTail, pinned, pinning, rowTime, rowAccount, ofAccount, windowOffset, windowReset, FREE_WINDOW_MODELS, FREE_WINDOW_CN, FREE_WINDOW_AI, FREE_WINDOW_SPAN, FREE_WINDOW_GAP, FREE_WINDOW_LEAD, checkinOf, API_MESSAGES: NPM_MESSAGES, API_CHAT: NPM }
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-workbuddy-auth",
|
||||
"version": "0.2.12",
|
||||
"version": "0.2.13",
|
||||
"description": "OpenCode provider plugins for WorkBuddy's plans: WorkBuddy (CodeBuddy, copilot.tencent.com) and WorkBuddy AI (www.workbuddy.ai)",
|
||||
"type": "module",
|
||||
"main": "./index.mjs",
|
||||
|
||||
Reference in New Issue
Block a user