@hypequery/datasets 0.32.0 → 0.35.0

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 (264) hide show
  1. package/dist/agent-catalog.d.ts +3 -3
  2. package/dist/agent-catalog.d.ts.map +1 -1
  3. package/dist/cache/protocol-cache-keys.d.ts.map +1 -1
  4. package/dist/cache/protocol-cache-keys.js +10 -48
  5. package/dist/cache/query-signature.d.ts.map +1 -1
  6. package/dist/cache/query-signature.js +16 -5
  7. package/dist/catalog.d.ts +5 -1
  8. package/dist/catalog.d.ts.map +1 -1
  9. package/dist/catalog.js +9 -0
  10. package/dist/client-contract/build-from-deployment.d.ts +2 -2
  11. package/dist/client-contract/build-from-deployment.d.ts.map +1 -1
  12. package/dist/client-contract/build-from-deployment.js +7 -0
  13. package/dist/client-contract/dataset-fields.d.ts.map +1 -1
  14. package/dist/client-contract/dataset-fields.js +2 -1
  15. package/dist/cloud-publication.d.ts +3 -3
  16. package/dist/cloud-publication.d.ts.map +1 -1
  17. package/dist/cloud-publishing.d.ts +2 -2
  18. package/dist/cloud-publishing.d.ts.map +1 -1
  19. package/dist/codegen/dataset-source.d.ts.map +1 -1
  20. package/dist/codegen/dataset-source.js +10 -1
  21. package/dist/contract-3-authoring.fixture.d.ts +103 -0
  22. package/dist/contract-3-authoring.fixture.d.ts.map +1 -0
  23. package/dist/contract-3-authoring.fixture.js +40 -0
  24. package/dist/contract.d.ts +5 -1
  25. package/dist/contract.d.ts.map +1 -1
  26. package/dist/contract.js +9 -0
  27. package/dist/dataset-compilation.d.ts +3 -0
  28. package/dist/dataset-compilation.d.ts.map +1 -1
  29. package/dist/dataset-query.d.ts +5 -0
  30. package/dist/dataset-query.d.ts.map +1 -1
  31. package/dist/dataset.d.ts.map +1 -1
  32. package/dist/dataset.js +12 -2
  33. package/dist/event-operations.d.ts +43 -0
  34. package/dist/event-operations.d.ts.map +1 -0
  35. package/dist/event-operations.js +137 -0
  36. package/dist/execution-capabilities.d.ts +16 -3
  37. package/dist/execution-capabilities.d.ts.map +1 -1
  38. package/dist/execution-capabilities.js +5 -3
  39. package/dist/execution-capabilities.json +7 -8
  40. package/dist/executor.d.ts +13 -0
  41. package/dist/executor.d.ts.map +1 -1
  42. package/dist/executor.js +42 -8
  43. package/dist/index.d.ts +7 -3
  44. package/dist/index.d.ts.map +1 -1
  45. package/dist/index.js +4 -1
  46. package/dist/portable-execution-errors.d.ts +11 -0
  47. package/dist/portable-execution-errors.d.ts.map +1 -1
  48. package/dist/portable-execution-errors.js +14 -0
  49. package/dist/portable-executor.d.ts +22 -5
  50. package/dist/portable-executor.d.ts.map +1 -1
  51. package/dist/portable-executor.js +64 -5
  52. package/dist/protocol-adapter.d.ts +12 -0
  53. package/dist/protocol-adapter.d.ts.map +1 -1
  54. package/dist/protocol-adapter.js +32 -10
  55. package/dist/protocol-deployment-adapter.d.ts +10 -3
  56. package/dist/protocol-deployment-adapter.d.ts.map +1 -1
  57. package/dist/protocol-deployment-adapter.js +60 -26
  58. package/dist/protocol-rehydrate.d.ts +3 -16
  59. package/dist/protocol-rehydrate.d.ts.map +1 -1
  60. package/dist/protocol-rehydrate.js +72 -14
  61. package/dist/query-builder-protocol.d.ts +10 -0
  62. package/dist/query-builder-protocol.d.ts.map +1 -1
  63. package/dist/query-planner.d.ts.map +1 -1
  64. package/dist/query-planner.js +3 -1
  65. package/dist/relationship-check.d.ts.map +1 -1
  66. package/dist/relationship-check.js +2 -0
  67. package/dist/semantic-planner.d.ts.map +1 -1
  68. package/dist/semantic-planner.js +17 -4
  69. package/dist/semantic-query-schema.d.ts +18 -0
  70. package/dist/semantic-query-schema.d.ts.map +1 -1
  71. package/dist/semantic-query-schema.js +79 -55
  72. package/dist/tools.d.ts +6 -0
  73. package/dist/tools.d.ts.map +1 -1
  74. package/dist/types.d.ts +121 -10
  75. package/dist/types.d.ts.map +1 -1
  76. package/dist/utils/agent-catalog-projection.d.ts +2 -12
  77. package/dist/utils/agent-catalog-projection.d.ts.map +1 -1
  78. package/dist/utils/agent-catalog-projection.js +39 -2
  79. package/dist/utils/build-dataset-query-builder.d.ts.map +1 -1
  80. package/dist/utils/build-dataset-query-builder.js +4 -8
  81. package/dist/utils/calculation-stage-sql.d.ts +31 -0
  82. package/dist/utils/calculation-stage-sql.d.ts.map +1 -0
  83. package/dist/utils/calculation-stage-sql.js +98 -0
  84. package/dist/utils/compile-calculated-dataset-query.d.ts +24 -0
  85. package/dist/utils/compile-calculated-dataset-query.d.ts.map +1 -0
  86. package/dist/utils/compile-calculated-dataset-query.js +133 -0
  87. package/dist/utils/compile-dataset-query.d.ts.map +1 -1
  88. package/dist/utils/compile-dataset-query.js +11 -3
  89. package/dist/utils/dataset-definition-validation.d.ts.map +1 -1
  90. package/dist/utils/dataset-definition-validation.js +94 -7
  91. package/dist/utils/dataset-events.d.ts +19 -0
  92. package/dist/utils/dataset-events.d.ts.map +1 -0
  93. package/dist/utils/dataset-events.js +46 -0
  94. package/dist/utils/dataset-having.d.ts.map +1 -1
  95. package/dist/utils/dataset-having.js +6 -1
  96. package/dist/utils/dataset-query-result.d.ts.map +1 -1
  97. package/dist/utils/dataset-query-result.js +7 -1
  98. package/dist/utils/dataset-query-validation.d.ts +1 -1
  99. package/dist/utils/dataset-query-validation.d.ts.map +1 -1
  100. package/dist/utils/dataset-query-validation.js +25 -47
  101. package/dist/utils/dataset-source.d.ts +2 -2
  102. package/dist/utils/dataset-source.d.ts.map +1 -1
  103. package/dist/utils/dataset-source.js +8 -1
  104. package/dist/utils/dataset-validation.d.ts.map +1 -1
  105. package/dist/utils/dataset-validation.js +2 -1
  106. package/dist/utils/dimension-selection-overrides.d.ts +19 -0
  107. package/dist/utils/dimension-selection-overrides.d.ts.map +1 -0
  108. package/dist/utils/dimension-selection-overrides.js +22 -0
  109. package/dist/utils/event-breakdown-sql.d.ts +15 -0
  110. package/dist/utils/event-breakdown-sql.d.ts.map +1 -0
  111. package/dist/utils/event-breakdown-sql.js +17 -0
  112. package/dist/utils/event-condition-sql.d.ts +18 -0
  113. package/dist/utils/event-condition-sql.d.ts.map +1 -0
  114. package/dist/utils/event-condition-sql.js +63 -0
  115. package/dist/utils/event-operation-shape.d.ts +8 -0
  116. package/dist/utils/event-operation-shape.d.ts.map +1 -0
  117. package/dist/utils/event-operation-shape.js +66 -0
  118. package/dist/utils/event-operation-spec.d.ts +43 -0
  119. package/dist/utils/event-operation-spec.d.ts.map +1 -0
  120. package/dist/utils/event-operation-spec.js +68 -0
  121. package/dist/utils/event-range-span.d.ts +4 -0
  122. package/dist/utils/event-range-span.d.ts.map +1 -0
  123. package/dist/utils/event-range-span.js +22 -0
  124. package/dist/utils/event-result-values.d.ts +8 -0
  125. package/dist/utils/event-result-values.d.ts.map +1 -0
  126. package/dist/utils/event-result-values.js +21 -0
  127. package/dist/utils/event-source-sql.d.ts +38 -0
  128. package/dist/utils/event-source-sql.d.ts.map +1 -0
  129. package/dist/utils/event-source-sql.js +71 -0
  130. package/dist/utils/filter-predicate-tree.d.ts +28 -0
  131. package/dist/utils/filter-predicate-tree.d.ts.map +1 -0
  132. package/dist/utils/filter-predicate-tree.js +80 -0
  133. package/dist/utils/filter-tree.d.ts +42 -0
  134. package/dist/utils/filter-tree.d.ts.map +1 -0
  135. package/dist/utils/filter-tree.js +164 -0
  136. package/dist/utils/filtered-aggregation-sql.d.ts.map +1 -1
  137. package/dist/utils/filtered-aggregation-sql.js +22 -1
  138. package/dist/utils/funnel-rows.d.ts +10 -0
  139. package/dist/utils/funnel-rows.d.ts.map +1 -0
  140. package/dist/utils/funnel-rows.js +30 -0
  141. package/dist/utils/funnel-sql.d.ts +18 -0
  142. package/dist/utils/funnel-sql.d.ts.map +1 -0
  143. package/dist/utils/funnel-sql.js +104 -0
  144. package/dist/utils/metric-derived-query.d.ts.map +1 -1
  145. package/dist/utils/metric-derived-query.js +4 -5
  146. package/dist/utils/metric-query-builder.d.ts.map +1 -1
  147. package/dist/utils/metric-query-builder.js +4 -5
  148. package/dist/utils/metric-query-validation.d.ts.map +1 -1
  149. package/dist/utils/metric-query-validation.js +18 -7
  150. package/dist/utils/other-bucket-sql.d.ts +23 -0
  151. package/dist/utils/other-bucket-sql.d.ts.map +1 -0
  152. package/dist/utils/other-bucket-sql.js +51 -0
  153. package/dist/utils/portable-aggregations.d.ts +10 -6
  154. package/dist/utils/portable-aggregations.d.ts.map +1 -1
  155. package/dist/utils/portable-aggregations.js +13 -8
  156. package/dist/utils/portable-grains.d.ts +17 -8
  157. package/dist/utils/portable-grains.d.ts.map +1 -1
  158. package/dist/utils/portable-grains.js +26 -11
  159. package/dist/utils/portable-query-calculations.d.ts +14 -0
  160. package/dist/utils/portable-query-calculations.d.ts.map +1 -0
  161. package/dist/utils/portable-query-calculations.js +31 -0
  162. package/dist/utils/portable-semantic-query.d.ts.map +1 -1
  163. package/dist/utils/portable-semantic-query.js +27 -1
  164. package/dist/utils/protocol-contract-3.d.ts +30 -0
  165. package/dist/utils/protocol-contract-3.d.ts.map +1 -0
  166. package/dist/utils/protocol-contract-3.js +93 -0
  167. package/dist/utils/protocol-dataset-query.d.ts +19 -0
  168. package/dist/utils/protocol-dataset-query.d.ts.map +1 -0
  169. package/dist/utils/protocol-dataset-query.js +50 -0
  170. package/dist/utils/protocol-filter-nodes.d.ts +9 -0
  171. package/dist/utils/protocol-filter-nodes.d.ts.map +1 -0
  172. package/dist/utils/protocol-filter-nodes.js +68 -0
  173. package/dist/utils/protocol-metric-capabilities.d.ts.map +1 -1
  174. package/dist/utils/protocol-metric-capabilities.js +2 -1
  175. package/dist/utils/protocol-metric-expressions.d.ts +9 -1
  176. package/dist/utils/protocol-metric-expressions.d.ts.map +1 -1
  177. package/dist/utils/protocol-metric-expressions.js +27 -2
  178. package/dist/utils/protocol-rehydrate-filters.d.ts +8 -1
  179. package/dist/utils/protocol-rehydrate-filters.d.ts.map +1 -1
  180. package/dist/utils/protocol-rehydrate-filters.js +20 -1
  181. package/dist/utils/protocol-rehydrate-time-keys.d.ts +6 -0
  182. package/dist/utils/protocol-rehydrate-time-keys.d.ts.map +1 -0
  183. package/dist/utils/protocol-rehydrate-time-keys.js +7 -0
  184. package/dist/utils/query-calculation-errors.d.ts +6 -0
  185. package/dist/utils/query-calculation-errors.d.ts.map +1 -0
  186. package/dist/utils/query-calculation-errors.js +9 -0
  187. package/dist/utils/query-calculation-formula.d.ts +19 -0
  188. package/dist/utils/query-calculation-formula.d.ts.map +1 -0
  189. package/dist/utils/query-calculation-formula.js +77 -0
  190. package/dist/utils/query-calculation-outputs.d.ts +24 -0
  191. package/dist/utils/query-calculation-outputs.d.ts.map +1 -0
  192. package/dist/utils/query-calculation-outputs.js +72 -0
  193. package/dist/utils/query-calculation-plan.d.ts +67 -0
  194. package/dist/utils/query-calculation-plan.d.ts.map +1 -0
  195. package/dist/utils/query-calculation-plan.js +416 -0
  196. package/dist/utils/query-calculation-types.d.ts +97 -0
  197. package/dist/utils/query-calculation-types.d.ts.map +1 -0
  198. package/dist/utils/query-calculation-types.js +8 -0
  199. package/dist/utils/query-field-references.d.ts.map +1 -1
  200. package/dist/utils/query-field-references.js +3 -2
  201. package/dist/utils/query-filter-errors.d.ts +11 -0
  202. package/dist/utils/query-filter-errors.d.ts.map +1 -0
  203. package/dist/utils/query-filter-errors.js +65 -0
  204. package/dist/utils/query-schema-calculations.d.ts +55 -0
  205. package/dist/utils/query-schema-calculations.d.ts.map +1 -0
  206. package/dist/utils/query-schema-calculations.js +150 -0
  207. package/dist/utils/query-schema-filters.d.ts +47 -0
  208. package/dist/utils/query-schema-filters.d.ts.map +1 -0
  209. package/dist/utils/query-schema-filters.js +132 -0
  210. package/dist/utils/query-timezone.d.ts +6 -3
  211. package/dist/utils/query-timezone.d.ts.map +1 -1
  212. package/dist/utils/query-timezone.js +5 -1
  213. package/dist/utils/relationship-builder-plan.d.ts.map +1 -1
  214. package/dist/utils/relationship-builder-plan.js +2 -1
  215. package/dist/utils/relationship-fields.d.ts.map +1 -1
  216. package/dist/utils/relationship-fields.js +5 -0
  217. package/dist/utils/relationship-measure-sql.d.ts.map +1 -1
  218. package/dist/utils/relationship-measure-sql.js +4 -1
  219. package/dist/utils/relationship-measures.d.ts.map +1 -1
  220. package/dist/utils/relationship-measures.js +2 -1
  221. package/dist/utils/relationship-validation.d.ts +3 -1
  222. package/dist/utils/relationship-validation.d.ts.map +1 -1
  223. package/dist/utils/relationship-validation.js +8 -4
  224. package/dist/utils/relative-date-filters.d.ts +21 -0
  225. package/dist/utils/relative-date-filters.d.ts.map +1 -0
  226. package/dist/utils/relative-date-filters.js +86 -0
  227. package/dist/utils/relative-date-range.d.ts +20 -0
  228. package/dist/utils/relative-date-range.d.ts.map +1 -0
  229. package/dist/utils/relative-date-range.js +75 -0
  230. package/dist/utils/retention-rows.d.ts +9 -0
  231. package/dist/utils/retention-rows.d.ts.map +1 -0
  232. package/dist/utils/retention-rows.js +30 -0
  233. package/dist/utils/retention-sql.d.ts +16 -0
  234. package/dist/utils/retention-sql.d.ts.map +1 -0
  235. package/dist/utils/retention-sql.js +68 -0
  236. package/dist/utils/scoped-dataset-source.d.ts.map +1 -1
  237. package/dist/utils/scoped-dataset-source.js +4 -0
  238. package/dist/utils/segments.d.ts +3 -2
  239. package/dist/utils/segments.d.ts.map +1 -1
  240. package/dist/utils/segments.js +5 -4
  241. package/dist/utils/semantic-query-syntax.d.ts.map +1 -1
  242. package/dist/utils/semantic-query-syntax.js +8 -2
  243. package/dist/utils/sql-dataset-source.d.ts +36 -0
  244. package/dist/utils/sql-dataset-source.d.ts.map +1 -0
  245. package/dist/utils/sql-dataset-source.js +126 -0
  246. package/dist/utils/time-axis-bounds.d.ts +11 -4
  247. package/dist/utils/time-axis-bounds.d.ts.map +1 -1
  248. package/dist/utils/time-axis-bounds.js +14 -6
  249. package/dist/utils/time-measure-axis.d.ts +2 -2
  250. package/dist/utils/time-measure-axis.d.ts.map +1 -1
  251. package/dist/utils/time-measure-axis.js +13 -3
  252. package/dist/utils/time-measure-dataset-sql.d.ts +1 -1
  253. package/dist/utils/time-measure-dataset-sql.d.ts.map +1 -1
  254. package/dist/utils/time-measure-dataset-sql.js +15 -5
  255. package/dist/utils/time-measure-source-sql.d.ts +2 -2
  256. package/dist/utils/time-measure-source-sql.d.ts.map +1 -1
  257. package/dist/utils/time-measure-source-sql.js +7 -8
  258. package/dist/utils/time-query-measures.d.ts +5 -0
  259. package/dist/utils/time-query-measures.d.ts.map +1 -1
  260. package/dist/utils/time-query-measures.js +7 -0
  261. package/dist/utils/unsupported-contract-reasons.d.ts +5 -1
  262. package/dist/utils/unsupported-contract-reasons.d.ts.map +1 -1
  263. package/dist/utils/unsupported-contract-reasons.js +5 -1
  264. package/package.json +3 -3
@@ -0,0 +1,104 @@
1
+ import { resolveDatasetSqlDialect } from './dataset-sql-dialect.js';
2
+ import { assertRawSqlForDialect } from './raw-sql-dialect-check.js';
3
+ import { StatementParameters } from './statement-parameters.js';
4
+ import { buildEventSourceSql } from './event-source-sql.js';
5
+ import { filterLeaves } from './filter-tree.js';
6
+ import { eventConditionFlagSql } from './event-condition-sql.js';
7
+ import { rankedBreakdownSql } from './event-breakdown-sql.js';
8
+ /**
9
+ * The `strict` level: the deepest step reached by a chain of strictly later
10
+ * events whose last is within the window of its first.
11
+ *
12
+ * `windowFunnel(…, 'strict_increase')` alone is wrong when events share a
13
+ * timestamp: whether a chain survives depends on the order it reads ties in.
14
+ * Each event is therefore split into one row per step it satisfies, the rows
15
+ * are ordered by `time × (N + 1) + (N − step)`, and the window is scaled by
16
+ * `N + 1`. Higher steps at one instant then sort first, so an event can only
17
+ * extend a chain whose previous event is strictly earlier, and the window
18
+ * check is exact because the offset is smaller than one scaled millisecond.
19
+ */
20
+ function strictLevelSql(steps, windowMs) {
21
+ const scale = steps + 1;
22
+ const conditions = Array.from({ length: steps }, (_, index) => `_hq_j = ${index + 1}`).join(', ');
23
+ return {
24
+ arrayJoin: `ARRAY JOIN arrayFilter(_hq_k -> _hq_steps[_hq_k] = 1, range(1, ${steps + 1})) AS _hq_j`,
25
+ level: `windowFunnel(${windowMs * scale}, 'strict_increase')(`
26
+ + `toUInt64(toUnixTimestamp64Milli(_hq_time) * ${scale} + (${steps} - _hq_j)), ${conditions}) AS _hq_level`,
27
+ };
28
+ }
29
+ /**
30
+ * The `any` level: the largest k such that steps 1…k each have a matching
31
+ * event within one span of `window`, in any order. Every matching timestamp
32
+ * is tried as the span's start; the earliest event of a satisfying span is
33
+ * one of them, so the search is exact.
34
+ */
35
+ function anyLevelSql(steps, windowMs) {
36
+ const arrays = Array.from({ length: steps }, (_, index) => (`groupArrayIf(toUnixTimestamp64Milli(_hq_time), _hq_steps[${index + 1}] = 1) AS _hq_s${index + 1}`));
37
+ let prefix = String(steps);
38
+ for (let step = steps; step >= 1; step -= 1) {
39
+ prefix = `if(arrayExists(_hq_x -> _hq_x >= _hq_t AND _hq_x <= _hq_t + ${windowMs}, _hq_s${step}), ${prefix}, ${step - 1})`;
40
+ }
41
+ const anchors = `arrayConcat(${Array.from({ length: steps }, (_, index) => `_hq_s${index + 1}`).join(', ')})`;
42
+ return { arrays, level: `arrayMax(arrayMap(_hq_t -> ${prefix}, ${anchors})) AS _hq_level` };
43
+ }
44
+ /**
45
+ * Plan a funnel (RFC 0027) as one statement: scan → per-entity level →
46
+ * per-group counts of entities reaching each step → ranked breakdown groups.
47
+ * The caller expands each returned row into one row per step.
48
+ */
49
+ export function buildFunnelSql(ds, spec, options, readsFinal) {
50
+ const dialect = resolveDatasetSqlDialect(options.builderFactory);
51
+ if (dialect.name !== 'clickhouse') {
52
+ throw new Error(`Funnels need ClickHouse; the "${dialect.name}" datasets dialect has no equivalent yet.`);
53
+ }
54
+ assertRawSqlForDialect(ds, dialect);
55
+ const statement = new StatementParameters(dialect);
56
+ const conditionFields = [...new Set(spec.steps.flatMap(step => filterLeaves(step.where).map(condition => condition.field)))];
57
+ const source = buildEventSourceSql(ds, {
58
+ entity: spec.entity,
59
+ breakdown: spec.breakdown,
60
+ conditionFields,
61
+ filters: spec.filters,
62
+ ...(spec.timezone === undefined ? {} : { timezone: spec.timezone }),
63
+ }, options, statement);
64
+ const breakdown = source.breakdown;
65
+ const steps = spec.steps.length;
66
+ const flags = spec.steps.map(step => eventConditionFlagSql(step.where, source.conditionPredicates, statement));
67
+ const partition = ['_hq_entity', ...breakdown].join(', ');
68
+ // Only events that satisfy some step can move an entity through the funnel.
69
+ const flagged = `_hq_flagged AS (SELECT _hq_time, ${partition}, [${flags.join(', ')}] AS _hq_steps `
70
+ + 'FROM _hq_events WHERE has(_hq_steps, 1))';
71
+ const cohort = spec.by === undefined ? [] : ['_hq_first'];
72
+ let entities;
73
+ if (spec.order === 'any') {
74
+ const any = anyLevelSql(steps, spec.windowMs);
75
+ const first = spec.by === undefined ? [] : ['minIf(_hq_time, _hq_steps[1] = 1) AS _hq_first'];
76
+ entities = `_hq_entity_arrays AS (SELECT ${partition}, ${[...first, ...any.arrays].join(', ')} `
77
+ + `FROM _hq_flagged GROUP BY ${partition}), `
78
+ + `_hq_entities AS (SELECT ${[partition, ...cohort].join(', ')}, ${any.level} FROM _hq_entity_arrays)`;
79
+ }
80
+ else {
81
+ const strict = strictLevelSql(steps, spec.windowMs);
82
+ const first = spec.by === undefined ? [] : ['minIf(_hq_time, _hq_j = 1) AS _hq_first'];
83
+ entities = `_hq_entities AS (SELECT ${partition}, ${[...first, strict.level].join(', ')} `
84
+ + `FROM _hq_flagged ${strict.arrayJoin} GROUP BY ${partition})`;
85
+ }
86
+ const cohortColumn = spec.by === undefined
87
+ ? []
88
+ : [`formatDateTime(${dialect.truncateTime('_hq_first', spec.by)}, '%Y-%m-%d') AS _hq_cohort`];
89
+ const reached = Array.from({ length: steps }, (_, index) => (`countIf(_hq_level >= ${index + 1}) AS _hq_r${index + 1}`));
90
+ const groupKeys = [...breakdown, ...(spec.by === undefined ? [] : ['_hq_cohort'])];
91
+ // With no grouping key the aggregate returns one row even for no entities,
92
+ // so an empty funnel still reports zero at every step.
93
+ const groups = `_hq_groups AS (SELECT ${[...breakdown.map(alias => alias), ...cohortColumn, ...reached].join(', ')} `
94
+ + `FROM _hq_entities${groupKeys.length ? ` WHERE _hq_level >= 1 GROUP BY ${groupKeys.join(', ')}` : ''})`;
95
+ const orderBy = [
96
+ ...(spec.by === undefined ? [] : ['_hq_cohort ASC']),
97
+ ...(breakdown.length ? ['_hq_rank ASC'] : []),
98
+ ];
99
+ const body = rankedBreakdownSql({
100
+ relation: '_hq_groups', breakdown, sizeColumn: '_hq_r1', limit: spec.breakdownLimit, orderBy,
101
+ });
102
+ const text = `WITH ${[...source.ctes, flagged, entities, groups].join(', ')} ${body}`;
103
+ return { statement: { text, parameters: statement }, breakdown, readsFinal: readsFinal(source.joinCtx) };
104
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"metric-derived-query.d.ts","sourceRoot":"","sources":["../../src/utils/metric-derived-query.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,SAAS,EAAE,WAAW,EAAE,gBAAgB,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACvF,OAAO,KAAK,EAAE,uBAAuB,EAAoB,MAAM,8BAA8B,CAAC;AAQ9F,OAAO,EAAuB,KAAK,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAKvF,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAMrD,wBAAgB,qBAAqB,CACnC,GAAG,EAAE,SAAS,EACd,IAAI,EAAE,iBAAiB,EACvB,KAAK,EAAE,WAAW,EAClB,KAAK,EAAE,SAAS,GAAG,SAAS,EAC5B,cAAc,EAAE,uBAAuB,EACvC,OAAO,CAAC,EAAE,gBAAgB,GACzB,gBAAgB,CAmHlB"}
1
+ {"version":3,"file":"metric-derived-query.d.ts","sourceRoot":"","sources":["../../src/utils/metric-derived-query.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,SAAS,EAAE,WAAW,EAAE,gBAAgB,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACvF,OAAO,KAAK,EAAE,uBAAuB,EAAoB,MAAM,8BAA8B,CAAC;AAU9F,OAAO,EAAuB,KAAK,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAKvF,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAMrD,wBAAgB,qBAAqB,CACnC,GAAG,EAAE,SAAS,EACd,IAAI,EAAE,iBAAiB,EACvB,KAAK,EAAE,WAAW,EAClB,KAAK,EAAE,SAAS,GAAG,SAAS,EAC5B,cAAc,EAAE,uBAAuB,EACvC,OAAO,CAAC,EAAE,gBAAgB,GACzB,gBAAgB,CAkHlB"}
@@ -5,6 +5,8 @@ import { resolveDatasetSqlDialect } from './dataset-sql-dialect.js';
5
5
  import { assertRawSqlForDialect } from './raw-sql-dialect-check.js';
6
6
  import { applyAggregationSpec, buildDimensionSelectionPlan, resolveDimensionExpression, resolveFilterField, } from '../query-planner.js';
7
7
  import { queryTimeFilter } from './query-timezone.js';
8
+ import { applyFilterTree } from './filter-predicate-tree.js';
9
+ import { filterLeaves } from './filter-tree.js';
8
10
  import { StatementParameters } from './statement-parameters.js';
9
11
  import { formulaExpressionSql } from './derived-measure-sql.js';
10
12
  import { isTenantScopedFilter } from './metric-handle.js';
@@ -49,15 +51,12 @@ export function buildDerivedMetricSql(ref, spec, query, grain, builderFactory, c
49
51
  aggregateAliases.push(quoted);
50
52
  }
51
53
  // Filters on CTE
52
- for (const filter of query.filters ?? []) {
54
+ for (const filter of filterLeaves(query.filters)) {
53
55
  if (isTenantScopedFilter(ds, filter, context)) {
54
56
  throw new Error(`Cannot filter on tenant field "${filter.field}" when runtime tenancy enforcement is active.`);
55
57
  }
56
- const resolvedField = resolveFilterField(ds, filter.field, joinCtx);
57
- for (const predicate of queryTimeFilter(dialect, ds, filter, resolvedField, query.timezone)) {
58
- cteBuilder = cteBuilder.where(predicate.expression, predicate.operator, predicate.value);
59
- }
60
58
  }
59
+ cteBuilder = applyFilterTree(cteBuilder, query.filters, filter => (queryTimeFilter(dialect, ds, filter, resolveFilterField(ds, filter.field, joinCtx), query.timezone)));
61
60
  for (const filter of segmentFilters(ds, query.segments)) {
62
61
  const predicates = queryTimeFilter(dialect, ds, filter, resolveDimensionExpression(ds, filter.field, joinCtx), query.timezone, { field: 'dimension' });
63
62
  for (const predicate of predicates) {
@@ -1 +1 @@
1
- {"version":3,"file":"metric-query-builder.d.ts","sourceRoot":"","sources":["../../src/utils/metric-query-builder.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,SAAS,EAAE,WAAW,EAAE,gBAAgB,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACvF,OAAO,KAAK,EAAE,uBAAuB,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAa9F,OAAO,KAAK,EAAE,eAAe,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAEvE,wBAAgB,uBAAuB,CACrC,GAAG,EAAE,SAAS,EACd,IAAI,EAAE,eAAe,EACrB,OAAO,EAAE,kBAAkB,EAC3B,KAAK,EAAE,WAAW,EAClB,KAAK,EAAE,SAAS,GAAG,SAAS,EAC5B,cAAc,EAAE,uBAAuB,EACvC,OAAO,CAAC,EAAE,gBAAgB,GACzB,gBAAgB,CAsDlB"}
1
+ {"version":3,"file":"metric-query-builder.d.ts","sourceRoot":"","sources":["../../src/utils/metric-query-builder.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,SAAS,EAAE,WAAW,EAAE,gBAAgB,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACvF,OAAO,KAAK,EAAE,uBAAuB,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAe9F,OAAO,KAAK,EAAE,eAAe,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAEvE,wBAAgB,uBAAuB,CACrC,GAAG,EAAE,SAAS,EACd,IAAI,EAAE,eAAe,EACrB,OAAO,EAAE,kBAAkB,EAC3B,KAAK,EAAE,WAAW,EAClB,KAAK,EAAE,SAAS,GAAG,SAAS,EAC5B,cAAc,EAAE,uBAAuB,EACvC,OAAO,CAAC,EAAE,gBAAgB,GACzB,gBAAgB,CAqDlB"}
@@ -5,6 +5,8 @@ import { resolveDatasetSqlDialect } from './dataset-sql-dialect.js';
5
5
  import { assertRawSqlForDialect } from './raw-sql-dialect-check.js';
6
6
  import { applyAggregationSpec, appendOrderLimitOffset, buildDimensionSelectionPlan, resolveDimensionExpression, resolveFilterField, } from '../query-planner.js';
7
7
  import { queryTimeFilter } from './query-timezone.js';
8
+ import { applyFilterTree } from './filter-predicate-tree.js';
9
+ import { filterLeaves } from './filter-tree.js';
8
10
  import { isTenantScopedFilter } from './metric-handle.js';
9
11
  import { buildRelationshipBuilderContext } from './relationship-builder-plan.js';
10
12
  import { segmentFilters } from './segments.js';
@@ -29,15 +31,12 @@ export function buildMetricQueryBuilder(ref, spec, dataset, query, grain, builde
29
31
  }
30
32
  qb = applyAggregationSpec(qb, ds, spec, ref.name, joinCtx, dialect);
31
33
  // User filters
32
- for (const filter of query.filters ?? []) {
34
+ for (const filter of filterLeaves(query.filters)) {
33
35
  if (isTenantScopedFilter(ds, filter, context)) {
34
36
  throw new Error(`Cannot filter on tenant field "${filter.field}" when runtime tenancy enforcement is active.`);
35
37
  }
36
- const resolvedField = resolveFilterField(ds, filter.field, joinCtx);
37
- for (const predicate of queryTimeFilter(dialect, ds, filter, resolvedField, query.timezone)) {
38
- qb = qb.where(predicate.expression, predicate.operator, predicate.value);
39
- }
40
38
  }
39
+ qb = applyFilterTree(qb, query.filters, filter => (queryTimeFilter(dialect, ds, filter, resolveFilterField(ds, filter.field, joinCtx), query.timezone)));
41
40
  // Segments: author-defined, so they resolve dimensions directly rather
42
41
  // than through the caller-facing filter allow-list.
43
42
  for (const filter of segmentFilters(ds, query.segments)) {
@@ -1 +1 @@
1
- {"version":3,"file":"metric-query-validation.d.ts","sourceRoot":"","sources":["../../src/utils/metric-query-validation.ts"],"names":[],"mappings":"AAEA,gFAAgF;AAChF,OAAO,KAAK,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AACjE,OAAO,EAAuB,KAAK,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAI9E,OAAO,EAAsD,KAAK,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAW3G,wBAAgB,wBAAwB,CACtC,MAAM,EAAE,YAAY,EACpB,KAAK,EAAE,WAAW,EAClB,OAAO,CAAC,EAAE,gBAAgB,GACzB,gBAAgB,CAwIlB"}
1
+ {"version":3,"file":"metric-query-validation.d.ts","sourceRoot":"","sources":["../../src/utils/metric-query-validation.ts"],"names":[],"mappings":"AAIA,gFAAgF;AAChF,OAAO,KAAK,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AACjE,OAAO,EAAuB,KAAK,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAI9E,OAAO,EAAsD,KAAK,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAW3G,wBAAgB,wBAAwB,CACtC,MAAM,EAAE,YAAY,EACpB,KAAK,EAAE,WAAW,EAClB,OAAO,CAAC,EAAE,gBAAgB,GACzB,gBAAgB,CAiJlB"}
@@ -1,3 +1,5 @@
1
+ import { relativeDateFilterError } from './relative-date-filters.js';
2
+ import { effectiveFilterLeaves, filterLeafCount, filterTreeErrors } from './filter-tree.js';
1
3
  import { notGroupableError } from './groupable.js';
2
4
  import { semanticQuerySyntaxErrors } from './semantic-query-syntax.js';
3
5
  import { validateFilterValue } from '../validation.js';
@@ -38,7 +40,7 @@ export function validateMetricQueryInput(metric, query, context) {
38
40
  if (relationshipTenantError) {
39
41
  errors.push(relationshipTenantError);
40
42
  }
41
- errors.push(...enforcedConstraintErrors(ds, context, query.filters?.length ?? 0));
43
+ errors.push(...enforcedConstraintErrors(ds, context, filterLeafCount(query.filters)));
42
44
  if (metric.__type === 'grained_metric_ref' && query.by && query.by !== metric.grain) {
43
45
  errors.push(`Metric "${ref.name}" is already grained by "${metric.grain}" and cannot be queried with by="${query.by}".`);
44
46
  }
@@ -62,9 +64,16 @@ export function validateMetricQueryInput(metric, query, context) {
62
64
  }
63
65
  }
64
66
  // Validate filters
65
- for (const filter of query.filters ?? []) {
67
+ const filterEntries = filterTreeErrors(query.filters).length === 0 ? effectiveFilterLeaves(query.filters) : [];
68
+ for (const { filter, operators } of filterEntries) {
69
+ // The client resolves every valid relative range first (RFC 0029); one
70
+ // still here could not be resolved, and says why.
71
+ if (filter.operator === 'inDateRange') {
72
+ errors.push(relativeDateFilterError(ds, filter) ?? `Filter "${filter.field}": "inDateRange" was not resolved before validation.`);
73
+ continue;
74
+ }
66
75
  if (isQualifiedField(filter.field)) {
67
- const filterError = validateQualifiedFilter(ds, filter, context);
76
+ const filterError = validateQualifiedFilter(ds, filter, context, operators);
68
77
  if (filterError) {
69
78
  errors.push(filterError);
70
79
  }
@@ -75,8 +84,9 @@ export function validateMetricQueryInput(metric, query, context) {
75
84
  continue;
76
85
  }
77
86
  const filterDefinition = filters[filter.field];
78
- if (!filterAllowsOperator(filterDefinition, filter.operator)) {
79
- errors.push(`Filter "${filter.field}" does not allow operator "${filter.operator}". Allowed: ${(filterDefinition?.operators ?? SEMANTIC_FILTER_OPERATORS).join(', ')}`);
87
+ const refused = operators.find(operator => !filterAllowsOperator(filterDefinition, operator));
88
+ if (refused) {
89
+ errors.push(`Filter "${filter.field}" does not allow operator "${refused}"${refused === filter.operator ? '' : ` (the negation of "${filter.operator}")`}. Allowed: ${(filterDefinition?.operators ?? SEMANTIC_FILTER_OPERATORS).join(', ')}`);
80
90
  continue;
81
91
  }
82
92
  const resolvedField = filterDefinition.field;
@@ -122,8 +132,9 @@ export function validateMetricQueryInput(metric, query, context) {
122
132
  if (ds.limits.maxMeasures && 1 > ds.limits.maxMeasures) {
123
133
  errors.push(`Too many measures (1). Max: ${ds.limits.maxMeasures}`);
124
134
  }
125
- if (ds.limits.maxFilters && (query.filters?.length ?? 0) > ds.limits.maxFilters) {
126
- errors.push(`Too many filters (${query.filters?.length}). Max: ${ds.limits.maxFilters}`);
135
+ const filterCount = filterLeafCount(query.filters);
136
+ if (ds.limits.maxFilters && filterCount > ds.limits.maxFilters) {
137
+ errors.push(`Too many filters (${filterCount}). Max: ${ds.limits.maxFilters}`);
127
138
  }
128
139
  if (ds.limits.maxResultSize && query.limit != null && query.limit > ds.limits.maxResultSize) {
129
140
  errors.push(`Too many results requested (${query.limit}). Max: ${ds.limits.maxResultSize}`);
@@ -0,0 +1,23 @@
1
+ /**
2
+ * RFC 0026 `other`: the top-N ranking statement, and the dataset view whose
3
+ * selected dimension reads `if(value IN top-N, value, label)`.
4
+ *
5
+ * Every row is regrouped from source, so every measure in the remainder row
6
+ * is exact, `countDistinct` included. The ranking runs over the same filters,
7
+ * segments and tenancy as the query, over its whole range rather than per
8
+ * period, and never counts NULL as a top value.
9
+ */
10
+ import type { DatasetSqlDialectRules } from '../dataset-sql-dialect.js';
11
+ import type { DatasetQueryExecutionOptions } from '../dataset-query.js';
12
+ import type { AnyDatasetInstance } from '../types.js';
13
+ import type { PlannedOther, QueryCalculationPlan } from './query-calculation-plan.js';
14
+ import type { PlannedStatement } from './statement-parameters.js';
15
+ /**
16
+ * Why this dialect cannot run the plan's stage, as one message, or undefined.
17
+ * `limitBy`, `other` and joined share denominators rely on ClickHouse SQL.
18
+ */
19
+ export declare function unsupportedStageMessage(plan: QueryCalculationPlan, dialect: DatasetSqlDialectRules): string | undefined;
20
+ export declare function assertStageSupported(plan: QueryCalculationPlan, dialect: DatasetSqlDialectRules): void;
21
+ export declare function withOtherBucket(ds: AnyDatasetInstance, other: PlannedOther, dialect: DatasetSqlDialectRules): AnyDatasetInstance;
22
+ export declare function otherRankingSql(ds: AnyDatasetInstance, other: PlannedOther, options: DatasetQueryExecutionOptions, dialect: DatasetSqlDialectRules): PlannedStatement;
23
+ //# sourceMappingURL=other-bucket-sql.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"other-bucket-sql.d.ts","sourceRoot":"","sources":["../../src/utils/other-bucket-sql.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AACxE,OAAO,KAAK,EAAE,4BAA4B,EAAE,MAAM,qBAAqB,CAAC;AACxE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAKtD,OAAO,KAAK,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,6BAA6B,CAAC;AACtF,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAGlE;;;GAGG;AACH,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,oBAAoB,EAAE,OAAO,EAAE,sBAAsB,GAAG,MAAM,GAAG,SAAS,CASvH;AAED,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,oBAAoB,EAAE,OAAO,EAAE,sBAAsB,GAAG,IAAI,CAGtG;AAED,wBAAgB,eAAe,CAC7B,EAAE,EAAE,kBAAkB,EACtB,KAAK,EAAE,YAAY,EACnB,OAAO,EAAE,sBAAsB,GAC9B,kBAAkB,CAIpB;AAED,wBAAgB,eAAe,CAC7B,EAAE,EAAE,kBAAkB,EACtB,KAAK,EAAE,YAAY,EACnB,OAAO,EAAE,4BAA4B,EACrC,OAAO,EAAE,sBAAsB,GAC9B,gBAAgB,CAUlB"}
@@ -0,0 +1,51 @@
1
+ /**
2
+ * RFC 0026 `other`: the top-N ranking statement, and the dataset view whose
3
+ * selected dimension reads `if(value IN top-N, value, label)`.
4
+ *
5
+ * Every row is regrouped from source, so every measure in the remainder row
6
+ * is exact, `countDistinct` included. The ranking runs over the same filters,
7
+ * segments and tenancy as the query, over its whole range rather than per
8
+ * period, and never counts NULL as a top value.
9
+ */
10
+ import { buildDatasetQueryBuilder } from './build-dataset-query-builder.js';
11
+ import { buildDerivedDatasetSql } from './dataset-derived-query.js';
12
+ import { withDimensionSelectionRewrite } from './dimension-selection-overrides.js';
13
+ import { OTHER_TOP_CTE } from './calculation-stage-sql.js';
14
+ import { UnsupportedQueryCalculationError } from './query-calculation-errors.js';
15
+ /**
16
+ * Why this dialect cannot run the plan's stage, as one message, or undefined.
17
+ * `limitBy`, `other` and joined share denominators rely on ClickHouse SQL.
18
+ */
19
+ export function unsupportedStageMessage(plan, dialect) {
20
+ if (dialect.name === 'clickhouse')
21
+ return undefined;
22
+ const reasons = [
23
+ ...(plan.limitBy === undefined ? [] : ['"limitBy"']),
24
+ ...(plan.other === undefined ? [] : ['"other"']),
25
+ ...(plan.shares.some(share => share.denominator !== undefined) ? ['a share of a non-additive measure'] : []),
26
+ ];
27
+ if (reasons.length === 0)
28
+ return undefined;
29
+ return `${reasons.join(', ')} ${reasons.length === 1 ? 'is' : 'are'} not supported on the "${dialect.name}" dialect.`;
30
+ }
31
+ export function assertStageSupported(plan, dialect) {
32
+ const message = unsupportedStageMessage(plan, dialect);
33
+ if (message !== undefined)
34
+ throw new UnsupportedQueryCalculationError([message]);
35
+ }
36
+ export function withOtherBucket(ds, other, dialect) {
37
+ const top = `SELECT ${dialect.quoteIdentifier(other.dimension)} FROM ${dialect.quoteIdentifier(OTHER_TOP_CTE)}`;
38
+ const label = dialect.measureFilterLiteral(other.label);
39
+ return withDimensionSelectionRewrite(ds, other.dimension, expression => `if(${expression} IN (${top}), ${expression}, ${label})`);
40
+ }
41
+ export function otherRankingSql(ds, other, options, dialect) {
42
+ const ranked = buildDerivedDatasetSql(ds, other.ranking, options, buildDatasetQueryBuilder);
43
+ const quote = dialect.quoteIdentifier;
44
+ const dimension = quote(other.dimension);
45
+ // Ties break on the value itself, so the list is deterministic.
46
+ return {
47
+ text: `SELECT ${dimension} FROM (${ranked.text}) AS ${quote('_hq_other_ranked')} WHERE ${dimension} IS NOT NULL`
48
+ + ` ORDER BY ${quote(other.measure)} DESC, ${dimension} ASC LIMIT ${other.n}`,
49
+ parameters: ranked.parameters,
50
+ };
51
+ }
@@ -1,17 +1,21 @@
1
1
  /**
2
2
  * Aggregations that the published deployment contract can carry.
3
3
  *
4
- * `approxCountDistinct` runs locally, but it is an expression extension 2 and
5
- * deployment contract 3 feature (RFC 0015). Publishing emits contract 2 until
6
- * it can emit contract 3, so it refuses the measure with an error naming it.
4
+ * `approxCountDistinct` is an expression extension 2 and deployment contract 3
5
+ * feature (RFC 0015). A deployment carries it as a contract 3 measure; the
6
+ * standalone dataset contract and published metrics stay on contract 2 and
7
+ * refuse it with an error naming it.
7
8
  * `merge` is a deployment measure with its state function (RFC 0022), but the
8
9
  * expression grammar has no merge aggregate, so a metric over one is refused.
9
10
  */
10
- import type { ProtocolAggregation, ProtocolDatasetMeasure } from '@hypequery/protocol';
11
+ import type { ProtocolAggregation, ProtocolDatasetMeasureV3 } from '@hypequery/protocol';
11
12
  import type { AggregationType } from '../types.js';
12
13
  type PortableAggregation = Exclude<ProtocolAggregation, 'approxCountDistinct'>;
13
- /** A dataset measure's aggregation as the contract carries it; otherwise throws naming `owner`. */
14
- export declare function requirePublishableMeasureAggregation(aggregation: AggregationType, owner: string): ProtocolDatasetMeasure['aggregation'];
14
+ /**
15
+ * A dataset measure's aggregation as the contract carries it; otherwise throws
16
+ * naming `owner`. Contract 3 carries `approxCountDistinct`; contract 2 does not.
17
+ */
18
+ export declare function requirePublishableMeasureAggregation(aggregation: AggregationType, owner: string, contractVersion?: 2 | 3): ProtocolDatasetMeasureV3['aggregation'];
15
19
  /** Returns `aggregation` when an expression can carry it; otherwise throws naming `owner`. */
16
20
  export declare function requirePortableAggregation(aggregation: AggregationType, owner: string): PortableAggregation;
17
21
  export {};
@@ -1 +1 @@
1
- {"version":3,"file":"portable-aggregations.d.ts","sourceRoot":"","sources":["../../src/utils/portable-aggregations.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,mBAAmB,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AACvF,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAEnD,KAAK,mBAAmB,GAAG,OAAO,CAAC,mBAAmB,EAAE,qBAAqB,CAAC,CAAC;AAc/E,mGAAmG;AACnG,wBAAgB,oCAAoC,CAClD,WAAW,EAAE,eAAe,EAC5B,KAAK,EAAE,MAAM,GACZ,sBAAsB,CAAC,aAAa,CAAC,CAGvC;AAED,8FAA8F;AAC9F,wBAAgB,0BAA0B,CACxC,WAAW,EAAE,eAAe,EAC5B,KAAK,EAAE,MAAM,GACZ,mBAAmB,CASrB"}
1
+ {"version":3,"file":"portable-aggregations.d.ts","sourceRoot":"","sources":["../../src/utils/portable-aggregations.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,KAAK,EAAE,mBAAmB,EAAE,wBAAwB,EAAE,MAAM,qBAAqB,CAAC;AACzF,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAEnD,KAAK,mBAAmB,GAAG,OAAO,CAAC,mBAAmB,EAAE,qBAAqB,CAAC,CAAC;AAc/E;;;GAGG;AACH,wBAAgB,oCAAoC,CAClD,WAAW,EAAE,eAAe,EAC5B,KAAK,EAAE,MAAM,EACb,eAAe,GAAE,CAAC,GAAG,CAAK,GACzB,wBAAwB,CAAC,aAAa,CAAC,CAGzC;AAED,8FAA8F;AAC9F,wBAAgB,0BAA0B,CACxC,WAAW,EAAE,eAAe,EAC5B,KAAK,EAAE,MAAM,GACZ,mBAAmB,CASrB"}
@@ -1,21 +1,26 @@
1
1
  /**
2
2
  * Aggregations that the published deployment contract can carry.
3
3
  *
4
- * `approxCountDistinct` runs locally, but it is an expression extension 2 and
5
- * deployment contract 3 feature (RFC 0015). Publishing emits contract 2 until
6
- * it can emit contract 3, so it refuses the measure with an error naming it.
4
+ * `approxCountDistinct` is an expression extension 2 and deployment contract 3
5
+ * feature (RFC 0015). A deployment carries it as a contract 3 measure; the
6
+ * standalone dataset contract and published metrics stay on contract 2 and
7
+ * refuse it with an error naming it.
7
8
  * `merge` is a deployment measure with its state function (RFC 0022), but the
8
9
  * expression grammar has no merge aggregate, so a metric over one is refused.
9
10
  */
10
11
  function refuseApproximate(aggregation, owner) {
11
12
  if (aggregation === 'approxCountDistinct') {
12
- throw new Error(`${owner} uses approxCountDistinct, which cannot be published yet: approximate aggregations ` +
13
- 'need deployment contract 3 (RFC 0015). Use it for local queries, or publish countDistinct instead.');
13
+ throw new Error(`${owner} uses approxCountDistinct, which cannot be published here: approximate aggregations ` +
14
+ 'need deployment contract 3 (RFC 0015). Publish it as a dataset measure, or use countDistinct here.');
14
15
  }
15
16
  }
16
- /** A dataset measure's aggregation as the contract carries it; otherwise throws naming `owner`. */
17
- export function requirePublishableMeasureAggregation(aggregation, owner) {
18
- refuseApproximate(aggregation, owner);
17
+ /**
18
+ * A dataset measure's aggregation as the contract carries it; otherwise throws
19
+ * naming `owner`. Contract 3 carries `approxCountDistinct`; contract 2 does not.
20
+ */
21
+ export function requirePublishableMeasureAggregation(aggregation, owner, contractVersion = 2) {
22
+ if (contractVersion === 2)
23
+ refuseApproximate(aggregation, owner);
19
24
  return aggregation;
20
25
  }
21
26
  /** Returns `aggregation` when an expression can carry it; otherwise throws naming `owner`. */
@@ -1,20 +1,29 @@
1
1
  /**
2
2
  * Time grains that the published deployment contract can carry.
3
3
  *
4
- * `minute` and `hour` run locally, but they are expression extension 2 and
5
- * deployment contract 3 features (RFC 0015). Publishing emits contract 2 until
6
- * it can emit contract 3, so a dataset that pins a sub-day grain is refused
7
- * with an error naming what needs it, rather than failing later as an opaque
8
- * contract validation error.
4
+ * Contract 2 carries `day` through `year`. Contract 3 (RFC 0015) adds `minute`
5
+ * and `hour`, and the portable runtime accepts them in a query's `by` through
6
+ * semantic invocation 2. Metrics and the standalone dataset contract stay on
7
+ * the contract 2 registry.
9
8
  */
10
- import type { ProtocolTimeGrain } from '@hypequery/protocol';
9
+ import type { ProtocolQueryTimeGrain, ProtocolTimeGrain } from '@hypequery/protocol';
11
10
  import type { TimeGrain } from '../types.js';
12
11
  /** Grains deployment contract 2 and invocation 1 carry, in ascending order. */
13
12
  export declare const PORTABLE_TIME_GRAINS: readonly ProtocolTimeGrain[];
13
+ /**
14
+ * Grains a rebuilt dataset accepts: every grain the planner can bucket on.
15
+ * Invocation 1 still refuses `minute` and `hour` before they reach it.
16
+ */
17
+ export declare const PUBLISHED_TIME_GRAINS: readonly ProtocolQueryTimeGrain[];
14
18
  export declare function isPortableTimeGrain(grain: TimeGrain): grain is ProtocolTimeGrain;
15
- /** Returns `grain` when publishing can carry it; otherwise throws naming `owner`. */
19
+ export declare function isSubDayTimeGrain(grain: TimeGrain): boolean;
20
+ /** Returns `grain` when contract 2 can carry it; otherwise throws naming `owner`. */
16
21
  export declare function requirePortableTimeGrain(grain: TimeGrain, owner: string): ProtocolTimeGrain;
17
- /** Contract 2 cannot represent a dataset-level restriction on portable grains. */
22
+ /**
23
+ * No deployment contract carries a dataset-level grain restriction, and a
24
+ * published dataset accepts every grain. Publishing a restriction would
25
+ * silently widen it, so a dataset must either declare none or list them all.
26
+ */
18
27
  export declare function assertPublishableTimeGrains(dataset: {
19
28
  readonly name: string;
20
29
  readonly timeGrains?: readonly TimeGrain[];
@@ -1 +1 @@
1
- {"version":3,"file":"portable-grains.d.ts","sourceRoot":"","sources":["../../src/utils/portable-grains.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAC7D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAE7C,+EAA+E;AAC/E,eAAO,MAAM,oBAAoB,EAAE,SAAS,iBAAiB,EAE3D,CAAC;AAIH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,SAAS,GAAG,KAAK,IAAI,iBAAiB,CAEhF;AAED,qFAAqF;AACrF,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,GAAG,iBAAiB,CAQ3F;AAED,kFAAkF;AAClF,wBAAgB,2BAA2B,CACzC,OAAO,EAAE;IAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,UAAU,CAAC,EAAE,SAAS,SAAS,EAAE,CAAA;CAAE,GAC7E,IAAI,CASN"}
1
+ {"version":3,"file":"portable-grains.d.ts","sourceRoot":"","sources":["../../src/utils/portable-grains.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,sBAAsB,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAErF,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAE7C,+EAA+E;AAC/E,eAAO,MAAM,oBAAoB,EAAE,SAAS,iBAAiB,EAE3D,CAAC;AAEH;;;GAGG;AACH,eAAO,MAAM,qBAAqB,EAAE,SAAS,sBAAsB,EAErC,CAAC;AAI/B,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,SAAS,GAAG,KAAK,IAAI,iBAAiB,CAEhF;AAED,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,SAAS,GAAG,OAAO,CAE3D;AAED,qFAAqF;AACrF,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,GAAG,iBAAiB,CAQ3F;AAED;;;;GAIG;AACH,wBAAgB,2BAA2B,CACzC,OAAO,EAAE;IAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,UAAU,CAAC,EAAE,SAAS,SAAS,EAAE,CAAA;CAAE,GAC7E,IAAI,CAUN"}
@@ -1,35 +1,50 @@
1
1
  /**
2
2
  * Time grains that the published deployment contract can carry.
3
3
  *
4
- * `minute` and `hour` run locally, but they are expression extension 2 and
5
- * deployment contract 3 features (RFC 0015). Publishing emits contract 2 until
6
- * it can emit contract 3, so a dataset that pins a sub-day grain is refused
7
- * with an error naming what needs it, rather than failing later as an opaque
8
- * contract validation error.
4
+ * Contract 2 carries `day` through `year`. Contract 3 (RFC 0015) adds `minute`
5
+ * and `hour`, and the portable runtime accepts them in a query's `by` through
6
+ * semantic invocation 2. Metrics and the standalone dataset contract stay on
7
+ * the contract 2 registry.
9
8
  */
9
+ import { SUPPORTED_TIME_GRAINS } from '../constants.js';
10
10
  /** Grains deployment contract 2 and invocation 1 carry, in ascending order. */
11
11
  export const PORTABLE_TIME_GRAINS = Object.freeze([
12
12
  'day', 'week', 'month', 'quarter', 'year',
13
13
  ]);
14
+ /**
15
+ * Grains a rebuilt dataset accepts: every grain the planner can bucket on.
16
+ * Invocation 1 still refuses `minute` and `hour` before they reach it.
17
+ */
18
+ export const PUBLISHED_TIME_GRAINS = Object.freeze([
19
+ ...SUPPORTED_TIME_GRAINS,
20
+ ]);
14
21
  const CONTRACT_2_GRAINS = new Set(PORTABLE_TIME_GRAINS);
15
22
  export function isPortableTimeGrain(grain) {
16
23
  return CONTRACT_2_GRAINS.has(grain);
17
24
  }
18
- /** Returns `grain` when publishing can carry it; otherwise throws naming `owner`. */
25
+ export function isSubDayTimeGrain(grain) {
26
+ return grain === 'minute' || grain === 'hour';
27
+ }
28
+ /** Returns `grain` when contract 2 can carry it; otherwise throws naming `owner`. */
19
29
  export function requirePortableTimeGrain(grain, owner) {
20
30
  if (!isPortableTimeGrain(grain)) {
21
- throw new Error(`${owner} uses the "${grain}" time grain, which cannot be published yet: sub-day grains ` +
31
+ throw new Error(`${owner} uses the "${grain}" time grain, which cannot be published here: sub-day grains ` +
22
32
  'need deployment contract 3 (RFC 0015). Use it for local queries, or pin a grain of a day or longer.');
23
33
  }
24
34
  return grain;
25
35
  }
26
- /** Contract 2 cannot represent a dataset-level restriction on portable grains. */
36
+ /**
37
+ * No deployment contract carries a dataset-level grain restriction, and a
38
+ * published dataset accepts every grain. Publishing a restriction would
39
+ * silently widen it, so a dataset must either declare none or list them all.
40
+ */
27
41
  export function assertPublishableTimeGrains(dataset) {
28
42
  if (dataset.timeGrains === undefined)
29
43
  return;
30
- const missing = PORTABLE_TIME_GRAINS.filter(grain => !dataset.timeGrains?.includes(grain));
44
+ const missing = SUPPORTED_TIME_GRAINS.filter(grain => !dataset.timeGrains?.includes(grain));
31
45
  if (missing.length > 0) {
32
- throw new Error(`Dataset "${dataset.name}" timeGrains excludes ${missing.join(', ')}, but deployment contract 2 ` +
33
- 'cannot preserve dataset-level grain restrictions. Use all day-through-year grains or keep this dataset local.');
46
+ throw new Error(`Dataset "${dataset.name}" timeGrains excludes ${missing.join(', ')}, but deployment contracts ` +
47
+ 'cannot preserve dataset-level grain restrictions, and a published dataset accepts every grain. ' +
48
+ 'Remove timeGrains to publish it, or keep this dataset local.');
34
49
  }
35
50
  }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * RFC 0026 fields of a validated portable query, in the dataset client's
3
+ * shape: identifiers become strings and a filter calculation's `where`
4
+ * comparisons become `{ field, operator, value }` filters, exactly as the
5
+ * query's own `filters` do.
6
+ */
7
+ import type { ProtocolDatasetQuery } from '@hypequery/protocol';
8
+ import type { DatasetQueryCalculation, DatasetQueryLimitBy, DatasetQueryOtherBucket } from './query-calculation-types.js';
9
+ export declare function portableCalculationFields(operation: ProtocolDatasetQuery): {
10
+ calculations?: DatasetQueryCalculation[];
11
+ limitBy?: DatasetQueryLimitBy;
12
+ other?: DatasetQueryOtherBucket;
13
+ };
14
+ //# sourceMappingURL=portable-query-calculations.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"portable-query-calculations.d.ts","sourceRoot":"","sources":["../../src/utils/portable-query-calculations.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAIhE,OAAO,KAAK,EAAE,uBAAuB,EAAE,mBAAmB,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AAO1H,wBAAgB,yBAAyB,CAAC,SAAS,EAAE,oBAAoB,GAAG;IAC1E,YAAY,CAAC,EAAE,uBAAuB,EAAE,CAAC;IACzC,OAAO,CAAC,EAAE,mBAAmB,CAAC;IAC9B,KAAK,CAAC,EAAE,uBAAuB,CAAC;CACjC,CAsBA"}
@@ -0,0 +1,31 @@
1
+ /**
2
+ * RFC 0026 fields of a validated portable query, in the dataset client's
3
+ * shape: identifiers become strings and a filter calculation's `where`
4
+ * comparisons become `{ field, operator, value }` filters, exactly as the
5
+ * query's own `filters` do.
6
+ */
7
+ import { PortableExecutionUnsupportedError } from '../portable-execution-errors.js';
8
+ import { rehydrateMeasureFilter } from './protocol-rehydrate-filters.js';
9
+ import { UNSUPPORTED_CONTRACT_REASONS } from './unsupported-contract-reasons.js';
10
+ /** A protocol value whose identifiers are branded strings, as plain JSON. */
11
+ function plain(value) {
12
+ return JSON.parse(JSON.stringify(value));
13
+ }
14
+ export function portableCalculationFields(operation) {
15
+ const calculations = operation.calculations?.map((entry, index) => {
16
+ if (!('filter' in entry))
17
+ return plain(entry);
18
+ return {
19
+ name: String(entry.name),
20
+ filter: {
21
+ measure: String(entry.filter.measure),
22
+ where: entry.filter.where.map((expression, at) => rehydrateMeasureFilter(expression, () => new PortableExecutionUnsupportedError(`Calculation ${index} condition ${at} is not a field/operator/value comparison, so it cannot be planned.`, { reason: UNSUPPORTED_CONTRACT_REASONS.queryFilterNotComparison }))),
23
+ },
24
+ };
25
+ });
26
+ return {
27
+ ...(calculations === undefined || calculations.length === 0 ? {} : { calculations }),
28
+ ...(operation.limitBy === undefined ? {} : { limitBy: plain(operation.limitBy) }),
29
+ ...(operation.other === undefined ? {} : { other: plain(operation.other) }),
30
+ };
31
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"portable-semantic-query.d.ts","sourceRoot":"","sources":["../../src/utils/portable-semantic-query.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AACjE,OAAO,KAAK,EAIV,qBAAqB,EAEtB,MAAM,aAAa,CAAC;AAKrB,wBAAgB,aAAa,CAAC,MAAM,EAAE,OAAO,GAAG,qBAAqB,GAAG,SAAS,CAKhF;AAYD,wBAAgB,aAAa,CAAC,SAAS,EAAE,qBAAqB,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAgCxG"}
1
+ {"version":3,"file":"portable-semantic-query.d.ts","sourceRoot":"","sources":["../../src/utils/portable-semantic-query.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAsB,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AACrF,OAAO,KAAK,EAIV,qBAAqB,EAEtB,MAAM,aAAa,CAAC;AAMrB,wBAAgB,aAAa,CAAC,MAAM,EAAE,OAAO,GAAG,qBAAqB,GAAG,SAAS,CAKhF;AA4BD,wBAAgB,aAAa,CAAC,SAAS,EAAE,qBAAqB,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CA0CxG"}
@@ -1,6 +1,7 @@
1
1
  import { PortableExecutionUnsupportedError } from '../portable-execution-errors.js';
2
2
  import { rehydrateMeasureFilter } from './protocol-rehydrate-filters.js';
3
3
  import { UNSUPPORTED_CONTRACT_REASONS } from './unsupported-contract-reasons.js';
4
+ import { portableCalculationFields } from './portable-query-calculations.js';
4
5
  export function tenantRuntime(tenant) {
5
6
  if (tenant === undefined || tenant === null)
6
7
  return undefined;
@@ -10,8 +11,23 @@ export function tenantRuntime(tenant) {
10
11
  return { in: tenant.map(String) };
11
12
  return tenant;
12
13
  }
14
+ /**
15
+ * A query predicate as a dataset filter node. `logical` nodes become groups
16
+ * (RFC 0029); every leaf must be a field/operator/value comparison or a null
17
+ * check, which is all the data plane validated against the contract.
18
+ */
19
+ function operationFilter(expression, index) {
20
+ if (expression.kind === 'logical') {
21
+ return expression.operator === 'not'
22
+ ? { not: operationFilter(expression.operand, index) }
23
+ : expression.operator === 'and'
24
+ ? { and: expression.operands.map(operand => operationFilter(operand, index)) }
25
+ : { or: expression.operands.map(operand => operationFilter(operand, index)) };
26
+ }
27
+ return rehydrateMeasureFilter(expression, () => new PortableExecutionUnsupportedError(`Filter ${index} holds a comparison that is not a field/operator/value comparison, so it cannot be planned.`, { reason: UNSUPPORTED_CONTRACT_REASONS.queryFilterNotComparison }));
28
+ }
13
29
  function operationFilters(operation) {
14
- return (operation.filters ?? []).map((expression, index) => rehydrateMeasureFilter(expression, () => new PortableExecutionUnsupportedError(`Filter ${index} is not a field/operator/value comparison, so it cannot be planned.`, { reason: UNSUPPORTED_CONTRACT_REASONS.queryFilterNotComparison })));
30
+ return (operation.filters ?? []).map(operationFilter);
15
31
  }
16
32
  export function semanticQuery(operation, maxRows) {
17
33
  const filters = operationFilters(operation);
@@ -27,12 +43,18 @@ export function semanticQuery(operation, maxRows) {
27
43
  ? { measures: operation.measures.map(String) }
28
44
  : {}),
29
45
  ...(filters.length > 0 ? { filters } : {}),
46
+ // RFC 0015: the rebuilt dataset resolves each name and rejects unknown ones.
47
+ ...(operation.segments === undefined || operation.segments.length === 0
48
+ ? {}
49
+ : { segments: operation.segments.map(String) }),
30
50
  ...(orderBy.length > 0 ? { orderBy } : {}),
31
51
  // An omitted limit becomes the budget, so a caller cannot ask for an
32
52
  // unbounded scan by leaving it out.
33
53
  limit: operation.limit ?? maxRows,
34
54
  ...(operation.offset === undefined ? {} : { offset: operation.offset }),
35
55
  ...(operation.by === undefined ? {} : { by: operation.by }),
56
+ // RFC 0029: the data plane checked the axis against the contract.
57
+ ...(operation.timeKey === undefined ? {} : { timeKey: String(operation.timeKey) }),
36
58
  // RFC 0025: the dataset client applies both on the queryBuilder path,
37
59
  // and validates `having` against the selection again.
38
60
  ...(operation.kind === 'dataset' && operation.having !== undefined
@@ -44,5 +66,9 @@ export function semanticQuery(operation, maxRows) {
44
66
  }
45
67
  : {}),
46
68
  ...(operation.timezone === undefined ? {} : { timezone: operation.timezone }),
69
+ // RFC 0026: calculations reach the dataset client in its own shape.
70
+ ...(operation.kind === 'dataset' ? portableCalculationFields(operation) : {}),
71
+ // RFC 0029: the dataset client plans a filled series on the time axis.
72
+ ...(operation.kind === 'dataset' && operation.fill === true ? { fill: true } : {}),
47
73
  };
48
74
  }