@coasys/ad4m 0.13.0-test-4 → 0.13.0-test-6

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.
Files changed (72) hide show
  1. package/lib/index.cjs +1507 -1372
  2. package/lib/index.js +1505 -1370
  3. package/lib/src/Ad4mClient.d.ts +1 -1
  4. package/lib/src/Ad4mClient.js +12 -1
  5. package/lib/src/agent/AgentClient.d.ts +16 -0
  6. package/lib/src/agent/AgentClient.js +74 -4
  7. package/lib/src/cache/PersistentCache.d.ts +40 -0
  8. package/lib/src/cache/PersistentCache.js +139 -0
  9. package/lib/src/expression/ExpressionClient.d.ts +8 -0
  10. package/lib/src/expression/ExpressionClient.js +113 -5
  11. package/lib/src/index.d.ts +1 -0
  12. package/lib/src/index.js +1 -0
  13. package/lib/src/model/Ad4mModel.d.ts +20 -7
  14. package/lib/src/model/Ad4mModel.js +102 -108
  15. package/lib/src/model/Ad4mModel.test.js +688 -1434
  16. package/lib/src/model/ModelQueryBuilder.d.ts +6 -6
  17. package/lib/src/model/ModelQueryBuilder.js +29 -20
  18. package/lib/src/model/Subject.js +6 -6
  19. package/lib/src/model/hydration.d.ts +2 -39
  20. package/lib/src/model/hydration.js +2 -260
  21. package/lib/src/model/query-surreal.d.ts +44 -0
  22. package/lib/src/model/query-surreal.js +249 -0
  23. package/lib/src/model/query-utils.d.ts +1 -0
  24. package/lib/src/model/query-utils.js +46 -1
  25. package/lib/src/model/relation-filtering.test.js +15 -15
  26. package/lib/src/model/surreal-utils.d.ts +42 -0
  27. package/lib/src/model/surreal-utils.js +128 -0
  28. package/lib/src/model/types.d.ts +4 -6
  29. package/lib/src/perspectives/PerspectiveClient.d.ts +1 -1
  30. package/lib/src/perspectives/PerspectiveClient.js +15 -13
  31. package/lib/src/perspectives/PerspectiveProxy.d.ts +14 -0
  32. package/lib/src/perspectives/PerspectiveProxy.js +16 -3
  33. package/lib/src/perspectives/PerspectiveResolver.d.ts +1 -0
  34. package/lib/src/perspectives/PerspectiveResolver.js +11 -0
  35. package/lib/src/runtime/RuntimeResolver.d.ts +1 -28
  36. package/lib/src/runtime/RuntimeResolver.js +4 -197
  37. package/lib/src/schema.gql +1 -27
  38. package/lib/src/shacl/SHACLShape.test.js +0 -82
  39. package/package.json +11 -8
  40. package/src/Ad4mClient.test.ts +14 -4
  41. package/src/Ad4mClient.ts +12 -1
  42. package/src/agent/AgentClient.ts +84 -2
  43. package/src/cache/PersistentCache.ts +145 -0
  44. package/src/cache/cache.test.ts +713 -0
  45. package/src/expression/ExpressionClient.ts +137 -3
  46. package/src/index.ts +1 -0
  47. package/src/model/Ad4mModel.test.ts +59 -358
  48. package/src/model/Ad4mModel.ts +112 -108
  49. package/src/model/ModelQueryBuilder.ts +29 -17
  50. package/src/model/hydration.ts +2 -279
  51. package/src/model/query-utils.ts +47 -2
  52. package/src/model/types.ts +5 -6
  53. package/src/perspectives/PerspectiveClient.ts +26 -17
  54. package/src/perspectives/PerspectiveProxy.ts +24 -3
  55. package/lib/src/model/hydration-batch.d.ts +0 -34
  56. package/lib/src/model/hydration-batch.js +0 -147
  57. package/lib/src/model/hydration-batching.test.d.ts +0 -7
  58. package/lib/src/model/hydration-batching.test.js +0 -456
  59. package/lib/src/model/model-manifest.d.ts +0 -41
  60. package/lib/src/model/model-manifest.js +0 -11
  61. package/lib/src/model/query-cache.test.d.ts +0 -1
  62. package/lib/src/model/query-cache.test.js +0 -43
  63. package/lib/src/model/query-sparql-batch.d.ts +0 -17
  64. package/lib/src/model/query-sparql-batch.js +0 -260
  65. package/lib/src/model/query-sparql.test.d.ts +0 -1
  66. package/lib/src/model/query-sparql.test.js +0 -312
  67. package/lib/src/model/subscription-delta.test.d.ts +0 -24
  68. package/lib/src/model/subscription-delta.test.js +0 -180
  69. package/lib/src/model/subscription-pool.d.ts +0 -39
  70. package/lib/src/model/subscription-pool.js +0 -165
  71. package/lib/src/perspectives/PerspectiveClient.test.d.ts +0 -1
  72. package/lib/src/perspectives/PerspectiveClient.test.js +0 -224
@@ -2,16 +2,36 @@ import { ApiClient } from "../apiClient";
2
2
  import { InteractionCall, InteractionMeta } from "../language/Language";
3
3
  import { ExpressionRendered } from "./Expression";
4
4
  import { Literal } from "../Literal";
5
+ import { PersistentCache, createPersistentCache } from "../cache/PersistentCache";
5
6
  import type { CreateExpressionRequest, ExpressionManyRequest } from "../generated/api";
6
7
 
8
+ interface CachedExpression {
9
+ data: ExpressionRendered;
10
+ size: number;
11
+ }
12
+
7
13
  export class ExpressionClient {
8
14
  #apiClient: ApiClient
9
15
 
16
+ // L1: in-memory LRU cache (hot path, sub-ms)
17
+ #memCache = new Map<string, CachedExpression>();
18
+ #inflight = new Map<string, Promise<ExpressionRendered>>();
19
+ /** Maximum number of entries in the L1 memory cache. */
20
+ static MAX_MEM_ENTRIES = 200;
21
+ /** Maximum total size (in bytes) of L1 memory cache values. */
22
+ static MAX_MEM_BYTES = 5 * 1024 * 1024; // 5 MB
23
+ #totalMemBytes = 0;
24
+
25
+ // L2: persistent cache (IndexedDB in browser, NullCache in Node)
26
+ #persistent: PersistentCache<ExpressionRendered>;
27
+
10
28
  constructor(baseUrl: string, token?: string, sharedApiClient?: ApiClient) {
11
29
  this.#apiClient = sharedApiClient || new ApiClient(baseUrl, token)
30
+ this.#persistent = createPersistentCache<ExpressionRendered>('ad4m-expression-cache', 'expressions');
12
31
  }
13
32
 
14
33
  async get(url: string, alwaysGet: boolean = false): Promise<ExpressionRendered> {
34
+ // Existing literal fast-path
15
35
  if(!alwaysGet){
16
36
  try {
17
37
  let literalValue = Literal.fromUrl(url).get();
@@ -23,11 +43,120 @@ export class ExpressionClient {
23
43
  } catch(e) {}
24
44
  }
25
45
 
26
- return this.#apiClient.call<ExpressionRendered>('expression.get', { url })
46
+ // L1: memory hit
47
+ if (!alwaysGet) {
48
+ const memHit = this.#memCache.get(url);
49
+ if (memHit) return memHit.data;
50
+ }
51
+
52
+ // Deduplicate in-flight requests
53
+ if (!alwaysGet) {
54
+ const existing = this.#inflight.get(url);
55
+ if (existing) return existing;
56
+ }
57
+
58
+ // L2 check + L3 network
59
+ const promise = (async () => {
60
+ if (!alwaysGet) {
61
+ const persisted = await this.#persistent.get(url);
62
+ if (persisted) {
63
+ this.#memCacheResult(url, persisted); // promote to L1
64
+ return persisted;
65
+ }
66
+ }
67
+
68
+ // L3: network fetch
69
+ const result = await this.#apiClient.call<ExpressionRendered>('expression.get', { url });
70
+ this.#memCacheResult(url, result);
71
+ this.#persistent.put(url, result); // fire-and-forget write to L2
72
+ return result;
73
+ })();
74
+
75
+ this.#inflight.set(url, promise);
76
+
77
+ try {
78
+ return await promise;
79
+ } finally {
80
+ this.#inflight.delete(url);
81
+ }
27
82
  }
28
83
 
29
84
  async getMany(urls: string[]): Promise<ExpressionRendered[]> {
30
- return this.#apiClient.call<ExpressionRendered[]>('expression.getMany', { urls })
85
+ // Check L1 first
86
+ const results: (ExpressionRendered | null)[] = urls.map(
87
+ u => this.#memCache.get(u)?.data ?? null
88
+ );
89
+ let uncachedIndices = results
90
+ .map((r, i) => r === null ? i : -1)
91
+ .filter(i => i >= 0);
92
+
93
+ if (uncachedIndices.length === 0) return results as ExpressionRendered[];
94
+
95
+ // Check L2 for remaining misses
96
+ const l2Results = await Promise.all(
97
+ uncachedIndices.map(i => this.#persistent.get(urls[i]))
98
+ );
99
+ const stillMissing: number[] = [];
100
+ for (let j = 0; j < uncachedIndices.length; j++) {
101
+ const idx = uncachedIndices[j];
102
+ if (l2Results[j]) {
103
+ results[idx] = l2Results[j]!;
104
+ this.#memCacheResult(urls[idx], l2Results[j]!); // promote to L1
105
+ } else {
106
+ stillMissing.push(idx);
107
+ }
108
+ }
109
+
110
+ if (stillMissing.length === 0) return results as ExpressionRendered[];
111
+
112
+ // L3: fetch only truly uncached URLs
113
+ const uncachedUrls = stillMissing.map(i => urls[i]);
114
+ const fetched = await this.#apiClient.call<ExpressionRendered[]>(
115
+ 'expression.getMany', { urls: uncachedUrls }
116
+ );
117
+
118
+ for (let i = 0; i < stillMissing.length; i++) {
119
+ const idx = stillMissing[i];
120
+ results[idx] = fetched[i];
121
+ if (fetched[i]) {
122
+ this.#memCacheResult(uncachedUrls[i], fetched[i]);
123
+ this.#persistent.put(uncachedUrls[i], fetched[i]); // fire-and-forget
124
+ }
125
+ }
126
+
127
+ return results as ExpressionRendered[];
128
+ }
129
+
130
+ /**
131
+ * Insert a result into L1 memory cache with LRU eviction.
132
+ */
133
+ #memCacheResult(url: string, data: ExpressionRendered): void {
134
+ const size = JSON.stringify(data).length;
135
+
136
+ // Evict oldest entries if we'd exceed limits
137
+ while (
138
+ this.#memCache.size >= ExpressionClient.MAX_MEM_ENTRIES ||
139
+ this.#totalMemBytes + size > ExpressionClient.MAX_MEM_BYTES
140
+ ) {
141
+ const oldest = this.#memCache.keys().next().value;
142
+ if (!oldest) break;
143
+ const entry = this.#memCache.get(oldest)!;
144
+ this.#totalMemBytes -= entry.size;
145
+ this.#memCache.delete(oldest);
146
+ }
147
+
148
+ this.#memCache.set(url, { data, size });
149
+ this.#totalMemBytes += size;
150
+ }
151
+
152
+ /**
153
+ * Clear both L1 (memory) and L2 (persistent) expression caches.
154
+ */
155
+ clearCache(): void {
156
+ this.#memCache.clear();
157
+ this.#inflight.clear();
158
+ this.#totalMemBytes = 0;
159
+ this.#persistent.clear(); // fire-and-forget
31
160
  }
32
161
 
33
162
  async getRaw(url: string): Promise<string> {
@@ -44,6 +173,11 @@ export class ExpressionClient {
44
173
  }
45
174
 
46
175
  async interact(url: string, interactionCall: InteractionCall): Promise<string|null> {
47
- return this.#apiClient.call<string|null>('expression.interact', { url, interactionCall })
176
+ const result = await this.#apiClient.call<string|null>('expression.interact', { url, interactionCall });
177
+ // Interactions can mutate the expression — invalidate cache so next get() fetches fresh
178
+ this.#memCache.delete(url);
179
+ this.#inflight.delete(url);
180
+ this.#persistent.delete(url); // fire-and-forget
181
+ return result;
48
182
  }
49
183
  }
package/src/index.ts CHANGED
@@ -2,6 +2,7 @@ export * from "./Ad4mClient"
2
2
  export * from "./Address";
3
3
  export * from "./agent/Agent";
4
4
  export * from "./agent/AgentStatus";
5
+ export * from "./cache/PersistentCache";
5
6
  export * from "./Exception";
6
7
  export * from "./expression/Expression";
7
8
  export * from "./expression/ExpressionRef";
@@ -1059,7 +1059,6 @@ describe("formatSPARQLValue", () => {
1059
1059
  // Comprehensive SPARQL migration unit tests
1060
1060
  // ──────────────────────────────────────────────────────────
1061
1061
 
1062
- import { matchesCondition } from "./hydration";
1063
1062
  import { Literal } from "../Literal";
1064
1063
 
1065
1064
  // Helper: create literal URLs using JSON encoding (which handles all types including booleans)
@@ -1069,102 +1068,6 @@ function literalUrl(value: any): string {
1069
1068
  return `literal:json:${encodeURIComponent(JSON.stringify(value))}`;
1070
1069
  }
1071
1070
 
1072
- describe("matchesCondition()", () => {
1073
- // Simple equality
1074
- it("simple string equality — match", () => {
1075
- expect(matchesCondition("hello", "hello")).toBe(true);
1076
- });
1077
- it("simple string equality — mismatch", () => {
1078
- expect(matchesCondition("hello", "world")).toBe(false);
1079
- });
1080
- it("simple boolean equality — true", () => {
1081
- expect(matchesCondition(true, true)).toBe(true);
1082
- });
1083
- it("simple boolean equality — false", () => {
1084
- expect(matchesCondition(false, false)).toBe(true);
1085
- });
1086
- it("boolean mismatch", () => {
1087
- expect(matchesCondition(true, false)).toBe(false);
1088
- });
1089
- it("simple number equality", () => {
1090
- expect(matchesCondition(42, 42)).toBe(true);
1091
- });
1092
- it("number mismatch", () => {
1093
- expect(matchesCondition(42, 99)).toBe(false);
1094
- });
1095
-
1096
- // Array IN clause
1097
- it("array IN clause — value present", () => {
1098
- expect(matchesCondition("a", ["a", "b", "c"])).toBe(true);
1099
- });
1100
- it("array IN clause — value absent", () => {
1101
- expect(matchesCondition("d", ["a", "b", "c"])).toBe(false);
1102
- });
1103
-
1104
- // NOT operator
1105
- it("not operator with string", () => {
1106
- expect(matchesCondition("bob", { not: "alice" })).toBe(true);
1107
- expect(matchesCondition("alice", { not: "alice" })).toBe(false);
1108
- });
1109
- it("not operator with array (NOT IN)", () => {
1110
- expect(matchesCondition("a", { not: ["b", "c"] })).toBe(true);
1111
- expect(matchesCondition("b", { not: ["b", "c"] })).toBe(false);
1112
- });
1113
-
1114
- // Comparison operators
1115
- it("gt", () => {
1116
- expect(matchesCondition(10, { gt: 5 })).toBe(true);
1117
- expect(matchesCondition(5, { gt: 5 })).toBe(false);
1118
- });
1119
- it("gte", () => {
1120
- expect(matchesCondition(5, { gte: 5 })).toBe(true);
1121
- expect(matchesCondition(4, { gte: 5 })).toBe(false);
1122
- });
1123
- it("lt", () => {
1124
- expect(matchesCondition(3, { lt: 5 })).toBe(true);
1125
- expect(matchesCondition(5, { lt: 5 })).toBe(false);
1126
- });
1127
- it("lte", () => {
1128
- expect(matchesCondition(5, { lte: 5 })).toBe(true);
1129
- expect(matchesCondition(6, { lte: 5 })).toBe(false);
1130
- });
1131
- it("combined gt + lt (range)", () => {
1132
- expect(matchesCondition(5, { gt: 3, lt: 7 })).toBe(true);
1133
- expect(matchesCondition(3, { gt: 3, lt: 7 })).toBe(false);
1134
- expect(matchesCondition(7, { gt: 3, lt: 7 })).toBe(false);
1135
- });
1136
-
1137
- // Between
1138
- it("between — inclusive range", () => {
1139
- expect(matchesCondition(5, { between: [3, 7] })).toBe(true);
1140
- expect(matchesCondition(3, { between: [3, 7] })).toBe(true);
1141
- expect(matchesCondition(7, { between: [3, 7] })).toBe(true);
1142
- expect(matchesCondition(2, { between: [3, 7] })).toBe(false);
1143
- expect(matchesCondition(8, { between: [3, 7] })).toBe(false);
1144
- });
1145
-
1146
- // Contains
1147
- it("contains with string", () => {
1148
- expect(matchesCondition("hello world", { contains: "world" })).toBe(true);
1149
- expect(matchesCondition("hello world", { contains: "xyz" })).toBe(false);
1150
- });
1151
- it("contains with array", () => {
1152
- expect(matchesCondition(["a", "b", "c"], { contains: "b" })).toBe(true);
1153
- expect(matchesCondition(["a", "b", "c"], { contains: "d" })).toBe(false);
1154
- });
1155
-
1156
- // Edge cases
1157
- it("returns false for undefined value with equality check", () => {
1158
- expect(matchesCondition(undefined, "hello")).toBe(false);
1159
- });
1160
- it("returns false for empty string when condition is non-empty", () => {
1161
- expect(matchesCondition("", "Recipe 2")).toBe(false);
1162
- });
1163
- it("returns true for undefined with not operator", () => {
1164
- expect(matchesCondition(undefined, { not: "hello" })).toBe(true);
1165
- });
1166
- });
1167
-
1168
1071
  describe("buildSPARQLQuery edge cases", () => {
1169
1072
  @Model({ name: "FlagModel" })
1170
1073
  class FlagModel extends Ad4mModel {
@@ -1400,192 +1303,7 @@ describe("Lightweight fingerprint optimization", () => {
1400
1303
  });
1401
1304
  });
1402
1305
 
1403
- // ── Native SPARQL getter evaluation ──────────────────────────────────────────
1404
- describe("Native SPARQL getter evaluation", () => {
1405
- const { evaluateCustomGettersForInstance } = require("./hydration");
1406
-
1407
- const mockPerspective = {
1408
- getLinks: jest.fn().mockResolvedValue([]),
1409
- querySparql: jest.fn(),
1410
- get: jest.fn().mockResolvedValue([]),
1411
- };
1412
-
1413
- beforeEach(() => {
1414
- jest.clearAllMocks();
1415
- });
1416
1306
 
1417
- it("should execute SELECT getter directly via querySparql", async () => {
1418
- const metadata = {
1419
- properties: {
1420
- replyingTo: {
1421
- predicate: "flux://has_reply",
1422
- getter: 'SELECT ?target WHERE { ?target <flux://has_reply> ?source . } LIMIT 1',
1423
- type: "string",
1424
- }
1425
- },
1426
- relations: {},
1427
- };
1428
-
1429
- mockPerspective.querySparql.mockResolvedValue([
1430
- { target: { value: "literal:string:msg123" } }
1431
- ]);
1432
-
1433
- const instance = { id: "test://msg1", replyingTo: undefined };
1434
- await evaluateCustomGettersForInstance(instance, mockPerspective, metadata);
1435
-
1436
- expect(mockPerspective.querySparql).toHaveBeenCalledWith(
1437
- expect.stringContaining("SELECT ?target WHERE")
1438
- );
1439
- expect(instance.replyingTo).toBe("literal:string:msg123");
1440
- });
1441
-
1442
- it("should execute ASK getter and return boolean", async () => {
1443
- const metadata = {
1444
- properties: {
1445
- isPopular: {
1446
- predicate: "flux://is_popular",
1447
- getter: 'ASK WHERE { SELECT (COUNT(DISTINCT ?reactor) AS ?count) WHERE { ?reactor <flux://reaction> ?source . } HAVING(?count > 5) }',
1448
- type: "boolean",
1449
- readOnly: true,
1450
- }
1451
- },
1452
- relations: {},
1453
- };
1454
-
1455
- mockPerspective.querySparql.mockResolvedValue(true);
1456
-
1457
- const instance = { id: "test://msg1", isPopular: false };
1458
- await evaluateCustomGettersForInstance(instance, mockPerspective, metadata);
1459
-
1460
- expect(mockPerspective.querySparql).toHaveBeenCalledWith(
1461
- expect.stringContaining("ASK WHERE")
1462
- );
1463
- expect(instance.isPopular).toBe(true);
1464
- });
1465
-
1466
- it("should replace ?source with instance ID in SPARQL getter", async () => {
1467
- const metadata = {
1468
- properties: {
1469
- author: {
1470
- predicate: "test://author",
1471
- getter: 'SELECT ?target WHERE { ?source <test://author> ?target . }',
1472
- type: "string",
1473
- }
1474
- },
1475
- relations: {},
1476
- };
1477
-
1478
- mockPerspective.querySparql.mockResolvedValue([
1479
- { target: { value: "did:key:abc123" } }
1480
- ]);
1481
-
1482
- const instance = { id: "test://post1", author: undefined };
1483
- await evaluateCustomGettersForInstance(instance, mockPerspective, metadata);
1484
-
1485
- expect(mockPerspective.querySparql).toHaveBeenCalledWith(
1486
- expect.stringContaining("<test://post1>")
1487
- );
1488
- expect(mockPerspective.querySparql).not.toHaveBeenCalledWith(
1489
- expect.stringContaining("?source")
1490
- );
1491
- });
1492
-
1493
- it("should handle empty SPARQL results gracefully", async () => {
1494
- const metadata = {
1495
- properties: {
1496
- replyingTo: {
1497
- predicate: "flux://has_reply",
1498
- getter: 'SELECT ?target WHERE { ?target <flux://has_reply> ?source . } LIMIT 1',
1499
- type: "string",
1500
- }
1501
- },
1502
- relations: {},
1503
- };
1504
-
1505
- mockPerspective.querySparql.mockResolvedValue([]);
1506
-
1507
- const instance = { id: "test://msg1", replyingTo: "original" };
1508
- await evaluateCustomGettersForInstance(instance, mockPerspective, metadata);
1509
-
1510
- // Should not overwrite with undefined
1511
- expect(instance.replyingTo).toBe("original");
1512
- });
1513
-
1514
- it("should handle SPARQL getter errors without crashing", async () => {
1515
- const metadata = {
1516
- properties: {
1517
- broken: {
1518
- predicate: "test://broken",
1519
- getter: 'SELECT ?target WHERE { INVALID SPARQL }',
1520
- type: "string",
1521
- }
1522
- },
1523
- relations: {},
1524
- };
1525
-
1526
- mockPerspective.querySparql.mockRejectedValue(new Error("SPARQL parse error"));
1527
-
1528
- const instance = { id: "test://msg1", broken: undefined };
1529
- const consoleSpy = jest.spyOn(console, "warn").mockImplementation();
1530
- await evaluateCustomGettersForInstance(instance, mockPerspective, metadata);
1531
- consoleSpy.mockRestore();
1532
-
1533
- // Should not throw, should warn
1534
- expect(instance.broken).toBeUndefined();
1535
- });
1536
-
1537
- it("should execute SPARQL getter for relations", async () => {
1538
- const metadata = {
1539
- properties: {},
1540
- relations: {
1541
- tags: {
1542
- predicate: "test://has_tag",
1543
- getter: 'SELECT ?target WHERE { ?source <test://has_tag> ?target . }',
1544
- direction: "forward",
1545
- }
1546
- },
1547
- };
1548
-
1549
- mockPerspective.querySparql.mockResolvedValue([
1550
- { target: { value: "tag:a" } },
1551
- { target: { value: "tag:b" } },
1552
- ]);
1553
-
1554
- const instance = { id: "test://post1", tags: [] };
1555
- await evaluateCustomGettersForInstance(instance, mockPerspective, metadata);
1556
-
1557
- expect(instance.tags).toEqual(["tag:a", "tag:b"]);
1558
- });
1559
-
1560
- it("should warn for legacy SurrealDB-style getter syntax instead of converting", async () => {
1561
- const metadata = {
1562
- properties: {
1563
- legacy: {
1564
- predicate: "test://legacy",
1565
- getter: "(<-link[WHERE predicate = 'test://legacy'].in.uri)[0]",
1566
- type: "string",
1567
- }
1568
- },
1569
- relations: {},
1570
- };
1571
-
1572
- const warnSpy = jest.spyOn(console, 'warn').mockImplementation(() => {});
1573
-
1574
- const instance = { id: "test://msg1", legacy: undefined };
1575
- await evaluateCustomGettersForInstance(instance, mockPerspective, metadata);
1576
-
1577
- // Should NOT call querySparql — legacy getters are no longer converted
1578
- expect(mockPerspective.querySparql).not.toHaveBeenCalled();
1579
- // Should warn about unsupported syntax
1580
- expect(warnSpy).toHaveBeenCalledWith(
1581
- expect.stringContaining("Unsupported legacy getter syntax")
1582
- );
1583
- // Value should remain undefined
1584
- expect(instance.legacy).toBeUndefined();
1585
-
1586
- warnSpy.mockRestore();
1587
- });
1588
- });
1589
1307
 
1590
1308
  // ── Subscribe callback timing ──────────────────────────────────────────
1591
1309
  describe("ModelQueryBuilder subscribe callback timing", () => {
@@ -1706,66 +1424,6 @@ describe("ModelQueryBuilder paginateSubscribe", () => {
1706
1424
  expect(queryJson.offset).toBe(0);
1707
1425
  });
1708
1426
 
1709
- it("paginateSubscribe should skip isInit messages from subscription", async () => {
1710
- const mockSubscriptionId = "paginate-init-sub";
1711
- let capturedCallback: ((result: any) => void) | null = null;
1712
-
1713
- const mockClient = {
1714
- modelSubscribe: jest.fn().mockResolvedValue({
1715
- subscriptionId: mockSubscriptionId,
1716
- result: { instances: [], totalCount: 0 },
1717
- }),
1718
- subscribeToQueryUpdates: jest.fn().mockImplementation((_id: string, cb: any) => {
1719
- capturedCallback = cb;
1720
- return () => {};
1721
- }),
1722
- keepAliveQuery: jest.fn().mockResolvedValue(true),
1723
- disposeQuerySubscription: jest.fn().mockResolvedValue(true),
1724
- };
1725
-
1726
- let modelQueryCallCount = 0;
1727
- const mockPerspective = {
1728
- uuid: "test-uuid",
1729
- client: mockClient,
1730
- modelSubscribe: jest.fn().mockImplementation(async (className: string, queryJson: string, shapeJson?: string) => {
1731
- return mockClient.modelSubscribe("test-uuid", className, queryJson, shapeJson);
1732
- }),
1733
- modelQuery: jest.fn().mockImplementation(async () => {
1734
- modelQueryCallCount++;
1735
- return { instances: [], totalCount: 0 };
1736
- }),
1737
- } as any;
1738
-
1739
- const { Ad4mModel, Model, Flag, Property } = require("./index");
1740
-
1741
- @Model({ name: "InitGuardTest" })
1742
- class InitGuardTest extends Ad4mModel {
1743
- @Flag({ through: "test://type", value: "test://init" })
1744
- type: string = "test://init";
1745
- @Property({ through: "test://name" })
1746
- name: string = "";
1747
- }
1748
-
1749
- const userCallback = jest.fn();
1750
- const builder = InitGuardTest.query(mockPerspective);
1751
- await builder.paginateSubscribe(10, 1, userCallback);
1752
-
1753
- // Reset the count after initial fetch
1754
- const initialCallCount = modelQueryCallCount;
1755
-
1756
- // Simulate an isInit message from subscription
1757
- expect(capturedCallback).not.toBeNull();
1758
- capturedCallback!({ isInit: true });
1759
-
1760
- // Wait for any async processing
1761
- await new Promise(r => setTimeout(r, 50));
1762
-
1763
- // modelQuery should NOT have been called again (isInit was filtered)
1764
- expect(modelQueryCallCount).toBe(initialCallCount);
1765
- // User callback should NOT have been invoked by isInit
1766
- expect(userCallback).not.toHaveBeenCalled();
1767
- });
1768
-
1769
1427
  it("paginateSubscribe should re-fetch on real subscription updates", async () => {
1770
1428
  const mockSubscriptionId = "paginate-update-sub";
1771
1429
  let capturedCallback: ((result: any) => void) | null = null;
@@ -1812,7 +1470,7 @@ describe("ModelQueryBuilder paginateSubscribe", () => {
1812
1470
 
1813
1471
  const initialCallCount = modelQueryCallCount;
1814
1472
 
1815
- // Simulate a real subscription update (not isInit)
1473
+ // Simulate a subscription update
1816
1474
  capturedCallback!({ instances: [{ id: "new-item" }], totalCount: 1 });
1817
1475
 
1818
1476
  // Wait for async processing
@@ -1961,10 +1619,10 @@ describe("Lazy Conformance Filters", () => {
1961
1619
  });
1962
1620
 
1963
1621
  // ──────────────────────────────────────────────────────────
1964
- // deepQuery opt-in — getter evaluation on collection queries
1622
+ // deepQuery — getter evaluation on collection queries
1965
1623
  // ──────────────────────────────────────────────────────────
1966
1624
 
1967
- describe("deepQuery opt-in — getter evaluation", () => {
1625
+ describe("deepQuery — getter evaluation", () => {
1968
1626
  @Model({ name: "DeepQueryTestMessage" })
1969
1627
  class DeepQueryTestMessage extends Ad4mModel {
1970
1628
  @Flag({ through: "flux://entry_type", value: "flux://message" })
@@ -2004,6 +1662,11 @@ describe("deepQuery opt-in — getter evaluation", () => {
2004
1662
  }
2005
1663
  return { instances: [], totalCount: 0 };
2006
1664
  }),
1665
+ evaluateGetters: jest.fn(async (className: string, instanceIds: string[], shapeJson: string, propertyNames?: string[]) => {
1666
+ // Return empty results by default — tests can override this mock
1667
+ const result: Record<string, Record<string, any>> = {};
1668
+ return result;
1669
+ }),
2007
1670
  querySparql: jest.fn(async (q: string) => {
2008
1671
  sparqlCalls.push(q);
2009
1672
  return [];
@@ -2016,6 +1679,8 @@ describe("deepQuery opt-in — getter evaluation", () => {
2016
1679
  beforeEach(() => {
2017
1680
  sparqlCalls = [];
2018
1681
  mockPerspective.querySparql.mockClear();
1682
+ mockPerspective.evaluateGetters.mockClear();
1683
+ mockPerspective.modelQuery.mockClear();
2019
1684
  mockPerspective.get.mockClear();
2020
1685
  });
2021
1686
 
@@ -2047,34 +1712,50 @@ describe("deepQuery opt-in — getter evaluation", () => {
2047
1712
  });
2048
1713
 
2049
1714
  describe("Ad4mModel.evaluateGetters()", () => {
2050
- it("resolves getters for a batch of instances", async () => {
1715
+ it("resolves getters for a batch of instances via single RPC", async () => {
2051
1716
  const instances = makeInstances(4);
2052
- sparqlCalls = [];
2053
1717
 
2054
1718
  await DeepQueryTestMessage.evaluateGetters(instances.slice(0, 2), mockPerspective, ["replyingTo"]);
2055
1719
 
2056
- const replyCalls = sparqlCalls.filter((q) => q.includes("flux://has_reply"));
2057
- expect(replyCalls.length).toBe(2);
2058
- const popularCalls = sparqlCalls.filter((q) => q.includes("flux://is_popular"));
2059
- expect(popularCalls.length).toBe(0);
1720
+ // Should make exactly 1 RPC call via perspective.evaluateGetters
1721
+ expect(mockPerspective.evaluateGetters).toHaveBeenCalledTimes(1);
1722
+ const [className, instanceIds, shapeJson, propertyNames] = mockPerspective.evaluateGetters.mock.calls[0];
1723
+ expect(className).toBe("DeepQueryTestMessage");
1724
+ expect(instanceIds).toEqual(["flux://msg-0", "flux://msg-1"]);
1725
+ expect(propertyNames).toEqual(["replyingTo"]);
1726
+ // No querySparql calls — all done in-process
1727
+ expect(sparqlCalls.length).toBe(0);
2060
1728
  });
2061
1729
 
2062
1730
  it("evaluates all getters when propertyNames is omitted", async () => {
2063
1731
  const instances = makeInstances(2);
2064
- sparqlCalls = [];
2065
1732
 
2066
1733
  await DeepQueryTestMessage.evaluateGetters(instances, mockPerspective);
2067
1734
 
2068
- const replyCalls = sparqlCalls.filter((q) => q.includes("flux://has_reply"));
2069
- const popularCalls = sparqlCalls.filter((q) => q.includes("flux://is_popular"));
2070
- expect(replyCalls.length).toBe(2);
2071
- expect(popularCalls.length).toBe(2);
1735
+ expect(mockPerspective.evaluateGetters).toHaveBeenCalledTimes(1);
1736
+ const [className, instanceIds, shapeJson, propertyNames] = mockPerspective.evaluateGetters.mock.calls[0];
1737
+ expect(className).toBe("DeepQueryTestMessage");
1738
+ expect(instanceIds).toEqual(["flux://msg-0", "flux://msg-1"]);
1739
+ expect(propertyNames).toBeUndefined();
1740
+ });
1741
+
1742
+ it("applies results to instances and syncs snapshots", async () => {
1743
+ const instances = makeInstances(2);
1744
+ // Simulate Rust returning getter results
1745
+ mockPerspective.evaluateGetters.mockResolvedValueOnce({
1746
+ "flux://msg-0": { replyingTo: "flux://msg-99" },
1747
+ "flux://msg-1": { replyingTo: "flux://msg-88" },
1748
+ });
1749
+
1750
+ await DeepQueryTestMessage.evaluateGetters(instances, mockPerspective, ["replyingTo"]);
1751
+
1752
+ expect((instances[0] as any).replyingTo).toBe("flux://msg-99");
1753
+ expect((instances[1] as any).replyingTo).toBe("flux://msg-88");
2072
1754
  });
2073
1755
 
2074
1756
  it("handles empty array gracefully", async () => {
2075
- sparqlCalls = [];
2076
1757
  await DeepQueryTestMessage.evaluateGetters([], mockPerspective);
2077
- expect(sparqlCalls.length).toBe(0);
1758
+ expect(mockPerspective.evaluateGetters).not.toHaveBeenCalled();
2078
1759
  });
2079
1760
  });
2080
1761
 
@@ -2084,6 +1765,26 @@ describe("deepQuery opt-in — getter evaluation", () => {
2084
1765
  (builder as any).deepQuery();
2085
1766
  expect((builder as any).queryParams.deepQuery).toBe(true);
2086
1767
  });
1768
+
1769
+ it("deepQuery defaults to true when not explicitly set", async () => {
1770
+ mockPerspective.modelQuery.mockResolvedValueOnce({ instances: [], totalCount: 0 });
1771
+ await DeepQueryTestMessage.query(mockPerspective).get();
1772
+
1773
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
1774
+ const [, queryJson] = mockPerspective.modelQuery.mock.calls[0];
1775
+ const qi = JSON.parse(queryJson);
1776
+ expect(qi.deepQuery).toBe(true);
1777
+ });
1778
+
1779
+ it("deepQuery can be explicitly set to false", async () => {
1780
+ mockPerspective.modelQuery.mockResolvedValueOnce({ instances: [], totalCount: 0 });
1781
+ await DeepQueryTestMessage.query(mockPerspective).deepQuery(false).get();
1782
+
1783
+ expect(mockPerspective.modelQuery).toHaveBeenCalledTimes(1);
1784
+ const [, queryJson] = mockPerspective.modelQuery.mock.calls[0];
1785
+ const qi = JSON.parse(queryJson);
1786
+ expect(qi.deepQuery).toBe(false);
1787
+ });
2087
1788
  });
2088
1789
  });
2089
1790