diff --git a/doc/idle-teams-consent-expiry.md b/doc/idle-teams-consent-expiry.md index 6220c74ab20..6faa09fca42 100644 --- a/doc/idle-teams-consent-expiry.md +++ b/doc/idle-teams-consent-expiry.md @@ -7,8 +7,10 @@ independent timer, provider request or external-wake capability. ## Obligation and trigger Only `consent_pending`, `awaiting_consent` and `upload_pending` rows are eligible. -Each uses its saved `expiresAt`. Startup reconstructs these rows in 100-row UUID -pages. Committed writes reload the affected transfer ID. The service registers +Each uses its saved `expiresAt`. Registered startup reconstruction yields after +one 100-row UUID page per scope refresh and resumes through the shared scheduler. +Registration resets the owner’s cursors so a partial scan restarts safely. The +explicit one-shot inventory method still returns the complete inventory. Committed writes reload the affected transfer ID. The service registers intent before insertion and its central versioned update, within the existing transaction. Nested savepoints wait for outer settlement. The shared work-signals protocol retains ambiguous outcomes; callers do not manage recovery wrappers. @@ -59,3 +61,12 @@ projection rollback, fairness, drain/resume and shutdown. Production integration registers the worker before Board publication and proves expiry cancels the publication without another provider call. Existing authority, publication and consent suites remain covered. See the [audit and failure ledger](plans/2026-10-25-teams-consent-expiry-sleep-audit.md). + + +Current local acceptance covers 223 distinct cases: 209 across five complete +protocol/publication/consent/runtime/wiring suites, plus 14 selected real Board +producer and Teams-authority integration cases. The other 1,580 integration +cases were skipped. A real 105-row regression proves bounded startup, same-owner +restart, complete saved-deadline expiry, and quiet SQL. A guarded missing-reset +mutation fails that regression. See the audit for exact revisions, earlier +fixture failures, current-parent integration status and deployment limits. diff --git a/doc/plans/2026-10-25-teams-consent-expiry-sleep-audit.md b/doc/plans/2026-10-25-teams-consent-expiry-sleep-audit.md index 2b4a055871c..cffea6acd9f 100644 --- a/doc/plans/2026-10-25-teams-consent-expiry-sleep-audit.md +++ b/doc/plans/2026-10-25-teams-consent-expiry-sleep-audit.md @@ -119,3 +119,65 @@ Parent #17586 at 250fca6cff has passing Actions, security and Greptile checks; Paperclip Review is still running at the latest inspection. This does not clear older stack findings or imply merge authority. Refreshed master is b7dc594bfa; final whole-stack reconciliation is still required. + + +## Bounded reconstruction and current-parent acceptance — October 28 + +The published Teams head `aa082e4679` was inspected after the report parent was +prepared on landed master. Its worker's registered load still looped through +all pages in one scheduler pass. This acceptance repairs that existing slice; +it does not introduce another queue, scheduler, database change or duty. + +A local normal merge prepares the slice on report candidate `c28de398`. The +explicit-base merge had one stack-plan append conflict. The complete report +plan and complete Teams appendix are both preserved; all source blobs match +the clean explicit-base composition. An initial literal patch comparison +rejected shifted queue line numbers (47 to 49) and blob IDs, then an overly +broad merge whitespace check flagged an inherited runner report-lock patch. +The actual patch content and owned-scope whitespace check pass; inherited +upstream files were not altered. Actual landed-parent reconciliation and fresh +remote gates are required before publication and merge. + +The new 105-transfer PostgreSQL regression failed against the original reader: +startup selected 105 rows instead of yielding after 100. The worker now splits +one-page selection from complete explicit inventory reads. Registered refresh +returns the existing shared `{rows, complete}` contract and retains per-scope +cursors; registration clears them. Restarting the same service halfway through +a scan reconstructs all 105 saved deadlines, expires them at the original time, +and leaves no recurring SQL before the deadline or after settlement. No consent +card or upload is sent. Removing only cursor reset makes the restart read five +rows instead of 100; original source was restored before final acceptance. + +The first regression fixture faked all timers before establishing its first +database connection and timed out, including teardown. That was not the intended +row-budget failure and is not accepted as regression evidence. Seeding now uses +real network timers with only Date frozen, then controls scheduler timers after +seeding. The corrected unchanged-reader run fails at 105 versus 100, and the +fixed worker passes. Both the failed setup and actual regression remain recorded. + +Current acceptance: all 209 cases in the complete transfer (66), publication, +consent, consent-runtime and app-wiring suites pass on a new migrated fixture; +14 selected real Board-producer and Teams-authority integration cases pass on a +separate new migrated fixture (1,580 others skipped). Total 223 distinct cases; +the targeted red/green case is not added again. Server production typecheck, +build and module-boundary checks pass. The new source remains within the +existing Teams owner and existing test file. No schema, shared-worker contract, +workflow or lockfile change is introduced. The old 222-case evidence remains +historical. This does not claim a complete local repository suite, a live Teams +tenant, external Cloud wake, physical suspension or cost savings. + +Logs: `/tmp/sleep26-bounded-reconstruction-red.log` (invalid timer setup), +`/tmp/sleep26-bounded-reconstruction-actual-red.log` (105 vs 100), +`/tmp/sleep26-bounded-reconstruction-green.log`, +`/tmp/sleep26-bounded-cursor-mutant-red.log` (5 vs 100 after restart), +`/tmp/sleep26-bounded-final-protocols.log`, +`/tmp/sleep26-bounded-final-producers.log`, +`/tmp/sleep26-bounded-final-types.log`, `/tmp/sleep26-bounded-final-build.log`, +and `/tmp/sleep26-bounded-final-boundaries.log`. + +Current stack state supersedes the historical outstanding-gates paragraph: +cleanup and retention have landed, including the repaired legacy ownership case +and the explicitly accepted company-deletion ownership policy. The report parent +has a documentation-only follow-up after `c28de398` and still needs its own latest +CI/reviews. This local Teams preparation must preserve that actual landed parent +before publication; it is not authority to merge into an unmerged feature branch. diff --git a/server/src/services/chat-channels/microsoft-teams/consent-expiry-work.ts b/server/src/services/chat-channels/microsoft-teams/consent-expiry-work.ts index e4dd2044531..7a2a9f8e97d 100644 --- a/server/src/services/chat-channels/microsoft-teams/consent-expiry-work.ts +++ b/server/src/services/chat-channels/microsoft-teams/consent-expiry-work.ts @@ -13,25 +13,35 @@ export function notifyTeamsConsentExpiry(tx: object, id: string) { /** Owns only unused consent deadlines, not transport attempts or unknown outcomes. */ export function teamsConsentExpiryWork(db: Db, expire: (companyId: string, id: string) => Promise) { - async function load(id?: string, signal?: AbortSignal): Promise { + const cursors = new Map(); + async function page(id?: string, cursor?: string, signal?: AbortSignal): Promise { try { - const entries: Entry[] = []; let cursor: string | undefined; - for (;;) { - signal?.throwIfAborted(); - const rows = await db.select({ id: chatTeamsFileTransfers.id, companyId: chatTeamsFileTransfers.companyId, - dueAt: sql`ceil(extract(epoch from ${chatTeamsFileTransfers.expiresAt}) * 1000)`, - }).from(chatTeamsFileTransfers).where(and(inArray(chatTeamsFileTransfers.phase, unusedTeamsConsentPhases), - id ? eq(chatTeamsFileTransfers.id, id) : undefined, - cursor ? gt(chatTeamsFileTransfers.id, cursor) : undefined)).orderBy(chatTeamsFileTransfers.id).limit(100); - entries.push(...rows.map(row => ({ ...row, dueAt: Number(row.dueAt) }))); - if (rows.length < 100) return entries; - cursor = rows[rows.length - 1].id; - } + signal?.throwIfAborted(); + const rows = await db.select({ id: chatTeamsFileTransfers.id, companyId: chatTeamsFileTransfers.companyId, + dueAt: sql`ceil(extract(epoch from ${chatTeamsFileTransfers.expiresAt}) * 1000)`, + }).from(chatTeamsFileTransfers).where(and(inArray(chatTeamsFileTransfers.phase, unusedTeamsConsentPhases), + id ? eq(chatTeamsFileTransfers.id, id) : undefined, + cursor ? gt(chatTeamsFileTransfers.id, cursor) : undefined)).orderBy(chatTeamsFileTransfers.id).limit(100); + signal?.throwIfAborted(); + return rows.map(row => ({ ...row, dueAt: Number(row.dueAt) })); } catch { - // Never expose private transfer envelopes or SQL parameter errors. throw new Error("Teams consent expiry selection is temporarily unavailable"); } } + async function load(id?: string, signal?: AbortSignal): Promise { + const entries: Entry[] = []; let cursor: string | undefined; + for (;;) { + const rows = await page(id, cursor, signal); + entries.push(...rows); + if (rows.length < 100) return entries; + cursor = rows[rows.length - 1].id; + } + } + async function refresh(id?: string, signal?: AbortSignal) { + const key = id ?? "*", rows = await page(id, cursors.get(key), signal), complete = rows.length < 100; + if (complete) cursors.delete(key); else cursors.set(key, rows[rows.length - 1].id); + return { rows, complete }; + } async function check(entry: Entry, signal?: AbortSignal): Promise { const current = (await load(entry.id, signal))[0]; if (!current) return null; @@ -42,11 +52,12 @@ export function teamsConsentExpiryWork(db: Db, expire: (companyId: string, id: s return (await load(entry.id, signal))[0] ?? null; } function register(coordinator: ReturnType, canRun: () => boolean) { + cursors.clear(); return registerScopedDeadlineWork(coordinator, { queue: DELIVERY_QUEUES.chatTeamsConsentExpiry, decodeScope: (hint: string) => hint === "*" ? undefined : hint, matches: (entry: Entry, id?: string) => !id || entry.id === id, - load, check, + load: refresh, check, }, canRun); } return { load, check, register }; diff --git a/server/src/services/chat-teams-file-transfers.test.ts b/server/src/services/chat-teams-file-transfers.test.ts index 504f921f276..0dd72d0f387 100644 --- a/server/src/services/chat-teams-file-transfers.test.ts +++ b/server/src/services/chat-teams-file-transfers.test.ts @@ -361,6 +361,59 @@ suite( try { await vi.advanceTimersByTimeAsync(ms); expect(select).not.toHaveBeenCalled(); expect(transaction).not.toHaveBeenCalled(); expect(execute).not.toHaveBeenCalled(); } finally { select.mockRestore(); transaction.mockRestore(); execute.mockRestore(); } } + it("bounds reconstruction and resets its cursor on same-owner restart", async () => { + vi.useFakeTimers({ toFake: ["Date"] }); + const f = await transfer(), due = Date.now() + 300_000; + await db.update(chatTeamsFileTransfers).set({ expiresAt: new Date(due) }).where(eq(chatTeamsFileTransfers.id, f.created.id)); + for (let index = 0; index < 104; index++) { + const publicationId = randomUUID(); + await db.insert(chatPublications).values({ id: publicationId, companyId: f.a.companyId, + endpointId: f.a.endpointId, conversationId: f.a.conversationId, issueId: f.a.issueId, + commentId: f.a.commentId, idempotencyKey: `expiry-restart:${publicationId}`, + payload: { text: "Same authorized file", attachmentIds: [f.a.attachmentId] } }); + const a = { ...f.a, publicationId }; + const created = await teamsFileTransferService(db, { ...f.opts, authorize: async () => a }).issue(a, new Date(due)); + transferIds.push(created.id); + } + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"], shouldAdvanceTime: false }); + const counts: number[] = [], select = db.select.bind(db); + const reads = vi.spyOn(db, "select").mockImplementation((...args) => { + const selection = select(...args), from = selection.from.bind(selection); + vi.spyOn(selection, "from").mockImplementation(table => { + const query = from(table); + if (table === chatTeamsFileTransfers) { + const execute = query.execute.bind(query); + vi.spyOn(query, "execute").mockImplementation(async () => { + const rows = await execute(); counts.push(rows.length); return rows; + }); + } + return query; + }); + return selection; + }); + const expire = vi.fn(f.service().expireUnusedConsent), work = teamsConsentExpiryWork(db, expire); + const start = () => { + coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => enabled, canReconcile: () => true, onError: error => errors.push(error) }); + return work.register(coordinator, () => enabled).ready; + }; + try { + await start(); expect(counts.reduce((sum, count) => sum + count, 0)).toBe(100); + await coordinator!.stop(); coordinator = undefined; + const before = counts.length; + await start(); expect(counts.slice(before).reduce((sum, count) => sum + count, 0)).toBe(100); + await vi.advanceTimersByTimeAsync(1000); + await vi.waitFor(() => expect(coordinator!.nextWakeAt()).toBe(due), { interval: 0 }); + expect(Math.max(...counts)).toBeLessThanOrEqual(100); reads.mockRestore(); + expect(await work.load()).toHaveLength(105); + await quiet(1000); expect(expire).not.toHaveBeenCalled(); + await vi.advanceTimersByTimeAsync(due - Date.now()); await settled(); + expect(expire).toHaveBeenCalledTimes(105); + expect(await db.select().from(chatTeamsFileTransfers).where(inArray(chatTeamsFileTransfers.id, transferIds))) + .toEqual(expect.arrayContaining([expect.objectContaining({ id: f.created.id, phase: "expired" })])); + expect(await work.load()).toEqual([]); expect(errors).toEqual([]); + await quiet(); expect(f.opts.postConsent).not.toHaveBeenCalled(); expect(f.opts.uploadRequest).not.toHaveBeenCalled(); + } finally { reads.mockRestore(); } + }, 30_000); it("is quiet with configured endpoints and cancelled history", async () => { const f = await transfer(); await f.service().cancel(f.a.companyId, f.created.id); const expire = vi.fn(f.service().expireUnusedConsent);