From 43d9b32ad706a923a651c4e1592fda5e5e3fe5b3 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 18:07:41 +0000 Subject: [PATCH 1/7] wip(plugin-audit): store a reply's thread root and count replies by it; page threads by millisecond Claude-Session: https://claude.ai/code/session_01WGufziM2GUsShZcjp6TiyD Co-authored-by: Claude --- .../src/comment-participants-backfill.ts | 87 +++- .../plugin-audit/src/comment-participants.ts | 199 ++++++-- .../plugin-audit/src/comment-threads-query.ts | 481 +++++++++++++----- .../src/objects/sys-comment.object.ts | 47 ++ 4 files changed, 643 insertions(+), 171 deletions(-) diff --git a/packages/plugins/plugin-audit/src/comment-participants-backfill.ts b/packages/plugins/plugin-audit/src/comment-participants-backfill.ts index 79bc00050c1..3b4adfedba7 100644 --- a/packages/plugins/plugin-audit/src/comment-participants-backfill.ts +++ b/packages/plugins/plugin-audit/src/comment-participants-backfill.ts @@ -2,11 +2,13 @@ /** * The stored-row backfill of `sys_comment`'s platform-written participant - * list (`comment-participants.ts`). + * list and thread root (`comment-participants.ts`). * - * Threads written before the column existed carry no list, so a filter on + * Threads written before the list existed carry none, so a filter on * `participants` ("the threads involving me") does not find them until this - * runs. `os migrate comment-participants` is its door. + * runs; replies written before the thread root existed carry none, and the + * comment threads read counts them by following `parent_id` for those rows + * until this stamps them. `os migrate comment-participants` is its door. * * ## One derivation * @@ -19,19 +21,21 @@ * * Rows are read and rewritten as the platform (a SYSTEM context); each rewrite * names the row's stored `updated_at` under `preserveAudit`, so the backfill - * changes no comment's `updated_at`, and names nothing but the list. The walk - * pages over top-level comments by `id` and reconciles each record's - * discussion once. + * changes no comment's `updated_at`, and names nothing but the list and the + * root. The walk pages over top-level comments by `id` and reconciles each + * record's discussion once; a second walk then pages over the replies still + * carrying no root (a discussion with no top-level comment left, whose + * replies are all in no thread) and reconciles theirs. * * ## Idempotent, its own verification * - * A list already equal to the rule's answer is not written, so a second run + * A list or root already equal to the rule's answer is not written, so a second run * changes nothing, and re-running and reading a clean report is the check. No * `sys_migration` flag is recorded: nothing gates irreversible behaviour on it. */ import type { IDataEngine } from '@objectstack/spec/contracts'; -import { reconcileCommentThreadParticipants } from './comment-participants.js'; +import { COMMENT_THREAD_ROOT_COLUMN, reconcileCommentThreadParticipants } from './comment-participants.js'; import type { MigrationLogger } from './stored-metadata-body-migration.js'; const COMMENT_OBJECT = 'sys_comment'; @@ -51,8 +55,10 @@ export interface CommentParticipantsBackfillReport { discussions: number; /** Threads (top-level comments) in them. */ threads: number; - /** Rows whose stored list differed from the rule: rewritten (or, in dry-run, would be). */ + /** Rows whose stored list or thread root differed from the rule: rewritten (or, in dry-run, would be). */ changed: number; + /** Of those, the rows whose stored thread root differed (a subset of `changed`). */ + roots: number; /** A failed read, or a rewrite that threw (apply mode) — re-run to finish. */ failures: number; } @@ -66,8 +72,9 @@ function asArray(result: unknown): Record[] { } /** - * Bring every `sys_comment` thread's stored participant list to the rule's - * answer. Dry-run by default; `apply` writes. Idempotent. + * Bring every `sys_comment` thread's stored participant list, and every + * reply's stored thread root, to the rule's answer. Dry-run by default; + * `apply` writes. Idempotent. */ export async function backfillCommentParticipants( engine: CommentParticipantsBackfillEngine, @@ -76,12 +83,48 @@ export async function backfillCommentParticipants( ): Promise { const apply = options.apply === true; const pageSize = options.pageSize && options.pageSize > 0 ? options.pageSize : COMMENT_PARTICIPANTS_BACKFILL_PAGE_SIZE; - const report: CommentParticipantsBackfillReport = { apply, discussions: 0, threads: 0, changed: 0, failures: 0 }; + const report: CommentParticipantsBackfillReport = { apply, discussions: 0, threads: 0, changed: 0, roots: 0, failures: 0 }; const seen = new Set(); + // Every discussion with a top-level comment, then every one a reply with no + // stored root is still on. Each discussion is reconciled once. + if (await walkDiscussions(engine, logger, { parent_id: { $null: true } }, pageSize, apply, seen, report)) { + await walkDiscussions( + engine, + logger, + { $and: [{ parent_id: { $null: false } }, { [COMMENT_THREAD_ROOT_COLUMN]: { $null: true } }] }, + pageSize, + apply, + seen, + report, + ); + } + + logger.info?.( + `[comment-participants-backfill] ${apply ? 'wrote' : 'would write'} ${report.changed} row(s) — ` + + `${report.roots} reply thread root(s) among them — across ${report.threads} thread(s) in ` + + `${report.discussions} record discussion(s)` + + (report.failures > 0 ? ` (${report.failures} failed — re-run to finish)` : ''), + ); + return report; +} + +/** + * Page over the comments `match` selects by `id`, reconciling the discussion + * each one is on unless `seen` has it. `false` when a page could not be read + * (counted): the run stops there. + */ +async function walkDiscussions( + engine: CommentParticipantsBackfillEngine, + logger: MigrationLogger, + match: Record, + pageSize: number, + apply: boolean, + seen: Set, + report: CommentParticipantsBackfillReport, +): Promise { let after: string | undefined; for (;;) { - const topLevel: Record = { parent_id: { $null: true } }; - const where = after === undefined ? topLevel : { $and: [topLevel, { id: { $gt: after } }] }; + const where = after === undefined ? match : { $and: [match, { id: { $gt: after } }] }; let rows: Record[]; try { rows = asArray( @@ -104,9 +147,9 @@ export async function backfillCommentParticipants( `[comment-participants-backfill] could not read ${COMMENT_OBJECT} — its remaining threads were NOT ` + `examined: ${(e as Error)?.message ?? String(e)}`, ); - break; + return false; } - if (rows.length === 0) break; + if (rows.length === 0) return true; for (const row of rows) { const threadId = typeof row.thread_id === 'string' ? row.thread_id : null; @@ -118,12 +161,13 @@ export async function backfillCommentParticipants( apply, onRewriteFailure: (commentId, e) => logger.warn( - `[comment-participants-backfill] failed to write the participants of ${COMMENT_OBJECT}/${commentId}: ` + + `[comment-participants-backfill] failed to write the participants or thread root of ${COMMENT_OBJECT}/${commentId}: ` + `${(e as Error)?.message ?? String(e)}`, ), }); report.threads += done.threads; report.changed += done.changed; + report.roots += done.roots; report.failures += done.failures; } catch (e) { report.failures += 1; @@ -135,14 +179,7 @@ export async function backfillCommentParticipants( } const last = rows[rows.length - 1]?.id; - if (rows.length < pageSize || typeof last !== 'string' || last === '') break; + if (rows.length < pageSize || typeof last !== 'string' || last === '') return true; after = last; } - - logger.info?.( - `[comment-participants-backfill] ${apply ? 'wrote' : 'would write'} ${report.changed} participant list(s) across ` + - `${report.threads} thread(s) in ${report.discussions} record discussion(s)` + - (report.failures > 0 ? ` (${report.failures} failed — re-run to finish)` : ''), - ); - return report; } diff --git a/packages/plugins/plugin-audit/src/comment-participants.ts b/packages/plugins/plugin-audit/src/comment-participants.ts index 380ee1f1494..9981ab8ec88 100644 --- a/packages/plugins/plugin-audit/src/comment-participants.ts +++ b/packages/plugins/plugin-audit/src/comment-participants.ts @@ -74,6 +74,21 @@ * at `error` with the remedy, `os migrate comment-participants --apply` * ({@link reconcileCommentThreadParticipants} is that command's step too). * + * ## The thread root, kept by the same reconcile + * + * `sys_comment.thread_root_id` (`objects/sys-comment.object.ts`, "Platform- + * written: the thread root") is the second fact this keeper stores: on each + * reply, the id of the top-level comment its `parent_id` chain reaches by the + * same rule ({@link threadRootByRow}), or the reply's own id when it is in no + * thread; `null` on a top-level comment. The comment threads read groups a + * page's replies by it (`comment-threads-query.ts`). It rides every step + * above: the create stamps a reply from its parent (one read of the parents, + * as the platform), and the reconcile brings every row of the discussion to + * the rule, in the same single-id write that carries the list. A reply that + * still carries `null` has not been stamped (written before the column, or + * its parent was itself unstamped at create); the next reconcile of its + * discussion, or `os migrate comment-participants --apply`, stamps it. + * * ## The reply notice is a separate audience * * Who a reply NOTIFIES (`readThreadParticipants` in `audit-writers.ts`: the @@ -88,6 +103,9 @@ import { isReplyRow } from './comment-resolution.js'; /** The platform-written list of a thread's participants, on its top-level comment. */ export const COMMENT_PARTICIPANTS_COLUMN = 'participants'; +/** The platform-written thread root of a reply: its top-level comment's id, or its own id when it is in no thread. */ +export const COMMENT_THREAD_ROOT_COLUMN = 'thread_root_id'; + const COMMENT_OBJECT = 'sys_comment'; const PACKAGE_ID = 'com.objectstack.audit'; @@ -104,7 +122,20 @@ const SYSTEM_CTX = { isSystem: true } as const; const SYSTEM_PRESERVING_CTX = { isSystem: true, preserveAudit: true } as const; /** The columns of a discussion row the rule reads. */ -const DISCUSSION_FIELDS = ['id', 'parent_id', 'author_id', 'mentions', 'created_at', 'updated_at', 'organization_id', COMMENT_PARTICIPANTS_COLUMN]; +const DISCUSSION_FIELDS = [ + 'id', + 'parent_id', + 'author_id', + 'mentions', + 'created_at', + 'updated_at', + 'organization_id', + COMMENT_PARTICIPANTS_COLUMN, + COMMENT_THREAD_ROOT_COLUMN, +]; + +/** The columns of a parent row the create stamp reads. */ +const PARENT_FIELDS = ['id', 'parent_id', 'thread_id', COMMENT_THREAD_ROOT_COLUMN]; /** The columns whose change can move a thread's participants. */ const PARTICIPATION_COLUMNS = ['mentions', 'parent_id', 'thread_id'] as const; @@ -147,12 +178,36 @@ function namedBy(row: Row): string[] { * Every top-level comment in `rows` has an entry. */ export function participantsByThread(rows: ReadonlyArray): Map { + const rootIdOf = threadRootResolver(rows); + const threads = new Map(); + for (const row of rows) { + if (isReplyRow(row)) continue; + const id = idOf(row.id); + if (id) threads.set(id, namedBy(row)); + } + for (const row of rows) { + if (!isReplyRow(row)) continue; + const rootId = rootIdOf(row); + const list = rootId === null ? undefined : threads.get(rootId); + if (!list) continue; + for (const uid of namedBy(row)) if (!list.includes(uid)) list.push(uid); + } + return threads; +} + +/** + * The rule that places a row in a thread, over ONE record's discussion: the + * id of the top-level comment `row`'s `parent_id` chain reaches within `rows` + * (a top-level row's own id), or `null` when the chain leaves `rows` or runs + * past {@link THREAD_ROOT_MAX_HOPS} hops. + */ +function threadRootResolver(rows: ReadonlyArray): (row: Row) => string | null { const byId = new Map(); for (const row of rows) { const id = idOf(row.id); if (id) byId.set(id, row); } - const rootIdOf = (row: Row): string | null => { + return (row: Row): string | null => { let current = row; for (let hop = 0; hop < THREAD_ROOT_MAX_HOPS; hop++) { if (!isReplyRow(current)) return idOf(current.id); @@ -162,20 +217,26 @@ export function participantsByThread(rows: ReadonlyArray): Map(); +} + +/** + * The stored thread root each row of ONE record's discussion should carry, + * keyed by row id: on a reply, its thread's top-level comment id by the rule + * {@link participantsByThread} places it with, or the reply's OWN id when the + * rule places it in no thread (its chain leaves `rows` or runs past the hop + * bound); `null` on a top-level comment. So a reply carrying `null` is one not + * yet stamped, and a grouped read by root never counts a reply in no thread + * (no top-level comment has a reply's id). + */ +export function threadRootByRow(rows: ReadonlyArray): Map { + const rootIdOf = threadRootResolver(rows); + const out = new Map(); for (const row of rows) { - if (isReplyRow(row)) continue; const id = idOf(row.id); - if (id) threads.set(id, namedBy(row)); - } - for (const row of rows) { - if (!isReplyRow(row)) continue; - const rootId = rootIdOf(row); - const list = rootId === null ? undefined : threads.get(rootId); - if (!list) continue; - for (const uid of namedBy(row)) if (!list.includes(uid)) list.push(uid); + if (!id) continue; + out.set(id, isReplyRow(row) ? rootIdOf(row) ?? id : null); } - return threads; + return out; } /** A stored list as ids, whatever the read handed back (an array, or its JSON text). */ @@ -245,27 +306,34 @@ async function currentUpdatedAt(engine: Pick, export interface ThreadParticipantsReconciliation { /** Top-level comments read. */ threads: number; - /** Rows whose stored list differed from the rule's answer: rewritten (or, in dry-run, would be). */ + /** Rows whose stored list or thread root differed from the rule's answer: rewritten (or, in dry-run, would be). */ changed: number; + /** Of those, the rows whose stored thread root differed (a subset of `changed`). */ + roots: number; /** Rewrites that threw (apply mode only). */ failures: number; } /** - * Bring every stored list of the discussion `threadId` names to the rule's - * answer: a top-level comment's list to {@link participantsByThread}'s, and a - * reply's to `null`. Rows already right are not written, so a second call - * writes nothing. Dry-run unless `apply`. A failed read throws; a failed + * Bring every stored list and thread root of the discussion `threadId` names + * to the rule's answer: a top-level comment's list to + * {@link participantsByThread}'s and a reply's to `null`; each row's root to + * {@link threadRootByRow}'s. Rows already right are not written, so a second + * call writes nothing; a row written names only the columns that differ. The + * root is left alone when `roots` is `false` (a `sys_comment` that does not + * declare the column). Dry-run unless `apply`. A failed read throws; a failed * rewrite is counted (and named on `onRewriteFailure`) and the rest proceed. */ export async function reconcileCommentThreadParticipants( engine: Pick, threadId: string, - options: { apply: boolean; onRewriteFailure?: (commentId: string, error: unknown) => void }, + options: { apply: boolean; roots?: boolean; onRewriteFailure?: (commentId: string, error: unknown) => void }, ): Promise { const rows = await readDiscussion(engine, threadId); const derived = participantsByThread(rows); - const result: ThreadParticipantsReconciliation = { threads: derived.size, changed: 0, failures: 0 }; + const keepRoots = options.roots !== false; + const roots = keepRoots ? threadRootByRow(rows) : undefined; + const result: ThreadParticipantsReconciliation = { threads: derived.size, changed: 0, roots: 0, failures: 0 }; for (const row of rows) { const id = idOf(row.id); if (!id) continue; @@ -273,8 +341,12 @@ export async function reconcileCommentThreadParticipants( const have = row[COMMENT_PARTICIPANTS_COLUMN] === undefined || row[COMMENT_PARTICIPANTS_COLUMN] === null ? null : storedList(row[COMMENT_PARTICIPANTS_COLUMN]); - if (sameList(want, have)) continue; + const listDiffers = !sameList(want, have); + const wantRoot = roots ? roots.get(id) ?? null : null; + const rootDiffers = roots !== undefined && wantRoot !== idOf(row[COMMENT_THREAD_ROOT_COLUMN]); + if (!listDiffers && !rootDiffers) continue; result.changed += 1; + if (rootDiffers) result.roots += 1; if (!options.apply) continue; try { if (typeof engine.update !== 'function') throw new Error('the data engine composed here serves no update'); @@ -289,7 +361,8 @@ export async function reconcileCommentThreadParticipants( COMMENT_OBJECT, { id, - [COMMENT_PARTICIPANTS_COLUMN]: want, + ...(listDiffers ? { [COMMENT_PARTICIPANTS_COLUMN]: want } : {}), + ...(rootDiffers ? { [COMMENT_THREAD_ROOT_COLUMN]: wantRoot } : {}), ...(updatedAt !== undefined && updatedAt !== null ? { updated_at: updatedAt } : {}), }, { context: organization ? { ...SYSTEM_PRESERVING_CTX, tenantId: organization } : SYSTEM_PRESERVING_CTX }, @@ -302,17 +375,67 @@ export async function reconcileCommentThreadParticipants( return result; } -/** Whether the registered `sys_comment` declares the column (an engine that cannot say is taken to). */ -function declaresParticipants(engine: Pick): boolean { +/** Whether the registered `sys_comment` declares `column` (an engine that cannot say is taken to). */ +function declaresColumn(engine: Pick, column: string): boolean { if (typeof engine.getSchema !== 'function') return true; try { const schema = engine.getSchema(COMMENT_OBJECT) as { fields?: Record } | undefined; - return !!schema?.fields && COMMENT_PARTICIPANTS_COLUMN in schema.fields; + return !!schema?.fields && column in schema.fields; } catch { return false; } } +const declaresParticipants = (engine: Pick): boolean => + declaresColumn(engine, COMMENT_PARTICIPANTS_COLUMN); + +/** + * The create stamp of the thread root, for the reply rows of one insert: one + * read of their parents, as the platform. A reply whose parent is top-level on + * the same record's discussion is stamped with the parent's id; one whose + * parent is a reply there that carries a root of a thread (not its own id) is + * stamped with that root. Anything else — a parent not found, on another + * discussion, unstamped, or itself in no thread — is stamped `null`, and the + * after-insert reconcile, which runs on every reply, brings it to the rule + * (as it does a reply the hop bound places in no thread). A top-level row is + * stamped `null`. Every value a writer sent is replaced. + */ +async function stampThreadRoots(engine: Pick, rows: Row[]): Promise { + const parentIds = [...new Set(rows.filter(isReplyRow).map((r) => idOf(r.parent_id)).filter((id): id is string => id !== null))]; + const parents = new Map(); + if (parentIds.length > 0) { + for (const parent of asRows( + await engine.find(COMMENT_OBJECT, { + where: { id: { $in: parentIds } }, + fields: PARENT_FIELDS, + limit: parentIds.length, + context: SYSTEM_CTX, + }), + )) { + const id = idOf(parent.id); + if (id) parents.set(id, parent); + } + } + for (const row of rows) { + if (!isReplyRow(row)) { + row[COMMENT_THREAD_ROOT_COLUMN] = null; + continue; + } + const parentId = idOf(row.parent_id); + const parent = parentId === null ? undefined : parents.get(parentId); + if (!parent || parentId === null || idOf(parent.thread_id) !== idOf(row.thread_id)) { + row[COMMENT_THREAD_ROOT_COLUMN] = null; + continue; + } + if (!isReplyRow(parent)) { + row[COMMENT_THREAD_ROOT_COLUMN] = parentId; + continue; + } + const parentRoot = idOf(parent[COMMENT_THREAD_ROOT_COLUMN]); + row[COMMENT_THREAD_ROOT_COLUMN] = parentRoot !== null && parentRoot !== parentId ? parentRoot : null; + } +} + const hasOwn = (o: object, k: string): boolean => Object.prototype.hasOwnProperty.call(o, k); /** The record discussions a write touched, from its result, its payload and the row as it was. */ @@ -349,6 +472,7 @@ export function installCommentParticipants(engine: CommentParticipantsEngine, lo const reconcile = async (ctx: any): Promise => { if (!declaresParticipants(engine)) return; + const roots = declaresColumn(engine, COMMENT_THREAD_ROOT_COLUMN); for (const threadId of touchedThreads(ctx)) { try { // Re-check after any pass that wrote, until one writes nothing: a @@ -357,6 +481,7 @@ export function installCommentParticipants(engine: CommentParticipantsEngine, lo for (let pass = 0; pass < MAX_RECONCILE_PASSES; pass++) { const done = await reconcileCommentThreadParticipants(engine, threadId, { apply: true, + roots, onRewriteFailure: (commentId, e) => reportFailure(threadId, commentId, e), }); if (done.changed === 0 || done.failures > 0) break; @@ -367,16 +492,31 @@ export function installCommentParticipants(engine: CommentParticipantsEngine, lo } }; - // ── Create: the new row's own list, over whatever the writer sent ── + // ── Create: the new row's own list and thread root, over whatever the writer sent ── engine.registerHook( 'beforeInsert', - (ctx: any) => { + async (ctx: any) => { if (!declaresParticipants(engine)) return; const data = ctx?.input?.data; + const rows: Row[] = []; for (const row of Array.isArray(data) ? data : [data]) { if (!row || typeof row !== 'object' || Array.isArray(row)) continue; const r = row as Row; r[COMMENT_PARTICIPANTS_COLUMN] = isReplyRow(r) ? null : namedBy(r); + rows.push(r); + } + if (rows.length === 0 || !declaresColumn(engine, COMMENT_THREAD_ROOT_COLUMN)) return; + try { + await stampThreadRoots(engine, rows); + } catch (e) { + // The parents could not be read: stamp nothing (an unstamped reply is + // still counted by the threads read), and let the after-insert + // reconcile write the root. The write itself is not refused for it. + for (const r of rows) r[COMMENT_THREAD_ROOT_COLUMN] = null; + logger.warn( + `[audit] comment thread root: the parent of a new reply could not be read, so its thread root is left for ` + + `the after-insert reconcile to write. Cause: ${e instanceof Error ? e.message : String(e)}`, + ); } }, { object: COMMENT_OBJECT, packageId: PACKAGE_ID }, @@ -391,8 +531,9 @@ export function installCommentParticipants(engine: CommentParticipantsEngine, lo // referential-cleanup marker), land. if (ctx?.session?.isSystem === true || ctx?.referentialFieldClear === true) return; const data = ctx?.input?.data; - if (data && typeof data === 'object' && !Array.isArray(data) && hasOwn(data, COMMENT_PARTICIPANTS_COLUMN)) { - delete (data as Row)[COMMENT_PARTICIPANTS_COLUMN]; + if (data && typeof data === 'object' && !Array.isArray(data)) { + if (hasOwn(data, COMMENT_PARTICIPANTS_COLUMN)) delete (data as Row)[COMMENT_PARTICIPANTS_COLUMN]; + if (hasOwn(data, COMMENT_THREAD_ROOT_COLUMN)) delete (data as Row)[COMMENT_THREAD_ROOT_COLUMN]; } }, { object: COMMENT_OBJECT, packageId: PACKAGE_ID }, diff --git a/packages/plugins/plugin-audit/src/comment-threads-query.ts b/packages/plugins/plugin-audit/src/comment-threads-query.ts index d52aea330a5..17bb6a48803 100644 --- a/packages/plugins/plugin-audit/src/comment-threads-query.ts +++ b/packages/plugins/plugin-audit/src/comment-threads-query.ts @@ -37,7 +37,7 @@ import { import type { ExecutionContext } from '@objectstack/spec/kernel'; import { resolveThrownHttpError, sendError, sendOk, sendServerFault } from '@objectstack/types'; -import { COMMENT_PARTICIPANTS_COLUMN } from './comment-participants.js'; +import { COMMENT_PARTICIPANTS_COLUMN, COMMENT_THREAD_ROOT_COLUMN } from './comment-participants.js'; import { COMMENT_RESOLVED_FIELD, isReplyRow } from './comment-resolution.js'; /** @@ -83,13 +83,20 @@ import { COMMENT_RESOLVED_FIELD, isReplyRow } from './comment-resolution.js'; * 5. **The threads**: ONE `find` on `sys_comment` — the object, the scope, * top-level only, unresolved unless asked, "involving me" * (`participants` contains the caller) when asked, after the cursor — - * newest first by `(created_at, id)`, one row past the page to learn - * whether another page follows. The comment read gate ANDs its own - * condition in, as on `GET /data/sys_comment`. - * 6. **The page's extras**: the replies on the page's records (author - * columns and the parent pointer only), from which each thread's reply - * count at any depth and its latest distinct repliers are taken; and the - * page's records' display names, one read of the object for their ids. + * newest first, one row past the page to learn whether another page + * follows; and, when one does, one bounded read of the millisecond the + * page ends in (see "The keyset" below). The comment read gate ANDs its + * own condition in, as on `GET /data/sys_comment`. + * 6. **The page's extras**: ONE grouped read of the replies to the page's + * threads, by their stored thread root and author (a count and the newest + * creation time per pair), and one read of the newest reply of each + * candidate replier, from which each thread's reply count at any depth + * and its latest distinct repliers are taken; the replies on the page's + * records that carry no stored root yet, placed by following `parent_id` + * (see "Replies not stamped yet" below); and the page's records' display + * names, one read of the object for their ids. However many replies a + * page's threads hold, a page on a backfilled table costs the same + * statements. * * ## The planned scope is planned per request, never kept * @@ -100,12 +107,39 @@ import { COMMENT_RESOLVED_FIELD, isReplyRow } from './comment-resolution.js'; * * ## Threads, replies, and the record page's rule * - * A thread is a top-level comment and every reply under it at any depth: a - * reply is placed in a thread by following `parent_id` up to its top-level - * comment, at most 16 hops, the rule a thread's participants are kept by + * A thread is a top-level comment and every reply under it: a reply is placed + * in a thread by following `parent_id` up to its top-level comment within the + * record's discussion, at most 16 hops (so a reply 16 or more levels deep is + * in no thread), the rule a thread's participants are kept by * (`comment-participants.ts`) and the one the console groups a record's - * comments by. A reply whose chain leaves the record's discussion counts in - * no thread. + * comments by. The platform stores that answer on each reply as + * `thread_root_id` (the top-level comment's id, or the reply's own id when it + * is in no thread), and step 6 groups by it. A reply whose chain leaves the + * record's discussion counts in no thread. + * + * ## Replies not stamped yet + * + * A reply written before `thread_root_id` existed carries `null` there until + * `os migrate comment-participants --apply` stamps it, or until the next write + * to its record's discussion reconciles it. Its thread's count must not drop + * meanwhile, so step 6 reads the replies on the page's records that carry no + * root (keyset-paged by `id`; on a backfilled table, one read that answers + * nothing) and places each by following `parent_id`, reading the missing + * ancestors a level at a time (at most 16 levels), as the caller. That is the + * old walk, kept for those rows only. + * + * ## The keyset + * + * Threads are paged newest first by the millisecond they were created in, + * then by `id`. A creation time is read back at milliseconds on every dialect + * (the read door folds PostgreSQL's microsecond `timestamptz` to the canonical + * millisecond text), while PostgreSQL compares the stored microseconds. So the + * cursor names a millisecond `c` and an id, and the next page is the threads + * created before `c`, or in `c` (from `c` to just before `c` plus 1 ms) with a + * smaller id: the comparison truncates on both sides. A page whose last + * millisecond may hold more threads than the page shows ends with the threads + * of that millisecond read again ordered by `id`, so the page and the cursor + * agree on which of them were answered, at any precision the column keeps. * * ## What is not served here * @@ -125,11 +159,14 @@ const COMMENT_OBJECT = 'sys_comment'; /** How many `parent_id` hops a reply is followed to its thread's top-level comment — the participants rule's bound. */ const THREAD_ROOT_MAX_HOPS = 16; -/** Reply rows read per page in step 6; a page of threads whose records hold more is read in further pages. */ -const REPLY_PAGE_SIZE = 1_000; +/** Unstamped reply rows read per page in step 6; more are read in further pages. */ +const UNSTAMPED_PAGE_SIZE = 1_000; + +/** The reply columns step 6 reads: the author it shows, the time it orders by, and the pointers it places a reply with. */ +const REPLY_FIELDS = ['id', 'parent_id', 'thread_id', COMMENT_THREAD_ROOT_COLUMN, 'author_id', 'author_name', 'author_avatar_url', 'created_at']; -/** The reply columns step 6 reads: the pointer it follows and the author it shows. */ -const REPLY_FIELDS = ['id', 'parent_id', 'author_id', 'author_name', 'author_avatar_url', 'created_at']; +/** The columns of an ancestor the unstamped walk reads. */ +const ANCESTOR_FIELDS = ['id', 'parent_id', 'thread_id']; /** Newest first, `id` breaking ties: the order the threads are paged in. */ const NEWEST_FIRST = [ @@ -142,6 +179,7 @@ type Row = Record; /** The slice of the data engine the read uses — `ObjectQL`'s own members. */ export interface CommentThreadsEngine { find(object: string, query: Record): Promise; + aggregate(object: string, query: Record, options?: Record): Promise; planReadScope(object: string, target: string, options?: PlanReadScopeOptions): Promise; /** The registered object definition, or `undefined` for a name the registry does not hold. */ getSchema(object: string): unknown; @@ -180,20 +218,49 @@ function asRows(result: unknown): Row[] { return []; } -/** A stored instant as the text the keyset compares: an ISO string for a `Date`, the stored text otherwise. */ -function instantText(value: unknown): string | null { - if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value.toISOString(); - if (typeof value === 'string' && value !== '') return value; - if (typeof value === 'number' && Number.isFinite(value)) return new Date(value).toISOString(); - return null; +/** + * A stored instant as epoch milliseconds (the millisecond it falls in), or + * `null` for a value that is not one: a `Date`, epoch milliseconds, or text + * the SQL drivers write (`T` or a space between day and time, a zone as `Z`, + * `+HH`, `+HHMM` or `+HH:MM`, any fraction). + */ +export function instantMs(value: unknown): number | null { + if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value.getTime(); + if (typeof value === 'number') return Number.isFinite(value) ? Math.floor(value) : null; + if (typeof value !== 'string' || value === '') return null; + const m = /^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2}(?::\d{2})?)(?:\.(\d+))?(Z|[+-]\d{2}(?::?\d{2})?)?$/.exec(value.trim()); + if (!m) return null; + const fraction = (m[3] ?? '').slice(0, 3).padEnd(3, '0'); + let zone = m[4] ?? 'Z'; + if (zone !== 'Z') zone = zone.length === 3 ? `${zone}:00` : zone.includes(':') ? zone : `${zone.slice(0, 3)}:${zone.slice(3)}`; + const time = m[2].length === 5 ? `${m[2]}:00` : m[2]; + const ms = Date.parse(`${m[1]}T${time}.${fraction}${zone}`); + return Number.isNaN(ms) ? null : ms; } -/** The keyset position a cursor carries: the last thread's creation time and id. */ +const isoOf = (ms: number): string => new Date(ms).toISOString(); + +/** The keyset position a cursor carries: the millisecond the last thread was created in (canonical text), and its id. */ interface CursorPosition { createdAt: string; id: string; } +/** + * The keyset condition "after `position`" (see "The keyset"): created before + * its millisecond, or in it with a smaller id. Both sides compare at the + * millisecond whatever precision the column keeps. + */ +function afterPosition(position: CursorPosition): Row { + const start = instantMs(position.createdAt) as number; + return { + $or: [ + { created_at: { $lt: isoOf(start) } }, + { $and: [{ created_at: { $gte: isoOf(start) } }, { created_at: { $lt: isoOf(start + 1) } }, { id: { $lt: position.id } }] }, + ], + }; +} + /** Encode a position as an opaque, URL-safe cursor. */ export function encodeThreadsCursor(position: CursorPosition): string { const text = encodeURIComponent(JSON.stringify([position.createdAt, position.id])); @@ -221,8 +288,11 @@ export function decodeThreadsCursor(cursor: string): CursorPosition | null { // the engine (its temporal door, its filter-token resolver) about a // condition the client never wrote. if (!CURSOR_INSTANT_RE.test(createdAt) || isUninterpretableTemporalComparand('datetime', createdAt)) return null; + const at = instantMs(createdAt); + if (at === null) return null; if (id === '' || id.trim() !== id || classifyFilterToken(id) !== null) return null; - return { createdAt, id }; + // Normalised to the millisecond it names, the keyset's unit. + return { createdAt: isoOf(at), id }; } catch { return null; } @@ -341,35 +411,18 @@ export async function queryCommentThreads( parent_id: { $null: true }, ...(request.showResolved === true ? {} : { [COMMENT_RESOLVED_FIELD]: { $ne: true } }), ...(request.onlyMine === true ? { [COMMENT_PARTICIPANTS_COLUMN]: { $contains: callerId } } : {}), - ...(position - ? { - $or: [ - { created_at: { $lt: position.createdAt } }, - { $and: [{ created_at: position.createdAt }, { id: { $lt: position.id } }] }, - ], - } - : {}), + ...(position ? afterPosition(position) : {}), }; - const found = asRows( - await engine.find(COMMENT_OBJECT, { where: threadWhere, orderBy: NEWEST_FIRST, limit: limit + 1, context }), - ); - const page = found.slice(0, limit); - const last = page[page.length - 1]; - let nextCursor: string | null = null; - if (found.length > limit && last) { - const createdAt = instantText(last.created_at); - const id = idOf(last.id); - if (createdAt && id) nextCursor = encodeThreadsCursor({ createdAt, id }); - } + const { page, nextCursor } = await readThreadsPage(engine, threadWhere, limit, context); if (page.length === 0) return { threads: [], nextCursor }; // Step 6: the replies and the record names, for this page only. const recordIds = [...new Set(page.map((row) => idOf(row.record_id)).filter((id): id is string => id !== null))]; - const [replies, names] = await Promise.all([ - readReplies(engine, object, recordIds, context), + const threadIds = page.map((row) => idOf(row.id)).filter((id): id is string => id !== null); + const [extras, names] = await Promise.all([ + readThreadExtras(engine, object, recordIds, threadIds, context), readRecordNames(engine, object, def, recordIds, context), ]); - const extras = threadExtras(page, replies); const threads: CommentThread[] = page.map((row) => { const id = String(row.id); @@ -385,40 +438,45 @@ export async function queryCommentThreads( return { threads, nextCursor }; } -/** Every reply on `recordIds` the caller may read, newest first, keyset-paged. */ -async function readReplies( +/** + * Step 5's page: the threads `threadWhere` selects, newest first, at most + * `limit`, and the cursor after the last one (`null` on the last page). One + * read of `limit + 1` rows; when another page follows, one more read of the + * millisecond the page ends in, ordered by `id` and bounded to the rows the + * page still has room for plus one, so the page's last millisecond holds + * exactly the rows of it with the largest ids and the cursor resumes after + * them (see "The keyset"). + */ +async function readThreadsPage( engine: CommentThreadsEngine, - object: string, - recordIds: readonly string[], + threadWhere: Row, + limit: number, context: ExecutionContext, -): Promise { - const rows: Row[] = []; - let after: CursorPosition | null = null; - for (;;) { - const where: Row = { - object_name: object, - record_id: { $in: [...recordIds] }, - parent_id: { $null: false }, - ...(after - ? { - $or: [ - { created_at: { $lt: after.createdAt } }, - { $and: [{ created_at: after.createdAt }, { id: { $lt: after.id } }] }, - ], - } - : {}), - }; - const batch = asRows( - await engine.find(COMMENT_OBJECT, { where, fields: REPLY_FIELDS, orderBy: NEWEST_FIRST, limit: REPLY_PAGE_SIZE, context }), - ); - rows.push(...batch); - const tail = batch[batch.length - 1]; - const createdAt = tail ? instantText(tail.created_at) : null; - const id = tail ? idOf(tail.id) : null; - if (batch.length < REPLY_PAGE_SIZE || !createdAt || !id) break; - after = { createdAt, id }; - } - return rows; +): Promise<{ page: Row[]; nextCursor: string | null }> { + const found = asRows(await engine.find(COMMENT_OBJECT, { where: threadWhere, orderBy: NEWEST_FIRST, limit: limit + 1, context })); + if (found.length <= limit) return { page: found, nextCursor: null }; + const edge = instantMs(found[limit - 1]?.created_at); + if (edge === null) return { page: found.slice(0, limit), nextCursor: null }; + // Every millisecond above the edge is whole in `found` (the rows come newest + // first, so a millisecond's rows are contiguous); the edge's own may not be. + const above = found.slice(0, limit).filter((row) => { + const at = instantMs(row.created_at); + return at !== null && at > edge; + }); + const room = limit - above.length; + const inEdge = asRows( + await engine.find(COMMENT_OBJECT, { + where: { $and: [threadWhere, { created_at: { $gte: isoOf(edge) } }, { created_at: { $lt: isoOf(edge + 1) } }] }, + orderBy: [{ field: 'id', order: 'desc' as const }], + limit: room + 1, + context, + }), + ); + const page = [...above, ...inEdge.slice(0, room)]; + const last = page[page.length - 1]; + const id = last ? idOf(last.id) : null; + // `found` held a row past the page, so another page follows. + return { page, nextCursor: id ? encodeThreadsCursor({ createdAt: isoOf(edge), id }) : null }; } /** The display name of each of `recordIds` the caller reads, by the object's title field (ADR-0079). */ @@ -446,53 +504,237 @@ async function readRecordNames( return names; } +/** One thread's reply count and latest distinct repliers. */ +interface ThreadExtra { + count: number; + repliers: CommentThreadReplier[]; +} + +/** One group of step 6's grouped read: the replies one author wrote in one thread, how many, and the newest's time. */ +export interface StampedReplyGroup { + rootId: string; + authorId: string; + count: number; + latestMs: number; +} + /** - * Each thread's reply count and latest distinct repliers, from the page's - * threads and the replies on their records (newest first). A reply joins the - * thread of its top-level ancestor, followed at most - * {@link THREAD_ROOT_MAX_HOPS} hops; one whose chain leaves the rows read is - * in no thread. + * Step 6: each page thread's reply count and latest distinct repliers, as the + * caller. One grouped read of the stamped replies to `threadIds` by root and + * author; one read of the newest reply of each author who can be among a + * thread's latest repliers; and the unstamped replies on `recordIds`, placed by + * following `parent_id` ({@link readUnstampedPlaced}). */ -export function threadExtras( - threads: ReadonlyArray, - replies: ReadonlyArray, -): Map { +async function readThreadExtras( + engine: CommentThreadsEngine, + object: string, + recordIds: readonly string[], + threadIds: readonly string[], + context: ExecutionContext, +): Promise> { + const onPage: Row = { object_name: object, record_id: { $in: [...recordIds] } }; + const [groups, unstamped] = await Promise.all([ + (async () => + asRows( + await engine.aggregate( + COMMENT_OBJECT, + { + where: { ...onPage, [COMMENT_THREAD_ROOT_COLUMN]: { $in: [...threadIds] } }, + groupBy: [COMMENT_THREAD_ROOT_COLUMN, 'author_id'], + aggregations: [ + { function: 'count', field: 'id', alias: 'replies' }, + { function: 'max', field: 'created_at', alias: 'latest' }, + ], + }, + { context }, + ), + ).flatMap((row): StampedReplyGroup[] => { + const rootId = idOf(row[COMMENT_THREAD_ROOT_COLUMN]); + const authorId = idOf(row.author_id); + const count = Number(row.replies); + const latestMs = instantMs(row.latest); + if (rootId === null || authorId === null || !Number.isFinite(count) || latestMs === null) return []; + return [{ rootId, authorId, count, latestMs }]; + }))(), + readUnstampedPlaced(engine, onPage, new Set(threadIds), context), + ]); + + // The newest reply of each author who can still be among a thread's latest + // repliers: per thread, the authors whose newest reply is at or after the + // third-newest author's millisecond. An author below that is pushed further + // down by anything the unstamped rows add, never up. + const candidates: StampedReplyGroup[] = []; + const byRoot = new Map(); + for (const g of groups) byRoot.set(g.rootId, [...(byRoot.get(g.rootId) ?? []), g]); + for (const list of byRoot.values()) { + list.sort((a, b) => b.latestMs - a.latestMs); + const floor = list[Math.min(list.length, COMMENT_THREADS_MAX_REPLIERS) - 1]?.latestMs ?? Infinity; + candidates.push(...list.filter((g) => g.latestMs >= floor)); + } + const newest = + candidates.length === 0 + ? [] + : asRows( + await engine.find(COMMENT_OBJECT, { + where: { + ...onPage, + $or: candidates.map((g) => ({ + $and: [ + { [COMMENT_THREAD_ROOT_COLUMN]: g.rootId }, + { author_id: g.authorId }, + { created_at: { $gte: isoOf(g.latestMs) } }, + { created_at: { $lt: isoOf(g.latestMs + 1) } }, + ], + })), + }, + fields: REPLY_FIELDS, + orderBy: NEWEST_FIRST, + // One row per candidate in practice (an author's newest reply in a + // thread); the bound only keeps a degenerate millisecond finite. + limit: candidates.length * 10, + context, + }), + ); + const newestPlaced = newest.flatMap((row) => { + const rootId = idOf(row[COMMENT_THREAD_ROOT_COLUMN]); + return rootId === null ? [] : [{ rootId, row }]; + }); + return assembleThreadExtras(threadIds, groups, newestPlaced, unstamped); +} + +/** A reply row and the page thread it is placed in. */ +export interface PlacedReply { + rootId: string; + row: Row; +} + +/** + * Each thread's reply count and latest distinct repliers, from the grouped + * read's `groups` (the stamped replies, counted), `newest` (the newest reply + * of each candidate author, which name repliers and count nothing) and + * `unstamped` (each unstamped reply placed in a page thread: counted, and a + * replier candidate). Repliers are newest first by the millisecond of their + * newest reply, `id` breaking a tie, distinct by author, at most + * {@link COMMENT_THREADS_MAX_REPLIERS}. + */ +export function assembleThreadExtras( + threadIds: readonly string[], + groups: readonly StampedReplyGroup[], + newest: readonly PlacedReply[], + unstamped: readonly PlacedReply[], +): Map { + const out = new Map(); + for (const id of threadIds) out.set(id, { count: 0, repliers: [] }); + for (const g of groups) { + const entry = out.get(g.rootId); + if (entry) entry.count += g.count; + } + for (const { rootId } of unstamped) { + const entry = out.get(rootId); + if (entry) entry.count += 1; + } + const rows = [...newest, ...unstamped].filter(({ rootId, row }) => out.has(rootId) && idOf(row.author_id) !== null); + const at = (row: Row) => instantMs(row.created_at) ?? -Infinity; + rows.sort((a, b) => at(b.row) - at(a.row) || (String(a.row.id) < String(b.row.id) ? 1 : String(a.row.id) > String(b.row.id) ? -1 : 0)); + for (const { rootId, row } of rows) { + const entry = out.get(rootId) as ThreadExtra; + const author = idOf(row.author_id) as string; + if (entry.repliers.length >= COMMENT_THREADS_MAX_REPLIERS || entry.repliers.some((r) => r.id === author)) continue; + entry.repliers.push({ + id: author, + name: typeof row.author_name === 'string' && row.author_name !== '' ? row.author_name : null, + avatarUrl: typeof row.author_avatar_url === 'string' && row.author_avatar_url !== '' ? row.author_avatar_url : null, + }); + } + return out; +} + +/** + * The replies on the page's records that carry no stored thread root, each + * with the page thread it belongs to (see "Replies not stamped yet"): read + * keyset-paged by `id`, then placed by following `parent_id` within the + * reply's discussion, the ancestors not yet read fetched a level at a time, + * at most {@link THREAD_ROOT_MAX_HOPS} levels, all as the caller. A reply the + * rule places in no thread, or in a thread not on the page, is left out. On a + * backfilled table this is one read that answers nothing. + */ +async function readUnstampedPlaced( + engine: CommentThreadsEngine, + onPage: Row, + pageThreads: ReadonlySet, + context: ExecutionContext, +): Promise { + const unstamped: Row[] = []; + let after: string | null = null; + for (;;) { + const where: Row = { + ...onPage, + parent_id: { $null: false }, + [COMMENT_THREAD_ROOT_COLUMN]: { $null: true }, + ...(after !== null ? { id: { $gt: after } } : {}), + }; + const batch = asRows( + await engine.find(COMMENT_OBJECT, { + where, + fields: REPLY_FIELDS, + orderBy: [{ field: 'id', order: 'asc' as const }], + limit: UNSTAMPED_PAGE_SIZE, + context, + }), + ); + unstamped.push(...batch); + const tail = idOf(batch[batch.length - 1]?.id); + if (batch.length < UNSTAMPED_PAGE_SIZE || tail === null) break; + after = tail; + } + if (unstamped.length === 0) return []; + const byId = new Map(); - for (const row of [...threads, ...replies]) { + for (const row of unstamped) { const id = idOf(row.id); if (id) byId.set(id, row); } - const out = new Map(); - for (const row of threads) { - const id = idOf(row.id); - if (id) out.set(id, { count: 0, repliers: [] }); + // Read the ancestors a level at a time: each round fetches the parents no + // row read so far names, until none is missing or the hop bound is spent. + for (let level = 0; level < THREAD_ROOT_MAX_HOPS; level++) { + const missing = new Set(); + for (const row of byId.values()) { + if (!isReplyRow(row)) continue; + const parentId = idOf(row.parent_id); + if (parentId !== null && !byId.has(parentId)) missing.add(parentId); + } + if (missing.size === 0) break; + const ids = [...missing]; + const parents = asRows( + await engine.find(COMMENT_OBJECT, { where: { id: { $in: ids } }, fields: ANCESTOR_FIELDS, limit: ids.length, context }), + ); + for (const parent of parents) { + const id = idOf(parent.id); + if (id) byId.set(id, parent); + } + // An id asked for and not answered is gone (or not the caller's to read): + // a chain through it is in no thread. Recorded so it is not asked again. + for (const id of ids) if (!byId.has(id)) byId.set(id, { id, parent_id: null, thread_id: null, missing: true }); } - const rootIdOf = (row: Row): string | null => { - let current = row; - for (let hop = 0; hop <= THREAD_ROOT_MAX_HOPS; hop++) { - if (!isReplyRow(current)) return idOf(current.id); + + const placed: PlacedReply[] = []; + for (const reply of unstamped) { + const discussion = idOf(reply.thread_id); + let current = reply; + let rootId: string | null = null; + for (let hop = 0; hop < THREAD_ROOT_MAX_HOPS; hop++) { + if (current.missing === true || idOf(current.thread_id) !== discussion) break; + if (!isReplyRow(current)) { + rootId = idOf(current.id); + break; + } const parent = byId.get(String(current.parent_id)); - if (!parent) return null; + if (!parent) break; current = parent; } - return null; - }; - for (const reply of replies) { - if (!isReplyRow(reply)) continue; - const rootId = rootIdOf(reply); - const entry = rootId === null ? undefined : out.get(rootId); - if (!entry) continue; - entry.count += 1; - const author = idOf(reply.author_id); - if (!author || entry.repliers.length >= COMMENT_THREADS_MAX_REPLIERS) continue; - if (entry.repliers.some((r) => r.id === author)) continue; - entry.repliers.push({ - id: author, - name: typeof reply.author_name === 'string' && reply.author_name !== '' ? reply.author_name : null, - avatarUrl: typeof reply.author_avatar_url === 'string' && reply.author_avatar_url !== '' ? reply.author_avatar_url : null, - }); + if (rootId !== null && pageThreads.has(rootId)) placed.push({ rootId, row: reply }); } - return out; + return placed; } async function handleCommentThreadsQuery(req: IHttpRequest, res: IHttpResponse, deps: CommentThreadsQueryDeps): Promise { @@ -543,8 +785,13 @@ async function handleCommentThreadsQuery(req: IHttpRequest, res: IHttpResponse, } const engine = deps.getEngine(); - if (!engine || typeof engine.planReadScope !== 'function' || typeof engine.getSchema !== 'function') { - sendError(res, 503, 'SERVICE_UNAVAILABLE', 'Comment threads cannot be read right now: no data engine that plans a read scope is registered.'); + if (!engine || typeof engine.planReadScope !== 'function' || typeof engine.getSchema !== 'function' || typeof engine.aggregate !== 'function') { + sendError( + res, + 503, + 'SERVICE_UNAVAILABLE', + 'Comment threads cannot be read right now: no data engine that plans a read scope and serves a grouped read is registered.', + ); return; } diff --git a/packages/plugins/plugin-audit/src/objects/sys-comment.object.ts b/packages/plugins/plugin-audit/src/objects/sys-comment.object.ts index 3f9498e469f..607faa0845d 100644 --- a/packages/plugins/plugin-audit/src/objects/sys-comment.object.ts +++ b/packages/plugins/plugin-audit/src/objects/sys-comment.object.ts @@ -217,6 +217,37 @@ import { ObjectSchema, Field } from '@objectstack/spec/data'; * until `os migrate comment-participants --apply` writes their lists; until * then a participant filter does not find them. * + * ## Platform-written: the thread root `thread_root_id` + * + * Which thread a reply belongs to, stored on the reply so the comment threads + * read counts a thread's replies and picks its latest repliers with one grouped + * read by this column instead of following `parent_id` over every reply + * (`comment-threads-query.ts`). It is a pointer, not a roll-up: the count stays + * an aggregate over the replies, taken at read time (see `reply_count` above). + * + * - **The value.** On a reply, the id of the top-level comment its `parent_id` + * chain reaches within the record's discussion, by the participants rule (at + * most 16 hops, so a reply 16 or more levels deep is in no thread). A reply + * whose chain leaves the discussion or runs past the bound carries its OWN + * id: it is in no thread, and no top-level comment has that id. On a + * top-level comment it is `null`. A reply that carries `null` has not been + * stamped yet. + * - **The stamp.** On create, for every caller and over any value sent, a + * reply is stamped from its parent (the parent's id when the parent is + * top-level, else the parent's own root) and a top-level comment with + * `null`. The keeper that maintains `participants` brings every reply of the + * discussion to the rule in the same reconcile and the same system write, so + * a re-point or a delete moves the roots under it too. + * - **Read-only.** `readonly: true`: on update a non-system caller's value is + * stripped and reported (`droppedFields`), and dropped under `preserveAudit` + * too; on create the stamp is assigned over it. + * - **Stored rows.** Replies written before the column existed carry `null` + * until `os migrate comment-participants --apply` stamps them, or until the + * next write to their record's discussion reconciles it. Until then the + * threads read still counts them, by following `parent_id` for those rows + * only, so no reply count drops on a deployment that has not run the + * backfill. + * * @namespace sys */ export const SysComment = ObjectSchema.create({ @@ -387,6 +418,20 @@ export const SysComment = ObjectSchema.create({ group: 'Thread', }), + // ── Thread root ────────────────────────────────────────────── + // Platform-written (see "Platform-written: the thread root" above): the + // top-level comment a reply belongs to; its own id on a reply in no + // thread; `null` on a top-level comment, and on a reply not yet stamped. + thread_root_id: Field.text({ + label: 'Thread Root', + required: false, + readonly: true, + maxLength: 255, + description: + 'The top-level comment this reply belongs to (its own id when it is in no thread; empty on a top-level comment) — stamped by the platform, never written by authors', + group: 'Thread', + }), + // No `visibility` field: who can see a comment is decided by the record // `thread_id` points at (#4630, #4756) — one rule, no second source. @@ -411,6 +456,8 @@ export const SysComment = ObjectSchema.create({ // `object_name`, and its probe of unbackfilled rows is `object_name IS NULL`. { fields: ['object_name', 'record_id'] }, { fields: ['parent_id'] }, + // The threads read's grouped count of a page's replies, by thread. + { fields: ['thread_root_id'] }, { fields: ['author_id'] }, ], From 1e82ae1cac62986c5f6bc0a173e02e1b69c6063e Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 18:15:38 +0000 Subject: [PATCH 2/7] wip: tests for the stored thread root, the unstamped fallback and the millisecond keyset Claude-Session: https://claude.ai/code/session_01WGufziM2GUsShZcjp6TiyD Co-authored-by: Claude --- .../src/comment-participants.test.ts | 163 ++++++++++- .../comment-threads-query.integration.test.ts | 61 +++- .../src/comment-threads-query.test.ts | 267 ++++++++++++++++-- 3 files changed, 448 insertions(+), 43 deletions(-) diff --git a/packages/plugins/plugin-audit/src/comment-participants.test.ts b/packages/plugins/plugin-audit/src/comment-participants.test.ts index 3f6c45545b9..2a2e686e7ee 100644 --- a/packages/plugins/plugin-audit/src/comment-participants.test.ts +++ b/packages/plugins/plugin-audit/src/comment-participants.test.ts @@ -1,14 +1,20 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. import { describe, it, expect, vi } from 'vitest'; -import { participantsByThread, installCommentParticipants, reconcileCommentThreadParticipants } from './comment-participants.js'; +import { + installCommentParticipants, + participantsByThread, + reconcileCommentThreadParticipants, + threadRootByRow, +} from './comment-participants.js'; import { threadsInvolvingUser } from './comment-resolution.js'; /** * The pure half of the stored participant list: the derivation, pinned EQUAL * to the comment panel's "involving me" rule over the same rows, and the * keeper's decisions that need no engine (what a reconcile writes, what a - * failed rewrite reports). The engine-decided half — the column landing, the + * failed rewrite reports), and the thread root the same rule stores on each + * reply (its derivation, its reconcile, its create stamp). The engine-decided half — the column landing, the * filter, the backfill on SQL — is `comment-participants.integration.test.ts`. */ @@ -110,34 +116,34 @@ describe('reconcileCommentThreadParticipants — what one reconcile writes', () it('rewrites only the rows that differ, keeps updated_at as the platform, and a second run writes nothing', async () => { const rows: Row[] = [ { id: 'a', thread_id: T, parent_id: null, author_id: 'u_a', mentions: null, participants: ['u_a'], updated_at: 'T1', created_at: '1' }, - { id: 'a.1', thread_id: T, parent_id: 'a', author_id: 'u_b', mentions: JSON.stringify(['u_c']), participants: null, updated_at: 'T2', created_at: '2' }, + { id: 'a.1', thread_id: T, parent_id: 'a', thread_root_id: 'a', author_id: 'u_b', mentions: JSON.stringify(['u_c']), participants: null, updated_at: 'T2', created_at: '2' }, { id: 'z', thread_id: T, parent_id: null, author_id: 'u_z', mentions: null, participants: ['u_z'], updated_at: 'T3', created_at: '3' }, ]; const engine = discussionEngine(rows); const first = await reconcileCommentThreadParticipants(engine, T, { apply: true }); - expect(first).toEqual({ threads: 2, changed: 1, failures: 0 }); + expect(first).toEqual({ threads: 2, changed: 1, roots: 0, failures: 0 }); expect(engine.updates).toEqual([ { data: { id: 'a', participants: ['u_a', 'u_b', 'u_c'], updated_at: 'T1' }, options: { context: { isSystem: true, preserveAudit: true } } }, ]); const second = await reconcileCommentThreadParticipants(engine, T, { apply: true }); - expect(second).toEqual({ threads: 2, changed: 0, failures: 0 }); + expect(second).toEqual({ threads: 2, changed: 0, roots: 0, failures: 0 }); expect(engine.updates).toHaveLength(1); }); it('clears a list stored on a reply, and reads a list stored as JSON text', async () => { const rows: Row[] = [ { id: 'a', thread_id: T, parent_id: null, author_id: 'u_a', mentions: null, participants: '["u_a"]', created_at: '1' }, - { id: 'a.1', thread_id: T, parent_id: 'a', author_id: 'u_a', mentions: null, participants: ['u_a'], created_at: '2' }, + { id: 'a.1', thread_id: T, parent_id: 'a', thread_root_id: 'a', author_id: 'u_a', mentions: null, participants: ['u_a'], created_at: '2' }, ]; const engine = discussionEngine(rows); - expect(await reconcileCommentThreadParticipants(engine, T, { apply: true })).toEqual({ threads: 1, changed: 1, failures: 0 }); + expect(await reconcileCommentThreadParticipants(engine, T, { apply: true })).toEqual({ threads: 1, changed: 1, roots: 0, failures: 0 }); expect(engine.updates.map((u) => u.data)).toEqual([{ id: 'a.1', participants: null }]); }); it('dry-run counts and writes nothing', async () => { const rows: Row[] = [{ id: 'a', thread_id: T, parent_id: null, author_id: 'u_a', mentions: null, participants: null, created_at: '1' }]; const engine = discussionEngine(rows); - expect(await reconcileCommentThreadParticipants(engine, T, { apply: false })).toEqual({ threads: 1, changed: 1, failures: 0 }); + expect(await reconcileCommentThreadParticipants(engine, T, { apply: false })).toEqual({ threads: 1, changed: 1, roots: 0, failures: 0 }); expect(engine.updates).toHaveLength(0); }); }); @@ -174,7 +180,7 @@ describe('installCommentParticipants — the keeper', () => { it('a failed rewrite after a reply is reported at error, with the consequence and the remedy', async () => { const rows: Row[] = [ { id: 'a', thread_id: T, parent_id: null, author_id: 'u_a', mentions: null, participants: ['u_a'], created_at: '1' }, - { id: 'a.1', thread_id: T, parent_id: 'a', author_id: 'u_b', mentions: null, participants: null, created_at: '2' }, + { id: 'a.1', thread_id: T, parent_id: 'a', thread_root_id: 'a', author_id: 'u_b', mentions: null, participants: null, created_at: '2' }, ]; const engine = discussionEngine(rows, { failUpdate: true }); const error = vi.fn(); @@ -189,12 +195,12 @@ describe('installCommentParticipants — the keeper', () => { it('re-checks after a pass that wrote: a reply that landed after the read is put back by the next pass', async () => { const rows: Row[] = [ { id: 'a', thread_id: T, parent_id: null, author_id: 'u_a', mentions: null, participants: ['u_a'], created_at: '1' }, - { id: 'a.1', thread_id: T, parent_id: 'a', author_id: 'u_b', mentions: null, participants: null, created_at: '2' }, + { id: 'a.1', thread_id: T, parent_id: 'a', thread_root_id: 'a', author_id: 'u_b', mentions: null, participants: null, created_at: '2' }, ]; // B's reply's write lands; while it runs, C replies (a row the first pass never read). const engine = discussionEngine(rows, { afterUpdate: (n) => { - if (n === 1) rows.push({ id: 'a.2', thread_id: T, parent_id: 'a', author_id: 'u_c', mentions: null, participants: null, created_at: '3' }); + if (n === 1) rows.push({ id: 'a.2', thread_id: T, parent_id: 'a', thread_root_id: 'a', author_id: 'u_c', mentions: null, participants: null, created_at: '3' }); }, }); installCommentParticipants(engine, { warn: vi.fn() }); @@ -222,7 +228,7 @@ describe('installCommentParticipants — the keeper', () => { it('lets the engine\'s referential cleanup of a deleted user through, and reconciles a top-level comment an import stores', async () => { const rows: Row[] = [ { id: 'a', thread_id: T, parent_id: null, author_id: 'u_a', mentions: null, participants: null, created_at: '1' }, - { id: 'a.1', thread_id: T, parent_id: 'a', author_id: 'u_b', mentions: null, participants: null, created_at: '2' }, + { id: 'a.1', thread_id: T, parent_id: 'a', thread_root_id: 'a', author_id: 'u_b', mentions: null, participants: null, created_at: '2' }, ]; const engine = discussionEngine(rows); installCommentParticipants(engine, { warn: vi.fn() }); @@ -247,3 +253,136 @@ describe('installCommentParticipants — the keeper', () => { expect(engine.updates.map((u) => u.data.id)).toEqual(['a']); }); }); + +describe('threadRootByRow — the thread root, by the same rule', () => { + it('a reply at any depth carries its top-level comment; a top-level comment carries null; an orphan carries its own id', () => { + const roots = threadRootByRow(ROWS); + expect(roots.get('started')).toBeNull(); + expect(roots.get('replied.1')).toBe('replied'); + expect(roots.get('nested.1')).toBe('nested'); + expect(roots.get('nested.1.1')).toBe('nested'); + expect(roots.get('orphan')).toBe('orphan'); + }); + + it('places a reply in exactly the thread participantsByThread lists its author in, past the hop bound too', () => { + const chain: Row[] = [{ id: 'r', parent_id: null, author_id: 'u_root', mentions: null }]; + for (let i = 1; i <= 17; i++) chain.push({ id: `r.${i}`, parent_id: i === 1 ? 'r' : `r.${i - 1}`, author_id: `u_${i}`, mentions: null }); + const roots = threadRootByRow(chain); + const lists = participantsByThread(chain); + // Depth 15 is the deepest in a thread; depth 16 and deeper are in none. + expect(roots.get('r.15')).toBe('r'); + expect(roots.get('r.16')).toBe('r.16'); + expect(roots.get('r.17')).toBe('r.17'); + for (const row of chain.slice(1)) { + const inThread = roots.get(String(row.id)) === 'r'; + expect(lists.get('r')!.includes(String(row.author_id)), String(row.id)).toBe(inThread); + } + }); +}); + +describe('the thread root — reconcile and create stamp', () => { + const handler = (engine: ReturnType, event: string) => { + const found = engine.hooks.find((h) => h.event === event); + if (!found) throw new Error(`no ${event} hook`); + return found.handler; + }; + + it('a reconcile writes each wrong root, naming only the column that differs, and a second run writes nothing', async () => { + const rows: Row[] = [ + { id: 'a', thread_id: T, parent_id: null, author_id: 'u_a', mentions: null, participants: ['u_a', 'u_b'], thread_root_id: 'stale', updated_at: 'T1', created_at: '1' }, + { id: 'a.1', thread_id: T, parent_id: 'a', author_id: 'u_b', mentions: null, participants: null, updated_at: 'T2', created_at: '2' }, + { id: 'a.1.1', thread_id: T, parent_id: 'a.1', author_id: 'u_b', mentions: null, participants: null, thread_root_id: 'a', created_at: '3' }, + { id: 'lost', thread_id: T, parent_id: 'gone', author_id: 'u_b', mentions: null, participants: null, created_at: '4' }, + ]; + const engine = discussionEngine(rows); + const first = await reconcileCommentThreadParticipants(engine, T, { apply: true }); + expect(first).toEqual({ threads: 1, changed: 3, roots: 3, failures: 0 }); + expect(engine.updates.map((u) => u.data)).toEqual([ + { id: 'a', thread_root_id: null, updated_at: 'T1' }, + { id: 'a.1', thread_root_id: 'a', updated_at: 'T2' }, + { id: 'lost', thread_root_id: 'lost' }, + ]); + expect(await reconcileCommentThreadParticipants(engine, T, { apply: true })).toEqual({ threads: 1, changed: 0, roots: 0, failures: 0 }); + }); + + it('roots: false leaves the root alone (a sys_comment that does not declare it)', async () => { + const rows: Row[] = [ + { id: 'a', thread_id: T, parent_id: null, author_id: 'u_a', mentions: null, participants: ['u_a', 'u_b'], created_at: '1' }, + { id: 'a.1', thread_id: T, parent_id: 'a', author_id: 'u_b', mentions: null, participants: null, created_at: '2' }, + ]; + const engine = discussionEngine(rows); + expect(await reconcileCommentThreadParticipants(engine, T, { apply: true, roots: false })).toEqual({ threads: 1, changed: 0, roots: 0, failures: 0 }); + expect(engine.updates).toHaveLength(0); + }); + + it('a delete that strands a reply re-roots it to its own id; a re-point moves its root', async () => { + const rows: Row[] = [ + { id: 'a', thread_id: T, parent_id: null, author_id: 'u_a', mentions: null, participants: ['u_a', 'u_b'], created_at: '1' }, + { id: 'b', thread_id: T, parent_id: null, author_id: 'u_a', mentions: null, participants: ['u_a'], created_at: '2' }, + { id: 'a.1', thread_id: T, parent_id: 'a', thread_root_id: 'a', author_id: 'u_b', mentions: null, participants: null, created_at: '3' }, + { id: 'a.1.1', thread_id: T, parent_id: 'a.1', thread_root_id: 'a', author_id: 'u_b', mentions: null, participants: null, created_at: '4' }, + ]; + const engine = discussionEngine(rows); + installCommentParticipants(engine, { warn: vi.fn() }); + // a.1 is re-pointed under b: it and its reply move. + rows[2]!.parent_id = 'b'; + await handler(engine, 'afterUpdate')({ result: rows[2], input: { data: { parent_id: 'b' } }, previous: rows[2] }); + expect([rows[2]!.thread_root_id, rows[3]!.thread_root_id]).toEqual(['b', 'b']); + // a.1 is deleted: its reply is stranded, in no thread. + const [deleted] = rows.splice(2, 1); + await handler(engine, 'afterDelete')({ previous: deleted, input: {} }); + expect(rows.find((r) => r.id === 'a.1.1')!.thread_root_id).toBe('a.1.1'); + }); + + it('a create stamps a reply from its parent and a top-level comment with null, over a client value', async () => { + const parents: Row[] = [ + { id: 'top', thread_id: T, parent_id: null }, + { id: 'top.1', thread_id: T, parent_id: 'top', thread_root_id: 'top' }, + { id: 'unstamped', thread_id: T, parent_id: 'top', thread_root_id: null }, + { id: 'stranded', thread_id: T, parent_id: 'gone', thread_root_id: 'stranded' }, + { id: 'elsewhere', thread_id: 'doc:2', parent_id: null }, + ]; + const engine = discussionEngine(parents); + const reads: Row[] = []; + const find = engine.find; + engine.find = async (object: string, query: Row) => { + reads.push(query); + const where = (query?.where ?? {}) as Row; + const ids = (where.id as { $in?: string[] } | undefined)?.$in; + return ids ? parents.filter((p) => ids.includes(String(p.id))) : find(object, query); + }; + installCommentParticipants(engine, { warn: vi.fn() }); + const make = (parent: string | null): Row => ({ thread_id: T, parent_id: parent, author_id: 'u_x', thread_root_id: 'forged' }); + const rows = [make(null), make('top'), make('top.1'), make('unstamped'), make('stranded'), make('elsewhere'), make('missing')]; + await handler(engine, 'beforeInsert')({ input: { data: rows } }); + expect(rows.map((r) => r.thread_root_id)).toEqual([null, 'top', 'top', null, null, null, null]); + // One read of the parents, as the platform. + expect(reads).toHaveLength(1); + expect(reads[0]!.context).toEqual({ isSystem: true }); + }); + + it('a parent read that fails stamps null and says so at warn; the insert goes on', async () => { + const engine = discussionEngine([]); + engine.find = async () => { + throw new Error('db down'); + }; + const warn = vi.fn(); + installCommentParticipants(engine, { warn }); + const reply: Row = { thread_id: T, parent_id: 'p', author_id: 'u_x', thread_root_id: 'forged' }; + await handler(engine, 'beforeInsert')({ input: { data: reply } }); + expect(reply.thread_root_id).toBeNull(); + expect(warn).toHaveBeenCalledTimes(1); + }); + + it('a non-system update\'s root never lands; the platform\'s own write does', async () => { + const engine = discussionEngine([]); + installCommentParticipants(engine, { warn: vi.fn() }); + const before = handler(engine, 'beforeUpdate'); + const forged: Row = { thread_root_id: 'x', body: 'y' }; + await before({ session: { userId: 'u_a', preserveAudit: true }, input: { data: forged } }); + expect(forged).toEqual({ body: 'y' }); + const platform: Row = { thread_root_id: 'a' }; + await before({ session: { isSystem: true, preserveAudit: true }, input: { data: platform } }); + expect(platform).toEqual({ thread_root_id: 'a' }); + }); +}); diff --git a/packages/plugins/plugin-audit/src/comment-threads-query.integration.test.ts b/packages/plugins/plugin-audit/src/comment-threads-query.integration.test.ts index 81d0b3ae6fe..107440e5723 100644 --- a/packages/plugins/plugin-audit/src/comment-threads-query.integration.test.ts +++ b/packages/plugins/plugin-audit/src/comment-threads-query.integration.test.ts @@ -14,7 +14,10 @@ * title field, the resolved and "involving me" toggles over the stored * columns, and the keyset cursor walking every thread exactly once while a * comment is posted between pages and while two threads share a creation - * time. + * time; and the reply count and repliers taken from the stored thread root + * (a reply three deep counted, the latest three distinct repliers, an orphan + * left out) giving the same answer to two users before the backfill (no + * reply stamped), half way through it, and after it. * * The composition with the security service — members with different row * scope, a view past the id cap answered in full as one threads statement, @@ -29,6 +32,7 @@ import { ObjectQL, ObjectQLPlugin } from '@objectstack/objectql'; import { SqliteWasmDriver } from '@objectstack/driver-sqlite-wasm'; import { AuditPlugin } from './audit-plugin.js'; +import { backfillCommentParticipants } from './comment-participants-backfill.js'; import { queryCommentThreads } from './comment-threads-query.js'; import { installDefaultOrganization } from './default-organization.testkit.js'; @@ -178,4 +182,59 @@ describe('the comment threads read on the real engine and SQLite', () => { } expect(walked).toEqual([root.a4, ...[tieA, tieB].sort().reverse()]); }); + + it('counts a reply three deep, names the latest three distinct repliers and leaves an orphan out — the same for two users before, during and after the backfill', async () => { + const key = 'a6'; + acc[key] = String((await engine.insert(ACCOUNT, { title: 'Account a6', status: 'review' }, { context: SYS })).id); + const driver = engine.getDriverForObject(COMMENT) as any; + let minute = 0; + // Each comment one minute after the last, so "newest" never rests on a tie. + const at = async (id: string) => { + minute += 1; + await driver.update(COMMENT, id, { created_at: `2021-03-01T10:${String(minute).padStart(2, '0')}:00.000Z` }); + return id; + }; + const top = await at(await post(key, ANN)); + const r1 = await at(await post(key, BEN, { parent_id: top })); + const r2 = await at(await post(key, CAL, { parent_id: r1 })); + const r3 = await at(await post(key, DEE, { parent_id: r2 })); + const r4 = await at(await post(key, ANN, { parent_id: top })); + const r5 = await at(await post(key, BEN, { parent_id: r3 })); + // An orphan on the same record: its parent is a comment of another record's discussion. + const orphan = await at( + String((await engine.insert(COMMENT, { thread_id: `${ACCOUNT}:${acc[key]}`, body: 'lost', parent_id: root.a1 }, { context: SYS })).id), + ); + const replyIds = [r1, r2, r3, r4, r5, orphan]; + const stored = async (id: string) => (await engine.findOne(COMMENT, { where: { id }, context: SYS })) as Row; + expect((await stored(r3)).thread_root_id).toBe(top); + expect((await stored(orphan)).thread_root_id).toBe(orphan); + + const filter = [['status', '=', 'review']]; + const answerFor = async (by: Row) => { + const answer = await read(by, { filter }); + return answer.threads.map((t) => ({ id: String(t.comment.id), replyCount: t.replyCount, repliers: t.repliers.map((r) => r.id) })); + }; + const expected = [{ id: top, replyCount: 5, repliers: ['u_ben', 'u_ann', 'u_dee'] }]; + expect(await answerFor(ANN)).toEqual(expected); + expect(await answerFor(BEN)).toEqual(expected); + + // A database written before the column: no reply stamped. The counts hold. + for (const id of replyIds) await driver.update(COMMENT, id, { thread_root_id: null }); + expect(await answerFor(ANN)).toEqual(expected); + expect(await answerFor(BEN)).toEqual(expected); + + // Half way: some replies stamped, some not. The counts hold. + await driver.update(COMMENT, r1, { thread_root_id: top }); + await driver.update(COMMENT, r5, { thread_root_id: top }); + expect(await answerFor(ANN)).toEqual(expected); + + // After the backfill every reply carries its root, and the answer is the same. + const report = await backfillCommentParticipants(engine as any, { info() {}, warn() {} }, { apply: true }); + expect(report.failures).toBe(0); + expect((await stored(r2)).thread_root_id).toBe(top); + expect((await stored(r3)).thread_root_id).toBe(top); + expect((await stored(orphan)).thread_root_id).toBe(orphan); + expect(await answerFor(ANN)).toEqual(expected); + expect(await answerFor(BEN)).toEqual(expected); + }); }); diff --git a/packages/plugins/plugin-audit/src/comment-threads-query.test.ts b/packages/plugins/plugin-audit/src/comment-threads-query.test.ts index bad001bd7bb..58c3d642824 100644 --- a/packages/plugins/plugin-audit/src/comment-threads-query.test.ts +++ b/packages/plugins/plugin-audit/src/comment-threads-query.test.ts @@ -6,8 +6,10 @@ * read gives before the engine is asked, the reads it hands the engine (each * one carrying the caller's own context, the planned scope placed in the one * threads read), the per-request planning of that scope for two users, the - * cursor, and the thread assembly (reply count at any depth, latest distinct - * repliers, record names). + * cursor at millisecond precision (the boundary millisecond read again by + * id), the statements one page costs, and the thread assembly (reply counts + * from the grouped read by stored root plus the unstamped replies placed by + * the old walk, latest distinct repliers, record names). * * The same read on the real engine and SQL driver — one statement for the * threads, a view past the id cap answered in full, the comment read gate — @@ -21,10 +23,11 @@ import { COMMENT_THREADS_DEFAULT_LIMIT, COMMENT_THREADS_MAX_LIMIT } from '@objec import { COMMENT_THREADS_QUERY_ROUTE, + assembleThreadExtras, decodeThreadsCursor, encodeThreadsCursor, + instantMs, registerCommentThreadsQueryRoute, - threadExtras, type CommentThreadsEngine, type CommentThreadsQueryDeps, } from './comment-threads-query.js'; @@ -46,16 +49,40 @@ const BEN = { userId: 'u_ben', positions: ['org_member'], permissions: [] } as a interface Recorded { plans: Array<{ object: string; target: string; options: any; scope: object }>; finds: Array<{ object: string; query: any }>; + aggregates: Array<{ object: string; query: any; options: any }>; +} + +/** Which of the read's `sys_comment` finds a query is, by its shape. */ +function kindOf(query: any): 'threads' | 'edge' | 'unstamped' | 'newest' | 'ancestors' | 'other' { + const where = query.where ?? {}; + if (where.parent_id?.$null === true) return 'threads'; + if (Array.isArray(where.$and) && where.$and[0]?.parent_id?.$null === true) return 'edge'; + if (where.thread_root_id?.$null === true) return 'unstamped'; + if (Array.isArray(where.$or) && where.$or[0]?.$and?.[0]?.thread_root_id !== undefined) return 'newest'; + if (where.id?.$in) return 'ancestors'; + return 'other'; } /** * An engine that records every call. `planReadScope` answers a fresh token per * call, so a test can tell which call's scope a later read carries. `threads` - * is what the threads read answers; replies and records come from `replies` - * and `records`. + * is what the threads read answers (`edge` the boundary millisecond's re-read); + * `groups` the grouped read; `newest` the candidate repliers' read; + * `unstamped` and `ancestors` the unstamped walk; `records` the names read. */ -function recordingEngine(opts: { threads?: Row[]; replies?: Row[]; records?: Row[]; planError?: Error } = {}) { - const recorded: Recorded = { plans: [], finds: [] }; +function recordingEngine( + opts: { + threads?: Row[]; + edge?: Row[]; + groups?: Row[]; + newest?: Row[]; + unstamped?: Row[]; + ancestors?: Row[]; + records?: Row[]; + planError?: Error; + } = {}, +) { + const recorded: Recorded = { plans: [], finds: [], aggregates: [] }; const engine: CommentThreadsEngine & { recorded: Recorded } = { recorded, getSchema: vi.fn((object: string) => SCHEMAS[object]), @@ -67,9 +94,25 @@ function recordingEngine(opts: { threads?: Row[]; replies?: Row[]; records?: Row }), find: vi.fn(async (object: string, query: any) => { recorded.finds.push({ object, query }); - if (object === 'sys_comment' && query.where?.parent_id?.$null === true) return (opts.threads ?? []).slice(0, query.limit); - if (object === 'sys_comment') return opts.replies ?? []; - return opts.records ?? []; + if (object !== 'sys_comment') return opts.records ?? []; + switch (kindOf(query)) { + case 'threads': + return (opts.threads ?? []).slice(0, query.limit); + case 'edge': + return (opts.edge ?? []).slice(0, query.limit); + case 'unstamped': + return query.where.id?.$gt ? [] : opts.unstamped ?? []; + case 'newest': + return opts.newest ?? []; + case 'ancestors': + return (opts.ancestors ?? []).filter((r) => query.where.id.$in.includes(r.id)); + default: + return []; + } + }), + aggregate: vi.fn(async (object: string, query: any, options: any) => { + recorded.aggregates.push({ object, query, options }); + return opts.groups ?? []; }), }; return engine; @@ -382,7 +425,7 @@ describe('the comment threads read — what it hands the engine', () => { thread('c2', 'a1', '2026-12-02T10:00:02.000Z'), thread('c1', 'a1', '2026-12-02T10:00:01.000Z'), ]; - const engine = recordingEngine({ threads: rows }); + const engine = recordingEngine({ threads: rows, edge: [rows[1]] }); const first = await call(as(ANN, engine), { body: { object: ACCOUNT, limit: 2 } }); expect(first.body.data.threads.map((t: Row) => t.comment.id)).toEqual(['c3', 'c2']); expect(decodeThreadsCursor(first.body.data.nextCursor)).toEqual({ createdAt: '2026-12-02T10:00:02.000Z', id: 'c2' }); @@ -391,10 +434,57 @@ describe('the comment threads read — what it hands the engine', () => { const second = await call(as(ANN, engine2), { body: { object: ACCOUNT, limit: 2, cursor: first.body.data.nextCursor } }); expect(second.body.data.nextCursor).toBeNull(); const [read] = engine2.recorded.finds; + // Truncated on both sides: before the millisecond, or in it with a smaller id. expect(read.query.where.$or).toEqual([ { created_at: { $lt: '2026-12-02T10:00:02.000Z' } }, - { $and: [{ created_at: '2026-12-02T10:00:02.000Z' }, { id: { $lt: 'c2' } }] }, + { + $and: [ + { created_at: { $gte: '2026-12-02T10:00:02.000Z' } }, + { created_at: { $lt: '2026-12-02T10:00:02.001Z' } }, + { id: { $lt: 'c2' } }, + ], + }, ]); + // The last page re-reads no boundary millisecond. + expect(engine2.recorded.finds.filter((f) => kindOf(f.query) === 'edge')).toHaveLength(0); + }); + + it('a full page re-reads its last millisecond by id, so the page and the cursor agree on which of its threads were answered', async () => { + // Three threads in one millisecond (microseconds apart on PostgreSQL, read + // back alike): the threads read answers them in microsecond order, which is + // not id order; the re-read answers them by id, newest id first. + const ms = '2026-12-02T10:00:02.000Z'; + const top = thread('c9', 'a1', '2026-12-02T10:00:05.000Z'); + const [x, y, z] = [thread('cx', 'a1', ms), thread('cy', 'a1', ms), thread('cz', 'a1', ms)]; + const engine = recordingEngine({ threads: [top, x, z, y], edge: [z, y, x] }); + const answer = await call(as(ANN, engine), { body: { object: ACCOUNT, limit: 2 } }); + expect(answer.body.data.threads.map((t: Row) => t.comment.id)).toEqual(['c9', 'cz']); + expect(decodeThreadsCursor(answer.body.data.nextCursor)).toEqual({ createdAt: ms, id: 'cz' }); + + const [threads, edge] = engine.recorded.finds.filter((f) => ['threads', 'edge'].includes(kindOf(f.query))); + expect(edge.query.context).toBe(ANN); + expect(edge.query.where.$and).toEqual([ + threads.query.where, + { created_at: { $gte: ms } }, + { created_at: { $lt: '2026-12-02T10:00:02.001Z' } }, + ]); + expect(edge.query.orderBy).toEqual([{ field: 'id', order: 'desc' }]); + // Room left on the page (1) plus one. + expect(edge.query.limit).toBe(2); + }); + + it('reads a stored instant at the millisecond, whatever the driver spells', () => { + const at = Date.parse('2026-12-02T10:00:02.123Z'); + expect(instantMs('2026-12-02T10:00:02.123Z')).toBe(at); + expect(instantMs('2026-12-02T10:00:02.123456Z')).toBe(at); + expect(instantMs('2026-12-02 10:00:02.123456+00')).toBe(at); + expect(instantMs('2026-12-02 18:00:02.1239+0800')).toBe(at); + expect(instantMs('2026-12-02T18:00:02.123+08:00')).toBe(at); + expect(instantMs(new Date(at))).toBe(at); + expect(instantMs(at)).toBe(at); + expect(instantMs('{30_days_ago}')).toBeNull(); + expect(instantMs('')).toBeNull(); + expect(instantMs(null)).toBeNull(); }); it('a Date creation time keys the cursor by its ISO text', () => { @@ -409,36 +499,144 @@ describe('the comment threads read — what it hands the engine', () => { const answer = await call(as(ANN, engine), { body: { object: ACCOUNT } }); expect(answer.body.data).toEqual({ threads: [], nextCursor: null }); expect(engine.recorded.finds).toHaveLength(1); + expect(engine.recorded.aggregates).toHaveLength(0); + }); + + it('a backfilled page costs the same statements whatever its reply count: threads, grouped read, newest repliers, unstamped probe, names', async () => { + const page = [thread('c2', 'a2', '2026-12-02T10:00:02.000Z'), thread('c1', 'a1', '2026-12-02T10:00:01.000Z')]; + const groups = [ + { thread_root_id: 'c1', author_id: 'u_ben', replies: 4_000, latest: '2026-12-02T11:00:00.000Z' }, + { thread_root_id: 'c1', author_id: 'u_cal', replies: 6_000, latest: '2026-12-02T12:00:00.000Z' }, + ]; + const engine = recordingEngine({ threads: page, groups, records: [{ id: 'a1', name: 'Acme' }] }); + const answer = await call(as(ANN, engine), { body: { object: ACCOUNT } }); + expect(answer.status, JSON.stringify(answer.body)).toBe(200); + expect(answer.body.data.threads.find((t: Row) => t.comment.id === 'c1').replyCount).toBe(10_000); + + expect(engine.recorded.finds.map((f) => (f.object === 'sys_comment' ? kindOf(f.query) : f.object)).sort()).toEqual( + ['account', 'newest', 'threads', 'unstamped'].sort(), + ); + expect(engine.recorded.aggregates).toHaveLength(1); + const [agg] = engine.recorded.aggregates; + expect(agg.options.context).toBe(ANN); + expect(agg.query).toEqual({ + where: { object_name: ACCOUNT, record_id: { $in: ['a2', 'a1'] }, thread_root_id: { $in: ['c2', 'c1'] } }, + groupBy: ['thread_root_id', 'author_id'], + aggregations: [ + { function: 'count', field: 'id', alias: 'replies' }, + { function: 'max', field: 'created_at', alias: 'latest' }, + ], + }); + // The newest reply of each candidate author, in the millisecond its group named. + const newest = engine.recorded.finds.find((f) => kindOf(f.query) === 'newest')!; + expect(newest.query.where.$or).toContainEqual({ + $and: [ + { thread_root_id: 'c1' }, + { author_id: 'u_cal' }, + { created_at: { $gte: '2026-12-02T12:00:00.000Z' } }, + { created_at: { $lt: '2026-12-02T12:00:00.001Z' } }, + ], + }); + const unstamped = engine.recorded.finds.find((f) => kindOf(f.query) === 'unstamped')!; + expect(unstamped.query.where).toEqual({ + object_name: ACCOUNT, + record_id: { $in: ['a2', 'a1'] }, + parent_id: { $null: false }, + thread_root_id: { $null: true }, + }); + for (const f of engine.recorded.finds) expect(f.query.context, f.object).toBe(ANN); + }); + + it('no engine that serves a grouped read is 503 SERVICE_UNAVAILABLE', async () => { + const engine = recordingEngine() as any; + delete engine.aggregate; + const answer = await call(as(ANN, engine), { body: { object: ACCOUNT } }); + expect(answer.status).toBe(503); + expect(answer.body.error.code).toBe('SERVICE_UNAVAILABLE'); + expect(engine.recorded.finds).toHaveLength(0); }); }); describe('the comment threads read — the thread assembly', () => { - it('counts replies at any depth, names the latest three distinct repliers newest first, and leaves an orphan out', () => { - const roots = [thread('t1', 'a1', '2026-12-02T09:00:00.000Z'), thread('t2', 'a2', '2026-12-02T09:00:00.000Z')]; - // Newest first, as the replies read orders them. - const replies: Row[] = [ - { id: 'r6', parent_id: 'r1', author_id: 'u_dee', author_name: 'Dee', author_avatar_url: null }, - { id: 'r5', parent_id: 'r2', author_id: 'u_cal', author_name: 'Cal', author_avatar_url: 'https://x/c.png' }, - { id: 'r4', parent_id: 't1', author_id: 'u_dee', author_name: 'Dee', author_avatar_url: null }, - { id: 'r3', parent_id: 't1', author_id: 'u_eve', author_name: '', author_avatar_url: '' }, - { id: 'r2', parent_id: 't1', author_id: 'u_ben', author_name: 'Ben', author_avatar_url: null }, - { id: 'r1', parent_id: 't1', author_id: 'u_ann', author_name: 'Ann', author_avatar_url: null }, - { id: 'rx', parent_id: 'gone', author_id: 'u_zed', author_name: 'Zed', author_avatar_url: null }, + it('counts the grouped stamped replies plus the unstamped ones, and names the latest three distinct repliers newest first', () => { + const reply = (id: string, rootId: string, author: string, at: string, extra: Row = {}) => ({ + rootId, + row: { id, author_id: author, author_name: author.slice(2), author_avatar_url: null, created_at: at, ...extra }, + }); + const groups = [ + { rootId: 't1', authorId: 'u_ann', count: 2, latestMs: Date.parse('2026-12-02T09:01:00.000Z') }, + { rootId: 't1', authorId: 'u_dee', count: 1, latestMs: Date.parse('2026-12-02T09:05:00.000Z') }, + { rootId: 'elsewhere', authorId: 'u_zed', count: 9, latestMs: Date.parse('2026-12-02T09:09:00.000Z') }, + ]; + const newest = [ + reply('r4', 't1', 'u_dee', '2026-12-02T09:05:00.000Z'), + reply('r1', 't1', 'u_ann', '2026-12-02T09:01:00.000Z'), + ]; + const unstamped = [ + reply('r5', 't1', 'u_cal', '2026-12-02T09:06:00.000Z', { author_avatar_url: 'https://x/c.png' }), + reply('r3', 't1', 'u_eve', '2026-12-02T09:03:00.000Z', { author_name: '', author_avatar_url: '' }), + reply('r6', 't1', 'u_dee', '2026-12-02T09:04:00.000Z'), ]; - const extras = threadExtras(roots, replies); + const extras = assembleThreadExtras(['t1', 't2'], groups, newest, unstamped); expect(extras.get('t1')?.count).toBe(6); expect(extras.get('t1')?.repliers).toEqual([ - { id: 'u_dee', name: 'Dee', avatarUrl: null }, - { id: 'u_cal', name: 'Cal', avatarUrl: 'https://x/c.png' }, + { id: 'u_cal', name: 'cal', avatarUrl: 'https://x/c.png' }, + { id: 'u_dee', name: 'dee', avatarUrl: null }, { id: 'u_eve', name: null, avatarUrl: null }, ]); expect(extras.get('t2')).toEqual({ count: 0, repliers: [] }); + expect(extras.has('elsewhere')).toBe(false); + }); + + it('an unstamped reply is placed by following parent_id within its discussion, ancestors read a level at a time; an orphan and a reply past the bound count nowhere', async () => { + const D = 'account:a1'; + const at = '2026-12-02T09:00:00.000Z'; + const r = (id: string, parent: string | null, extra: Row = {}) => ({ + id, + parent_id: parent, + thread_id: D, + author_id: `u_${id}`, + author_name: id, + created_at: at, + ...extra, + }); + // r3 is three deep under c1 through two stamped ancestors (read as + // ancestors); rx's parent is gone; ro's parent is on another discussion; + // deep16 is 16 levels under c1 (in no thread). + const chain: Row[] = []; + let parent = 'c1'; + for (let depth = 1; depth <= 15; depth++) { + chain.push(r(`d${depth}`, parent, { thread_root_id: 'c1' })); + parent = `d${depth}`; + } + const engine = recordingEngine({ + threads: [thread('c1', 'a1', at, { thread_id: D })], + unstamped: [r('r3', 's2'), r('rx', 'gone'), r('ro', 'other'), r('deep16', 'd15')], + ancestors: [ + r('s2', 's1', { thread_root_id: 'c1' }), + r('s1', 'c1', { thread_root_id: 'c1' }), + { id: 'c1', parent_id: null, thread_id: D }, + { id: 'other', parent_id: null, thread_id: 'account:a2' }, + ...chain, + ], + }); + const answer = await call(as(ANN, engine), { body: { object: ACCOUNT } }); + expect(answer.status, JSON.stringify(answer.body)).toBe(200); + const [c1] = answer.body.data.threads; + expect(c1.replyCount).toBe(1); + expect(c1.repliers.map((x: Row) => x.id)).toEqual(['u_r3']); + const ancestorReads = engine.recorded.finds.filter((f) => kindOf(f.query) === 'ancestors'); + expect(ancestorReads.length).toBeLessThanOrEqual(16); + for (const f of ancestorReads) expect(f.query.context).toBe(ANN); }); it('each thread carries the record id and its display name, read as the caller; a record not read falls to the floor', async () => { const engine = recordingEngine({ threads: [thread('c2', 'a2', '2026-12-02T10:00:02.000Z'), thread('c1', 'a1', '2026-12-02T10:00:01.000Z')], - replies: [{ id: 'r1', parent_id: 'c1', author_id: 'u_ben', author_name: 'Ben', author_avatar_url: null }], + groups: [{ thread_root_id: 'c1', author_id: 'u_ben', replies: 1, latest: '2026-12-02T10:30:00.000Z' }], + newest: [ + { id: 'r1', parent_id: 'c1', thread_root_id: 'c1', author_id: 'u_ben', author_name: 'Ben', author_avatar_url: null, created_at: '2026-12-02T10:30:00.000Z' }, + ], records: [{ id: 'a1', name: 'Acme' }], }); const answer = await call(as(ANN, engine), { body: { object: ACCOUNT } }); @@ -450,8 +648,17 @@ describe('the comment threads read — the thread assembly', () => { const namesRead = engine.recorded.finds.find((f) => f.object === ACCOUNT); expect(namesRead?.query.where).toEqual({ id: { $in: ['a2', 'a1'] } }); expect(namesRead?.query.fields).toEqual(['id', 'name']); - const repliesRead = engine.recorded.finds.find((f) => f.object === 'sys_comment' && f.query.where?.parent_id?.$null === false); - expect(repliesRead?.query.where).toMatchObject({ object_name: ACCOUNT, record_id: { $in: ['a2', 'a1'] } }); - expect(repliesRead?.query.fields).toEqual(['id', 'parent_id', 'author_id', 'author_name', 'author_avatar_url', 'created_at']); + const newestRead = engine.recorded.finds.find((f) => kindOf(f.query) === 'newest'); + expect(newestRead?.query.where).toMatchObject({ object_name: ACCOUNT, record_id: { $in: ['a2', 'a1'] } }); + expect(newestRead?.query.fields).toEqual([ + 'id', + 'parent_id', + 'thread_id', + 'thread_root_id', + 'author_id', + 'author_name', + 'author_avatar_url', + 'created_at', + ]); }); }); From c771cfbe8b038dd2eddbbe007c424447a241490a Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 18:16:34 +0000 Subject: [PATCH 3/7] wip: integration pins for the thread root stamp, re-point and backfill Claude-Session: https://claude.ai/code/session_01WGufziM2GUsShZcjp6TiyD Co-authored-by: Claude --- .../comment-participants.integration.test.ts | 57 ++++++++++++++++++- 1 file changed, 56 insertions(+), 1 deletion(-) diff --git a/packages/plugins/plugin-audit/src/comment-participants.integration.test.ts b/packages/plugins/plugin-audit/src/comment-participants.integration.test.ts index feda3f61347..45178780364 100644 --- a/packages/plugins/plugin-audit/src/comment-participants.integration.test.ts +++ b/packages/plugins/plugin-audit/src/comment-participants.integration.test.ts @@ -10,7 +10,10 @@ * read (each reader under their own context, through the comment read gate), * the after-write keeper's rewrite on a reply, a mention edit and a delete, * the client's value never landing (and the update-side strip reporting it), - * and the stored-row backfill making pre-existing threads findable, once. + * and the stored-row backfill making pre-existing threads findable, once; and + * the thread root the same keeper stores on each reply (stamped at create, + * moved by a re-point, never a client's value, and backfilled, including on a + * discussion with no top-level comment left). */ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; @@ -226,4 +229,56 @@ describe('sys_comment — a thread stores its participants, and "involving me" i expect(again.changed).toBe(0); expect(again.failures).toBe(0); }); + + it('a reply is stored with its thread root at any depth, a top-level comment with none, and a client\'s value never lands', async () => { + const thread = await newThread(); + const root = await post(thread, A, { thread_root_id: 'forged' }); + const r1 = await post(thread, B, { parent_id: root, thread_root_id: 'forged' }); + const r2 = await post(thread, C, { parent_id: r1 }); + const r3 = await post(thread, D, { parent_id: r2 }); + expect((await read(root)).thread_root_id ?? null).toBeNull(); + expect([(await read(r1)).thread_root_id, (await read(r2)).thread_root_id, (await read(r3)).thread_root_id]).toEqual([root, root, root]); + + const update = await engine.update(COMMENT, { id: r1, thread_root_id: 'forged' }, { context: B }); + expect((await read(r1)).thread_root_id).toBe(root); + expect(JSON.stringify(update ?? null)).not.toContain('"thread_root_id":"forged"'); + }); + + it('a reply moved under another thread of the record takes its replies\' roots with it', async () => { + const thread = await newThread(); + const x = await post(thread, A); + const y = await post(thread, A); + const r1 = await post(thread, B, { parent_id: x }); + const r2 = await post(thread, C, { parent_id: r1 }); + await engine.update(COMMENT, { id: r1, parent_id: y }, { context: B }); + expect([(await read(r1)).thread_root_id, (await read(r2)).thread_root_id]).toEqual([y, y]); + }); + + it('the backfill stamps replies written before the column, on a discussion with no top-level comment left too', async () => { + const thread = await newThread(); + const root = await post(thread, A); + const r1 = await post(thread, B, { parent_id: root }); + const r2 = await post(thread, C, { parent_id: r1 }); + // A discussion whose only comment is a reply to a comment of another discussion: in no thread. + const lonely = await newThread(); + const stray = String((await engine.insert(COMMENT, { thread_id: lonely, body: 'stray', parent_id: root }, { context: SYS })).id); + expect((await read(stray)).thread_root_id).toBe(stray); + const driver = engine.getDriverForObject(COMMENT) as any; + for (const id of [r1, r2, stray]) await driver.update(COMMENT, id, { thread_root_id: null }); + + const dry = await backfillCommentParticipants(engine as any, silentLogger); + expect(dry.roots).toBeGreaterThanOrEqual(3); + expect((await read(r2)).thread_root_id ?? null).toBeNull(); + + const applied = await backfillCommentParticipants(engine as any, silentLogger, { apply: true, pageSize: 1 }); + expect(applied.failures).toBe(0); + expect(applied.roots).toBe(dry.roots); + expect([(await read(r1)).thread_root_id, (await read(r2)).thread_root_id, (await read(stray)).thread_root_id]).toEqual([root, root, stray]); + // Keeping the root is not an edit of the reply. + expect((await read(r2)).is_edited ?? false).toBe(false); + + const again = await backfillCommentParticipants(engine as any, silentLogger, { apply: true }); + expect(again.changed).toBe(0); + expect(again.roots).toBe(0); + }); }); From b22cc32657b6634663c9a97cd4c8004e560e6d22 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 18:19:06 +0000 Subject: [PATCH 4/7] wip: docs, CLI wording, census row and changeset for the thread root Claude-Session: https://claude.ai/code/session_01WGufziM2GUsShZcjp6TiyD Co-authored-by: Claude --- .changeset/39142-comment-thread-root.md | 17 ++++++++++ content/docs/api/data-api.mdx | 16 ++++++--- content/docs/deployment/cli.mdx | 25 ++++++++++---- content/docs/permissions/system-context.mdx | 2 +- .../commands/migrate/comment-participants.ts | 34 +++++++++++-------- .../plugin-audit/src/comment-threads-query.ts | 4 +-- packages/plugins/plugin-audit/src/index.ts | 7 ++-- .../src/objects/sys-comment.object.ts | 4 +-- 8 files changed, 77 insertions(+), 32 deletions(-) create mode 100644 .changeset/39142-comment-thread-root.md diff --git a/.changeset/39142-comment-thread-root.md b/.changeset/39142-comment-thread-root.md new file mode 100644 index 00000000000..7c77082131c --- /dev/null +++ b/.changeset/39142-comment-thread-root.md @@ -0,0 +1,17 @@ +--- +'@objectstack/plugin-audit': patch +'@objectstack/cli': patch +--- + +perf(plugin-audit): the comment threads read counts replies with one grouped read, and pages at PostgreSQL microsecond precision without skipping a thread + +Clause-②: yes (widening) +Metadata-protocol: none + +`sys_comment` gains `thread_root_id`, a read-only column the platform writes on each reply: the id of the top-level comment the reply's `parent_id` chain leads to within its record's discussion, or the reply's own id when it is in no thread; `null` on a top-level comment. A reply belongs to a thread up to 15 levels below its top-level comment, the rule a thread's participants are already kept by; a reply 16 or more levels deep belongs to none. The create stamps a reply from its parent, and the keeper that maintains `participants` brings every reply of a discussion to the rule in the same reconcile and the same system write (the comment's `updated_at` kept), so a re-point or a delete moves the roots under it. A client's value never lands: the create stamp replaces it, an ordinary update has it stripped and reported in `droppedFields`, and an update under `preserveAudit` has it dropped. + +The comment threads read (`POST /api/v1/comments/threads/query`) now takes each thread's reply count and latest distinct repliers from one grouped read of the page's replies by that column, and one read of each candidate replier's newest reply, as the caller. Before, it read every reply on the page's records and followed `parent_id` in the server. The answer's shape is unchanged. One count differs: a reply exactly 16 levels deep was counted before and is not now, matching the rule the participants list and the comment panel follow. + +The read's cursor now pages by the millisecond a thread was created in, then by id, compared at the millisecond on both sides. PostgreSQL stores microseconds while every read hands back milliseconds, so two threads a database default stamped microseconds apart could be skipped at a page edge. A page whose last millisecond may hold more threads ends with that millisecond read again by id, so the page and the cursor agree. A cursor issued before this release still reads. + +**After upgrading, run the backfill.** Replies written before this release carry no root. The read still counts them, by following each one up its chain, so no count drops, but that read grows with the number of such replies. `os migrate comment-participants --apply` stamps them (dry run first, `os migrate comment-participants`; idempotent), and the next comment written on a record also stamps that record's replies. diff --git a/content/docs/api/data-api.mdx b/content/docs/api/data-api.mdx index a541a5990c1..155f14a40c1 100644 --- a/content/docs/api/data-api.mdx +++ b/content/docs/api/data-api.mdx @@ -720,8 +720,14 @@ next page (`null` on the last): } } ``` -`replyCount` counts the replies under the thread at any depth; `repliers` are -the latest distinct ones, newest first, at most three. `record.name` is the +`replyCount` counts the replies under the thread up to 15 levels below it: a +reply 16 or more levels deep belongs to no thread, by the rule the thread's +participants are kept by. `repliers` are the latest distinct ones, newest first, at most +three. Both are taken with one grouped read of the page's replies by the thread +each reply stores (`thread_root_id`), so a page costs the same however many +replies its threads hold. Replies written before that column existed are still +counted, by following each up its chain, until `os migrate comment-participants +--apply` stamps them. `record.name` is the record's title field read as the caller (`Record #` and the id when it is empty or not served). @@ -731,8 +737,10 @@ as one subquery, so a view of any size is answered in full; where the engine cannot prove that read it reads the ids as the caller and refuses past its cap (`400 INVALID_FILTER`), never a part of the view. The comment read is an ordinary read of `sys_comment`, so the comment read gate decides as on -`GET /data/sys_comment`. The cursor is a keyset over creation time and id: a -comment posted while you page does not repeat or skip a thread. +`GET /data/sys_comment`. The cursor is a keyset over the millisecond a thread +was created in and its id, compared at the millisecond on both sides, so a +comment posted while you page does not repeat or skip a thread, and neither do +threads a database default stamped microseconds apart on PostgreSQL. Refusals: diff --git a/content/docs/deployment/cli.mdx b/content/docs/deployment/cli.mdx index 468a40683eb..2b7a42c909d 100644 --- a/content/docs/deployment/cli.mdx +++ b/content/docs/deployment/cli.mdx @@ -1560,7 +1560,7 @@ where the data lives. | `os migrate audit-side-copies` | Remove the side-copy columns (another record's field values, such as an approval request's `payload_json`) from the `sys_audit_log` and `sys_activity` copies written before the audit writer omitted them. Covers the `archive` datasource `sys_audit_log` archives to as well. `--object` narrows it to one copy table. Reports counts only, per table and store. No flag; idempotent. See [below](#os-migrate-audit-side-copies) | | `os migrate list-preferences` | Delete the per-reader list preference rows an earlier Console stored in `sys_user_preference` under `ui.list.`, which the Console no longer reads. Dry run by default (counts per key, writes no row); `--apply` deletes, only with an owner-only `--export` written and read back first. Run it once after upgrading. See [below](#os-migrate-list-preferences) | | `os migrate comment-parent-pair` | Stamp the parent pair (`object_name`, `record_id`) on the `sys_comment` rows written before it existed. Until it runs, a broad comment read past 2,000 candidate rows omits comments the reader may see, and its total agrees with the short list, so run it at once after upgrading. No flag; idempotent | -| `os migrate comment-participants` | Write the participant list (who started, replied in or is mentioned in each thread) on the `sys_comment` threads written before it existed. Until it runs, a "threads involving me" filter does not find those threads. Dry run by default; `--apply` writes. Idempotent. See [below](#os-migrate-comment-participants) | +| `os migrate comment-participants` | Write the participant list (who started, replied in or is mentioned in each thread) on the `sys_comment` threads, and the thread root on the replies, written before they existed. Until it runs, a "threads involving me" filter does not find those threads, and the list page's comment threads read counts those replies the slow way. Dry run by default; `--apply` writes. Idempotent. See [below](#os-migrate-comment-participants) | | `os migrate meta --stored` | Replay the metadata conversion chain over this deployment's `sys_metadata` rows and rewrite the ones still carrying a pre-protocol shape. Hygiene, not a gate — nothing depends on it having run | | `os migrate security-catalog-overlays` | List the environment-wide permission-set and position rows (the legacy plurals `permissions` / `positions` included) stored over a name a configured package holds — the rows a v18 cold boot refuses — each with the package that holds its name; `--apply` deletes them, one history tombstone per row. Run it before the first v18 boot, with the flags and environment the deployment boots with: the platform security plugin's sets are held only where `os serve` composes it (an auth secret set, and the `auth` tier on), and the step takes `serve`'s `--preset` and `--dev` with `serve`'s meaning. Adopts nothing; exits 1 while it lists a row | | `os migrate packageless-overlays` | List the package-less view, dashboard, report, translation and email-template rows stored over a name exactly one installed package ships — the customizations Setup saved before ADR-0146 D11 closed that write — and with `--apply` move each into that package's paired `.custom` (created when absent) as a declared override, `basedOn` the base's installed version; the package-less row is deleted only after the moved one reads back as served. A name no package ships is environment metadata and is not touched; a name several packages ship, or one the pair already holds a row of, is listed and left with the reason. So is a view container (`list` and `listViews`, and the `form` / `formViews` members a row stored before protocol 19 holds): only a single view declares an override, so it is listed `cannot_declare` and never attempted, with the way out — save each of its lists into the pair as a single view, then, once `os migrate protocol --to 19 --apply` has moved its form members, delete the container row. Takes `serve`'s `--preset` and `--dev`. Idempotent: a second run moves nothing. Run it once after upgrading | @@ -2522,17 +2522,28 @@ carry no list, and until this command runs that filter does not find them. A record's own comment panel is unaffected: it works the rule out from the comments it has loaded. +Each reply also stores which thread it belongs to (`thread_root_id`): the +first comment its chain of replies leads up to. A reply up to 15 levels below +that comment belongs to its thread; one 16 or more levels deep belongs to none +and is counted in none. The list +page's comment threads read counts a page's replies and picks their latest +repliers with one grouped read by that column. Replies written before the +upgrade carry no root. The read still counts them, by following each one up +its chain, so no count drops before this command runs, but that read grows +with the number of such replies on the page's records. This command stamps +them, and so does the next comment written on the same record. + ```bash os migrate comment-participants # Dry run: counts, writes no rows -os migrate comment-participants --apply # Write the lists (prompts) +os migrate comment-participants --apply # Write the lists and roots (prompts) os migrate comment-participants --apply --yes --json # CI / scripts ``` -Each record's comments are read together and every thread's list is worked out -by the rule the platform keeps new threads with; the row's `updated_at` is -kept. **Idempotent**: a list that is already right is not written, so a second -run changes nothing, and re-running is how an interrupted run is finished. The -column arrives with the upgraded deployment's schema sync, which an `--apply` +Each record's comments are read together and every thread's list, and every +reply's root, is worked out by the rule the platform keeps new comments with; +the row's `updated_at` is kept. **Idempotent**: a list or root that is already +right is not written, so a second run changes nothing, and re-running is how an +interrupted run is finished. The columns arrive with the upgraded deployment's schema sync, which an `--apply` run performs itself: a dry run against a database no upgraded process has opened cannot read it, reports the failed read and exits `1`. A failed read or write exits `1`. diff --git a/content/docs/permissions/system-context.mdx b/content/docs/permissions/system-context.mdx index 8d7aec63805..4d07433035f 100644 --- a/content/docs/permissions/system-context.mdx +++ b/content/docs/permissions/system-context.mdx @@ -191,7 +191,7 @@ One of the largest consumers of the flag; | 43 | Approval actor / submitter / pending-approver checks bypassed (9 sites) | plugin-approvals | Get: approve, reject, recall, reassign without being a pending approver or the submitter, and a decision or comment that attaches files the actor did not upload (every other caller attaches only files it uploaded, in the request's organization) | `isOverrideActor`, `resolveActor`, `sendBack`, `resubmit`, `reassign`, `remind`, `requestInfo`, `comment`, `assertAttachmentsUploadedByCaller` | | 44 | Attachment access hooks return early (insert + update + delete, the referenced-file check on insert + update, and the read AST) | service-storage | Lose: attachment visibility scoping | `installAttachmentAccessHooks`, `installAttachmentFileReferenceGate`, `installAttachmentReadVisibility` | | 45 | Comment access hooks return early (insert + update + delete, and the read AST), and so do the activity and audit-log read gates (their read AST), the activity field redaction and the audit-log field redaction (the rows a read serves), the activity summary's message code (the rows a read serves), and the query guard over both objects' value-bearing columns (the read AST) | plugin-audit | Get: the whole activity row and the whole `sys_audit_log` row, its before/after snapshots included, and the activity row's stored summary code (`metadata.summary_message`), on `find` / `findOne` — the audit writer, each read gate's bounded probe and the activity backfill — and a filter, sort or grouping by those columns. Lose: comment visibility scoping, the narrowing of `sys_activity` and of `sys_audit_log` to rows whose parent record the caller can read, the redaction of a parent field's value from an activity row's text and recorded change and from a ledger row's before/after snapshots, the withholding of an activity row recording an update whose every changed field the reader is withheld, of a fired milestone row whose watched fields it is not all served, and of an unstamped row (on `count` and `aggregate` too, so a total agrees with the rows), the removal of that summary code from the activity row's `metadata` (its params are field values), and the refusal of a query over those columns for a reader withheld a field of the objects it can reach, and the withholding of those columns from such a reader's server-chosen search set (#34700) | `installCommentAccessHooks`, `installCommentReadVisibility`, `installActivityReadVisibility`, `installAuditLogReadVisibility`, `installActivityFieldRedaction`, `installAuditLogFieldRedaction`, `installActivitySummaryLocale`, `installParentFieldQueryGuard`, `withheldSearchColumns` | -| 45a | The `sys_comment` participant keeper lets a system update write `participants` (#39081) | plugin-audit | Get: the platform's own rewrite of a thread's stored participant list — the after-write reconcile on a reply, a mention edit or a delete, and `os migrate comment-participants --apply` — lands under `preserveAudit` with the row's `updated_at` kept. Lose: nothing a user held — every other update has `participants` dropped before the write (reported in `droppedFields` on an ordinary update, dropped unreported under `preserveAudit`), except the engine's removal of a deleted user (`referentialFieldClear`), and a create is stamped by the platform over any value the caller sends | `installCommentParticipants` | +| 45a | The `sys_comment` participant keeper lets a system update write `participants` and `thread_root_id` (#39081, #39142), and reads a new reply's parent as the system | plugin-audit | Get: the platform's own rewrite of a thread's stored participant list and of each reply's stored thread root — the after-write reconcile on a reply, a mention edit, a re-point or a delete, and `os migrate comment-participants --apply` — lands under `preserveAudit` with the row's `updated_at` kept; and the create stamp reads the parent of each new reply (its id, parent, discussion and root) to stamp the reply's root. Lose: nothing a user held — every other update has `participants` and `thread_root_id` dropped before the write (reported in `droppedFields` on an ordinary update, dropped unreported under `preserveAudit`), except the engine's removal of a deleted user from `participants` (`referentialFieldClear`), and a create is stamped by the platform over any value the caller sends; the parent read serves only the stamp, never the caller | `installCommentParticipants` | | 46 | Knowledge search returns hits unfiltered, and searches every source; a knowledge source is saved without its author being judged | service-knowledge, metadata-core, runtime | Lose: the permission filter over search results, and the source admission ahead of it — an `object` source over an object the caller's exposure decision refuses (disabled package, `apiEnabled` / `apiMethods` for `search`, a `sys_*` object without `enable.aiReadable: true`), or serving a field the caller may not query, is searched. Lose at the `/meta` and MCP save doors: the same admission asked for the author before a `knowledge_source` is saved (ADR-0161 K4), so the engine's own write saves a source over an object or a field no author was judged for. Lose at the package duplicate door: the same admission asked for the caller, for each knowledge source the copy would save. Lose at the package move-in door: the same admission asked for the caller, for each selected knowledge source the move saves again under the package | `applyPermissionFilter`, `admitSources`, `searchByKey`, `admitAuthoredSource`, `authoredKnowledgeSourceRefusal`, `refuseDuplicatedKnowledgeSources`, `handlePackagesRequest` | | 46a | Knowledge search under the system identity is not ordered for the asker: a source's `affinity` entries move nothing | service-knowledge | Get: every hit in the order its store answered, and no read of a user or business unit. Lose: nothing a user held. The system identity is no person, so it has no unit to order by; every other caller's user id and unit chain are read as that caller may read them | `resolveAffinityFacts` | | 47 | The inbound-mail read gates return early (the read AST) | service-mailbox | Get: every `sys_mail_message` and `sys_mail_association` row on `find` / `findOne` — the ingest writer and each gate's own pre-scan, which read the association and mailbox rows a decision needs. Lose: the narrowing of a message to callers who can read a record it is associated with or who own its mailbox (so the unassociated pool is restricted), and of an association to callers who can read the record it names (on `count` and `aggregate` too, so a total agrees with the rows) | `gateMiddleware` | diff --git a/packages/cli/src/commands/migrate/comment-participants.ts b/packages/cli/src/commands/migrate/comment-participants.ts index 1bc80e0afa7..52dc9a81665 100644 --- a/packages/cli/src/commands/migrate/comment-participants.ts +++ b/packages/cli/src/commands/migrate/comment-participants.ts @@ -35,14 +35,19 @@ async function confirm(question: string): Promise { /** * `os migrate comment-participants` — the stored-row backfill of `sys_comment`'s - * platform-written participant list. + * platform-written participant list and thread root. * * A thread's top-level comment stores who took part in it (its author, every * replier at any depth, everyone any of its comments mentions), so "the - * threads involving me" is one filter, `participants: { $contains: USER }`. - * New threads are kept by the platform at write time; threads written before - * the upgrade carry no list, and that filter does not find them until this - * runs. Operators run it after upgrading, dry run first. + * threads involving me" is one filter, `participants: { $contains: USER }`; + * and each reply stores the top-level comment it belongs to + * (`thread_root_id`), so the comment threads read counts a thread's replies + * with one grouped read. New comments are kept by the platform at write time. + * Threads written before the upgrade carry no list, and that filter does not + * find them until this runs; replies written before it carry no root, and the + * threads read counts them by following `parent_id` for those rows, a read + * that grows with them, until this runs. Operators run it after upgrading, + * dry run first. * * Each record's discussion is brought to the rule by the step the platform's * own after-write keeper runs (`@objectstack/plugin-audit`'s @@ -57,8 +62,9 @@ async function confirm(question: string): Promise { */ export default class MigrateCommentParticipants extends Command { static override description = - 'Write the participant list on the sys_comment threads written before it existed: until it runs, a ' + - '"threads involving me" filter does not find them. Dry run by default; --apply writes. Run it after upgrading.'; + 'Write the participant list on the sys_comment threads, and the thread root on the replies, written before ' + + 'they existed: until it runs, a "threads involving me" filter does not find those threads, and the comment ' + + 'threads read counts those replies the slow way. Dry run by default; --apply writes. Run it after upgrading.'; static override examples = [ '$ os migrate comment-participants', @@ -72,7 +78,7 @@ export default class MigrateCommentParticipants extends Command { env: 'OS_DATABASE_URL', }), apply: Flags.boolean({ - description: 'Write the participant lists (default is a read-only dry run)', + description: 'Write the participant lists and thread roots (default is a read-only dry run)', default: false, }), yes: Flags.boolean({ char: 'y', description: 'Skip the --apply confirmation prompt', default: false }), @@ -127,7 +133,7 @@ export default class MigrateCommentParticipants extends Command { return; } const ok = await confirm( - chalk.bold('\nWrite the participant list of every sys_comment thread on this database? [y/N] '), + chalk.bold('\nWrite the participant list of every sys_comment thread, and the thread root of every reply, on this database? [y/N] '), ); if (!ok) { printInfo('Aborted — no changes made.'); @@ -179,7 +185,7 @@ export default class MigrateCommentParticipants extends Command { // of a table that is not there (a database no process has opened) reads // as no rows (`absentTableReads`). ⛔ Any other refused read — a // `sys_comment` the upgraded schema sync has not yet given its - // `participants` column, included — is still counted in `failures` and + // `participants` or `thread_root_id` column, included — is still counted in `failures` and // still exits non-zero. `--apply` booted plain; its writes go to the // engine itself. const reads = absentTableReads(stack, (object) => engine.getObject(object)); @@ -202,7 +208,7 @@ export default class MigrateCommentParticipants extends Command { console.log(''); console.log( ` ${chalk.white('sys_comment')}: ${report.threads} thread(s) in ${report.discussions} record discussion(s), ` + - `${report.changed} list(s) ${apply ? 'written' : 'to write'}`, + `${report.changed} row(s) ${apply ? 'written' : 'to write'} (${report.roots} reply thread root(s) among them)`, ); console.log(''); @@ -210,12 +216,12 @@ export default class MigrateCommentParticipants extends Command { printError(`${report.failures} read(s) or row(s) failed — re-run to finish them.`); } else if (apply && report.changed > 0) { printSuccess( - `Wrote ${report.changed} participant list(s). Re-run any time — it only writes lists that differ.`, + `Wrote ${report.changed} row(s). Re-run any time — it only writes lists and roots that differ.`, ); } else if (!apply && report.changed > 0) { - printInfo(`Dry run only — ${report.changed} list(s) would be written. Re-run with --apply.`); + printInfo(`Dry run only — ${report.changed} row(s) would be written. Re-run with --apply.`); } else { - printSuccess('Nothing to write — every sys_comment thread carries its participant list.'); + printSuccess('Nothing to write — every sys_comment thread carries its participant list, and every reply its thread root.'); } console.log(chalk.dim(` ${timer.display()}`)); console.log(''); diff --git a/packages/plugins/plugin-audit/src/comment-threads-query.ts b/packages/plugins/plugin-audit/src/comment-threads-query.ts index 17bb6a48803..a863fb2c77d 100644 --- a/packages/plugins/plugin-audit/src/comment-threads-query.ts +++ b/packages/plugins/plugin-audit/src/comment-threads-query.ts @@ -109,8 +109,8 @@ import { COMMENT_RESOLVED_FIELD, isReplyRow } from './comment-resolution.js'; * * A thread is a top-level comment and every reply under it: a reply is placed * in a thread by following `parent_id` up to its top-level comment within the - * record's discussion, at most 16 hops (so a reply 16 or more levels deep is - * in no thread), the rule a thread's participants are kept by + * record's discussion, at most 16 hops (so a reply up to 15 levels below it + * is in the thread, and one 16 or more levels deep is in none), the rule a thread's participants are kept by * (`comment-participants.ts`) and the one the console groups a record's * comments by. The platform stores that answer on each reply as * `thread_root_id` (the top-level comment's id, or the reply's own id when it diff --git a/packages/plugins/plugin-audit/src/index.ts b/packages/plugins/plugin-audit/src/index.ts index 4eeb8cc56cd..23f9e18ec84 100644 --- a/packages/plugins/plugin-audit/src/index.ts +++ b/packages/plugins/plugin-audit/src/index.ts @@ -131,13 +131,16 @@ export type { CommentParentPairBackfillReport, } from './comment-parent-pair-backfill.js'; // The platform-written participant list of a comment thread ("the threads -// involving me" as one filter), its keeper and its stored-row backfill. The -// CLI command (`os migrate comment-participants`) drives the backfill. +// involving me" as one filter) and thread root of each reply (the threads +// read's grouped count), their keeper and their stored-row backfill. The CLI +// command (`os migrate comment-participants`) drives the backfill. export { COMMENT_PARTICIPANTS_COLUMN, + COMMENT_THREAD_ROOT_COLUMN, installCommentParticipants, participantsByThread, reconcileCommentThreadParticipants, + threadRootByRow, } from './comment-participants.js'; export type { CommentParticipantsEngine, diff --git a/packages/plugins/plugin-audit/src/objects/sys-comment.object.ts b/packages/plugins/plugin-audit/src/objects/sys-comment.object.ts index 607faa0845d..71d177afd10 100644 --- a/packages/plugins/plugin-audit/src/objects/sys-comment.object.ts +++ b/packages/plugins/plugin-audit/src/objects/sys-comment.object.ts @@ -226,8 +226,8 @@ import { ObjectSchema, Field } from '@objectstack/spec/data'; * an aggregate over the replies, taken at read time (see `reply_count` above). * * - **The value.** On a reply, the id of the top-level comment its `parent_id` - * chain reaches within the record's discussion, by the participants rule (at - * most 16 hops, so a reply 16 or more levels deep is in no thread). A reply + * chain reaches within the record's discussion, by the participants rule (a + * reply up to 15 levels below it; one 16 or more levels deep is in no thread). A reply * whose chain leaves the discussion or runs past the bound carries its OWN * id: it is in no thread, and no top-level comment has that id. On a * top-level comment it is `null`. A reply that carries `null` has not been From 0f587de14c6814efb9559987dc5cd58fd123177b Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 18:26:40 +0000 Subject: [PATCH 5/7] wip: translated labels for the thread root column Claude-Session: https://claude.ai/code/session_01WGufziM2GUsShZcjp6TiyD Co-authored-by: Claude --- .../plugin-audit/src/translations/ar.objects.generated.ts | 4 ++++ .../plugin-audit/src/translations/de.objects.generated.ts | 4 ++++ .../plugin-audit/src/translations/en.objects.generated.ts | 4 ++++ .../plugin-audit/src/translations/es-ES.objects.generated.ts | 4 ++++ .../plugin-audit/src/translations/fr.objects.generated.ts | 4 ++++ .../plugin-audit/src/translations/ja-JP.objects.generated.ts | 4 ++++ .../plugin-audit/src/translations/ko.objects.generated.ts | 4 ++++ .../plugin-audit/src/translations/pt-BR.objects.generated.ts | 4 ++++ .../plugin-audit/src/translations/ru.objects.generated.ts | 4 ++++ .../plugin-audit/src/translations/zh-CN.objects.generated.ts | 4 ++++ .../src/translations/zh-Hant.objects.generated.ts | 4 ++++ 11 files changed, 44 insertions(+) diff --git a/packages/plugins/plugin-audit/src/translations/ar.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/ar.objects.generated.ts index 530e2a8527e..41d71ee58bb 100644 --- a/packages/plugins/plugin-audit/src/translations/ar.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/ar.objects.generated.ts @@ -282,6 +282,10 @@ export const arObjects: NonNullable = { label: "المشاركون", help: "من شارك في السلسلة التي يبدأها هذا التعليق (كاتبه وكل من ردّ وكل من أُشير إليه) — تسجّله المنصة، ولا يكتبه المؤلفون أبدًا" }, + thread_root_id: { + label: "جذر السلسلة", + help: "التعليق ذو المستوى الأعلى الذي ينتمي إليه هذا الرد (معرّفه نفسه إذا لم ينتمِ إلى أي سلسلة؛ فارغ في التعليق ذي المستوى الأعلى) — تسجّله المنصة، ولا يكتبه المؤلفون أبدًا" + }, created_at: { label: "تاريخ الإنشاء" }, diff --git a/packages/plugins/plugin-audit/src/translations/de.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/de.objects.generated.ts index b1b9abbe185..49235ce298e 100644 --- a/packages/plugins/plugin-audit/src/translations/de.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/de.objects.generated.ts @@ -282,6 +282,10 @@ export const deObjects: NonNullable = { label: "Beteiligte", help: "Wer an dem Thread beteiligt ist, den dieser Kommentar beginnt (Verfasser, alle Antwortenden, alle Erwähnten) – von der Plattform erfasst, nie von Autoren geschrieben" }, + thread_root_id: { + label: "Thread-Ursprung", + help: "Der oberste Kommentar, zu dem diese Antwort gehört (ihre eigene ID, wenn sie zu keinem Thread gehört; leer bei einem obersten Kommentar) – von der Plattform erfasst, nie von Autoren geschrieben" + }, created_at: { label: "Erstellt am" }, diff --git a/packages/plugins/plugin-audit/src/translations/en.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/en.objects.generated.ts index bdf28433107..80b1a6246d9 100644 --- a/packages/plugins/plugin-audit/src/translations/en.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/en.objects.generated.ts @@ -282,6 +282,10 @@ export const enObjects: NonNullable = { label: "Participants", help: "Who took part in the thread this top-level comment starts (its author, every replier, everyone mentioned) — stamped by the platform, never written by authors" }, + thread_root_id: { + label: "Thread Root", + help: "The top-level comment this reply belongs to (its own id when it is in no thread; empty on a top-level comment) — stamped by the platform, never written by authors" + }, created_at: { label: "Created At" }, diff --git a/packages/plugins/plugin-audit/src/translations/es-ES.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/es-ES.objects.generated.ts index 5f841ea7cc8..ec7f2a578c1 100644 --- a/packages/plugins/plugin-audit/src/translations/es-ES.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/es-ES.objects.generated.ts @@ -282,6 +282,10 @@ export const esESObjects: NonNullable = { label: "Participantes", help: "Quién participa en el hilo que inicia este comentario (su autor, quienes responden y quienes son mencionados): lo registra la plataforma, nunca los autores" }, + thread_root_id: { + label: "Raíz del hilo", + help: "El comentario de primer nivel al que pertenece esta respuesta (su propio id si no pertenece a ningún hilo; vacío en un comentario de primer nivel): lo registra la plataforma, nunca lo escriben los autores" + }, created_at: { label: "Creado el" }, diff --git a/packages/plugins/plugin-audit/src/translations/fr.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/fr.objects.generated.ts index 0fd78b18f62..ccddb097bf4 100644 --- a/packages/plugins/plugin-audit/src/translations/fr.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/fr.objects.generated.ts @@ -282,6 +282,10 @@ export const frObjects: NonNullable = { label: "Participants", help: "Qui prend part au fil que ce commentaire ouvre (son auteur, chaque personne qui répond, chaque personne mentionnée) — enregistré par la plateforme, jamais saisi par les auteurs" }, + thread_root_id: { + label: "Racine du fil", + help: "Le commentaire de premier niveau auquel appartient cette réponse (son propre id si elle n’appartient à aucun fil ; vide sur un commentaire de premier niveau) — enregistré par la plateforme, jamais écrit par les auteurs" + }, created_at: { label: "Créé le" }, diff --git a/packages/plugins/plugin-audit/src/translations/ja-JP.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/ja-JP.objects.generated.ts index 892846fef76..b7b36a9fe65 100644 --- a/packages/plugins/plugin-audit/src/translations/ja-JP.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/ja-JP.objects.generated.ts @@ -282,6 +282,10 @@ export const jaJPObjects: NonNullable = { label: "参加者", help: "このコメントで始まるスレッドの参加者(投稿者、返信者、メンションされた人)。プラットフォームが記録し、作成者は書き込めません" }, + thread_root_id: { + label: "スレッドの起点", + help: "この返信が属するトップレベルのコメント(どのスレッドにも属さない場合は自身の ID、トップレベルのコメントでは空)。プラットフォームが記録し、作成者は書き込めません" + }, created_at: { label: "作成日時" }, diff --git a/packages/plugins/plugin-audit/src/translations/ko.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/ko.objects.generated.ts index ce3c2913af1..ab813a8533d 100644 --- a/packages/plugins/plugin-audit/src/translations/ko.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/ko.objects.generated.ts @@ -282,6 +282,10 @@ export const koObjects: NonNullable = { label: "참여자", help: "이 댓글로 시작된 스레드의 참여자(작성자, 답글 작성자, 멘션된 사람). 플랫폼이 기록하며 작성자는 입력할 수 없습니다" }, + thread_root_id: { + label: "스레드 루트", + help: "이 답글이 속한 최상위 댓글(어느 스레드에도 속하지 않으면 자신의 ID, 최상위 댓글에서는 비어 있음) — 플랫폼이 기록하며 작성자는 쓸 수 없습니다" + }, created_at: { label: "생성 일시" }, diff --git a/packages/plugins/plugin-audit/src/translations/pt-BR.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/pt-BR.objects.generated.ts index 77331c385ce..37fd0b9c2e4 100644 --- a/packages/plugins/plugin-audit/src/translations/pt-BR.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/pt-BR.objects.generated.ts @@ -282,6 +282,10 @@ export const ptBRObjects: NonNullable = { label: "Participantes", help: "Quem participa do tópico que este comentário inicia (o autor, quem respondeu e quem foi mencionado) — registrado pela plataforma, nunca escrito pelos autores" }, + thread_root_id: { + label: "Raiz da conversa", + help: "O comentário de nível superior ao qual esta resposta pertence (seu próprio id quando não pertence a nenhuma conversa; vazio em um comentário de nível superior) — registrado pela plataforma, nunca escrito pelos autores" + }, created_at: { label: "Criado em" }, diff --git a/packages/plugins/plugin-audit/src/translations/ru.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/ru.objects.generated.ts index 063b43debcb..64ccc369edc 100644 --- a/packages/plugins/plugin-audit/src/translations/ru.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/ru.objects.generated.ts @@ -282,6 +282,10 @@ export const ruObjects: NonNullable = { label: "Участники", help: "Кто участвует в ветке, которую начинает этот комментарий (автор, все ответившие, все упомянутые) — записывается платформой, авторы не заполняют" }, + thread_root_id: { + label: "Корень ветки", + help: "Комментарий верхнего уровня, к которому относится этот ответ (его собственный id, если он не относится ни к одной ветке; пусто у комментария верхнего уровня) — записывается платформой, авторы его не заполняют" + }, created_at: { label: "Создано" }, diff --git a/packages/plugins/plugin-audit/src/translations/zh-CN.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/zh-CN.objects.generated.ts index 951e8b88120..0b719f1f197 100644 --- a/packages/plugins/plugin-audit/src/translations/zh-CN.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/zh-CN.objects.generated.ts @@ -282,6 +282,10 @@ export const zhCNObjects: NonNullable = { label: "参与人", help: "这一串评论的参与人(发起人、每位回复人、每位被 @ 的人)——由平台记录,作者不能填写" }, + thread_root_id: { + label: "讨论串根", + help: "这条回复所属的顶层评论(不属于任何讨论串时为它自己的 id;顶层评论为空)——由平台记录,作者不能填写" + }, created_at: { label: "创建时间" }, diff --git a/packages/plugins/plugin-audit/src/translations/zh-Hant.objects.generated.ts b/packages/plugins/plugin-audit/src/translations/zh-Hant.objects.generated.ts index 72599a6a245..423e9cd6e90 100644 --- a/packages/plugins/plugin-audit/src/translations/zh-Hant.objects.generated.ts +++ b/packages/plugins/plugin-audit/src/translations/zh-Hant.objects.generated.ts @@ -282,6 +282,10 @@ export const zhHantObjects: NonNullable = { label: "參與人", help: "這一串評論的參與人(發起人、每位回覆人、每位被 @ 的人)——由平台記錄,作者不能填寫" }, + thread_root_id: { + label: "討論串根", + help: "這則回覆所屬的頂層評論(不屬於任何討論串時為它自己的 id;頂層評論為空)——由平台記錄,作者不能填寫" + }, created_at: { label: "建立時間" }, From 7e8c04ac401406f000655b8ced76c35f32991635 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 18:31:02 +0000 Subject: [PATCH 6/7] wip: dogfood pins for the microsecond page edge and the stored thread root on sqlite and postgres Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01WGufziM2GUsShZcjp6TiyD --- .../comment-threads-query.dogfood.test.ts | 76 ++++++++++++++++++- 1 file changed, 74 insertions(+), 2 deletions(-) diff --git a/packages/qa/dogfood/test/comment-threads-query.dogfood.test.ts b/packages/qa/dogfood/test/comment-threads-query.dogfood.test.ts index d9433dd2f1c..76ef4edcb86 100644 --- a/packages/qa/dogfood/test/comment-threads-query.dogfood.test.ts +++ b/packages/qa/dogfood/test/comment-threads-query.dogfood.test.ts @@ -35,7 +35,13 @@ // threads statement on SQLite AND PostgreSQL, the row-scoped member, the // member with no read, and two users through one engine — each request plans // its own scope under its own context, never a scope kept from another -// request. The PostgreSQL cell runs where `OS_TEST_POSTGRES_URL` is set (it +// request; the keyset walking two threads stored one microsecond apart (on +// PostgreSQL, where the column keeps microseconds and every read hands back +// milliseconds) across a page edge, each answered once; and the reply count +// and latest repliers taken from the stored thread root on that driver — +// replies microseconds past their millisecond, three deep — the same before +// the backfill (no reply stamped) and after it. The PostgreSQL cell runs +// where `OS_TEST_POSTGRES_URL` is set (it // creates a database of its own there and drops it) and is a named skip // otherwise; no CI job provisions that variable for this suite, so it is // red-capable and un-run in CI, and the PR that landed this file names its @@ -46,7 +52,7 @@ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { bootStack, type VerifyStack } from '@objectstack/verify'; -import { AuditPlugin, queryCommentThreads } from '@objectstack/plugin-audit'; +import { AuditPlugin, backfillCommentParticipants, queryCommentThreads } from '@objectstack/plugin-audit'; import { SecurityPlugin, securityDefaultPermissionSets } from '@objectstack/plugin-security'; import { ObjectKernel, assembleExecutionContext, resolveAuthzContext, type Plugin, type PluginContext } from '@objectstack/core'; import { ObjectQL, ObjectQLPlugin } from '@objectstack/objectql'; @@ -658,6 +664,72 @@ for (const cell of CELLS) { expect(accountReads).toHaveLength(1); expect(accountReads[0].query?.limit ?? 0).toBeLessThanOrEqual(2); }, 120_000); + + /** A stored creation time, written past the engine: microseconds on PostgreSQL, the millisecond on SQLite. */ + const stampCreatedAt = async (id: string, pgText: string, sqliteText: string) => { + if (cell.id === 'pg') await driver.execute(`update ${COMMENT} set created_at = '${pgText}' where id = '${id}'`); + else await driver.execute(`update ${COMMENT} set created_at = '${sqliteText}' where id = '${id}'`); + }; + + it('two threads stored one microsecond apart, across a page edge: both answered, once each', async () => { + await ql.insert(ACCOUNT, { id: 'acc_micro', name: 'micro', region: 'NA', status: 'micro', secret: 'x' }, { context: SYS_ORG } as never); + const ids: string[] = []; + for (const body of ['x', 'y']) { + const row = await ql.insert(COMMENT, { thread_id: `${ACCOUNT}:acc_micro`, author_id: ALICE, body }, { context: { ...SYS_ORG, userId: ALICE } } as never); + ids.push(String(row.id)); + } + // One microsecond apart inside one millisecond, as a database default stamps them. + await stampCreatedAt(ids[0], '2022-01-01 00:00:00.000500+00', '2022-01-01T00:00:00.000Z'); + await stampCreatedAt(ids[1], '2022-01-01 00:00:00.000501+00', '2022-01-01T00:00:00.000Z'); + const walked: string[] = []; + let cursor: string | undefined; + for (let i = 0; i < 5; i++) { + const answer = await read(ALICE, { filter: { status: 'micro' }, limit: 1, ...(cursor ? { cursor } : {}) }); + walked.push(...threadIds(answer)); + if (!answer.nextCursor) break; + cursor = answer.nextCursor; + } + expect([...walked].sort()).toEqual([...ids].sort()); + expect(new Set(walked).size).toBe(walked.length); + }); + + it('reply count and latest repliers from the stored thread root, three deep and microseconds past the millisecond: the same before and after the backfill', async () => { + await ql.insert(ACCOUNT, { id: 'acc_counted', name: 'counted', region: 'NA', status: 'counted', secret: 'x' }, { context: SYS_ORG } as never); + const post = async (by: string, parent?: string) => + String( + ( + await ql.insert( + COMMENT, + { thread_id: `${ACCOUNT}:acc_counted`, author_id: by, body: 'text', ...(parent ? { parent_id: parent } : {}) }, + { context: { ...SYS_ORG, userId: by } } as never, + ) + ).id, + ); + const top = await post(ALICE); + const r1 = await post(BOB, top); + const r2 = await post(CAROL, r1); + const r3 = await post(ALICE, r2); + await stampCreatedAt(r1, '2022-02-01 00:00:01.000100+00', '2022-02-01T00:00:01.000Z'); + await stampCreatedAt(r2, '2022-02-01 00:00:02.000200+00', '2022-02-01T00:00:02.000Z'); + await stampCreatedAt(r3, '2022-02-01 00:00:03.000300+00', '2022-02-01T00:00:03.000Z'); + const answer = async (userId: string) => + (await read(userId, { filter: { status: 'counted' } })).threads.map((x) => [String(x.comment.id), x.replyCount, x.repliers.map((r: Row) => r.id)]); + const expected = [[top, 3, [ALICE, CAROL, BOB]]]; + expect(await answer(ALICE)).toEqual(expected); + expect(await answer(BOB)).toEqual(expected); + + // A database written before the column: no reply stamped. The count holds. + await driver.execute(`update ${COMMENT} set thread_root_id = null where record_id = 'acc_counted'`); + expect(await answer(ALICE)).toEqual(expected); + expect(await answer(BOB)).toEqual(expected); + + const report = await backfillCommentParticipants(ql as any, { info() {}, warn() {} }, { apply: true }); + expect(report.failures).toBe(0); + expect(report.roots).toBeGreaterThanOrEqual(3); + const stored = (await ql.find(COMMENT, { where: { id: { $in: [r1, r2, r3] } }, fields: ['id', 'thread_root_id'], context: SYS_ORG } as never)) as Row[]; + expect(stored.map((r) => r.thread_root_id)).toEqual([top, top, top]); + expect(await answer(ALICE)).toEqual(expected); + }); }, ); } From 2b906d9bf66c2ebee3c9aa3d0166c6f9edf57e1d Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 19:33:47 +0000 Subject: [PATCH 7/7] fix(plugin-audit): a write stamps only the rows it wrote; the backfill stamps the backlog The keeper's reconcile after a user's write corrected every reply of the discussion to the root rule, so the first reply on a discussion with many replies written before the column existed turned into one system update (with its audit and activity rows) per old reply, inside the user's request. It now corrects stamped roots and stamps only the rows the write wrote; the backfill stamps the rest, and the threads read counts unstamped replies by their chain until it has. Docs and the changeset say so, and no longer claim that the next comment stamps a record's replies. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01WGufziM2GUsShZcjp6TiyD --- .changeset/39142-comment-thread-root.md | 6 +-- content/docs/api/data-api.mdx | 7 +-- content/docs/deployment/cli.mdx | 3 +- .../src/comment-participants.test.ts | 24 +++++++++ .../plugin-audit/src/comment-participants.ts | 53 ++++++++++++++++--- .../src/objects/sys-comment.object.ts | 11 ++-- 6 files changed, 85 insertions(+), 19 deletions(-) diff --git a/.changeset/39142-comment-thread-root.md b/.changeset/39142-comment-thread-root.md index 7c77082131c..e3f4030087f 100644 --- a/.changeset/39142-comment-thread-root.md +++ b/.changeset/39142-comment-thread-root.md @@ -8,10 +8,10 @@ perf(plugin-audit): the comment threads read counts replies with one grouped rea Clause-②: yes (widening) Metadata-protocol: none -`sys_comment` gains `thread_root_id`, a read-only column the platform writes on each reply: the id of the top-level comment the reply's `parent_id` chain leads to within its record's discussion, or the reply's own id when it is in no thread; `null` on a top-level comment. A reply belongs to a thread up to 15 levels below its top-level comment, the rule a thread's participants are already kept by; a reply 16 or more levels deep belongs to none. The create stamps a reply from its parent, and the keeper that maintains `participants` brings every reply of a discussion to the rule in the same reconcile and the same system write (the comment's `updated_at` kept), so a re-point or a delete moves the roots under it. A client's value never lands: the create stamp replaces it, an ordinary update has it stripped and reported in `droppedFields`, and an update under `preserveAudit` has it dropped. +`sys_comment` gains `thread_root_id`, a read-only column the platform writes on each reply: the id of the top-level comment the reply's `parent_id` chain leads to within its record's discussion, or the reply's own id when it is in no thread; `null` on a top-level comment. A reply belongs to a thread up to 15 levels below its top-level comment, the rule a thread's participants are already kept by; a reply 16 or more levels deep belongs to none. The create stamps a reply from its parent, and the keeper that maintains `participants` corrects every stamped root of a discussion in the same reconcile and the same system write (the comment's `updated_at` kept), so a re-point or a delete moves the roots under it. After a write it stamps only the rows that write wrote, so a reply on a discussion full of older replies never turns into one system update (with its audit and activity rows) per older reply. A client's value never lands: the create stamp replaces it, an ordinary update has it stripped and reported in `droppedFields`, and an update under `preserveAudit` has it dropped. -The comment threads read (`POST /api/v1/comments/threads/query`) now takes each thread's reply count and latest distinct repliers from one grouped read of the page's replies by that column, and one read of each candidate replier's newest reply, as the caller. Before, it read every reply on the page's records and followed `parent_id` in the server. The answer's shape is unchanged. One count differs: a reply exactly 16 levels deep was counted before and is not now, matching the rule the participants list and the comment panel follow. +The comment threads read (`POST /api/v1/comments/threads/query`) now takes each thread's reply count and latest distinct repliers from one grouped read of the page's replies by that column, and one read of each candidate replier's newest reply, as the caller. Before, it read every reply on the page's records and followed `parent_id` in the server. The answer's shape is unchanged. Two latest repliers who replied in the same millisecond are ordered by id. The exported `CommentThreadsEngine` type now requires `aggregate`, and without one the read answers 503. One count differs: a reply exactly 16 levels deep was counted before and is not now, matching the rule the participants list and the comment panel follow. The read's cursor now pages by the millisecond a thread was created in, then by id, compared at the millisecond on both sides. PostgreSQL stores microseconds while every read hands back milliseconds, so two threads a database default stamped microseconds apart could be skipped at a page edge. A page whose last millisecond may hold more threads ends with that millisecond read again by id, so the page and the cursor agree. A cursor issued before this release still reads. -**After upgrading, run the backfill.** Replies written before this release carry no root. The read still counts them, by following each one up its chain, so no count drops, but that read grows with the number of such replies. `os migrate comment-participants --apply` stamps them (dry run first, `os migrate comment-participants`; idempotent), and the next comment written on a record also stamps that record's replies. +**After upgrading, run the backfill.** Replies written before this release carry no root. The read still counts them, by following each one up its chain, so no count drops, but that read grows with the number of such replies. `os migrate comment-participants --apply` stamps them (dry run first, `os migrate comment-participants`; idempotent). Until it runs, they stay unstamped: a later reply or a re-point stamps only the rows it wrote, so that a user's request never pays for a discussion's backlog. diff --git a/content/docs/api/data-api.mdx b/content/docs/api/data-api.mdx index 155f14a40c1..ee40b603bb6 100644 --- a/content/docs/api/data-api.mdx +++ b/content/docs/api/data-api.mdx @@ -723,9 +723,10 @@ next page (`null` on the last): `replyCount` counts the replies under the thread up to 15 levels below it: a reply 16 or more levels deep belongs to no thread, by the rule the thread's participants are kept by. `repliers` are the latest distinct ones, newest first, at most -three. Both are taken with one grouped read of the page's replies by the thread -each reply stores (`thread_root_id`), so a page costs the same however many -replies its threads hold. Replies written before that column existed are still +three, ordered by id when two replied in the same millisecond. Both come from +one grouped read of the page's replies by the thread each reply stores +(`thread_root_id`), plus one read of the candidate repliers' newest replies, +so a page costs the same however many replies its threads hold. Replies written before that column existed are still counted, by following each up its chain, until `os migrate comment-participants --apply` stamps them. `record.name` is the record's title field read as the caller (`Record #` and the id when it is diff --git a/content/docs/deployment/cli.mdx b/content/docs/deployment/cli.mdx index 2b7a42c909d..fe8d2cff847 100644 --- a/content/docs/deployment/cli.mdx +++ b/content/docs/deployment/cli.mdx @@ -2531,7 +2531,8 @@ repliers with one grouped read by that column. Replies written before the upgrade carry no root. The read still counts them, by following each one up its chain, so no count drops before this command runs, but that read grows with the number of such replies on the page's records. This command stamps -them, and so does the next comment written on the same record. +them. Nothing else does: a later reply or a re-point stamps only the rows it +wrote, so a user's request never pays for a record's backlog of old replies. ```bash os migrate comment-participants # Dry run: counts, writes no rows diff --git a/packages/plugins/plugin-audit/src/comment-participants.test.ts b/packages/plugins/plugin-audit/src/comment-participants.test.ts index 2a2e686e7ee..ee1975d8c76 100644 --- a/packages/plugins/plugin-audit/src/comment-participants.test.ts +++ b/packages/plugins/plugin-audit/src/comment-participants.test.ts @@ -334,6 +334,30 @@ describe('the thread root — reconcile and create stamp', () => { expect(rows.find((r) => r.id === 'a.1.1')!.thread_root_id).toBe('a.1.1'); }); + it('a user\'s reply stamps only itself: the discussion\'s unstamped backlog waits for the backfill, a stamped root is still corrected', async () => { + const backlog = Array.from({ length: 50 }, (_, i): Row => ({ + id: `old.${i}`, thread_id: T, parent_id: 'a', author_id: 'u_b', mentions: null, participants: null, created_at: `0${i}`, + })); + const rows: Row[] = [ + { id: 'a', thread_id: T, parent_id: null, author_id: 'u_a', mentions: null, participants: ['u_a', 'u_b'], created_at: '00' }, + ...backlog, + // stamped, but wrong: corrected by any reconcile + { id: 'moved', thread_id: T, parent_id: 'a', thread_root_id: 'elsewhere', author_id: 'u_b', mentions: null, participants: null, created_at: '1' }, + // the new reply, under an unstamped parent: the create could not stamp it + { id: 'new', thread_id: T, parent_id: 'old.3', thread_root_id: null, author_id: 'u_c', mentions: null, participants: null, created_at: '2' }, + ]; + const engine = discussionEngine(rows); + installCommentParticipants(engine, { warn: vi.fn() }); + await handler(engine, 'afterInsert')({ result: rows[rows.length - 1], input: { data: {} } }); + const rootWrites = engine.updates.filter((u) => 'thread_root_id' in u.data).map((u) => [u.data.id, u.data.thread_root_id]); + expect(rootWrites).toEqual([['moved', 'a'], ['new', 'a']]); + expect(backlog.every((r) => r.thread_root_id === undefined)).toBe(true); + // The backfill (no stampOnly) stamps the backlog. + const backfill = await reconcileCommentThreadParticipants(engine, T, { apply: true }); + expect(backfill.roots).toBe(50); + expect(backlog.every((r) => r.thread_root_id === 'a')).toBe(true); + }); + it('a create stamps a reply from its parent and a top-level comment with null, over a client value', async () => { const parents: Row[] = [ { id: 'top', thread_id: T, parent_id: null }, diff --git a/packages/plugins/plugin-audit/src/comment-participants.ts b/packages/plugins/plugin-audit/src/comment-participants.ts index 9981ab8ec88..c658ba0519c 100644 --- a/packages/plugins/plugin-audit/src/comment-participants.ts +++ b/packages/plugins/plugin-audit/src/comment-participants.ts @@ -83,11 +83,15 @@ * thread; `null` on a top-level comment. The comment threads read groups a * page's replies by it (`comment-threads-query.ts`). It rides every step * above: the create stamps a reply from its parent (one read of the parents, - * as the platform), and the reconcile brings every row of the discussion to - * the rule, in the same single-id write that carries the list. A reply that - * still carries `null` has not been stamped (written before the column, or - * its parent was itself unstamped at create); the next reconcile of its - * discussion, or `os migrate comment-participants --apply`, stamps it. + * as the platform), and the reconcile corrects every stamped root of the + * discussion the rule moved (a re-point, a delete), in the same single-id + * write that carries the list. A reply that still carries `null` has not been + * stamped (written before the column, or its parent was itself unstamped at + * create). After a write, the reconcile stamps only the rows that write wrote, + * so the first reply on a discussion with a thousand old replies writes one + * root, not a thousand system updates with their audit and activity rows; + * `os migrate comment-participants --apply` stamps the rest, and the threads + * read counts unstamped replies by their chain until it has. * * ## The reply notice is a separate audience * @@ -327,7 +331,19 @@ export interface ThreadParticipantsReconciliation { export async function reconcileCommentThreadParticipants( engine: Pick, threadId: string, - options: { apply: boolean; roots?: boolean; onRewriteFailure?: (commentId: string, error: unknown) => void }, + options: { + apply: boolean; + roots?: boolean; + /** + * The unstamped replies this call may stamp. Absent: every one (the + * backfill). A set: only those ids (the keeper after a write names the + * rows it wrote), so a user's write never stamps a discussion's backlog — + * the backfill does that, and the threads read counts unstamped replies + * until then. A root already stamped is corrected either way. + */ + stampOnly?: ReadonlySet; + onRewriteFailure?: (commentId: string, error: unknown) => void; + }, ): Promise { const rows = await readDiscussion(engine, threadId); const derived = participantsByThread(rows); @@ -343,7 +359,11 @@ export async function reconcileCommentThreadParticipants( : storedList(row[COMMENT_PARTICIPANTS_COLUMN]); const listDiffers = !sameList(want, have); const wantRoot = roots ? roots.get(id) ?? null : null; - const rootDiffers = roots !== undefined && wantRoot !== idOf(row[COMMENT_THREAD_ROOT_COLUMN]); + const haveRoot = idOf(row[COMMENT_THREAD_ROOT_COLUMN]); + const rootDiffers = + roots !== undefined && + wantRoot !== haveRoot && + (haveRoot !== null || options.stampOnly === undefined || options.stampOnly.has(id)); if (!listDiffers && !rootDiffers) continue; result.changed += 1; if (rootDiffers) result.roots += 1; @@ -454,6 +474,24 @@ function touchedThreads(ctx: any): string[] { return out; } +/** The rows a write wrote (its result and its target id): the only unstamped replies its reconcile stamps. */ +function writtenIds(ctx: any): Set { + const out = new Set(); + const result = ctx?.result; + if (result && typeof result === 'object' && !Array.isArray(result)) { + const id = idOf((result as Row).id); + if (id) out.add(id); + } + const previous = ctx?.previous; + if (previous && typeof previous === 'object' && !Array.isArray(previous)) { + const id = idOf((previous as Row).id); + if (id) out.add(id); + } + const target = typeof ctx?.input?.id === 'string' ? idOf(ctx.input.id) : null; + if (target) out.add(target); + return out; +} + /** * Install the participant list's writers on `sys_comment`, for every caller * (see "Kept by the platform" in the module header). An engine whose @@ -482,6 +520,7 @@ export function installCommentParticipants(engine: CommentParticipantsEngine, lo const done = await reconcileCommentThreadParticipants(engine, threadId, { apply: true, roots, + stampOnly: writtenIds(ctx), onRewriteFailure: (commentId, e) => reportFailure(threadId, commentId, e), }); if (done.changed === 0 || done.failures > 0) break; diff --git a/packages/plugins/plugin-audit/src/objects/sys-comment.object.ts b/packages/plugins/plugin-audit/src/objects/sys-comment.object.ts index 71d177afd10..75b78d5aee4 100644 --- a/packages/plugins/plugin-audit/src/objects/sys-comment.object.ts +++ b/packages/plugins/plugin-audit/src/objects/sys-comment.object.ts @@ -235,15 +235,16 @@ import { ObjectSchema, Field } from '@objectstack/spec/data'; * - **The stamp.** On create, for every caller and over any value sent, a * reply is stamped from its parent (the parent's id when the parent is * top-level, else the parent's own root) and a top-level comment with - * `null`. The keeper that maintains `participants` brings every reply of the - * discussion to the rule in the same reconcile and the same system write, so - * a re-point or a delete moves the roots under it too. + * `null`. The keeper that maintains `participants` corrects every stamped + * root of the discussion in the same reconcile and the same system write, so + * a re-point or a delete moves the stamped roots under it too, and it stamps + * the rows the write itself wrote (a reply whose parent was unstamped). * - **Read-only.** `readonly: true`: on update a non-system caller's value is * stripped and reported (`droppedFields`), and dropped under `preserveAudit` * too; on create the stamp is assigned over it. * - **Stored rows.** Replies written before the column existed carry `null` - * until `os migrate comment-participants --apply` stamps them, or until the - * next write to their record's discussion reconciles it. Until then the + * until `os migrate comment-participants --apply` stamps them: a later + * write to their discussion stamps only the rows it wrote. Until then the * threads read still counts them, by following `parent_id` for those rows * only, so no reply count drops on a deployment that has not run the * backfill.