Skip to content

Commit 2f15c67

Browse files
committed
fix(domain model): drop cross-module associations with the entity they end at
DROP ENTITY swept only the regular Associations collection, so every CROSS-MODULE association pointing at the deleted entity survived. Dropping the local BY-ID (FROM) end left a 16-byte pointer to an element that no longer exists, and mxbuild 11.14.0 could then not LOAD the project: ERROR: System.AggregateException … (The given key '49751a65-d5f9-456c-887e-3f14bacb8822' was not present in the dictionary.) at StreamingBsonUnitReader.ResolvePostponedProperties() No CE code and no document named — the failure is in the storage layer, above the consistency checker, so it reads as "the project is corrupt". Dropping the BY-NAME (TO) end is milder and still wrong: CE1613 at the cross-module association. removeCrossAssocsReferencing matches both ends, because a cross-module association addresses them differently: FROM by element id (local to this domain model), TO by qualified name (it lives in another module). Called from DeleteEntity locally and in its cascade over the other domain models. Reported against a VIEW entity, whose associations are derived from its OQL so there is no CREATE ASSOCIATION to undo. Nothing here is view-entity specific: the first probe — view entity and source entity in the SAME module — did not reproduce, and that negative is what identified cross-module as the variable. A plain `create association A.X from A.X to B.Y` plus `drop entity A.X` reproduces the identical crash. Measured on mxbuild 11.14.0, one project carrying all three shapes: before drop by-id end project does not load (exception above) drop by-name end CE1613 at the cross-module association after all three drops project loads, 0 errors Controls: an untouched cross-module association survives both deletes (in the unit test and in the bug-test), and the single-module case still works. Before the fix the new test fails in both directions with the orphan left behind. Closes #553 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L2aYb3zDscezm874CDTH6R
1 parent 0ecde78 commit 2f15c67

4 files changed

Lines changed: 255 additions & 1 deletion

File tree

‎.claude/skills/fix-issue/findings/mdl-backend.jsonl‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,3 +119,4 @@
119119
{"area": "mdl/backend", "date": "2026-09-20", "symptom": "Every page mxcli wrote carried `Autofocus` (a property Mendix introduced in 11.1.0) and every page and snippet carried `Variables` (10.17.0), whatever the project's version. On a Mendix 10 project the document therefore held a key that project's metamodel does not declare — the class of defect that makes Studio Pro throw InvalidOperationException at MprProperty.cs while mxbuild reports 0 errors. Found while fixing mendixlabs/mxcli#1121 (the same defect in the page's PARAMETERS) and deferred there as out of scope.", "cause": "`pageToGen` called `SetAutofocus(\"DesktopOnly\")` unconditionally, and both `Forms$Page` and `Forms$Snippet` registered `Variables` in `codec.RegisterTypeDefaults(...).MandatoryLists`, which the encoder emits as an empty typed-array marker for every new element. The page writer had no version awareness at all until #1121 threaded `*types.ProjectVersion` into `pageToGen` for the parameter keys.", "file": "`mdl/backend/modelsdk/page_write.go` (pageSupportsAutofocus/pageSupportsVariables, encodePage, docEncoder), `mdl/backend/modelsdk/snippet_write.go` (encodeSnippet), `modelsdk/codec/encoder.go` (Encoder.OmitKeys). Tests `mdl/backend/modelsdk/page_version_keys_test.go`, `modelsdk/codec/omitkeys_test.go`.", "insight": "**A version-floored key can arrive by two different routes, and only one of them is a gen property.** `Autofocus` is set through gen, so the fix is to not set it; `Variables` exists only because the Studio Pro defaults registry adds it, and a gen `PartList` has no 'present but empty' state — so there is nothing to leave unset and the suppression has to happen in the encoder. That registry is global and keyed by `$Type` alone, so it cannot see a project version: hence `Encoder.OmitKeys`, per-encode. **Suppressing a key and dropping data are different things**: the empty `Variables` marker is safe to suppress, but variables the script DECLARED are refused instead (guard-don't-drop, ADR-0005) — silently dropping them leaves widgets referencing names that are gone (CE1151) from a statement that reported success. Two measurement traps hit on the way: the first control run died on a pre-existing entity before reaching the page statement, so the page was never rewritten and the unchanged output read as a pass — a control that does not run looks exactly like a control that passes; and ALTER PAGE turned out to be safe without any change, because the page mutator edits the stored raw BSON and marshals it back, so it can never invent a key. Check which write paths actually rebuild a document before assuming a header fix has to cover all of them.", "refs": ["#1121"]}
120120
{"area": "mdl/backend", "date": "2026-09-18", "symptom": "`ALTER PAGE M.P { SET Documentation = '...' }` is refused: \"unsupported page-level property: Documentation\". Documenting an existing page therefore means re-running its CREATE, because the `/** … */` doc comment on the create statement is the only other source", "cause": "`applyPageLevelSetMut` handled Title/Url/Popup*/Class/Style and had no Documentation case. The field was otherwise fully understood — `pageToGen` has always written it on CREATE via `out.SetDocumentation`, and gen binds it as `property.NewPrimitive[string](\"Documentation\")`. The grammar already parsed it (`identifierOrKeyword EQUALS propertyValueV3`) and the executor has no allowlist, so it was one missing case in the mutator, not a syntax gap", "file": "`mdl/backend/pagemutator/mutator.go` (`applyPageLevelSetMut`)", "insight": "One case covers **Page, Layout AND Snippet** — all three declare Documentation and all three reach this function through `SetWidgetProperty(\"\")`. Store an empty string rather than rejecting it: removing a doc comment from a script has to be expressible, and the property is a bare string with no unset value. **Update the unsupported-property message in the same change** — that list is the only guidance a reader gets, and a stale one sends them back to the CREATE workaround the fix exists to remove (a test asserts the message names Documentation). Note the re-run workaround is worse than it sounds: describe → exec is only as complete as what MDL can spell, so restating a page to document it can silently lose widgets", "refs": ["#527"]}
121121
{"area": "mdl/backend", "date": "2026-09-20", "symptom": "`describe page` → `exec` over a **Studio Pro-authored** page reports `Replaced page`, not `Unchanged` — the rebuild is not semantically equal to what was stored, so ADR-0008's elision cannot fire and the unit churns in version control on every re-run. `mx check` is 0 errors either way. Measured on ako/TestApp Rules.RuleAction_NewEdit at 11.14.0: fourteen differences", "cause": "Four independent classes, all 'the rebuild writes a constant where Studio Pro stores a value': (1) `pageToGen` hardcoded Autofocus/CanvasWidth/CanvasHeight; (2) save_changes/cancel_changes/close_page/delete_object never wrote `DisabledDuringExecution`, and save_changes wrote `SyncAutomatically` true; (3) `AttributeRef.EntityRef` emitted only on the navigated branch; (4) `Forms$PageVariable` had only the one name field set, so the other five keys were never marked dirty", "file": "`mdl/backend/modelsdk/page_write.go` (`carryStoredPageHeader`, `bsonInt`), `widget_write.go` (four action cases + two `RegisterTypeDefaults`), `modelsdk/codec/defaults.go` + `encoder.go` (new `FalseFields`)", "insight": "**mxcli round-tripping its own output proves NOTHING about this class** — measured: the MDL bug-test reports `Unchanged` on the unfixed build too, because mxcli writes the page and mxcli describes it, so its constants agree with themselves. The reference must be a Studio Pro document; a committed CI fixture only works if it is one. **A population selected by name can confirm whatever it excluded**: the first sweep filtered `$Type` on `endswith(\"ClientAction\")`, got a tidy 'True on 82 of 82', and so missed `Forms$NoAction` (False on 83 of ~7,300) and `Forms$MicroflowAction` (5 of 81) — scan by the PROPERTY, not by a name pattern. **Hardcoded looked safe and was not**: CanvasWidth takes seven distinct values across 67 pages and the hardcoded 1200 matched 4, so a round trip moved the canvas of 63. **The int width bit this fix once**: Studio Pro stores both canvas dimensions as int64 while the gen setter takes int32, so the natural `.(int32)` assertion matched nothing — and the first unit test passed anyway because its own fixture wrote int32, i.e. the test encoded the assumption under test (bson-numeric-width). Prefer `TypeDefaults` over patching each construction site: `Forms$PageVariable` is built in three places. Remaining after the fix: 1 of 14, a pluggable-widget Object property — CE0463 territory, deliberately out of scope", "refs": ["#541", "#529"]}
122+
{"area": "mdl/backend", "date": "2026-09-20", "symptom": "`DROP ENTITY` left every CROSS-MODULE association pointing at the deleted entity in place. Dropping the local BY-ID (FROM) end made mxbuild 11.14.0 unable to LOAD the project: `System.AggregateException \u2026 (The given key '<guid>' was not present in the dictionary.)` at `StreamingBsonUnitReader.ResolvePostponedProperties()` \u2014 no CE code, no document named, so the obvious reading is 'the project is corrupt, restore from git'. Dropping the BY-NAME (TO) end is milder and still wrong: CE1613 at the cross-module association. `show associations` shows a raw GUID where the parent entity should be.", "cause": "`removeAssocsReferencing` swept `dm.AssociationsItems()` and asserted `*genDm.Association` per item, so the SEPARATE `CrossAssociations` collection was never looked at. Fixed with `removeCrossAssocsReferencing`, matching BOTH ends because a cross-module association addresses them differently \u2014 FROM by element id (local), TO by qualified name (another module) \u2014 called in DeleteEntity locally and in its cascade over the other domain models.", "file": "`mdl/backend/modelsdk/domainmodel_alter.go` (removeCrossAssocsReferencing, DeleteEntity)", "insight": "**Reported against a view entity; nothing about it was view-entity specific.** The reporter met it dropping view entities (whose associations are DERIVED from OQL, so there is no CREATE ASSOCIATION to undo) and filed it that way. The first probe \u2014 a view entity and its source entity in the SAME module \u2014 did not reproduce at all, and that negative is the useful one: it says the variable is cross-module, not view-ness. A plain `create association A.X from A.X to B.Y` plus `drop entity A.X` reproduces the identical crash. Two lessons: when a repro fails, vary the dimension the report did not mention before doubting the report, and treat a collection-typed `.(*T)` assertion in a cascade as a place where a sibling type hides. mxbuild's diagnostic distinguishes the two ends for free \u2014 a dangling 16-byte pointer is a LOAD crash, a dangling qualified name is CE1613 \u2014 so testing only one end proves half the fix.", "refs": ["#553", "#556"]}
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
-- ako/mxcli#553 — DROP ENTITY left CROSS-MODULE associations pointing at the
2+
-- deleted entity, and mxbuild could then not LOAD the project:
3+
--
4+
-- ERROR: System.AggregateException … (The given key
5+
-- '49751a65-d5f9-456c-887e-3f14bacb8822' was not present in the dictionary.)
6+
-- at StreamingBsonUnitReader.ResolvePostponedProperties()
7+
--
8+
-- No CE code and no document named, because the failure is in the storage layer
9+
-- rather than the consistency checker — the obvious reading is "the project is
10+
-- corrupt, restore from git". The recovery was DROP ASSOCIATION on each orphan.
11+
--
12+
-- Reported against a VIEW entity, whose associations are derived from its OQL so
13+
-- there is no CREATE ASSOCIATION to undo. Measured here: nothing about it is
14+
-- view-entity specific. A plain cross-module association orphans identically;
15+
-- the single-module case was always handled, which is why it went unnoticed.
16+
--
17+
-- Both ends are covered because they fail differently: a dangling BY-ID end (the
18+
-- FROM entity, stored in this module) is the crash above, while a dangling
19+
-- BY-NAME end (the TO entity, in another module) is CE1613 at the cross-module
20+
-- association.
21+
--
22+
-- Run with `mxcli exec`, then `mxcli docker check --no-update-widgets`: the
23+
-- project must LOAD and report 0 errors. On the unfixed build `show associations`
24+
-- shows a raw GUID where the parent entity should be.
25+
26+
create module Dm553A;
27+
create module Dm553B;
28+
29+
create persistent entity Dm553A.Meter (
30+
MeterName: String(100)
31+
);
32+
33+
create persistent entity Dm553A.Reading (
34+
Kwh: Decimal
35+
);
36+
37+
create association Dm553A.Reading_Meter from Dm553A.Reading to Dm553A.Meter type reference;
38+
39+
-- 1. A view entity in another module, whose association to Dm553A.Meter is
40+
-- DERIVED from the OQL (`select m.ID as MeterRef`).
41+
create view entity Dm553B.MeterTotals (
42+
TotalKwh: Decimal
43+
) as (
44+
from Dm553A.Reading as r
45+
join r/Dm553A.Reading_Meter/Dm553A.Meter as m
46+
group by m.ID
47+
select m.ID as MeterRef, sum(r.Kwh) as TotalKwh
48+
);
49+
50+
-- 2. A plain cross-module association, dropped from its BY-ID (FROM) end.
51+
create persistent entity Dm553A.Parent1 (Label: String(100));
52+
create persistent entity Dm553B.Child1 (Label: String(100));
53+
create association Dm553A.Parent1_Child1 from Dm553A.Parent1 to Dm553B.Child1 type reference;
54+
55+
-- 3. The same shape, dropped from its BY-NAME (TO) end.
56+
create persistent entity Dm553A.Parent2 (Label: String(100));
57+
create persistent entity Dm553B.Child2 (Label: String(100));
58+
create association Dm553A.Parent2_Child2 from Dm553A.Parent2 to Dm553B.Child2 type reference;
59+
60+
-- The control: a cross-module association neither drop touches. It must survive.
61+
create persistent entity Dm553A.Keeper (Label: String(100));
62+
create persistent entity Dm553B.Kept (Label: String(100));
63+
create association Dm553A.Keeper_Kept from Dm553A.Keeper to Dm553B.Kept type reference;
64+
65+
drop entity Dm553B.MeterTotals;
66+
drop entity Dm553A.Parent1;
67+
drop entity Dm553B.Child2;

‎mdl/backend/modelsdk/domainmodel_alter.go‎

Lines changed: 56 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ package modelsdkbackend
44

55
import (
66
"fmt"
7+
"strings"
78

89
"github.com/mendixlabs/mxcli/model"
910
"github.com/mendixlabs/mxcli/modelsdk/codec"
@@ -61,6 +62,43 @@ func removeAssocsReferencing(dm *genDm.DomainModel, entityID model.ID) bool {
6162
return changed
6263
}
6364

65+
// removeCrossAssocsReferencing drops every CROSS-MODULE association in dm that
66+
// ends at the deleted entity. Returns whether anything was removed.
67+
//
68+
// A cross-module association is stored in the FROM entity's module, in a separate
69+
// collection from the regular ones, and its two ends are addressed differently:
70+
// the FROM end by element id (local to this domain model) and the TO end by
71+
// qualified name (it lives in another module). So both have to be matched, and
72+
// they fail differently when they are not (ako/mxcli#553):
73+
//
74+
// - a dangling BY-ID end is a 16-byte pointer to an element that is gone, and
75+
// mxbuild cannot LOAD the project — KeyNotFoundException at
76+
// StreamingBsonUnitReader.ResolvePostponedProperties(), with no CE code and
77+
// no document named.
78+
// - a dangling BY-NAME end is an ordinary model error, CE1613 at the
79+
// cross-module association.
80+
//
81+
// qualifiedName may be empty when the module name could not be established; the
82+
// by-name sweep is then skipped rather than guessed at, since an empty name would
83+
// match nothing at best and everything at worst.
84+
func removeCrossAssocsReferencing(dm *genDm.DomainModel, entityID model.ID, qualifiedName string) bool {
85+
changed := false
86+
items := dm.CrossAssociationsItems()
87+
for i := len(items) - 1; i >= 0; i-- {
88+
ca, ok := items[i].(*genDm.CrossAssociation)
89+
if !ok {
90+
continue
91+
}
92+
byID := string(ca.ParentRefID()) == string(entityID)
93+
byName := qualifiedName != "" && strings.EqualFold(ca.ChildQualifiedName(), qualifiedName)
94+
if byID || byName {
95+
dm.RemoveCrossAssociations(i)
96+
changed = true
97+
}
98+
}
99+
return changed
100+
}
101+
64102
// DeleteAttribute removes an attribute from an entity. The remaining attributes
65103
// pass through the codec unchanged; only the Attributes list is rebuilt. Mirrors
66104
// legacy semantics (no cascade — dangling index/validation refs are left as-is,
@@ -314,8 +352,18 @@ func (b *Backend) DeleteEntity(domainModelID, entityID model.ID) error {
314352
if eidx < 0 {
315353
return fmt.Errorf("entity not found: %s", entityID)
316354
}
355+
// The qualified name the OTHER modules' cross-module associations know this
356+
// entity by. Read before the entity is removed, for obvious reasons.
357+
qualifiedName := ""
358+
if ge := findGenEntity(dm, entityID); ge != nil {
359+
if moduleName := b.moduleNameFor(domainModelID); moduleName != "" {
360+
qualifiedName = moduleName + "." + ge.Name()
361+
}
362+
}
363+
317364
dm.RemoveEntities(eidx)
318365
removeAssocsReferencing(dm, entityID)
366+
removeCrossAssocsReferencing(dm, entityID, qualifiedName)
319367
if err := b.persistDM(domainModelID, dm); err != nil {
320368
return err
321369
}
@@ -338,7 +386,14 @@ func (b *Backend) DeleteEntity(domainModelID, entityID model.ID) error {
338386
if err != nil {
339387
return fmt.Errorf("DeleteEntity: cascade cleanup: load %s: %w", other.ID, err)
340388
}
341-
if removeAssocsReferencing(odm, entityID) {
389+
// Two sweeps, not one: a regular association here can only reference the
390+
// entity by id, while a cross-module one in ANOTHER module reaches it by
391+
// qualified name — which is the half that leaves CE1613 behind.
392+
removed := removeAssocsReferencing(odm, entityID)
393+
if removeCrossAssocsReferencing(odm, entityID, qualifiedName) {
394+
removed = true
395+
}
396+
if removed {
342397
if err := b.persistDM(other.ID, odm); err != nil {
343398
return fmt.Errorf("DeleteEntity: cascade cleanup: update %s: %w", other.ID, err)
344399
}

0 commit comments

Comments
 (0)