@platforma-sdk/model 1.84.17 → 1.84.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -140,6 +140,8 @@ function deriveStems(values: Entry[], options: DeriveLabelsOptions): string[] {
140
140
 
141
141
  const build = (typeSet: Set<string>, force: boolean) =>
142
142
  buildLabels(records, typeSet, forceTraceElements, separator, force);
143
+ const finalize = (minimized: Set<string>, rendered: string[]) =>
144
+ repairBareLabels(rendered, minimized, records, stats, forceTraceElements, separator);
143
145
 
144
146
  if (mainTypes.length === 0) {
145
147
  if (secondaryTypes.length !== 0)
@@ -168,15 +170,9 @@ function deriveStems(values: Entry[], options: DeriveLabelsOptions): string[] {
168
170
  forcedSet,
169
171
  separator,
170
172
  );
171
- const rendered = build(minimized, false) ?? throwError("Failed to derive unique labels");
172
- return repairBareByPresence(
173
- rendered,
173
+ return finalize(
174
174
  minimized,
175
- records,
176
- stats,
177
- forcedSet,
178
- forceTraceElements,
179
- separator,
175
+ build(minimized, false) ?? throwError("Failed to derive unique labels"),
180
176
  );
181
177
  }
182
178
 
@@ -196,15 +192,9 @@ function deriveStems(values: Entry[], options: DeriveLabelsOptions): string[] {
196
192
  forcedSet,
197
193
  separator,
198
194
  );
199
- const rendered = build(minimized, true) ?? throwError("Failed to derive unique labels");
200
- return repairBareByPresence(
201
- rendered,
195
+ return finalize(
202
196
  minimized,
203
- records,
204
- stats,
205
- forcedSet,
206
- forceTraceElements,
207
- separator,
197
+ build(minimized, true) ?? throwError("Failed to derive unique labels"),
208
198
  );
209
199
  }
210
200
 
@@ -451,92 +441,262 @@ function minimizeTypeSet(
451
441
  return result;
452
442
  }
453
443
 
454
- const ABSENT_VALUE = "absent"; // sentinel value for "row has no entry of this type"
455
-
456
- /** Whether `fullType`'s rendered value differs across the group (absence counts as a value). */
457
- function typeDistinguishes(records: EnrichedRecord[], group: number[], fullType: string): boolean {
458
- const values = new Set<string>();
459
- for (const i of group) {
460
- const ft = records[i].fullTrace.find((e) => e.fullType === fullType);
461
- values.add(ft?.label ?? ABSENT_VALUE);
462
- if (values.size > 1) return true;
463
- }
464
- return false;
465
- }
466
-
467
- /** The highest-importance trace type this row HAS (outside `typeSet`) that sets it apart from its
468
- * group peers. `undefined` when the row carries nothing distinguishing of its own. */
469
- function bestDistinguishingType(
470
- records: EnrichedRecord[],
471
- group: number[],
472
- row: number,
473
- typeSet: Set<string>,
474
- forcedSet: Set<string>,
475
- forceTraceElements: Set<string> | undefined,
476
- stats: TypeStats,
477
- ): string | undefined {
478
- return records[row].fullTrace.reduce<{ type: string; imp: number } | undefined>((best, ft) => {
479
- if (typeSet.has(ft.fullType) || forcedSet.has(ft.fullType) || forceTraceElements?.has(ft.type))
480
- return best;
481
- if (!typeDistinguishes(records, group, ft.fullType)) return best;
482
- const imp = stats.importances.get(ft.fullType) ?? 0;
483
- return best === undefined || imp > best.imp ? { type: ft.fullType, imp } : best;
484
- }, undefined)?.type;
485
- }
486
-
487
444
  /**
488
- * Un-bare columns distinguished only "by absence". After minimization a column can end up with a
489
- * bare trace zone (only the forced native label) while a peer sharing that same base renders extra
490
- * tokens — the column reads as unique purely because it LACKS what the peer has. For each such bare
491
- * column this re-renders JUST that column's label with the highest-importance trace type it actually
492
- * carries that tells it apart from its peers, so every colliding column is distinguished by a token
493
- * it HAS rather than by omission.
494
- *
495
- * Patches individual labels rather than the shared type set on purpose: the set is global, so adding
496
- * a type there would also decorate unrelated columns in other groups that happen to carry it. Only
497
- * bare columns' labels grow (a superset of their previous value), so uniqueness is preserved. Groups
498
- * are keyed by the base = the label rendered from the forced types alone.
445
+ * Repairs labels told apart only by what they lack: in a group with the same shown base, a
446
+ * member is bare when its shown parts are a strict subset of a peer's. The group is re-labelled
447
+ * from parts all members carry, or bare members add a hidden part (group-wide when labels stay
448
+ * unique), whichever keeps the more important distinction; labels stay unique across the list.
499
449
  */
500
- function repairBareByPresence(
450
+ function repairBareLabels(
501
451
  labels: string[],
502
452
  minimized: Set<string>,
503
453
  records: EnrichedRecord[],
504
454
  stats: TypeStats,
505
- forcedSet: Set<string>,
506
455
  forceTraceElements: Set<string> | undefined,
507
456
  separator: string,
508
457
  ): string[] {
509
- const base = records.map((r) => renderRecordLabel(r, forcedSet, forceTraceElements, separator));
510
- const isBare = records.map(
511
- (r, i) => renderRecordLabel(r, minimized, forceTraceElements, separator) === base[i],
512
- );
513
-
514
- const groups = records.reduce<Map<string, number[]>>(
515
- (acc, _, i) => acc.set(base[i] ?? "", [...(acc.get(base[i] ?? "") ?? []), i]),
516
- new Map(),
517
- );
458
+ const traces = records.map((r) => new Map(r.fullTrace.map((ft) => [ft.fullType, ft.label])));
459
+ const isQualification = (t: string) => isSyntheticType(t.split("@")[0]);
460
+ // Trace steps from the end of each column's trace, used to match parts of the same kind; the
461
+ // native label and qualification tags are not steps, so they don't shift the count.
462
+ const depths = records.map((r) => {
463
+ const steps = r.fullTrace.filter(
464
+ (ft) => ft.fullType !== LABEL_TYPE_FULL && !isQualification(ft.fullType),
465
+ );
466
+ return new Map(steps.map((ft, idx) => [ft.fullType, steps.length - idx]));
467
+ });
468
+ const isForced = (t: string) => forceTraceElements?.has(t.split("@")[0]) === true;
469
+ const isDistinctionType = (t: string) => t !== LABEL_TYPE_FULL && !isQualification(t);
470
+ const importance = (t: string) => stats.importances.get(t) ?? 0;
471
+ const byImportance = (a: string, b: string) => importance(b) - importance(a);
472
+ const render = (i: number, types: Set<string>) =>
473
+ renderRecordLabel(records[i], types, forceTraceElements, separator);
474
+ const partKey = (t: string, l: string | undefined) => `${t}\u0000${l}`;
475
+
476
+ const labelShown = minimized.has(LABEL_TYPE_FULL);
477
+ const baseTypes = new Set<string>(labelShown ? [LABEL_TYPE_FULL] : []);
478
+ const qualTypes = [...minimized].filter(isQualification);
479
+
480
+ // Group by the shown base; columns without one share a group and only get the bare fix.
481
+ const groups = new Map<string, number[]>();
482
+ records.forEach((_, i) => {
483
+ const key = render(i, baseTypes) ?? "";
484
+ const group = groups.get(key);
485
+ if (group) group.push(i);
486
+ else groups.set(key, [i]);
487
+ });
518
488
 
519
489
  const patched = [...labels];
520
- for (const group of groups.values()) {
521
- // Only asymmetric groups need repair: a bare column beside a richer peer. When every column is
522
- // equally bare there is nothing to un-hide (they carry no distinguishing token of their own).
523
- if (!group.some((i) => !isBare[i])) continue;
524
- for (const i of group) {
525
- if (!isBare[i]) continue;
526
- const chosen = bestDistinguishingType(
527
- records,
528
- group,
529
- i,
530
- minimized,
531
- forcedSet,
532
- forceTraceElements,
533
- stats,
490
+ const counts = new Map<string, number>();
491
+ const addCount = (l: string, d: number) => counts.set(l, (counts.get(l) ?? 0) + d);
492
+ for (const l of patched) addCount(l, 1);
493
+
494
+ // Applies new labels to some columns unless one clashes with a label elsewhere.
495
+ const tryApply = (members: number[], next: string[]): boolean => {
496
+ if (new Set(next).size !== members.length) return false;
497
+ for (const i of members) addCount(patched[i], -1);
498
+ const clashes = next.some((l) => (counts.get(l) ?? 0) > 0);
499
+ members.forEach((i, k) => {
500
+ if (!clashes) patched[i] = next[k];
501
+ addCount(patched[i], 1);
502
+ });
503
+ return !clashes;
504
+ };
505
+
506
+ for (const [key, group] of groups) {
507
+ if (group.length < 2) continue;
508
+ const shown = group.map((i) =>
509
+ [...traces[i]].filter(([t]) => t !== LABEL_TYPE_FULL && (minimized.has(t) || isForced(t))),
510
+ );
511
+ const partKeys = shown.map((parts) => parts.map(([t, l]) => partKey(t, l)));
512
+ // Members showing the same parts are compared once, as one part set; identical columns
513
+ // then cost nothing. sigOf maps each member to its set, setMembers lists a set's members.
514
+ const sigIndex = new Map<string, number>();
515
+ const setKeys: string[][] = [];
516
+ const setMembers: number[][] = [];
517
+ const sigOf = partKeys.map((keys, k) => {
518
+ const sig = [...keys].sort().join("\u0001");
519
+ let s = sigIndex.get(sig);
520
+ if (s === undefined) {
521
+ s = setKeys.length;
522
+ sigIndex.set(sig, s);
523
+ setKeys.push(keys);
524
+ setMembers.push([]);
525
+ }
526
+ setMembers[s].push(k);
527
+ return s;
528
+ });
529
+ const setSets = setKeys.map((keys) => new Set(keys));
530
+ const postings = new Map<string, number[]>();
531
+ setKeys.forEach((keys, s) =>
532
+ keys.forEach((p) => {
533
+ const list = postings.get(p);
534
+ if (list) list.push(s);
535
+ else postings.set(p, [s]);
536
+ }),
537
+ );
538
+ // Superset sets: part sets holding all of a set's parts and more (non-empty means bare).
539
+ // Candidates come from the posting list of its rarest part.
540
+ const withParts = setKeys.map((_, s) => s).filter((s) => setKeys[s].length > 0);
541
+ const supersetSets = setKeys.map((keys, s) => {
542
+ if (keys.length === 0) return withParts;
543
+ const rarest = keys.reduce((a, b) =>
544
+ postings.get(a)!.length <= postings.get(b)!.length ? a : b,
534
545
  );
535
- if (chosen === undefined) continue;
536
- const withToken = new Set([...minimized, chosen]);
537
- patched[i] =
538
- renderRecordLabel(records[i], withToken, forceTraceElements, separator) ?? patched[i];
546
+ return postings
547
+ .get(rarest)!
548
+ .filter(
549
+ (t) => t !== s && setSets[t].size > keys.length && keys.every((x) => setSets[t].has(x)),
550
+ );
551
+ });
552
+ const bare = group.map((_, k) => supersetSets[sigOf[k]].length > 0);
553
+ if (!bare.some(Boolean)) continue;
554
+
555
+ const typeCount = new Map<string, number>();
556
+ for (const i of group)
557
+ for (const t of traces[i].keys()) typeCount.set(t, (typeCount.get(t) ?? 0) + 1);
558
+ const isUneven = (t: string) => (typeCount.get(t) ?? 0) > 0 && typeCount.get(t)! < group.length;
559
+ const unevenMax = Math.max(
560
+ ...[...minimized]
561
+ .filter((t) => isDistinctionType(t) && !isForced(t) && isUneven(t))
562
+ .map(importance),
563
+ );
564
+
565
+ // Shared re-labelling, only when the base is a shown label so its text identifies the group.
566
+ // Parts are chosen without tags, so tags alone never stand in for a shared distinction.
567
+ let sharedLabels: string[] | undefined;
568
+ let sharedMax = Number.NEGATIVE_INFINITY;
569
+ if (labelShown && key !== "") {
570
+ const shared = [...typeCount]
571
+ .filter(([t, n]) => n === group.length && isDistinctionType(t))
572
+ .map(([t]) => t)
573
+ .sort(byImportance);
574
+ const chosen = new Set(baseTypes);
575
+ const distinctCount = (types: Set<string>) =>
576
+ new Set(group.map((i) => render(i, types) ?? "")).size;
577
+ let count = distinctCount(chosen);
578
+ for (const t of shared) {
579
+ if (count === group.length) break;
580
+ const next = distinctCount(new Set([...chosen, t]));
581
+ if (next > count) {
582
+ if (chosen.size === baseTypes.size) sharedMax = importance(t);
583
+ chosen.add(t);
584
+ count = next;
585
+ }
586
+ }
587
+ const withTags = new Set([...chosen, ...qualTypes]);
588
+ const rendered = group.map((i) => render(i, withTags));
589
+ const complete = rendered.filter((l): l is string => l !== undefined);
590
+ if (
591
+ count === group.length &&
592
+ complete.length === group.length &&
593
+ new Set(complete).size === group.length
594
+ )
595
+ sharedLabels = complete;
539
596
  }
597
+
598
+ // Bare fix: each bare member picks a hidden part that differs from at least one peer making it
599
+ // bare, preferring the trace step those peers show extra, then importance.
600
+ const applyBareFix = (): boolean => {
601
+ const bareMembers = group.filter((_, k) => bare[k]);
602
+ const oldBare = new Map<string, number>();
603
+ for (const i of bareMembers) oldBare.set(patched[i], (oldBare.get(patched[i]) ?? 0) + 1);
604
+ const isFree = (l: string) => (counts.get(l) ?? 0) - (oldBare.get(l) ?? 0) === 0;
605
+ const shownTypes = (k: number) => [...baseTypes, ...shown[k].map(([t]) => t), ...qualTypes];
606
+
607
+ // Per part set: each type's labels among its members, and how many members carry it, so
608
+ // "does some peer differ" is answered per set without scanning every member.
609
+ const setLabels = new Map<number, Map<string, { labels: Set<string>; n: number }>>();
610
+ const labelsIn = (s: number) => {
611
+ let byType = setLabels.get(s);
612
+ if (byType) return byType;
613
+ byType = new Map();
614
+ for (const m of setMembers[s])
615
+ for (const [t, l] of traces[group[m]]) {
616
+ const entry = byType.get(t) ?? { labels: new Set<string>(), n: 0 };
617
+ entry.labels.add(l);
618
+ entry.n++;
619
+ byType.set(t, entry);
620
+ }
621
+ setLabels.set(s, byType);
622
+ return byType;
623
+ };
624
+ const someDiffers = (s: number, u: string, mine: string | undefined) => {
625
+ const entry = labelsIn(s).get(u);
626
+ if (entry === undefined) return mine !== undefined;
627
+ if (entry.n < setMembers[s].length) return true;
628
+ return entry.labels.size > 1 || !entry.labels.has(mine ?? "");
629
+ };
630
+ const extraDepthsOf = new Map<number, Set<number | undefined>>();
631
+ const extraDepths = (s: number) => {
632
+ let depthsSet = extraDepthsOf.get(s);
633
+ if (depthsSet) return depthsSet;
634
+ depthsSet = new Set(
635
+ supersetSets[s].flatMap((t) => {
636
+ const rep = setMembers[t][0];
637
+ return shown[rep]
638
+ .filter(([u, l]) => !isQualification(u) && !setSets[s].has(partKey(u, l)))
639
+ .map(([u]) => depths[group[rep]].get(u));
640
+ }),
641
+ );
642
+ extraDepthsOf.set(s, depthsSet);
643
+ return depthsSet;
644
+ };
645
+
646
+ const picks = new Map<number, { type: string; label: string }>();
647
+ group.forEach((i, k) => {
648
+ if (!bare[k]) return;
649
+ const peers = supersetSets[sigOf[k]];
650
+ const kindDepths = extraDepths(sigOf[k]);
651
+ const sameKind = (u: string) => (kindDepths.has(depths[i].get(u)) ? 1 : 0);
652
+ const candidates = [...traces[i].keys()]
653
+ .filter((u) => !minimized.has(u) && !isForced(u))
654
+ .filter((u) => peers.some((t) => someDiffers(t, u, traces[i].get(u))))
655
+ .sort((a, b) => sameKind(b) - sameKind(a) || byImportance(a, b));
656
+ for (const u of candidates) {
657
+ const label = render(i, new Set([...shownTypes(k), u]));
658
+ if (label !== undefined && isFree(label)) {
659
+ picks.set(i, { type: u, label });
660
+ break;
661
+ }
662
+ }
663
+ });
664
+ if (picks.size === 0) return false;
665
+
666
+ // Consistent first: every member shows the picked part types it carries. Only within a
667
+ // shown-label group; without one the group spans unrelated columns.
668
+ if (labelShown && key !== "") {
669
+ const picked = [...new Set([...picks.values()].map((p) => p.type))];
670
+ const consistent = group.map((i, k) => render(i, new Set([...shownTypes(k), ...picked])));
671
+ const full = consistent.filter((l): l is string => l !== undefined);
672
+ if (full.length === group.length && tryApply(group, full)) return true;
673
+ }
674
+
675
+ // Otherwise only bare members change. They may share a new label only if they shared the old
676
+ // one, and none may take the old label of a bare member that keeps it; repeat until stable.
677
+ const proposed = new Map([...picks].map(([i, p]) => [i, p.label]));
678
+ for (let changed = true; changed; ) {
679
+ changed = false;
680
+ const firstOld = new Map<string, string>();
681
+ for (const [i, l] of proposed) {
682
+ const old = firstOld.get(l);
683
+ if (old === undefined) firstOld.set(l, patched[i]);
684
+ else if (old !== patched[i]) changed = proposed.delete(i);
685
+ }
686
+ const kept = new Set(bareMembers.filter((i) => !proposed.has(i)).map((i) => patched[i]));
687
+ for (const [i, l] of proposed) if (kept.has(l)) changed = proposed.delete(i);
688
+ }
689
+ for (const i of bareMembers) addCount(patched[i], -1);
690
+ for (const i of bareMembers) {
691
+ patched[i] = proposed.get(i) ?? patched[i];
692
+ addCount(patched[i], 1);
693
+ }
694
+ return proposed.size > 0;
695
+ };
696
+
697
+ if (sharedLabels && sharedMax >= unevenMax && tryApply(group, sharedLabels)) continue;
698
+ if (applyBareFix()) continue;
699
+ if (sharedLabels && sharedMax < unevenMax) tryApply(group, sharedLabels);
540
700
  }
541
701
 
542
702
  return patched;
@@ -57,6 +57,15 @@ type GetUniqueSourceValuesParams = {
57
57
  searchQueryValue?: string;
58
58
  };
59
59
 
60
+ type GetUniqueAxisValuesParams = {
61
+ axisSpec: AxisSpec;
62
+ /** Columns carrying the axis; their keys are merged. */
63
+ parentColumnIds: PObjectId[];
64
+ limit?: number;
65
+ searchQuery?: string;
66
+ searchQueryValue?: string;
67
+ };
68
+
60
69
  type GetAxisUniqueValuesParams = {
61
70
  axisId: AxisId;
62
71
  parentColumnIds: PObjectId[];
@@ -247,12 +256,12 @@ export async function getAxisUniqueValues(
247
256
  ),
248
257
  );
249
258
 
250
- const overflow = responses.some((r) => r.overflow);
259
+ const merged = uniq(
260
+ flatten(responses.map((r) => Array.from(r.values.data as ArrayLike<unknown>).map(String))),
261
+ );
251
262
  return {
252
- values: uniq(
253
- flatten(responses.map((r) => Array.from(r.values.data as ArrayLike<unknown>).map(String))),
254
- ),
255
- overflow,
263
+ values: merged.slice(0, limit),
264
+ overflow: merged.length > limit || responses.some((r) => r.overflow),
256
265
  };
257
266
  } catch (err) {
258
267
  console.error("PFrame: getUniqueValues for axis error", err);
@@ -345,7 +354,7 @@ function getDiscreteValuesFromAnnotation(columnSpec: PColumnSpec): undefined | S
345
354
  async function getAxisValuesWithLabels(
346
355
  handle: PFrameHandle,
347
356
  params: {
348
- columnId: PObjectId;
357
+ parentColumnIds: PObjectId[];
349
358
  axisSpec: AxisSpec;
350
359
  labelsColumnId: PObjectId | undefined;
351
360
  limit?: number;
@@ -353,7 +362,8 @@ async function getAxisValuesWithLabels(
353
362
  searchQueryValue?: string;
354
363
  },
355
364
  ): Promise<SuggestionResponse> {
356
- const { columnId, axisSpec, labelsColumnId, limit, searchQuery, searchQueryValue } = params;
365
+ const { parentColumnIds, axisSpec, labelsColumnId, limit, searchQuery, searchQueryValue } =
366
+ params;
357
367
  const strAxisId = canonicalizeAxisId(getAxisId(axisSpec));
358
368
 
359
369
  let filters: PTableRecordSingleValueFilterV2[] = [];
@@ -388,7 +398,7 @@ async function getAxisValuesWithLabels(
388
398
 
389
399
  const response = await getAxisUniqueValues(handle, {
390
400
  axisId: getAxisId(axisSpec),
391
- parentColumnIds: [columnId],
401
+ parentColumnIds,
392
402
  limit,
393
403
  filters,
394
404
  });
@@ -443,7 +453,7 @@ export async function getUniqueSourceValuesWithLabels(
443
453
  const labelsColumnId = await getColumnOrAxisValueLabelsId(handle, strAxisId);
444
454
 
445
455
  return getAxisValuesWithLabels(handle, {
446
- columnId,
456
+ parentColumnIds: [columnId],
447
457
  axisSpec,
448
458
  labelsColumnId,
449
459
  limit,
@@ -460,3 +470,26 @@ export async function getUniqueSourceValuesWithLabels(
460
470
  searchQueryValue,
461
471
  });
462
472
  }
473
+
474
+ /**
475
+ * Suggestions for an axis on its own, not through one column: keys are merged
476
+ * across all parent columns carrying the axis, labelled by the axis label column
477
+ * when the PFrame has one.
478
+ */
479
+ export async function getUniqueAxisValuesWithLabels(
480
+ handle: PFrameHandle,
481
+ params: GetUniqueAxisValuesParams,
482
+ ): Promise<SuggestionResponse> {
483
+ const { axisSpec, parentColumnIds, limit, searchQuery, searchQueryValue } = params;
484
+ const strAxisId = canonicalizeAxisId(getAxisId(axisSpec));
485
+ const labelsColumnId = await getColumnOrAxisValueLabelsId(handle, strAxisId);
486
+
487
+ return getAxisValuesWithLabels(handle, {
488
+ parentColumnIds,
489
+ axisSpec,
490
+ labelsColumnId,
491
+ limit,
492
+ searchQuery,
493
+ searchQueryValue,
494
+ });
495
+ }