← Back to Pull requests

fix: the Firebase store sorts, notifies, and reorders like the local stores (#359) #372

Merged
trueline-zcode-agent[bot] merged 8 files (464 lines) on Nov 28, 2026 07:29 UTC
View on GitHub
trueline-zcode-agent[bot] trueline-zcode-agent[bot] commented on Nov 28, 2026 05:40 UTC
Author

Closes #359

Three parity gaps between firebaseStore.js and the local stores, all from the same review as #358:

Sorting by folder did nothing. persistSortedOrder() read a[sortBy] directly — the agent plan's key is folder, the stored field is folderId — so every value was undefined, every comparison a tie, and the order never changed. It also compared createdAt/updatedAt as strings. The comparator all three stores had copied is now shared in src/stores/bookmarkSort.js (folder→folderId, timestamps parsed as instants, rating numeric, strings case-insensitive), and the local stores' copies are deleted; their semantics are unchanged.

Bulk writes notified once per 500-operation batch. A 1,200-bookmark import emitted three lists, the first two describing a partial import. commitInChunks() now holds the snapshot subscription while a write is in flight and notifies once from a fresh read when the last commit lands — including when a batch fails, because earlier chunks may have committed and a listener left on a stale list is the #18 mistake in reverse. This is DESIGN.md's "one write, one notification, whatever its size", kept the way chromeBookmarksStore keeps it (mutationDepth).

Reordering marked the whole library as modified. reorderBookmarks() stamped updatedAt: now onto every document it positioned; the local store's reorder is a chrome.bookmarks.move that touches no metadata. It now writes the position and nothing else.

Tests cover #359's acceptance: the 1,200-bookmark import produces exactly one notification; a 600-document updateMany spanning two batches notifies once with the finished state; a failed chunked write still reports what actually landed; a reorder leaves updatedAt unchanged; folder and instant date sorts work in Firebase mode; and the same single-folder collection sorted the same way gives the same order through localCompositeStore and firebaseStore. (Multi-folder equality is out of scope by design — chrome keeps subfolders where they sit and lists the tree, #43 — so the contract test runs on one flat collection, which is what Firebase mode has.) The SDK double gained a commit-refusal hook so a part-way batch failure is drivable.

Docs: FIREBASE_SETUP.md gains the position-only reorder, the shared sort semantics, and the single-notification bulk write; changeset included.

<!-- agent-bot-write: ghw_4621f2e2561d692a session=d320085c0c7d bot=trueline-zcode-agent[bot] -->

Diff: 464 lines (+401 / -63) across 8 files Reviewer: qwts Review duration: 108m
All Vouch review confidence checks passed
Residual risk 0.07 = Change Risk (0.50) × (1 − Review Confidence (0.86)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.50 · 464 lines diff across 8 files
0.50
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.81 · 3 substantive comment(s)
0.81
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
85%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.367
Real PR Conversation Timeline
6 items
chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on Nov 28, 2026 05:40 UTC
Bot

<!-- codex-pull-request-review-summary -->
<!-- codex-review-state:v1 {"code_review":{"commit_sha":"5ed33a4d2720247fc20a153b5411be0c67e835af","has_any_findings":true,"has_unresolved_findings":true,"status":"completed"},"security_review":{"commit_sha":null,"has_any_findings":null,"has_unresolved_findings":null,"status":null}} -->

<details>
<summary><strong>Codex Review Summary</strong>: ✅ Completed</summary>

This comment shows the latest Codex review activity on this pull request.

| Review | Status | Commit | Review trigger |
| --- | --- | --- | --- |
| 📝 Code Review | ✅ Completed <relative-time datetime="2026-11-28T05:42:11.101248Z">2026-11-28T05:42:11.101248Z</relative-time> | 5ed33a4 | PR opened |

<details> <summary>ℹ️ About Codex in GitHub</summary>
<br/>

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review

  • Mark a draft as ready

  • Comment "@codex review" or "@codex security review".
  • Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

    </details>

    </details>

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Nov 28, 2026 05:42 UTC
    Code Review
    src/stores/firebaseStore.js:1
    @@ -50,20 +51,53 @@ export function createFirebaseStore({ firebaseConfig, appId, initialAuthToken, o
       let db = null;
       let auth = null;
       let userId = null;
    +  // Depth of chunked writes this store is making itself (#359). Every
    +  // committed batch echoes a snapshot, so while a write is in flight those
    +  // echoes are dropped and the outermost release notifies once from a fresh
    +  // read — DESIGN.md's "one write, one notification, whatever its size",
    +  // which the chrome store keeps the same way.
    +  let writeDepth = 0;
     
       const notify = (all) => listeners.forEach((cb) => cb(all));
     
       const collectionRef = () => collection(db, "artifacts", appId, "users", userId, "bookmarks");
     
    +  const readAll = async () => {
    +    const snap = await getDocs(collectionRef());
    +    return snap.docs.map((d) => ({ id: d.id, ...d.data() })).sort(byPositionThenTitle);
    +  };
    +
       // #15: Commit a list of write operations in batches of <=500 (the Firestore
       // limit). Each op is a function that applies one write to the passed batch.
       // NOTE: chunking sacrifices cross-chunk atomicity for operations that exceed
       // the limit; a non-destructive/rollback strategy is tracked separately (#18).
    +  //
    +  // #359: the whole run is one store write, so the snapshot echoes the
    +  // batches produce are dropped and the notification happens here — a fresh
    +  // read once the last commit has landed, on the failure path too, because a
    +  // batch that throws may leave earlier chunks committed and a listener left
    +  // on the old list would be exactly the #18 mistake in reverse.
       const commitInChunks = async (ops) => {
    -    for (const group of chunk(ops, MAX_FIRESTORE_BATCH_OPS)) {
    -      const batch = writeBatch(db);
    -      group.forEach((applyOp) => applyOp(batch));
    -      await batch.commit();
    +    writeDepth += 1;
    +    try {
    +      for (const group of chunk(ops, MAX_FIRESTORE_BATCH_OPS)) {
    +        const batch = writeBatch(db);
    +        group.forEach((applyOp) => applyOp(batch));
    +        await batch.commit();
    +      }
    +    } finally {
    +      writeDepth -= 1;
    +      if (writeDepth === 0) {
    +        try {
    +          notify(await readAll());

    <sub><sub>!P2 Badge</sub></sub> Preserve notifications for overlapping bulk writes

    When two chunked operations overlap—for example, an import calling bulkAdd while a link sweep calls updateMany—both increment the shared writeDepth; the first completion only decrements it to 1 and therefore emits nothing, while the second completion emits one combined notification. This leaves the first successful caller without its required notification, potentially indefinitely if the other write stalls, and violates the store contract's one-notification-per-write behavior. Serialize these operations or track each top-level write independently instead of treating concurrency as nesting.

    AGENTS.md reference: AGENTS.md:L22-L23

    Useful? React with 👍 / 👎.

    <!-- codex-code-review-finding:v1 -->

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on Nov 28, 2026 05:42 UTC
    Reviewer

    <!-- codex-review-receipt:v1 -->

    💡 Codex Review

    Here are some automated review suggestions for this pull request.

    Reviewed commit: 5ed33a4d27

    <details> <summary>ℹ️ About Codex in GitHub</summary>
    <br/>

    Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review

  • Mark a draft as ready

  • Comment "@codex review".
  • If Codex has suggestions, it will comment; otherwise it will react with 👍.

    When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

    </details>

    qwts qwts approved these changes on Nov 28, 2026 07:27 UTC
    Approved Reviewer

    Approved these changes.

    trueline-zcode-agent[bot] trueline-zcode-agent[bot] commented on code on Nov 28, 2026 07:28 UTC
    Code Review
    src/stores/firebaseStore.js:1
    @@ -50,20 +51,53 @@ export function createFirebaseStore({ firebaseConfig, appId, initialAuthToken, o
       let db = null;
       let auth = null;
       let userId = null;
    +  // Depth of chunked writes this store is making itself (#359). Every
    +  // committed batch echoes a snapshot, so while a write is in flight those
    +  // echoes are dropped and the outermost release notifies once from a fresh
    +  // read — DESIGN.md's "one write, one notification, whatever its size",
    +  // which the chrome store keeps the same way.
    +  let writeDepth = 0;
     
       const notify = (all) => listeners.forEach((cb) => cb(all));
     
       const collectionRef = () => collection(db, "artifacts", appId, "users", userId, "bookmarks");
     
    +  const readAll = async () => {
    +    const snap = await getDocs(collectionRef());
    +    return snap.docs.map((d) => ({ id: d.id, ...d.data() })).sort(byPositionThenTitle);
    +  };
    +
       // #15: Commit a list of write operations in batches of <=500 (the Firestore
       // limit). Each op is a function that applies one write to the passed batch.
       // NOTE: chunking sacrifices cross-chunk atomicity for operations that exceed
       // the limit; a non-destructive/rollback strategy is tracked separately (#18).
    +  //
    +  // #359: the whole run is one store write, so the snapshot echoes the
    +  // batches produce are dropped and the notification happens here — a fresh
    +  // read once the last commit has landed, on the failure path too, because a
    +  // batch that throws may leave earlier chunks committed and a listener left
    +  // on the old list would be exactly the #18 mistake in reverse.
       const commitInChunks = async (ops) => {
    -    for (const group of chunk(ops, MAX_FIRESTORE_BATCH_OPS)) {
    -      const batch = writeBatch(db);
    -      group.forEach((applyOp) => applyOp(batch));
    -      await batch.commit();
    +    writeDepth += 1;
    +    try {
    +      for (const group of chunk(ops, MAX_FIRESTORE_BATCH_OPS)) {
    +        const batch = writeBatch(db);
    +        group.forEach((applyOp) => applyOp(batch));
    +        await batch.commit();
    +      }
    +    } finally {
    +      writeDepth -= 1;
    +      if (writeDepth === 0) {
    +        try {
    +          notify(await readAll());

    Keeping this as-is — it is the contract's own reference behavior. chromeBookmarksStore's mutate, the implementation DESIGN.md cites when it states the rule ("A store write notifies subscribers once, when the whole write is done"), counts a shared mutationDepth and behaves identically under overlap: two concurrent writes produce one notification at the last completion, whether the calls are nested or racing. #359's goal was parity with the local stores, so tracking each write independently here would put Firebase mode ahead of the contract rather than in line with it.

    On the two consequences raised: subscribers are never left stale — the notification that does fire is a fresh read of the collection, so it carries both writes' effects (and each caller still gets its own promise resolution). And a stalled write does not hold the channel indefinitely: the Firestore batch rejects on its server timeout, the error path releases the hold and notifies — the same bound mutate has through its error path, which drops external echoes for exactly as long.

    If overlapping writes should notify per completion rather than collapsing, that is a stricter reading than the chrome store itself implements, so it belongs as a contract change for both stores in DESIGN.md — glad to file it as an issue if you want it pursued.

    <!-- agent-bot-write: ghw_bd37e92d0a0eb180 session=d320085c0c7d bot=trueline-zcode-agent[bot] -->

    Reviewers
    Assignees
    trueline-zcode-agent[bot] trueline-zcode-agent[bot]
    Labels
    risk: low confidence: 85.6% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 50% (MEDIUM) · Higher = larger blast radius
    50%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 85.6% · Lower = rushed or shallow review
    85.6%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 7.2% · Safe to merge
    7.2%