@platforma-sdk/model 1.84.19 → 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.
@@ -968,3 +968,268 @@ describe("deriveDistinctLabels v2 — linker path & qualifications", () => {
968
968
  ]);
969
969
  });
970
970
  });
971
+
972
+ describe("shared distinctions over presence-only ones", () => {
973
+ const col = (label: string, trace: Trace): PColumnSpec =>
974
+ createSpec({
975
+ annotations: { [Annotation.Label]: label, [Annotation.Trace]: JSON.stringify(trace) },
976
+ });
977
+ const dataset = { type: "dataset", label: "DS", importance: 100 };
978
+ const seqCluster = { type: "seq-clustering", label: "Seq cluster", importance: 30 };
979
+ const esmCluster = { type: "esm-clustering", label: "ESM2 cluster", importance: 30 };
980
+ const enrichment = (label: string) => ({ type: "enrichment", label, importance: 35 });
981
+
982
+ test("a group keeps its own shared distinction when another group pins a presence-only type", () => {
983
+ // The clustering types stay in the global set for the Cluster Size pair, where they separate
984
+ // only by presence. They would also separate the Enrichment Quality pair the same way and
985
+ // push out each enrichment block's own label, which both of those columns carry.
986
+ const specs = [
987
+ col("Enrichment Quality", [dataset, seqCluster, enrichment("Enr seq")]),
988
+ col("Enrichment Quality", [dataset, esmCluster, enrichment("Enr esm")]),
989
+ col("Cluster Size", [dataset, seqCluster]),
990
+ col("Cluster Size", [dataset, esmCluster]),
991
+ col("UMAP1", []),
992
+ ];
993
+ expect(deriveDistinctLabels(specs)).toEqual([
994
+ "Enrichment Quality / Enr seq",
995
+ "Enrichment Quality / Enr esm",
996
+ "Cluster Size / Seq cluster",
997
+ "Cluster Size / ESM2 cluster",
998
+ "UMAP1",
999
+ ]);
1000
+ });
1001
+
1002
+ test("a member whose shown parts are a subset of a peer's counts as bare", () => {
1003
+ // Two datasets keep the dataset in every name, so "CS / DS1" is not the bare label itself.
1004
+ const ds = (label: string) => ({ ...dataset, label });
1005
+ const specs = [
1006
+ col("CS", [ds("DS1"), seqCluster]),
1007
+ col("CS", [ds("DS1"), esmCluster]),
1008
+ col("X", [ds("DS1")]),
1009
+ col("X", [ds("DS2")]),
1010
+ col("UMAP1", []),
1011
+ ];
1012
+ expect(deriveDistinctLabels(specs)).toEqual([
1013
+ "CS / DS1 / Seq cluster",
1014
+ "CS / DS1 / ESM2 cluster",
1015
+ "X / DS1",
1016
+ "X / DS2",
1017
+ "UMAP1",
1018
+ ]);
1019
+ });
1020
+
1021
+ test("re-labelled groups keep their qualification tags", () => {
1022
+ const anchor = "anc" as PObjectId;
1023
+ const qual = (k: string) => ({
1024
+ forQueries: { [anchor]: [{ axis: { name: "ax" }, contextDomain: { k } }] },
1025
+ forHit: [],
1026
+ });
1027
+ const entries: Entry[] = [
1028
+ { spec: col("EQ", [seqCluster, enrichment("e1")]), qualifications: qual("1") },
1029
+ { spec: col("EQ", [esmCluster, enrichment("e2")]), qualifications: qual("1") },
1030
+ { spec: col("CS", [seqCluster]), qualifications: qual("1") },
1031
+ { spec: col("CS", [seqCluster]), qualifications: qual("2") },
1032
+ { spec: col("CS", [esmCluster]), qualifications: qual("1") },
1033
+ ];
1034
+ expect(deriveDistinctLabels(entries)).toEqual([
1035
+ "EQ / e1 [anc: ax k=1]",
1036
+ "EQ / e2 [anc: ax k=1]",
1037
+ "CS / Seq cluster [anc: ax k=1]",
1038
+ "CS / Seq cluster [anc: ax k=2]",
1039
+ "CS / ESM2 cluster [anc: ax k=1]",
1040
+ ]);
1041
+ });
1042
+
1043
+ test("bare names are fixed in groups spanning several samples", () => {
1044
+ const sample = (label: string) => ({ type: "sample", label, importance: 50 });
1045
+ const specs = [
1046
+ col("Count", [sample("S1"), seqCluster]),
1047
+ col("Count", [sample("S1"), esmCluster]),
1048
+ col("Count", [sample("S2"), seqCluster]),
1049
+ col("Count", [sample("S2"), esmCluster]),
1050
+ col("UMAP1", []),
1051
+ ];
1052
+ expect(deriveDistinctLabels(specs)).toEqual([
1053
+ "Count / S1 / Seq cluster",
1054
+ "Count / S1 / ESM2 cluster",
1055
+ "Count / S2 / Seq cluster",
1056
+ "Count / S2 / ESM2 cluster",
1057
+ "UMAP1",
1058
+ ]);
1059
+ });
1060
+
1061
+ test("a low-importance shared part does not replace a more important own part", () => {
1062
+ const run = (label: string) => ({ type: "run", label, importance: 1 });
1063
+ const specs = [
1064
+ col("Score", [run("r1"), seqCluster]),
1065
+ col("Score", [run("r2"), esmCluster]),
1066
+ col("CS", [run("r1"), seqCluster]),
1067
+ col("CS", [run("r1"), esmCluster]),
1068
+ col("UMAP1", []),
1069
+ ];
1070
+ expect(deriveDistinctLabels(specs).slice(0, 2)).toEqual([
1071
+ "Score / Seq cluster",
1072
+ "Score / ESM2 cluster",
1073
+ ]);
1074
+ });
1075
+
1076
+ test("when the shared re-naming would clash, the bare member still gets its own part", () => {
1077
+ const specs = [
1078
+ col("EQ", [seqCluster, enrichment("e1")]),
1079
+ col("EQ", [esmCluster, enrichment("e2")]),
1080
+ col("EQ / e1", []), // takes the name the shared re-naming would give the first column
1081
+ col("CS", [seqCluster]),
1082
+ col("CS", [esmCluster]),
1083
+ col("UMAP1", []),
1084
+ ];
1085
+ const labels = deriveDistinctLabels(specs);
1086
+ // The bare member adds the part of the same kind its peer shows: its clustering.
1087
+ expect(labels.slice(0, 2)).toEqual(["EQ / Seq cluster", "EQ / ESM2 cluster"]);
1088
+ expect(new Set(labels).size).toBe(labels.length);
1089
+ });
1090
+
1091
+ test("without a shown label, only bare labels get a part", () => {
1092
+ const specs = [
1093
+ col("EQ", [dataset, seqCluster, enrichment("e1")]),
1094
+ col("EQ", [dataset, esmCluster, enrichment("e2")]),
1095
+ col("CS", [dataset, seqCluster]),
1096
+ col("CS", [dataset, esmCluster]),
1097
+ ];
1098
+ expect(deriveDistinctLabels(specs)).toEqual([
1099
+ "DS / Seq cluster / e1",
1100
+ "DS / e2",
1101
+ "CS / DS / Seq cluster",
1102
+ "DS / ESM2 cluster",
1103
+ ]);
1104
+ });
1105
+
1106
+ test("a bare column falls back to its hidden native label", () => {
1107
+ // The forced dataset alone is a strict subset of the peer's parts; only the label differs.
1108
+ const specs = [
1109
+ col("A", [dataset, { type: "t2", label: "T2", importance: 20 }]),
1110
+ col("B", [
1111
+ dataset,
1112
+ { type: "t1", label: "T1", importance: 10 },
1113
+ { type: "t2", label: "T2", importance: 0 },
1114
+ ]),
1115
+ ];
1116
+ expect(deriveDistinctLabels(specs, { forceTraceElements: ["dataset"] })).toEqual([
1117
+ "A / DS",
1118
+ "DS / T1",
1119
+ ]);
1120
+ });
1121
+
1122
+ test("without a shown label, unrelated columns get no suffix", () => {
1123
+ // One group spans the whole list here, so the picked part must not spread to other columns.
1124
+ const sample = (label: string) => ({ type: "sample", label, importance: 50 });
1125
+ const host = (label: string) => ({ type: "host", label, importance: 10 });
1126
+ const specs = [
1127
+ col("Same", [sample("S1"), host("H1")]),
1128
+ col("Same", [sample("S1"), { type: "x", label: "X", importance: 30 }]),
1129
+ col("Same", [sample("S2"), host("H2")]),
1130
+ col("Same", [sample("S3"), host("H3")]),
1131
+ col("Same", [sample("S4"), host("H4")]),
1132
+ ];
1133
+ expect(deriveDistinctLabels(specs)).toEqual(["S1 / H1", "S1 / X", "S2", "S3", "S4"]);
1134
+ });
1135
+
1136
+ test("the part a bare member adds is shown by every member that carries it", () => {
1137
+ const sample = (label: string) => ({ type: "sample", label, importance: 50 });
1138
+ const specs = [
1139
+ col("data", [sample("S2")]),
1140
+ col("data", [sample("S1"), seqCluster]),
1141
+ col("data", [sample("S1"), esmCluster]),
1142
+ col("UMAP1", []),
1143
+ ];
1144
+ expect(deriveDistinctLabels(specs)).toEqual([
1145
+ "data / S2",
1146
+ "data / S1 / Seq cluster",
1147
+ "data / S1 / ESM2 cluster",
1148
+ "UMAP1",
1149
+ ]);
1150
+ });
1151
+
1152
+ test("qualification tags never stand in for shared parts, and can be added to a bare label", () => {
1153
+ const anchor = "anc" as PObjectId;
1154
+ const qual = (k: string) => ({
1155
+ forQueries: { [anchor]: [{ axis: { name: "ax" }, contextDomain: { k } }] },
1156
+ forHit: [],
1157
+ });
1158
+ const run = (label: string) => ({ type: "run", label, importance: 1 });
1159
+ const tagged: Entry[] = [
1160
+ { spec: col("CS", [seqCluster]), qualifications: qual("1") },
1161
+ { spec: col("CS", [seqCluster]), qualifications: qual("2") },
1162
+ { spec: col("CS", [esmCluster]) },
1163
+ { spec: col("X", [seqCluster]) },
1164
+ { spec: col("X", [esmCluster]) },
1165
+ ];
1166
+ expect(deriveDistinctLabels(tagged).slice(0, 3)).toEqual([
1167
+ "CS / Seq cluster [anc: ax k=1]",
1168
+ "CS / Seq cluster [anc: ax k=2]",
1169
+ "CS / ESM2 cluster",
1170
+ ]);
1171
+ const onlyTag: Entry[] = [
1172
+ { spec: col("A", [run("run1")]) },
1173
+ { spec: col("A", []), qualifications: qual("1") },
1174
+ { spec: col("A", [run("run2")]) },
1175
+ { spec: col("UMAP1", []) },
1176
+ ];
1177
+ expect(deriveDistinctLabels(onlyTag).slice(0, 3)).toEqual([
1178
+ "A / run1",
1179
+ "A [anc: ax k=1]",
1180
+ "A / run2",
1181
+ ]);
1182
+ });
1183
+
1184
+ test("qualification tags don't change which kind of part a bare label adds", () => {
1185
+ const anchor = "anc" as PObjectId;
1186
+ const qual = (k: string) => ({
1187
+ forQueries: { [anchor]: [{ axis: { name: "ax" }, contextDomain: { k } }] },
1188
+ forHit: [],
1189
+ });
1190
+ const sample = { type: "sample", label: "S1", importance: 50 };
1191
+ const seq = (label: string) => ({ ...seqCluster, label });
1192
+ const run = { type: "run", label: "R", importance: 40 };
1193
+ const entries: Entry[] = [
1194
+ { spec: col("D", [sample, seq("Seq cluster")]), qualifications: qual("1") },
1195
+ { spec: col("D", [sample, seq("Seq cluster 2")]), qualifications: qual("1") },
1196
+ { spec: col("D", [sample, run, esmCluster]) },
1197
+ { spec: col("D", [sample, seq("Seq cluster")]), qualifications: qual("2") },
1198
+ { spec: col("UMAP1", []) },
1199
+ ];
1200
+ expect(deriveDistinctLabels(entries)[2]).toBe("D / ESM2 cluster");
1201
+ });
1202
+
1203
+ test("labels stay unique when different trace types share the same text", () => {
1204
+ const part = (type: string, label: string) => ({ type, label, importance: 10 });
1205
+ const specs = [
1206
+ col("L", [part("s1", "S"), part("x1", "X"), part("w", "W")]),
1207
+ col("L", [part("s1", "S"), part("x1", "X")]),
1208
+ col("L", [part("s1", "S"), part("t", "T")]),
1209
+ col("L", [part("s1", "S"), part("x2", "X")]),
1210
+ col("L", [part("q", "Q")]),
1211
+ col("L", [part("s2", "S")]),
1212
+ col("UMAP1", []),
1213
+ ];
1214
+ const labels = deriveDistinctLabels(specs);
1215
+ expect(new Set(labels).size).toBe(labels.length);
1216
+ });
1217
+
1218
+ test("with no shared distinction, the bare member shows its own part", () => {
1219
+ // Same enrichment subtitle on both (e.g. identical defaults), different clusterings.
1220
+ const specs = [
1221
+ col("Enrichment Quality", [dataset, seqCluster, enrichment("Same default")]),
1222
+ col("Enrichment Quality", [dataset, esmCluster, enrichment("Same default")]),
1223
+ col("Cluster Size", [dataset, seqCluster]),
1224
+ col("Cluster Size", [dataset, esmCluster]),
1225
+ col("UMAP1", []), // a column without trace keeps native labels in, as in a graph frame
1226
+ ];
1227
+ expect(deriveDistinctLabels(specs)).toEqual([
1228
+ "Enrichment Quality / Seq cluster",
1229
+ "Enrichment Quality / ESM2 cluster",
1230
+ "Cluster Size / Seq cluster",
1231
+ "Cluster Size / ESM2 cluster",
1232
+ "UMAP1",
1233
+ ]);
1234
+ });
1235
+ });
@@ -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;