Skip to content

Commit 2b906d9

Browse files
committed
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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WGufziM2GUsShZcjp6TiyD
1 parent 7e8c04a commit 2b906d9

6 files changed

Lines changed: 85 additions & 19 deletions

File tree

‎.changeset/39142-comment-thread-root.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,10 @@ perf(plugin-audit): the comment threads read counts replies with one grouped rea
88
Clause-②: yes (widening)
99
Metadata-protocol: none
1010

11-
`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.
11+
`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.
1212

13-
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.
13+
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.
1414

1515
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.
1616

17-
**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.
17+
**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.

‎content/docs/api/data-api.mdx‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -723,9 +723,10 @@ next page (`null` on the last):
723723
`replyCount` counts the replies under the thread up to 15 levels below it: a
724724
reply 16 or more levels deep belongs to no thread, by the rule the thread's
725725
participants are kept by. `repliers` are the latest distinct ones, newest first, at most
726-
three. Both are taken with one grouped read of the page's replies by the thread
727-
each reply stores (`thread_root_id`), so a page costs the same however many
728-
replies its threads hold. Replies written before that column existed are still
726+
three, ordered by id when two replied in the same millisecond. Both come from
727+
one grouped read of the page's replies by the thread each reply stores
728+
(`thread_root_id`), plus one read of the candidate repliers' newest replies,
729+
so a page costs the same however many replies its threads hold. Replies written before that column existed are still
729730
counted, by following each up its chain, until `os migrate comment-participants
730731
--apply` stamps them. `record.name` is the
731732
record's title field read as the caller (`Record #` and the id when it is

‎content/docs/deployment/cli.mdx‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2531,7 +2531,8 @@ repliers with one grouped read by that column. Replies written before the
25312531
upgrade carry no root. The read still counts them, by following each one up
25322532
its chain, so no count drops before this command runs, but that read grows
25332533
with the number of such replies on the page's records. This command stamps
2534-
them, and so does the next comment written on the same record.
2534+
them. Nothing else does: a later reply or a re-point stamps only the rows it
2535+
wrote, so a user's request never pays for a record's backlog of old replies.
25352536
25362537
```bash
25372538
os migrate comment-participants # Dry run: counts, writes no rows

‎packages/plugins/plugin-audit/src/comment-participants.test.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -334,6 +334,30 @@ describe('the thread root — reconcile and create stamp', () => {
334334
expect(rows.find((r) => r.id === 'a.1.1')!.thread_root_id).toBe('a.1.1');
335335
});
336336

337+
it('a user\'s reply stamps only itself: the discussion\'s unstamped backlog waits for the backfill, a stamped root is still corrected', async () => {
338+
const backlog = Array.from({ length: 50 }, (_, i): Row => ({
339+
id: `old.${i}`, thread_id: T, parent_id: 'a', author_id: 'u_b', mentions: null, participants: null, created_at: `0${i}`,
340+
}));
341+
const rows: Row[] = [
342+
{ id: 'a', thread_id: T, parent_id: null, author_id: 'u_a', mentions: null, participants: ['u_a', 'u_b'], created_at: '00' },
343+
...backlog,
344+
// stamped, but wrong: corrected by any reconcile
345+
{ id: 'moved', thread_id: T, parent_id: 'a', thread_root_id: 'elsewhere', author_id: 'u_b', mentions: null, participants: null, created_at: '1' },
346+
// the new reply, under an unstamped parent: the create could not stamp it
347+
{ id: 'new', thread_id: T, parent_id: 'old.3', thread_root_id: null, author_id: 'u_c', mentions: null, participants: null, created_at: '2' },
348+
];
349+
const engine = discussionEngine(rows);
350+
installCommentParticipants(engine, { warn: vi.fn() });
351+
await handler(engine, 'afterInsert')({ result: rows[rows.length - 1], input: { data: {} } });
352+
const rootWrites = engine.updates.filter((u) => 'thread_root_id' in u.data).map((u) => [u.data.id, u.data.thread_root_id]);
353+
expect(rootWrites).toEqual([['moved', 'a'], ['new', 'a']]);
354+
expect(backlog.every((r) => r.thread_root_id === undefined)).toBe(true);
355+
// The backfill (no stampOnly) stamps the backlog.
356+
const backfill = await reconcileCommentThreadParticipants(engine, T, { apply: true });
357+
expect(backfill.roots).toBe(50);
358+
expect(backlog.every((r) => r.thread_root_id === 'a')).toBe(true);
359+
});
360+
337361
it('a create stamps a reply from its parent and a top-level comment with null, over a client value', async () => {
338362
const parents: Row[] = [
339363
{ id: 'top', thread_id: T, parent_id: null },

‎packages/plugins/plugin-audit/src/comment-participants.ts‎

Lines changed: 46 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -83,11 +83,15 @@
8383
* thread; `null` on a top-level comment. The comment threads read groups a
8484
* page's replies by it (`comment-threads-query.ts`). It rides every step
8585
* above: the create stamps a reply from its parent (one read of the parents,
86-
* as the platform), and the reconcile brings every row of the discussion to
87-
* the rule, in the same single-id write that carries the list. A reply that
88-
* still carries `null` has not been stamped (written before the column, or
89-
* its parent was itself unstamped at create); the next reconcile of its
90-
* discussion, or `os migrate comment-participants --apply`, stamps it.
86+
* as the platform), and the reconcile corrects every stamped root of the
87+
* discussion the rule moved (a re-point, a delete), in the same single-id
88+
* write that carries the list. A reply that still carries `null` has not been
89+
* stamped (written before the column, or its parent was itself unstamped at
90+
* create). After a write, the reconcile stamps only the rows that write wrote,
91+
* so the first reply on a discussion with a thousand old replies writes one
92+
* root, not a thousand system updates with their audit and activity rows;
93+
* `os migrate comment-participants --apply` stamps the rest, and the threads
94+
* read counts unstamped replies by their chain until it has.
9195
*
9296
* ## The reply notice is a separate audience
9397
*
@@ -327,7 +331,19 @@ export interface ThreadParticipantsReconciliation {
327331
export async function reconcileCommentThreadParticipants(
328332
engine: Pick<CommentParticipantsEngine, 'find' | 'update'>,
329333
threadId: string,
330-
options: { apply: boolean; roots?: boolean; onRewriteFailure?: (commentId: string, error: unknown) => void },
334+
options: {
335+
apply: boolean;
336+
roots?: boolean;
337+
/**
338+
* The unstamped replies this call may stamp. Absent: every one (the
339+
* backfill). A set: only those ids (the keeper after a write names the
340+
* rows it wrote), so a user's write never stamps a discussion's backlog —
341+
* the backfill does that, and the threads read counts unstamped replies
342+
* until then. A root already stamped is corrected either way.
343+
*/
344+
stampOnly?: ReadonlySet<string>;
345+
onRewriteFailure?: (commentId: string, error: unknown) => void;
346+
},
331347
): Promise<ThreadParticipantsReconciliation> {
332348
const rows = await readDiscussion(engine, threadId);
333349
const derived = participantsByThread(rows);
@@ -343,7 +359,11 @@ export async function reconcileCommentThreadParticipants(
343359
: storedList(row[COMMENT_PARTICIPANTS_COLUMN]);
344360
const listDiffers = !sameList(want, have);
345361
const wantRoot = roots ? roots.get(id) ?? null : null;
346-
const rootDiffers = roots !== undefined && wantRoot !== idOf(row[COMMENT_THREAD_ROOT_COLUMN]);
362+
const haveRoot = idOf(row[COMMENT_THREAD_ROOT_COLUMN]);
363+
const rootDiffers =
364+
roots !== undefined &&
365+
wantRoot !== haveRoot &&
366+
(haveRoot !== null || options.stampOnly === undefined || options.stampOnly.has(id));
347367
if (!listDiffers && !rootDiffers) continue;
348368
result.changed += 1;
349369
if (rootDiffers) result.roots += 1;
@@ -454,6 +474,24 @@ function touchedThreads(ctx: any): string[] {
454474
return out;
455475
}
456476

477+
/** The rows a write wrote (its result and its target id): the only unstamped replies its reconcile stamps. */
478+
function writtenIds(ctx: any): Set<string> {
479+
const out = new Set<string>();
480+
const result = ctx?.result;
481+
if (result && typeof result === 'object' && !Array.isArray(result)) {
482+
const id = idOf((result as Row).id);
483+
if (id) out.add(id);
484+
}
485+
const previous = ctx?.previous;
486+
if (previous && typeof previous === 'object' && !Array.isArray(previous)) {
487+
const id = idOf((previous as Row).id);
488+
if (id) out.add(id);
489+
}
490+
const target = typeof ctx?.input?.id === 'string' ? idOf(ctx.input.id) : null;
491+
if (target) out.add(target);
492+
return out;
493+
}
494+
457495
/**
458496
* Install the participant list's writers on `sys_comment`, for every caller
459497
* (see "Kept by the platform" in the module header). An engine whose
@@ -482,6 +520,7 @@ export function installCommentParticipants(engine: CommentParticipantsEngine, lo
482520
const done = await reconcileCommentThreadParticipants(engine, threadId, {
483521
apply: true,
484522
roots,
523+
stampOnly: writtenIds(ctx),
485524
onRewriteFailure: (commentId, e) => reportFailure(threadId, commentId, e),
486525
});
487526
if (done.changed === 0 || done.failures > 0) break;

‎packages/plugins/plugin-audit/src/objects/sys-comment.object.ts‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -235,15 +235,16 @@ import { ObjectSchema, Field } from '@objectstack/spec/data';
235235
* - **The stamp.** On create, for every caller and over any value sent, a
236236
* reply is stamped from its parent (the parent's id when the parent is
237237
* top-level, else the parent's own root) and a top-level comment with
238-
* `null`. The keeper that maintains `participants` brings every reply of the
239-
* discussion to the rule in the same reconcile and the same system write, so
240-
* a re-point or a delete moves the roots under it too.
238+
* `null`. The keeper that maintains `participants` corrects every stamped
239+
* root of the discussion in the same reconcile and the same system write, so
240+
* a re-point or a delete moves the stamped roots under it too, and it stamps
241+
* the rows the write itself wrote (a reply whose parent was unstamped).
241242
* - **Read-only.** `readonly: true`: on update a non-system caller's value is
242243
* stripped and reported (`droppedFields`), and dropped under `preserveAudit`
243244
* too; on create the stamp is assigned over it.
244245
* - **Stored rows.** Replies written before the column existed carry `null`
245-
* until `os migrate comment-participants --apply` stamps them, or until the
246-
* next write to their record's discussion reconciles it. Until then the
246+
* until `os migrate comment-participants --apply` stamps them: a later
247+
* write to their discussion stamps only the rows it wrote. Until then the
247248
* threads read still counts them, by following `parent_id` for those rows
248249
* only, so no reply count drops on a deployment that has not run the
249250
* backfill.

0 commit comments

Comments
 (0)