farseer-cli 1.19.0 → 1.21.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 (165) hide show
  1. package/README.md +32 -9
  2. package/dist/commands/app.js +42 -3
  3. package/dist/commands/app.js.map +1 -1
  4. package/dist/commands/cells.js +120 -85
  5. package/dist/commands/cells.js.map +1 -1
  6. package/dist/commands/dashboards.js +246 -12
  7. package/dist/commands/dashboards.js.map +1 -1
  8. package/dist/commands/dimensions.js +72 -31
  9. package/dist/commands/dimensions.js.map +1 -1
  10. package/dist/commands/docs.js +82 -0
  11. package/dist/commands/docs.js.map +6 -0
  12. package/dist/commands/files.js +49 -0
  13. package/dist/commands/files.js.map +2 -2
  14. package/dist/commands/folders.js +76 -0
  15. package/dist/commands/folders.js.map +6 -0
  16. package/dist/commands/formula.js +38 -30
  17. package/dist/commands/formula.js.map +1 -1
  18. package/dist/commands/install.js +32 -30
  19. package/dist/commands/install.js.map +2 -2
  20. package/dist/commands/model.js +30 -5
  21. package/dist/commands/model.js.map +2 -2
  22. package/dist/commands/push.js +5 -3
  23. package/dist/commands/push.js.map +1 -1
  24. package/dist/commands/sheets.js +474 -52
  25. package/dist/commands/sheets.js.map +1 -1
  26. package/dist/commands/skills.js +157 -0
  27. package/dist/commands/skills.js.map +6 -0
  28. package/dist/commands/variables.js +246 -82
  29. package/dist/commands/variables.js.map +1 -1
  30. package/dist/index.js +102 -13
  31. package/dist/index.js.map +1 -1
  32. package/dist/mcp/resources/documentation.js +19 -12
  33. package/dist/mcp/resources/documentation.js.map +1 -1
  34. package/dist/mcp/tools/appTools.js +1 -7
  35. package/dist/mcp/tools/appTools.js.map +1 -1
  36. package/dist/mcp/tools/cellTools.js +6 -19
  37. package/dist/mcp/tools/cellTools.js.map +1 -1
  38. package/dist/mcp/tools/dashboardTools.js +30 -412
  39. package/dist/mcp/tools/dashboardTools.js.map +2 -2
  40. package/dist/mcp/tools/dataTools.js +15 -146
  41. package/dist/mcp/tools/dataTools.js.map +1 -1
  42. package/dist/mcp/tools/folderTools.js +12 -78
  43. package/dist/mcp/tools/folderTools.js.map +1 -1
  44. package/dist/mcp/tools/modelTools.js +33 -371
  45. package/dist/mcp/tools/modelTools.js.map +1 -1
  46. package/dist/mcp/tools/pipelineContract.js +5 -1
  47. package/dist/mcp/tools/pipelineContract.js.map +1 -1
  48. package/dist/mcp/tools/runTools.js +8 -69
  49. package/dist/mcp/tools/runTools.js.map +1 -1
  50. package/dist/mcp/tools/sheetTools.js +14 -264
  51. package/dist/mcp/tools/sheetTools.js.map +1 -1
  52. package/dist/mcp/tools/syncTools.js +5 -1
  53. package/dist/mcp/tools/syncTools.js.map +1 -1
  54. package/dist/mcp/utils/operationResponse.js +41 -0
  55. package/dist/mcp/utils/operationResponse.js.map +6 -0
  56. package/dist/operations/cells.js +444 -0
  57. package/dist/operations/cells.js.map +6 -0
  58. package/dist/operations/dashboards.js +357 -0
  59. package/dist/operations/dashboards.js.map +6 -0
  60. package/dist/operations/data.js +206 -0
  61. package/dist/operations/data.js.map +6 -0
  62. package/dist/operations/errors.js +64 -0
  63. package/dist/operations/errors.js.map +6 -0
  64. package/dist/operations/exportModel.js +59 -0
  65. package/dist/operations/exportModel.js.map +6 -0
  66. package/dist/operations/folderPath.js +128 -0
  67. package/dist/operations/folderPath.js.map +6 -0
  68. package/dist/operations/folders.js +80 -0
  69. package/dist/operations/folders.js.map +6 -0
  70. package/dist/operations/install.js +109 -0
  71. package/dist/operations/install.js.map +6 -0
  72. package/dist/operations/model.js +275 -0
  73. package/dist/operations/model.js.map +6 -0
  74. package/dist/operations/sheets.js +766 -0
  75. package/dist/operations/sheets.js.map +6 -0
  76. package/dist/pipeline/failStep.js +43 -0
  77. package/dist/pipeline/failStep.js.map +6 -0
  78. package/dist/pipeline/generated-reference.json +11 -11
  79. package/dist/pipeline/queryWorker.js +3 -1
  80. package/dist/pipeline/queryWorker.js.map +1 -1
  81. package/dist/pipeline/requests.js +3 -32
  82. package/dist/pipeline/requests.js.map +1 -1
  83. package/dist/pipeline/service.js +46 -2
  84. package/dist/pipeline/service.js.map +1 -1
  85. package/dist/services/appSyncService.js +59 -9
  86. package/dist/services/appSyncService.js.map +1 -1
  87. package/dist/services/apps.js +10 -0
  88. package/dist/services/apps.js.map +1 -1
  89. package/dist/services/farseerService.js +28 -6
  90. package/dist/services/farseerService.js.map +1 -1
  91. package/dist/skills/bundled.js +106 -0
  92. package/dist/skills/bundled.js.map +6 -0
  93. package/dist/skills/install.js +257 -0
  94. package/dist/skills/install.js.map +6 -0
  95. package/dist/skills/pipeline.js +10 -18
  96. package/dist/skills/pipeline.js.map +1 -1
  97. package/dist/utils/agentSandbox.js +1 -1
  98. package/dist/utils/dimensionMembers.js +54 -0
  99. package/dist/utils/dimensionMembers.js.map +6 -0
  100. package/dist/utils/entityResolver.js +74 -25
  101. package/dist/utils/entityResolver.js.map +1 -1
  102. package/dist/utils/errorFormatter.js +13 -0
  103. package/dist/utils/errorFormatter.js.map +1 -1
  104. package/dist/utils/formulaFilters.js +11 -2
  105. package/dist/utils/formulaFilters.js.map +1 -1
  106. package/dist/utils/operationCli.js +102 -0
  107. package/dist/utils/operationCli.js.map +6 -0
  108. package/docs/cli-guide.md +195 -1
  109. package/docs/pipeline-reference.md +138 -24
  110. package/docs/troubleshooting.md +18 -0
  111. package/package.json +2 -2
  112. package/skills/farseer-app-dev/SKILL.md +131 -0
  113. package/skills/farseer-app-dev/assignments.md +185 -0
  114. package/skills/farseer-app-dev/farseer-client-api-guide.md +907 -0
  115. package/skills/farseer-app-dev/farseer-client-release-notes.md +212 -0
  116. package/skills/farseer-app-dev/working-patterns.md +876 -0
  117. package/skills/farseer-authenticate-to-tenant/SKILL.md +60 -0
  118. package/skills/farseer-authenticate-to-tenant/app-authentication.md +91 -0
  119. package/skills/farseer-author-import-job/SKILL.md +114 -0
  120. package/skills/farseer-author-import-job/cell-writes.md +530 -0
  121. package/skills/farseer-author-import-job/deploying-a-farseer-app.md +383 -0
  122. package/skills/farseer-author-import-job/import-job-pattern.md +232 -0
  123. package/skills/farseer-build-model/SKILL.md +122 -0
  124. package/skills/farseer-build-model/formula-grain-alignment.md +612 -0
  125. package/skills/farseer-build-model/naming-conventions.md +435 -0
  126. package/skills/farseer-build-model/sparse-formulas-pattern.md +330 -0
  127. package/skills/farseer-build-pipeline/SKILL.md +190 -0
  128. package/skills/farseer-build-pipeline/erp-sales/README.md +108 -0
  129. package/skills/farseer-build-pipeline/erp-sales/erp-sales-etl/Models/bronze/erp_sales_invoice_lines.yaml +23 -0
  130. package/skills/farseer-build-pipeline/erp-sales/erp-sales-etl/Models/bronze/erp_sales_invoice_lines_raw.yaml +23 -0
  131. package/skills/farseer-build-pipeline/erp-sales/erp-sales-etl/Models/bronze/erp_sales_item_product_map.yaml +17 -0
  132. package/skills/farseer-build-pipeline/erp-sales/erp-sales-etl/Models/bronze/erp_sales_item_product_map_raw.yaml +11 -0
  133. package/skills/farseer-build-pipeline/erp-sales/erp-sales-etl/Models/gold/erp_sales_cells.yaml +40 -0
  134. package/skills/farseer-build-pipeline/erp-sales/erp-sales-etl/Models/silver/erp_sales_lines.yaml +35 -0
  135. package/skills/farseer-build-pipeline/erp-sales/erp-sales-etl/Models/silver/erp_sales_recon.yaml +43 -0
  136. package/skills/farseer-build-pipeline/erp-sales/erp-sales-etl/Models/silver/erp_sales_unmapped_items.yaml +28 -0
  137. package/skills/farseer-build-pipeline/erp-sales/erp-sales-etl/main.py +49 -0
  138. package/skills/farseer-build-pipeline/erp-sales/erp-sales-load/Models/in/erp_sales_cells.yaml +17 -0
  139. package/skills/farseer-build-pipeline/erp-sales/erp-sales-load/Models/in/erp_sales_cells_raw.yaml +14 -0
  140. package/skills/farseer-build-pipeline/erp-sales/erp-sales-load/Models/load/erp_sales_to_model.yaml +47 -0
  141. package/skills/farseer-build-pipeline/erp-sales/erp-sales-load/main.py +44 -0
  142. package/skills/farseer-build-pipeline/erp-sales/item_to_product.csv +5 -0
  143. package/skills/farseer-build-pipeline/pipeline-app-failure-report-pattern.md +103 -0
  144. package/skills/farseer-build-pipeline/pipeline-source-encoding.md +68 -0
  145. package/skills/farseer-dashboards/SKILL.md +222 -20
  146. package/skills/farseer-dashboards/cards.md +59 -0
  147. package/skills/farseer-dashboards/charts.md +245 -0
  148. package/skills/farseer-dashboards/check.md +91 -0
  149. package/skills/farseer-dashboards/measures.md +88 -0
  150. package/skills/farseer-dashboards/page.md +99 -0
  151. package/skills/farseer-dashboards/reporting-period.md +82 -0
  152. package/skills/farseer-dashboards/standard-set.md +182 -0
  153. package/skills/farseer-dashboards/tables.md +174 -0
  154. package/skills/farseer-help-center/SKILL.md +66 -0
  155. package/skills/farseer-modify-model/SKILL.md +158 -0
  156. package/skills/farseer-modify-model/model-validation-pattern.md +251 -0
  157. package/skills/farseer-optimize-model/SKILL.md +314 -0
  158. package/skills/farseer-optimize-model/stats-dump.ts +139 -0
  159. package/skills/farseer-pnl/SKILL.md +220 -0
  160. package/skills/farseer-review-model/SKILL.md +172 -0
  161. package/skills/farseer-run-apps/SKILL.md +102 -0
  162. package/skills/pipeline-authoring/SKILL.md +4 -4
  163. package/skills/pipeline-authoring/practices.md +17 -4
  164. package/dist/services/agentApprovalFetch.js +0 -90
  165. package/dist/services/agentApprovalFetch.js.map +0 -6
@@ -0,0 +1,612 @@
1
+ # Formula grain alignment — operand dims must match output grain
2
+
3
+ When a variable's formula combines two or more operand variables, the
4
+ output's grain (its tables) must be
5
+ **reachable from the union of the operand grains**, optionally via the
6
+ tables' FK columns.
7
+
8
+ If the output grain contains a dimension that is **not present in any
9
+ operand** (and not reachable via a parent/child relation from one), the
10
+ engine has no rule for which row of which operand maps to which output
11
+ cell. The behavior is one of:
12
+
13
+ - **Cartesian fan-out** — the same operand value is replicated across
14
+ every member of the orphan dimension. The result is silently wrong
15
+ (every member gets the same number) **and** the calculation grid
16
+ explodes by the size of that dimension.
17
+ - **Aggregation along the wrong axis** — the operand's "extra" dimension
18
+ (one that exists in the operand but not in the output) gets rolled up
19
+ via the variable's rollup. If the rollup is wrong (e.g. `sum` on a
20
+ per-row weight), the answer is wrong.
21
+
22
+ Either way, performance and correctness suffer together. The QA signal
23
+ is usually performance: a formula that should resolve in milliseconds
24
+ takes tens of seconds because the engine is materialising a much larger
25
+ cube than necessary.
26
+
27
+ This is the **single most common cause of slow formulas** we've seen in
28
+ practice. Always check grain alignment first when triaging a slow OUT.
29
+
30
+ Examples write a variable as `"Name" [Table, …] = formula`: its name, its tables in brackets (a fixed member as `Table = Member`), then its formula; properties such as `readonly` go on the lines below.
31
+
32
+ ---
33
+
34
+ ## §1 — Anti-example — orphan dimension in output grain
35
+
36
+ ```text
37
+ # Revenue
38
+ "Product Revenue OUT" [Channel, Region, Product_Line, Versions, Years, Months] =
39
+ "Product Mix IN" * "Channel Revenue by Region"
40
+ number format: currency
41
+ folder: Revenue
42
+ readonly
43
+
44
+ "Product Mix IN" [Channel, Product, Versions, Years, Months]
45
+ rollup: AVERAGE
46
+ number format: percentage
47
+ folder: Revenue
48
+
49
+ # Stores
50
+ "Channel Revenue by Region" [Channel, Region, Store, Versions, Years, Months] =
51
+ "Store Revenue OUT" * "Region Share IN"
52
+ folder: Stores
53
+ readonly
54
+ ```
55
+
56
+ What's wrong:
57
+
58
+ | Table | In `Product Revenue OUT`? | In `Product Mix IN`? | In `Channel Revenue by Region`? |
59
+ |---|---|---|---|
60
+ | `Channel` | yes | yes | yes |
61
+ | `Region` | yes | no | yes |
62
+ | **`Product_Line`** | **yes** | **no** | **no** |
63
+ | `Versions`, `Years`, `Months` | yes | yes | yes |
64
+ | `Product` | no | yes | no |
65
+ | `Store` | no | no | yes |
66
+
67
+ `Product_Line` is the orphan: it appears only in the output. Neither
68
+ operand carries it, so the engine fans out the product across every
69
+ `Product_Line` member. `Product` and `Store` go the other way —
70
+ they appear only in operands, so they're rolled up using each operand's
71
+ rollup before the multiplication.
72
+
73
+ Observed impact of this shape on one model: the formula took **tens of
74
+ seconds** to resolve. After the fix below: **well under a second** (about
75
+ two orders of magnitude faster).
76
+
77
+ ---
78
+
79
+ ## §2 — The fix — replace the orphan with the related dimension that the operand actually carries
80
+
81
+ The intent in this example was that `Product` and `Product_Line` are
82
+ related (an FK column from `Product` to `Product_Line`) — i.e.
83
+ `Product_Line` is the parent of `Product`. The output
84
+ "should" be at `Product_Line` grain because that's the level the
85
+ business cares about.
86
+
87
+ But the operand `"Product Mix IN"` carries the **child**
88
+ table `Product`, not the parent `Product_Line`. The correct fix is
89
+ to put **`Product`** in the output grain so the dimension actually flows
90
+ through the formula:
91
+
92
+ ```text
93
+ "Product Revenue OUT" [Channel, Region, Product, Versions, Years, Months] =
94
+ "Product Mix IN" * "Channel Revenue by Region"
95
+ number format: currency
96
+ folder: Revenue
97
+ readonly
98
+ ```
99
+
100
+ If the business needs the `Product_Line` view as well, get it for free
101
+ via the rollup along `Product → Product_Line` (the platform aggregates
102
+ when a consumer reads the parent). Don't pin the parent in the source
103
+ formula.
104
+
105
+ ---
106
+
107
+ ## §3 — How to spot this pattern (checklist)
108
+
109
+ For every variable with a formula:
110
+
111
+ 1. **List the output grain** — every table it carries.
112
+ 2. **List each operand's grain.**
113
+ 3. **Compute the union of operand grains.** Map child dims to their
114
+ parents (and vice versa) via the FK columns.
115
+ 4. **Compare to the output grain:**
116
+ - **Output dim not in any operand (directly or via relation)** →
117
+ **orphan**. Fix the output grain.
118
+ - **Operand dim not in output** → check the variable's rollup. If
119
+ it's intentional aggregation, fine; if not, you're collapsing detail
120
+ you wanted to keep.
121
+ 5. **Run the formula and time it.** A formula whose output is N cells
122
+ should not be hundreds of times slower than a similar formula with
123
+ matched dims.
124
+
125
+ The check is mechanical enough that it should be the first thing AI
126
+ review of a model does — both for new code and when a user reports
127
+ "this is slow."
128
+
129
+ ---
130
+
131
+ ## §4 — Mixed-grain operands — same problem, different shape
132
+
133
+ The orphan-dim antipattern above is the OUTPUT-side case: the output grain
134
+ declares a dim no operand carries. The mirror case is OPERAND-side:
135
+ operands carry **different grains from each other**, and the formula
136
+ combines them with `if(...)`, `+`, `*`, or `sum(A, B)`.
137
+
138
+ Symptom is the same — wrong values, sometimes-null cells, slow execution
139
+ — because the calculator's optimisation cannot reliably align operands
140
+ across different grains.
141
+
142
+ Common shapes:
143
+
144
+ ```text
145
+ # WRONG — three different grains in one if expression
146
+ "PL_Plan_OUT" [PL_Analytics, CostCenter, Versions, Years, Months] =
147
+ if(eq("FC_ONE_PASS_BY_INPUT", 1), # grain: [Versions, Years, Months]
148
+ "PL_Actual_upstream", # grain: [PL_Analytics, CC, Versions, Y, M]
149
+ sum("PL_Plan_IN")) # grain: [Account, CC, Versions, Y, M]
150
+ ```
151
+
152
+ The fix is the same shape as the orphan-dim fix: introduce an intermediate
153
+ variable that **projects each operand to the consumer's grain**, so the
154
+ consumer's formula combines variables that all sit at the same
155
+ dimensionality.
156
+
157
+ ```text
158
+ "PL_Plan_IN_at_PL_Analytics" [PL_Analytics, CostCenter, Versions, Years, Months] =
159
+ "PL_Plan_IN"
160
+ # Reduces Account → PL_Analytics via FK auto-rollup. No bare sum() needed.
161
+
162
+ "PL_Plan_OUT" [PL_Analytics, CostCenter, Versions, Years, Months] =
163
+ if(eq("FC_ONE_PASS_BY_INPUT", 1),
164
+ "PL_Actual_upstream", # broadcasts Versions; matches OUT grain ✓
165
+ "PL_Plan_IN_at_PL_Analytics") # same grain as OUT ✓
166
+ ```
167
+
168
+ **Naming convention for projections.** When projecting variable `X` from
169
+ grain `A` to grain `B`, name the intermediate `X_at_<grain>` (e.g.
170
+ `X_at_PL_Analytics`, `X_at_BS_Analytics`, `X_at_Reporting_Company`). The
171
+ chain is self-documenting at the call site.
172
+
173
+ **Properties on projections (the rule, stated once).** A projection
174
+ intermediate always carries `readonly` — it is derived, never
175
+ planner-editable. Turn Optimize calculation off (`optimizeCalculation: false`) **only when the
176
+ projection's source is import-fed** and the derived value must refresh
177
+ after a data load (the cross-grain-addition case below); a projection over
178
+ purely calculated sources does not need it. This is different from
179
+ disabling Optimize calculation on the **consumer**, which remains the
180
+ discouraged anti-fix below.
181
+
182
+ **Constraint on projection.** It only works when the source and target
183
+ dimensions are linked by FK relationships — the engine traverses the FK
184
+ to roll up. Projecting between unrelated dimensions (no FK path) is not
185
+ possible by formula alone; build the relationship as a data mapping or a
186
+ new FK column on the dim before attempting the projection.
187
+
188
+ **Patterns that often reveal mixed-grain operands:**
189
+
190
+ - `if(FC_gate, Actual, Plan)` — Actual and Plan often live at different
191
+ granularity. Project both to consumer grain first.
192
+ - Cross-statement formulas (BS pulling from PL, or vice versa) — almost
193
+ always need intermediates; the underlying dim graphs only meet at the
194
+ Account level.
195
+ - `sum()` aggregations where the input has more dims than the output —
196
+ fine when there's a single operand (engine auto-rolls), risky when
197
+ combined with other operands of yet-different grain.
198
+
199
+ **Anti-fix that's discouraged:** disabling "Optimize calculation" on the
200
+ consumer — UI "Optimize calculation",
201
+ API `variable.optimizeCalculation` (default `true`). This forces fresh
202
+ per-cell calculation, sidestepping the optimiser's grain assumptions. It
203
+ hides the real issue and makes the model harder to read; only use when an
204
+ intermediate-var refactor is genuinely impossible.
205
+
206
+ Calculate on demand (`calculateOnDemand`) is a **different** switch and is
207
+ **not** a fallback here: it stops the variable from being computed at all until
208
+ a dedicated API call demands it, so it and every stored formula reading it go
209
+ null. Turn it on only when the user explicitly asks for it, variable by
210
+ variable.
211
+
212
+ The "match dimensionality" rule is HARD: same-grain operands or no
213
+ combination at all. If a formula CAN be wrong on grain alignment, it
214
+ WILL be wrong eventually — don't rely on the calculator picking the
215
+ right axis.
216
+
217
+ ### Named anti-pattern — `sum(A * Flag)` across grains aggregates-then-multiplies, not element-wise
218
+
219
+ A specific, easy-to-miss shape of the mixed-grain problem above: multiplying two operands that
220
+ live at **different grains** inside a `sum()`, where the consuming variable's own grain carries
221
+ neither operand's extra dimension.
222
+
223
+ ```text
224
+ # "Var_A" [Dim, Position, Years, Months] — 10 members of Dim, ~100 each
225
+ # "Flag" [Dim] — 3 of Dim's 10 members flagged with value 1
226
+ # Target does NOT carry Dim in its grain:
227
+ "Target_CALC" [Years, Months] = sum("Var_A" * "Flag")
228
+ ```
229
+
230
+ This does **not** multiply element-by-element and sum the flagged subset (which would give
231
+ ≈300 — the sum of `Var_A` over the 3 flagged rows). Because neither operand's `Dim` reaches the
232
+ target grain, the engine **aggregates each operand to the target grain first** — `Var_A` sums
233
+ across all 10 members (≈1,000), `Flag` sums across all 10 members too (≈3, the *count* of
234
+ flagged rows) — **then multiplies the two aggregates**: ≈1,000 × 3 ≈ 3,000. The result is
235
+ `total × count-of-flagged`, not `sum-of-flagged-rows` — wrong by a factor that grows with how
236
+ many rows aren't flagged, and the number is usually still plausible-looking enough to pass a
237
+ casual sanity check.
238
+
239
+ **Fix — the same shape as the mixed-grain fix above: an intermediate variable at the common
240
+ grain.**
241
+
242
+ ```text
243
+ "Var_A_x_Flag_per_Dim" [Dim, Position, Years, Months] = "Var_A" * "Flag" # multiplies per Dim member
244
+ "Target_CALC" [Years, Months] = sum("Var_A_x_Flag_per_Dim") # now a true element-wise sum
245
+ ```
246
+
247
+ **Rule of thumb:** whenever a `sum()` wraps a product (or an `if`) of two operands that don't
248
+ already share a grain, don't trust the engine to align them — introduce the per-element
249
+ intermediate at the finer of the two operand grains first, and `sum()` that instead. This
250
+ applies generally to flag/enum-style variables used as multipliers or gates, not just the
251
+ `Var_A` / `Flag` shape above.
252
+
253
+ <a id="two-stage-gate-then-collapse"></a>
254
+
255
+ ### Named anti-pattern — a flag cannot gate an absent dimension (pre-aggregation is PER OPERAND)
256
+
257
+ The same mechanism as `sum(A * Flag)` above, stated as the boundary of the
258
+ 1/null-gate idiom: **a flag only gates a dimension that is present in
259
+ the RESULT's grain.** A dimension absent from the LHS grain is aggregated
260
+ away **on each operand independently, before the operation is applied** — so
261
+ a flag with one cell of value 1 on that dimension collapses to the scalar
262
+ `1`, and multiplying by it is a no-op returning the fully unfiltered total.
263
+
264
+ Measured on a live tenant: selecting one of four
265
+ `Versions` members via a role flag, with `Versions` omitted from the LHS
266
+ grain, both `In_Scope * Role_Budget` and `sum(In_Scope * Role_Budget)`
267
+ returned the **all-version total** (~3.6× the flagged slice), to the last
268
+ decimal at float grain. Nothing errors; the number looks plausible.
269
+ There are two fixes, for different needs:
270
+ the two-stage shape below **derives** the selected value into a coarser
271
+ output (right when you only need the selected number); a write-based
272
+ shape is required when the selected value must **live on a specific version
273
+ slot at full grain** — a formula cannot place data on a slot.
274
+
275
+ **The working shape is two-stage — gate first, collapse second.** Apply the
276
+ flag at a grain that still carries the dimension (the broadcast case, which
277
+ works); then reference that intermediate from a formula whose grain omits
278
+ the dimension — the very pre-aggregation that broke the single-stage form
279
+ now performs the selection, because the intermediate is null on every other
280
+ member:
281
+
282
+ ```text
283
+ # stage 1 — gate WITH the dimension in grain, once per selected role
284
+ "X_At_Budget" [Position, Versions, Years, Months] = "X_Month" * "IMPORT_Version_Role_Budget"
285
+ "X_At_Forecast" [Position, Versions, Years, Months] = "X_Month" * "IMPORT_Version_Role_Forecast"
286
+
287
+ # stage 2 — collapse: pre-aggregation over Versions IS the selection
288
+ "Variance" [Position, Years, Months] = "X_At_Forecast" - "X_At_Budget"
289
+ ```
290
+
291
+ **Pre-aggregation is PER OPERAND — which makes this composable.** Two
292
+ intermediates gated on *different* members can be combined in a single
293
+ grain-free formula and each resolves to its own member (verified on the same
294
+ model: two operands selecting different members, subtracted, returned
295
+ 89 = 809 − 720 — not 0). That is what lets a whole budget-vs-forecast
296
+ variance decomposition be written without naming a single dimension member
297
+ in a formula, wherever a project postulate forbids hardcoded members.
298
+
299
+ Two findings from the same probe:
300
+
301
+ - **`sum()`'s second argument is a dimension-member SCOPE, not a
302
+ predicate.** `sum(X, gt(SomeFlag, 0))` is rejected on push with
303
+ `HTTP 400 — Invalid formula: Sum requires exactly one arithmetic
304
+ expression`. There is no single-stage form; the gated intermediate
305
+ variable is mandatory.
306
+ - **`formula eval` cannot answer any grain question.** It collapses
307
+ operands to scalars before evaluating, so it reports the
308
+ aggregate-then-multiply answer regardless of what the stored-variable
309
+ engine does — it would have "confirmed" the broken single-stage form.
310
+ Probe grain behavior with a **stored variable** read back by value
311
+ (a probe variable needs a data-bearing operand to materialise at all:
312
+ [`sparse-formulas-pattern.md`](sparse-formulas-pattern.md), "A bare literal
313
+ with no dense operand to anchor a grain returns null").
314
+
315
+ ### Cross-grain addition — which operands place the cells (× inflates; + places cells only from full-grain operands)
316
+
317
+ The multiplication case above produces a **silently inflated** number. Addition across grains
318
+ fails differently, and the failure is about **which cells exist**, not about the arithmetic.
319
+ What decides is which operands place cells:
320
+
321
+ 1. Cells come only from operands that carry the consumer's **whole grain directly** — every
322
+ grain dimension as their own dimension or a pin. An operand that reaches a dimension by
323
+ projection, by an FK lookup or by broadcast does not place cells on it.
324
+ 2. If at least one such operand exists, **only its cells exist — even when it is empty**. Every
325
+ other operand contributes its value on those cells and nothing elsewhere.
326
+ 3. If no operand carries the whole grain, each operand is expanded over every member of the
327
+ dimensions it lacks, and the value decides (`null + null` stays empty; `0 + null` is `0`).
328
+ 4. In the arithmetic itself null counts as 0 in `+` / `-`, at any grain.
329
+
330
+ So a `+` that reads empty where an input plainly exists is rule 2: an operand carrying the full
331
+ grain has no cells there, and the lower-grain term cannot place any. **Before anything else,
332
+ check where that full-grain operand gets its data** — when it is fed by an import job, confirm
333
+ the import has run for those coordinates (an undo, a re-run under different labels, or
334
+ `importZeros` changes which cells exist). An
335
+ import job can change these numbers without any formula changing.
336
+
337
+ **The reliable fix when the term you need sits below the consumer's grain** is the same
338
+ intermediate-projection shape as the multiplication case — project it to the consumer's grain in a
339
+ named intermediate, so that it places its own cells:
340
+
341
+ ```text
342
+ "<Source>_at_<consumer grain>" [<consumer grain>] = "<Source>"
343
+ readonly
344
+ optimizeCalculation: false # source is import-fed — see the properties rule above
345
+ ```
346
+
347
+ The properties follow the "Properties on projections" rule stated with the naming
348
+ convention above: `readonly` always; `optimizeCalculation: false` because this
349
+ case's source is **import-fed** and the projection must refresh after a data load. It
350
+ sits on the **projection**, not the consumer — the discouraged anti-fix of disabling
351
+ Optimize calculation on the consumer stands.
352
+
353
+ **Scoping the sparse rule.** The rule "bare `A + B` treats null as 0 — never wrap in
354
+ `if(hasValue(B), B, 0)`" holds for the
355
+ **value** at any grain. It does not decide **where cells exist** — rules 1–3 above do — and a
356
+ `hasValue` wrap does not change that either.
357
+
358
+ **Cheap diagnostic — three throwaway variables at the consumer's grain:**
359
+
360
+ ```text
361
+ "DIAG X" [<consumer grain>] = X
362
+ "DIAG X plus 0" [<consumer grain>] = X + 0
363
+ "DIAG X plus S" [<consumer grain>] = X + <suspect operand>
364
+ ```
365
+
366
+ Three pushes, one minute, break located: if the first two materialise and the third has fewer
367
+ cells, the suspect operand carries the full grain and has no cells at the missing coordinates
368
+ (rule 2). That tells you whose source to check — including whether the import job that feeds it
369
+ has run for those coordinates, since an import can change which cells exist.
370
+
371
+ ---
372
+
373
+ ## §5 — Grain pins — operand broadcast and the "pin doesn't scope an inner `sum()`" trap
374
+
375
+ Gotchas specific to variables with a **member-pinned** grain (a specific
376
+ member fixed on the variable (the `members` array of `model.load`),
377
+ rather than the dim being free) that show up most often in sign-fix /
378
+ routing helpers, but are general Farseer behavior — not statutory-specific.
379
+ The through-line: **a pin decides where the value LANDS, never what is
380
+ READ.**
381
+
382
+ **Every dimension in the consumer's grain must be pinned on the injected
383
+ variable, or the value broadcasts.** If a coarse (pinned/reduced-grain)
384
+ variable is consumed by something carrying an extra dimension (e.g. a
385
+ partner/counterparty list) and the coarse variable doesn't pin that extra
386
+ dimension, its value broadcasts across every member of it — a 7-partner
387
+ consumer broadcast inflated a routed value 7×. Rule: when a coarse variable
388
+ feeds a finer-grained consumer, pin every consumer dimension you don't want
389
+ summed over. This is the operand-side face of the orphan-dimension
390
+ antipattern above — same failure mode (Cartesian fan-out), reached from the
391
+ opposite direction (a value too coarse rather than an output grain too
392
+ fine).
393
+
394
+ **A grain member-pin does not scope an explicit `sum()` inside the
395
+ formula.** Pinning a dimension on the *output* grain (a fixed member) does **not** constrain a `sum(base, member)` call written *inside* the
396
+ same formula — that inner sum still aggregates across every member of that
397
+ dimension unless the filter is placed **inside** the `sum()` itself, as
398
+ `sum(base, and(other_filter, "Dim" > "Member"))`. Output pin ≠ operand
399
+ filter — a frequent and expensive confusion, and the two read as equivalent
400
+ at a glance.
401
+
402
+ ```text
403
+ # ❌ the [Scenario = "After Adjustments"] pin on the OUTPUT does nothing
404
+ # to the sum() below — it still aggregates every scenario
405
+ "Group_Result_Signed_CALC" [Versions, Years, Months, Scenario = "After Adjustments"] =
406
+ sum("Overall_Report_CALC", "Position" > "<technical account>")
407
+
408
+ # ✅ the filter has to be repeated INSIDE the sum()
409
+ "Group_Result_Signed_CALC" [Versions, Years, Months, Scenario = "After Adjustments"] =
410
+ sum("Overall_Report_CALC", and("Position" > "<technical account>", "Scenario" > "After Adjustments"))
411
+ ```
412
+
413
+ **The same rule extends to BARE operands, not just `sum()` calls.** In a
414
+ member-pinned variable, a bare operand that carries the pinned dimension
415
+ rolls up over **all** members of it — the pin decides where the result
416
+ lands, never what the operand reads. One model reproduced this despite
417
+ having read the `sum()` form above: a check variable pinned to one group of
418
+ a filter dimension subtracted a bare ` IN` operand, which rolled up over
419
+ every member, so the control compared the pinned group against the TOTAL
420
+ input. Every operand carrying the pinned dimension needs the explicit
421
+ filtered form (`sum(operand, "Dim" > "Member")`). (Reported from one
422
+ model; the mechanism is exactly the documented per-operand
423
+ pre-aggregation, so treat it as the same rule, not a new one.)
424
+
425
+ **Never pin fixed members on TWO dimensions connected by an FK link.** A
426
+ grain like `[DimA = MemberX, DimB = MemberY]` where an FK column links DimA to DimB
427
+ exists works on the current engine but the **next-generation engine rejects
428
+ it** as ambiguous grain resolution ("two fixed members on FK-related
429
+ dimensions"). Pin the **child** (more specific) side only and let the FK
430
+ resolve the parent. Removing an existing double pin = `entities.mutate` on
431
+ `variable.memberGids` (surgical, no side effects; measured with zero value
432
+ deltas). (Reported against next-generation engine validation; not
433
+ re-verifiable on the current engine.)
434
+
435
+ **An FK is a router — and an EMPTY FK routes NOTHING.** Adding an FK
436
+ *column* to a dimension while leaving its *values* empty does not mean
437
+ "unconstrained"; it means every member reaches **nothing** through that
438
+ dimension. Measured once (not re-verified): after a routing dimension gained an empty FK
439
+ column toward a newly split dimension, a variable mapped purely through the FK
440
+ graph collapsed to **0** populated groups — every historic actual on every
441
+ member vanished; populating the FK restored it byte-for-byte. Rules: **add the FK column and populate it
442
+ in the same change** (the window in between is a broken model, not a neutral
443
+ intermediate state), and when a position-style dimension predates the split,
444
+ the correct value for existing members is **all** the new members — a
445
+ `Legacy` placeholder points at a member with no data and produces exactly
446
+ the collapse above.
447
+
448
+ **A pinned variable can read back as if the pin doesn't exist — a
449
+ dimensions-only listing omits pins.** The `dimensions` arrays of
450
+ `entities.list` / `entities.get` and the MCP tools (`farseer_get_variable`,
451
+ `farseer_list_variables`, `farseer_export_model`) return only the free tables
452
+ and silently omit pinned members — a pinned variable reads back as if the
453
+ pinned dimension were absent entirely. Never conclude "this variable doesn't
454
+ have Dim X" from a dimensions array; the usual sequels are a wrong broadcast
455
+ diagnosis or an error from re-adding a dimension that was pinned all along.
456
+ The faithful surfaces: `farseer model --variable "<Var>" <tenant>` (it prints
457
+ the pins as `Specific members:`), the `members` field of
458
+ `farseer model --json` (unless that read printed `/model/export failed …;
459
+ falling back`, which leaves every `members` empty), and the raw entity (`GET /entities/{id}/VAR` →
460
+ `variable.memberGids`).
461
+
462
+ ### Named trap — a coarse RATIO consumed at a finer grain must not carry rollup FORMULA
463
+
464
+ A share computed one level up (`Key [Versions, Years, Months] = Part / Whole`)
465
+ and multiplied into a finer grain (`Allocation [Account, CostCentre, Versions,
466
+ Years, Months] = sum(Pool) * Key`) is the standard allocation / mix / FX-weight
467
+ shape. Give the ratio **rollup FORMULA** and the consumer reads **null**:
468
+ measured 2026-10-15 on a sandbox tenant, a FORMULA-rollup variable has **no
469
+ materialised cells**, so every stored formula that references it reads null —
470
+ pinned or not. A direct query of the ratio still answers (that is what makes
471
+ it look fine), and the consumer's write and `farseer model --variable` are
472
+ both clean; downstream totals often do not move, because subtracting or
473
+ adding a null term changes nothing. The one tell in `formula eval`:
474
+ `[readonly, calculated]` means a value, bare `[readonly]` means no cell.
475
+
476
+ | Ratio's rollup | Consumer at the finer grain | Ratio's own year value (monthly 0.3 and 0.05) |
477
+ |---|---|---|
478
+ | `formula` | **null** | the true annual ratio (0.073) |
479
+ | `average` | correct | average of the monthly ratios (0.175) |
480
+ | `sum` (default) | correct | sum of the monthly ratios (0.35) — meaningless |
481
+
482
+ - **A ratio that a formula consumes → rollup AVERAGE.** It materialises
483
+ cells and its year value is at least a ratio.
484
+ - **Rollup FORMULA only for a display-only ratio** — it alone gives the
485
+ true annual ratio. Where both are needed, keep two variables: the consumed
486
+ one (`average`) and a display one (`formula`), and say which is which in
487
+ the notes.
488
+ - Same family, measured alongside: a FORMULA-rollup variable whose formula
489
+ pins versions (`sum(V, Versions > FC) / sum(V, Versions > Plan)`) also
490
+ reads null when read with a version pin.
491
+
492
+ ---
493
+
494
+ ## §6 — When the orphan is intentional
495
+
496
+ There are legitimate cases for a dimension in the output grain that
497
+ isn't in any operand:
498
+
499
+ - **Broadcast by design** — e.g. an OUT at `[Versions, Years, Months]`
500
+ computed from an IMPORT at `[Years, Months]`. The IMPORT
501
+ deliberately omits `Versions` so it fans out across all versions
502
+ . The fan-out is the
503
+ point.
504
+ - **Constant / scalar lookup** — a single value (e.g. `"FX EUR/USD"
505
+ [Years, Months]`) multiplied into a per-entity variable.
506
+
507
+ The distinguishing question: **"is the same value supposed to land in
508
+ every member of the orphan dim?"** If yes — broadcast is intentional,
509
+ leave it. If no — it's the antipattern, fix the grain.
510
+
511
+ **The reverse direction never works: an output that omits a dimension
512
+ cannot SELECT one member of it.** Broadcast (writing the same value into
513
+ every member of an absent dimension) is legitimate; selection (reading one
514
+ member of a dimension the output grain omits — e.g. gating on a flag to
515
+ pick one `Versions` slot) is not, because each operand pre-aggregates over
516
+ the absent dimension before the formula runs (see "a flag cannot gate an
517
+ absent dimension" above).
518
+
519
+ ---
520
+
521
+ ## §7 — Avoid it at the start (design-time performance rules)
522
+
523
+ The sections above are diagnostic — spot the antipattern once it's already
524
+ slow. These three rules are the same mechanisms stated as **design-time**
525
+ guidance: apply them while drafting the variable graph (the `farseer-build-model` skill, step
526
+ 4) and the cost never shows up in the first place. Measured magnitudes are
527
+ from one model's triage round; the mechanism generalizes.
528
+
529
+ **1. Broadcast onto `Versions` with a condition, not a product.** A
530
+ formula that multiplies by a version-carrier flag — `X * carrier` — pays
531
+ tens of times the model's median µs/cell because the engine materialises the
532
+ product across the flag's whole domain before collapsing it. The
533
+ functionally identical **condition** form —
534
+
535
+ ```text
536
+ "X OUT" = if(eq("FC ACT PASS IN", 1), "X ACT")
537
+ ```
538
+
539
+ — costs a small fraction of that, back near the median, for the same result. **The two forms are equivalent only when the
540
+ carrier stores `1` or `null` — never a stored `0`.** If the carrier can
541
+ hold an explicit `0` (a planner-entered "off", not "not applicable"), the
542
+ product zeroes the result while the condition nulls it — different values
543
+ downstream. Check the carrier's own semantics before converting.
544
+
545
+ **2. Never broadcast onto `Versions` and hop an FK in the same product.**
546
+ Stacking both inside one multiply — `"Coarser input at wider grain" *
547
+ "Keys at a different grain reached via FK"` — measured at
548
+ hundreds of times the median on one model (the single worst shape observed).
549
+ Split it into two stored steps instead of one product:
550
+
551
+ 1. Broadcast the coarse operand by rule 1 above (condition, not product).
552
+ 2. Lift it across the FK hop on its **own** sparse-grain intermediate
553
+ (rule 3 below — not `0 + X`).
554
+ 3. Multiply the two now-aligned-grain operands.
555
+
556
+ Result: back near the median, tens of times faster than the single fused product,
557
+ for the same values.
558
+
559
+ **3. Lift without zeros — `0 + X` is not a safe FK-hop idiom.** Using a
560
+ bare `0 + X` to lift a coarser variable across an FK hop materialises an
561
+ explicit `0` wherever `X` has no cell on the finer grain, on the current
562
+ engine — a **phantom cell**, not a null one. It inflates cell counts and
563
+ breaks any control shaped like "reached by both paths" (a zero cell reads
564
+ as "reached with nothing to report", not "not reached"). Use
565
+ `if(hasValue(X), X)` for the lift when the result must stay sparse; keep
566
+ `0 + X` only where an explicit zero really is the intended value (e.g. a
567
+ factor that must read `1 − 0`, not `1 − null`). This is the same
568
+ null-vs-zero discipline as
569
+ [`sparse-formulas-pattern.md`](sparse-formulas-pattern.md), applied to the
570
+ specific case of a cross-grain lift rather than an `if`'s false branch.
571
+
572
+ **Dense cell production — a class of problem, not a number.** The real
573
+ risk is a formula that **produces** a dense layout of cells: a broadcast or
574
+ cross product spread over a detail grain × `Versions` × periods, or a `0 + x`
575
+ / literal default expanded over every member. That is the same class of
576
+ problem at tens of millions of cells as at hundreds of millions — calculation
577
+ time, storage and memory grow with every cell, and a large enough one can
578
+ make the instance unusable for everyone on it. Do not rely on the platform to
579
+ stop it: today it does not warn loudly — symptoms range from a very slow
580
+ recalculation to a variable that silently reads null downstream. (A large
581
+ grain on its own is not the problem: a variable whose member-count product
582
+ was in the hundreds of millions but which held one cell computed normally —
583
+ what matters is how many cells formulas actually produce.)
584
+
585
+ **Prevent it in the model, never work around it after the fact.** Keep every
586
+ variable — above all OUT and merge variables — at the grain its consumers
587
+ need; let operands roll coarser dimensions away before a product; return
588
+ null, not `0`, on slices without data; place cells with sparse carriers, not
589
+ with broadcasts over a full grain; split a broadcast and an FK hop into
590
+ stored steps; and estimate the cells a new formula will produce (operand
591
+ cells × the members it broadcasts over) before pushing it.
592
+
593
+ ---
594
+
595
+ ## §8 — Refactor checklist
596
+
597
+ When you fix one of these in an existing model:
598
+
599
+ 1. Identify the orphan dim and the related dim that **is** in the operand.
600
+ 2. Verify the FK between them (`farseer model --table "Product" <tenant>` lists the table's FK columns: `→ Product_Line`).
601
+ 3. Change the output grain to use the operand-carried dim.
602
+ 4. Search the rest of the model for downstream consumers of the OUT —
603
+ if they pin the old (orphan) dim, they're either reading at the
604
+ parent level (still fine, parent rolls up) or they have the same
605
+ antipattern and need the same fix.
606
+ 5. Re-run the model and time the formula. Record the before/after with the
607
+ change — future engineers will face the same trade-off and the data point is
608
+ gold.
609
+ 6. If the variable is part of a sign-off'd UAT scenario, re-run that
610
+ scenario — the values should match (within rollup tolerance), only
611
+ faster.
612
+