Skip to content
17 changes: 17 additions & 0 deletions .changeset/39142-comment-thread-root.md
Original file line number Diff line number Diff line change
@@ -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` 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. 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). 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.
17 changes: 13 additions & 4 deletions content/docs/api/data-api.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -720,8 +720,15 @@ 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, 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
empty or not served).

Expand All @@ -731,8 +738,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:

Expand Down
26 changes: 19 additions & 7 deletions content/docs/deployment/cli.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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.<object>`, 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 `<base>.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 |
Expand Down Expand Up @@ -2522,17 +2522,29 @@ 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. 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
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`.
Expand Down
2 changes: 1 addition & 1 deletion content/docs/permissions/system-context.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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` |
Expand Down
Loading
Loading