Skip to content

fix(web): hydrate ManyToOneRef labels for groups and SearchFilter preview - #601

Merged
buke merged 7 commits into
mainfrom
feat/web-m2oref-group-label-hydrate
Nov 21, 2026
Merged

buke merged 7 commits into
mainfrom
feat/web-m2oref-group-label-hydrate

Conversation

@buke

@buke buke commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

User description

Summary

  • Hydrate ManyToOneRef group row labels on the frontend after readGroup via shared batchLoadRefRecordsByModel, keeping group keys as bare ids.
  • Resolve manytoone / manytooneref DisplayName in SearchFilter Preview with a short-lived label cache (condition storage stays ids).
  • Add unit coverage for group hydrate, filter id collection, cache stale-generation, and SearchFilter preview.

Test plan

  • ./choysum test typecheck web
  • ./choysum test unit web --fe
  • ./choysum test e2e web
  • ./choysum test e2e auth
  • Manually: /web/auth/users group by Company / Language — headers show names
  • Manually: open Search filter editor with CompanyId / LanguageId conditions — Preview shows DisplayName

Summary by Sourcery

Hydrate ManyToOneRef labels across grouped results and SearchFilter previews without altering stored query IDs.

Bug Fixes:

  • Display relation names in SearchFilter previews while preserving raw condition IDs.
  • Hydrate ManyToOneRef group labels for grouped query results while keeping group keys as IDs.

Enhancements:

  • Centralize batched relation-record loading and add short-lived, generation-safe relation label caching for filter previews.

Tests:

  • Add coverage for group label hydration, relation ID collection and formatting, batched loading, preview labels, cache invalidation, stale requests, and fallback behavior.

PR Type

Bug fix, Enhancement, Tests


Description

  • Hydrate ManyToOneRef group labels after readGroup via shared batch loader

  • Show relation DisplayName in SearchFilter preview with short-lived cache

  • Extract shared relation utilities and refactor executor hydration

  • Add unit tests for group hydrate, filter ids, cache staleness, preview


File Walkthrough

Relevant files
Tests
5 files
SearchFilter.preview.test.ts
Add preview DisplayName hydration tests                                   
+102/-1 
useFilterRelationLabelCache.test.ts
Test label cache hydration and stale generations                 
+82/-0   
executor.m2oref_group_hydrate.test.ts
Test readGroup ManyToOneRef label hydration                           
+206/-0 
displayNameBatch.test.ts
Test batch ref record loading utility                                       
+47/-0   
filterRelationLabels.test.ts
Test filter relation id collection helpers                             
+81/-0   
Enhancement
5 files
index.ts
Export new relation label cache composable                             
+1/-0     
useFilterRelationLabelCache.ts
Add short-lived filter relation label cache composable     
+91/-0   
executor.ts
Hydrate group ref labels and share batch loader                   
+89/-32 
displayNameBatch.ts
Add shared batch ref record loader                                             
+51/-0   
filterRelationLabels.ts
Add filter relation id collection and preview helpers       
+118/-0 
Bug fix
1 files
SearchFilter.vue
Resolve relation DisplayName in filter preview                     
+26/-7   

Summary by CodeRabbit

  • New Features
    • Search filter previews and grouped search results display related record names when available, including within nested groups.
    • Related names are loaded in batches, including for searches involving many records.
  • Bug Fixes
    • Related values retain their IDs when matching records are unavailable or cannot be loaded.
    • Preview labels update when filter values change, and results from older searches no longer overwrite newer labels.

buke added 2 commits November 21, 2026 21:28
Show DisplayName for *Ref groupbys (e.g. CompanyId/LanguageId) via
batch Search after readGroup, keeping group keys as bare ids.
Batch-resolve manytoone/manytooneref ids for the filter editor preview
while keeping stored condition values as bare ids.
@sourcery-ai

sourcery-ai Bot commented Nov 21, 2026

Copy link
Copy Markdown

Sorry @buke, you've used your own review budget of 250,000 diff characters for the last 7 days.

You can request another review in 3 days and 1 hour by commenting @sourcery-ai review. Upgrade to get a review now.

@sourcery-ai

sourcery-ai Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

API

Expose the relation-label cache composable and its dependencies for SearchFilter preview hydration.

  • modules/web/web/composables/search/index.ts L10
  • modules/web/web/composables/search/useFilterRelationLabelCache.ts L1-93

Implementation

Centralize batched relation-record loading and filter relation ID collection, signatures, cache keys, and preview formatting.

  • modules/web/web/query/utils/relation/displayNameBatch.ts L1-74
  • modules/web/web/query/utils/relation/filterRelationLabels.ts L1-117

Reuse the batch loader for record hydration and hydrate ManyToOneRef labels in grouped results without changing group keys or non-Ref labels.

  • modules/web/web/query/executor.ts L11-14, L25-31, L77-159 (+7 small edits)

UI

Use the relation-label cache to render manytoone and manytooneref preview values with DisplayName when available, falling back to IDs.

  • modules/web/web/components/view/search/SearchFilter.vue L98-111, L142-147, L187-191 (+2 small edits)

Tests

Verify SearchFilter preview hydration, missing-record fallback, and existing event behavior.

  • modules/web/web/components/view/search/SearchFilter.preview.test.ts L6, L150-249

Exercise cache hydration, stale-generation handling, replacement and clearing, and refresh error handling.

  • modules/web/web/composables/search/useFilterRelationLabelCache.test.ts L1-172

Verify readGroup label hydration for flat and nested Ref groups, fallback behavior, and preservation of ordinary ManyToOne labels.

  • modules/web/web/query/executor.m2oref_group_hydrate.test.ts L1-274

Cover shared batch loading behavior, chunking and failure handling, and temporal group alias normalization.

  • modules/web/web/query/utils/relation/displayNameBatch.test.ts L1-126

Test relation ID extraction and collection, stable batch signatures, preview formatting, and cache-key generation.

  • modules/web/web/query/utils/relation/filterRelationLabels.test.ts L1-84

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@coderabbitai

coderabbitai Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The change adds batched relation-label lookup for filter previews and grouped query results. Filter previews use cached display names for ManyToOne and ManyToOneRef values, with IDs as fallbacks. Grouped ManyToOneRef results receive matching labels without changes to their group keys.

Changes: Relation labels

Layer / File(s) Summary
Relation lookup utilities
modules/web/web/query/utils/relation/filterRelationLabels.ts, modules/web/web/query/utils/relation/filterRelationLabels.test.ts, modules/web/web/query/utils/relation/displayNameBatch.ts, modules/web/web/query/utils/relation/displayNameBatch.test.ts
Helpers extract relation IDs, collect IDs from nested filter groups, format preview values, and create stable batch signatures. The batch loader searches each model for requested IDs and indexes returned records by ID.
Filter preview label cache
modules/web/web/composables/search/useFilterRelationLabelCache.ts, modules/web/web/composables/search/useFilterRelationLabelCache.test.ts, modules/web/web/composables/search/index.ts, modules/web/web/components/view/search/SearchFilter.vue, modules/web/web/components/view/search/SearchFilter.preview.test.ts
The cache refreshes labels when relation IDs change and ignores stale search results. SearchFilter uses cached labels for ManyToOne and ManyToOneRef preview values, with IDs as fallbacks.
Grouped query reference labels
modules/web/web/query/executor.ts, modules/web/web/query/executor.m2oref_group_hydrate.test.ts
The executor batch-loads ManyToOneRef records for grouped results and updates matching row labels. It preserves group keys and leaves ordinary ManyToOne labels unchanged.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant SearchFilter
  participant useFilterRelationLabelCache
  participant batchLoadRefRecordsByModel
  participant ModelStore
  SearchFilter->>useFilterRelationLabelCache: provide store and filter root
  useFilterRelationLabelCache->>batchLoadRefRecordsByModel: load relation IDs
  batchLoadRefRecordsByModel->>ModelStore: Search IDs for Id and DisplayName
  ModelStore-->>batchLoadRefRecordsByModel: return matching records
  batchLoadRefRecordsByModel-->>useFilterRelationLabelCache: return records indexed by Id
  useFilterRelationLabelCache-->>SearchFilter: update cached labels
Loading
Merge Risk: Minimal · up to 2a99f

This change loads related-record display names for filter previews and grouped results, and falls back to raw IDs when a lookup fails. No concrete merge-blocking risk was identified. The manual checks of grouped Company/Language headers and SearchFilter previews are still outstanding.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title "fix(web): hydrate ManyToOneRef labels for groups and SearchFilter preview" names the two main changes: group label hydration after readGroup and relation DisplayName in SearchFilter preview…
Description check Passed The description covers the summary of changes, the test plan with checked and unchecked items, and a file walkthrough. The repository template contains only the CLA notice, which the description does …
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title "fix(web): hydrate ManyToOneRef labels for groups and SearchFilter preview" names the two main changes: group label hydration after readGroup and relation DisplayName in SearchFilter preview. It is specific and matches the changeset. It uses a conventional-commit prefix, which is acceptable.

Full details: Description check

Explanation

The description covers the summary of changes, the test plan with checked and unchecked items, and a file walkthrough. The repository template contains only the CLA notice, which the description does not need to repeat. The description is detailed, and the two unchecked manual verification steps are the only open items. The description does not follow the template literally, but the template has no required sections beyond the CLA footer, which is absent. The description gives enough context for reviewers.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 02ccd67 and 2a99fc7.

Files selected for processing: 4

  • modules/web/web/composables/search/useFilterRelationLabelCache.test.ts
  • modules/web/web/composables/search/useFilterRelationLabelCache.ts
  • modules/web/web/query/utils/relation/displayNameBatch.test.ts
  • modules/web/web/query/utils/relation/displayNameBatch.ts

Included review availability: This review used your included allowance. 0 included reviews remain after this review. Your included PR review attempts over the past 7 days set your current allowance at 2 reviews per hour.

Comment thread modules/web/web/query/executor.ts Resolved
Comment thread modules/web/web/query/executor.ts Resolved
@github-actions

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
🧪 PR contains tests
🔒 No security concerns identified
✅ No TODO sections

@github-actions

Copy link
Copy Markdown

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Possible bug
Preserve composite group labels

node.label is overwritten with the first alias's label whenever any alias changed,
which can clobber a backend-provided composite label (e.g. multi-field groupby).
Only set node.label when the row has a single group key, otherwise leave the backend
label intact.

modules/web/web/query/executor.ts [108-143]

     const apply = (nodes: GroupRow[]) => {
       for (const node of nodes) {
         const keys = node.keys || {};
         const labels: Record<string, string> = { ...(node.labels || {}) };
         let changed = false;
         for (const alias of Object.keys(keys)) {
           const field = refFields.get(baseFieldFromGroupAlias(alias));
           if (!field?.relationModel) continue;
           const val = keys[alias];
           if (!(val && typeof val === 'string')) continue;
           const rec = lookups.get(field.relationModel)?.get(val);
           if (!rec) continue;
           const display = String(rec.DisplayName ?? rec.Id ?? val);
           if (labels[alias] !== display) {
             labels[alias] = display;
             changed = true;
           }
         }
         if (changed) {
           node.labels = labels;
           if (node.raw && typeof node.raw === 'object') {
             (node.raw as { labels?: Record<string, string> }).labels = {
               ...((node.raw as { labels?: Record<string, string> }).labels || {}),
               ...labels,
             };
           }
-          const aliases = Object.keys(keys).sort();
-          const firstAlias = aliases[0];
-          if (firstAlias && labels[firstAlias] != null && labels[firstAlias] !== '') {
-            node.label = String(labels[firstAlias]);
+          const aliases = Object.keys(keys);
+          if (aliases.length === 1) {
+            const firstAlias = aliases[0];
+            if (labels[firstAlias] != null && labels[firstAlias] !== '') {
+              node.label = String(labels[firstAlias]);
+            }
           }
         }
         if (node.children?.length) apply(node.children);
       }
     };
Suggestion importance[1-10]: 7

__

Why: Overwriting node.label with the first alias's label can clobber a backend composite label for multi-field groupby, which is a plausible correctness regression. The improved_code correctly restricts the overwrite to single-key rows, though the impact depends on whether composite groupbys are actually used.

Medium
Performance
Avoid duplicate collection and debounce refresh

The watcher recomputes collectRelationIdsFromGroup twice per change (once for the
signature, once in the callback) and fires a Search on every keystroke-level draft
change. Compute the batch once in the getter and debounce the refresh so rapid edits
don't spam the target service.

modules/web/web/composables/search/useFilterRelationLabelCache.ts [61-78]

   watch(
     () => {
       const meta = (store as any)?.fieldsMetadata || {};
       const batch = collectRelationIdsFromGroup(getRoot(), meta);
-      return relationIdBatchSignature(batch);
+      return { signature: relationIdBatchSignature(batch), batch };
     },
-    async signature => {
+    async ({ signature, batch }) => {
       const gen = ++generation;
-      const meta = (store as any)?.fieldsMetadata || {};
-      const batch = collectRelationIdsFromGroup(getRoot(), meta);
       if (!signature) {
         await refresh(new Map(), gen);
         return;
       }
       await refresh(batch, gen);
     },
     { immediate: true }
   );
Suggestion importance[1-10]: 6

__

Why: The watcher does recompute collectRelationIdsFromGroup twice per change, and the improved_code correctly consolidates it into a single getter returning { signature, batch }. However, the suggestion's title mentions debouncing but the improved_code does not actually add debouncing, so it only partially delivers on its stated purpose.

Low
Chunk large id lookups

Array.from(ids) can grow unbounded (e.g. a filter with thousands of ids or a large
group result), producing an oversized in condition. Chunk the ids into bounded
batches and merge results so a single huge lookup can't fail or overload the target
service.

modules/web/web/query/utils/relation/displayNameBatch.ts [29-31]

-        const results = await targetStore.Search(['Id', 'in', Array.from(ids)], {
-          fields: ['Id', 'DisplayName'],
-        });
+        const CHUNK = 500;
+        const idList = Array.from(ids);
+        const map = new Map<string, any>();
+        for (let i = 0; i < idList.length; i += CHUNK) {
+          const chunk = idList.slice(i, i + CHUNK);
+          const results = await targetStore.Search(['Id', 'in', chunk], {
+            fields: ['Id', 'DisplayName'],
+          });
+          for (const r of (results as Array<{ Id?: unknown }>) || []) {
+            const key = String(r.Id ?? '');
+            if (!key || key === 'undefined') continue;
+            map.set(key, r);
+          }
+        }
+        lookups.set(model, map);
Suggestion importance[1-10]: 5

__

Why: Chunking the in condition is a reasonable hardening for large id sets, but the PR's batch sizes are typically small (filter drafts / group rows) and this is a speculative performance concern rather than a demonstrated bug. The improved_code correctly reflects the change.

Low
Possible issue
Make batch signature collision-safe

relationIdBatchSignature joins ids with , and models with |/=, so ids containing
those characters (or a model/id pair like a=b) can produce colliding signatures and
skip a needed refresh. Use a delimiter-safe encoding such as JSON.stringify of the
sorted structure.

modules/web/web/query/utils/relation/filterRelationLabels.ts [94-101]

+export function relationIdBatchSignature(batch: Map<string, Set<string>>): string {
+  const parts: string[] = [];
+  for (const model of Array.from(batch.keys()).sort()) {
+    const ids = Array.from(batch.get(model) || []).sort();
+    parts.push(`${JSON.stringify(model)}=${JSON.stringify(ids)}`);
+  }
+  return parts.join('|');
+}
 
-
Suggestion importance[1-10]: 4

__

Why: The delimiter-collision concern is theoretically valid but unlikely in practice since ids are typically opaque identifiers without ,/|/=. The existing_code is empty rather than matching the actual snippet, though the improved_code does correctly target relationIdBatchSignature.

Low

@codecov

codecov Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ All tests successful. No failed tests found.

📢 Thoughts on this report? Let us know!

- Replace filter label cache on each draft batch (evict stale ids)
- Chunk Ref DisplayName Search IN lists; only patch Ref raw.labels
- Cover empty-cache clear, catch path, and non-id preview values
@github-actions

Copy link
Copy Markdown

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Possible bug
Preserve partial results on chunk failure

If a later chunk's Search throws, the whole target is caught and lookups never gets
set, discarding records already resolved from earlier chunks. Wrap each chunk in its
own try/catch so partial results are preserved and only the failing chunk is
skipped.

modules/web/web/query/utils/relation/displayNameBatch.ts [34-44]

-        const results = await targetStore.Search(['Id', 'in', chunk], {
-          fields: ['Id', 'DisplayName'],
-        });
-        for (const r of (results as Array<{ Id?: unknown }>) || []) {
-          const key = String(r.Id ?? '');
-          if (!key || key === 'undefined') continue;
-          map.set(key, r);
+        for (let i = 0; i < idList.length; i += REF_DISPLAY_NAME_IN_CHUNK) {
+          const chunk = idList.slice(i, i + REF_DISPLAY_NAME_IN_CHUNK);
+          try {
+            const results = await targetStore.Search(['Id', 'in', chunk], {
+              fields: ['Id', 'DisplayName'],
+            });
+            for (const r of (results as Array<{ Id?: unknown }>) || []) {
+              const key = String(r.Id ?? '');
+              if (!key || key === 'undefined') continue;
+              map.set(key, r);
+            }
+          } catch (e) {
+            console.warn(`${logPrefix} Failed to hydrate chunk for target '${model}'`, e);
+          }
         }
Suggestion importance[1-10]: 6

__

Why: Correct observation: a failure in a later chunk discards already-resolved records from earlier chunks because the whole target is wrapped in one try/catch. Per-chunk try/catch is a reasonable hardening, though the impact is limited since callers fall back to raw ids.

Low
Possible issue
Avoid double collection and unhandled rejection

The watcher recomputes collectRelationIdsFromGroup twice per change (once in the
getter, once in the callback), and the callback's await refresh(...) rejection is
unhandled. Reuse the collected batch from the getter and guard the async callback so
a failed batch load cannot surface as an unhandled rejection.

modules/web/web/composables/search/useFilterRelationLabelCache.ts [58-75]

   watch(
     () => {
       const meta = (store as any)?.fieldsMetadata || {};
       const batch = collectRelationIdsFromGroup(getRoot(), meta);
-      return relationIdBatchSignature(batch);
+      return { signature: relationIdBatchSignature(batch), batch };
     },
-    async signature => {
+    async ({ signature, batch }) => {
       const gen = ++generation;
-      const meta = (store as any)?.fieldsMetadata || {};
-      const batch = collectRelationIdsFromGroup(getRoot(), meta);
-      if (!signature) {
-        await refresh(new Map(), gen);
-        return;
+      try {
+        if (!signature) {
+          await refresh(new Map(), gen);
+          return;
+        }
+        await refresh(batch, gen);
+      } catch (e) {
+        console.warn('[SearchFilter] Failed to hydrate relation labels', e);
       }
-      await refresh(batch, gen);
     },
     { immediate: true }
   );
Suggestion importance[1-10]: 6

__

Why: The double collectRelationIdsFromGroup call and the unguarded await refresh(...) in the async watcher callback are real, if minor, issues. The improved code correctly reuses the collected batch and guards against unhandled rejections, improving robustness without changing behavior.

Low
Performance
Avoid blocking group query on hydration

hydrateGroupRefLabels awaits a network Search before returning the snapshot, so
every readGroup now blocks on an extra round-trip (and on a slow/hanging target
store). Consider making the hydration non-blocking (fire-and-forget with a re-emit)
or at least bounding it with a timeout so a slow relation store cannot stall the
whole group query.

modules/web/web/query/executor.ts [699-702]

     const rows = toGroupRows(groups);
     // *Ref display names are frontend-only: rewrite group labels without changing keys.
-    await hydrateGroupRefLabels(store, rows, storeDeps);
+    // Do not let a slow relation store block the group snapshot.
+    await Promise.race([
+      hydrateGroupRefLabels(store, rows, storeDeps),
+      new Promise<void>(resolve => setTimeout(resolve, 3000)),
+    ]);
     return { kind: 'group', rows, total, planHash: main.hash, ts: Date.now(), uiView };
Suggestion importance[1-10]: 4

__

Why: The concern about an extra round-trip is valid, but the proposed Promise.race with a fixed timeout is a fragile fix: it leaves the hydration promise running and mutating rows after the snapshot is returned, causing non-deterministic labels. The PR intentionally awaits hydration to produce correct labels, so this is a design trade-off rather than a clear bug.

Low
Maintainability
Hoist resolved Ref aliases once

baseFieldFromGroupAlias splits on __, but a groupby alias can also carry a temporal
suffix on a non-Ref field whose base name collides with a Ref field name. More
importantly, Object.keys(keys) is iterated twice (here and in the raw.labels patch)
with the same lookup; hoist the resolved aliases once to avoid divergence if the two
loops ever drift.

modules/web/web/query/executor.ts [108-125]

     const apply = (nodes: GroupRow[]) => {
       for (const node of nodes) {
         const keys = node.keys || {};
         const labels: Record<string, string> = { ...(node.labels || {}) };
-        let changed = false;
+        const resolved: Array<{ alias: string; display: string }> = [];
         for (const alias of Object.keys(keys)) {
           const field = refFields.get(baseFieldFromGroupAlias(alias));
           if (!field?.relationModel) continue;
           const val = keys[alias];
           if (!(val && typeof val === 'string')) continue;
           const rec = lookups.get(field.relationModel)?.get(val);
           if (!rec) continue;
           const display = String(rec.DisplayName ?? rec.Id ?? val);
-          if (labels[alias] !== display) {
-            labels[alias] = display;
-            changed = true;
-          }
+          resolved.push({ alias, display });
+          labels[alias] = display;
         }
+        const changed = resolved.some(r => node.labels?.[r.alias] !== r.display);
Suggestion importance[1-10]: 3

__

Why: This is a maintainability refactor with no functional bug. The improved_code also changes changed semantics (comparing against node.labels rather than the copied labels), which is subtly different and not clearly equivalent, so the benefit is marginal.

Low

Keep earlier Search chunks when a later chunk fails, and avoid
double-collect / unhandled rejection in the filter label watcher.
@buke

buke commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor Author

Evaluated the optional suggestions in #601 (comment):

Suggestion Decision
Preserve partial results on chunk failure Adopted — per-chunk try/catch; earlier chunks kept
Avoid double collection + unhandled rejection Adopted — stash batch from watch source; wrap refresh in try/catch
Avoid blocking group query (Promise.race timeout) Declined — would race-mutate labels after return; intentional await
Hoist resolved Ref aliases Declined — maintainability-only; proposed changed semantics are not equivalent

Pushed as 6e2f2634.

@github-actions

Copy link
Copy Markdown

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Possible bug
Avoid stale pending batch in watcher

The watch source mutates the shared pendingBatch and the callback reads it back, so
if the source re-runs before the async callback executes, batch may not match
signature. Recompute the batch inside the callback from getRoot() (or key a map by
signature) so the fetched ids always correspond to the signature that triggered the
refresh.

modules/web/web/composables/search/useFilterRelationLabelCache.ts [60-68]

   watch(
     () => {
       const meta = (store as any)?.fieldsMetadata || {};
-      pendingBatch = collectRelationIdsFromGroup(getRoot(), meta);
-      return relationIdBatchSignature(pendingBatch);
+      return relationIdBatchSignature(collectRelationIdsFromGroup(getRoot(), meta));
     },
     async signature => {
       const gen = ++generation;
-      const batch = pendingBatch;
+      const meta = (store as any)?.fieldsMetadata || {};
+      const batch = collectRelationIdsFromGroup(getRoot(), meta);
Suggestion importance[1-10]: 5

__

Why: The concern is plausible: pendingBatch is mutated in the watch source and read in the async callback, so a re-run before the callback executes could mismatch signature and batch. However, the generation guard already discards stale results, and Vue watchers run the callback synchronously after the source, so the practical risk is low. A valid but modest hardening.

Low
Normalize field alias before metadata lookup

c.field is used directly as a metadata key; if a condition field carries a
temporal/alias suffix (e.g. CompanyId__month) the lookup misses and the id is never
hydrated. Normalize the field name (strip __ suffix) before the metadata lookup,
consistent with baseFieldFromGroupAlias.

modules/web/web/query/utils/relation/filterRelationLabels.ts [63-66]

   const walkCond = (c: Condition) => {
     if (isNullOperator(c.operator)) return;
-    const fieldMeta = meta[c.field];
+    const fieldName = String(c.field || '').split('__')[0];
+    const fieldMeta = meta[fieldName];
     if (!isRelationPreviewMeta(fieldMeta)) return;
Suggestion importance[1-10]: 4

__

Why: Filter condition fields typically use base field names without temporal suffixes (those appear in groupby aliases, not filter leaves), so the miss scenario is unlikely in practice. The change is harmless and consistent with baseFieldFromGroupAlias, but addresses a speculative edge case rather than a confirmed bug.

Low
Possible issue
Record empty map on store creation failure

createModelStore is called outside the per-chunk try, so if it throws for one model
the outer catch skips lookups.set(model, map) and the whole target is dropped
(callers fall back to raw ids). Wrap the store creation so a failure still records
an empty map for that model, keeping behavior consistent with the chunk-failure
path.

modules/web/web/query/utils/relation/displayNameBatch.ts [28-31]

-        const targetStore = createModelStore(model) as {
-          Search?: (condition?: any, options?: any) => Promise<any>;
-        };
+        let targetStore: { Search?: (condition?: any, options?: any) => Promise<any> };
+        try {
+          targetStore = createModelStore(model);
+        } catch (e) {
+          console.warn(`${logPrefix} Failed to create store for target '${model}'`, e);
+          lookups.set(model, new Map());
+          return;
+        }
         if (typeof targetStore.Search !== 'function') return;
Suggestion importance[1-10]: 4

__

Why: The suggestion is technically accurate about the asymmetry between store-creation failure and chunk failure, but the outer catch already logs and callers fall back to raw ids, so behavior is functionally equivalent. This is a minor consistency improvement rather than a real bug fix.

Low
Performance
Verify blocking hydrate latency on readGroup

hydrateGroupRefLabels awaits a network Search before returning the group snapshot,
adding latency to every readGroup even when no Ref groupby is present. Consider
short-circuiting earlier (it already returns when refFields.size === 0) and, for
correctness, ensure a slow/failed hydrate cannot block the result — the internal
try/catch handles errors, but the await still delays first paint; verify this is
acceptable or make hydration non-blocking.

modules/web/web/query/executor.ts [699-702]

+    const rows = toGroupRows(groups);
+    // *Ref display names are frontend-only: rewrite group labels without changing keys.
+    await hydrateGroupRefLabels(store, rows, storeDeps);
+    return { kind: 'group', rows, total, planHash: main.hash, ts: Date.now(), uiView };
 
-
Suggestion importance[1-10]: 3

__

Why: The improved_code is identical to existing_code, so no actual change is proposed. It only asks the author to verify latency, which is a legitimate but low-impact observation; the early refFields.size === 0 return already avoids work when no Ref groupby exists.

Low

Recollect filter ids in the watch callback so batch matches signature,
and always record an empty lookup map when store creation fails.
@buke

buke commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor Author

Evaluated #601 (comment):

Suggestion Decision
Avoid stale pendingBatch in watcher Adopted — recollect batch in the callback so it matches the firing signature
Normalize filter field __ alias before metadata lookup Declined — filter leaves use base field names; temporal suffixes are groupby aliases
Record empty map on createModelStore failure Adopted — consistent with the per-chunk failure path
Verify blocking hydrate / non-blocking Declined — no code change proposed; intentional await (already discussed)

Pushed as 2f7f10c3.

@github-actions

Copy link
Copy Markdown

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Possible bug
Preserve reactive props for store dependencies

Wrap createModelStore resolution or access in a getter/computed property. If
props.createModelStore changes across parent re-renders, storeDeps will retain the
initial function instance since it is evaluated only once during setup.

modules/web/web/components/view/search/SearchFilter.vue [98-100]

 const storeDeps = {
-  createModelStore: props.createModelStore ?? defaultCreateModelStore,
+  get createModelStore() {
+    return props.createModelStore ?? defaultCreateModelStore;
+  },
 };
Suggestion importance[1-10]: 3

__

Why: The suggestion is technically valid: storeDeps is evaluated once in setup, so a changed props.createModelStore would not be picked up. However, createModelStore is a test/host override that is not expected to change reactively, and the useFilterEditorBindings/useFilterRelationLabelCache consumers capture it at setup anyway, so the practical impact is marginal.

Low

@buke
buke merged commit 21f5254 into main Nov 21, 2026
25 checks passed
@buke
buke deleted the feat/web-m2oref-group-label-hydrate branch November 21, 2026 14:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant