[core] Component constructors must not mutate the entity graph (components and hierarchy)

Aperta
#3,114 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
4/5
Tempo stimato
3-5 giorni
Idoneità per principianti
54/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
typescript
Ambito
backend

Direzione di ricerca

Start with Entity construction, addComponent, _removeComponent, createChild, addChild, and _createCloneEntity; inspect the #3073 fixture mentioned in the issue as well. Trace when component constructors run and how clone replay handles components and children. Done means graph mutations from constructors fail clearly without residue, and accepted entities clone with matching component order and valid transform dependencies.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

bug

Summary

A component constructor is currently allowed to mutate the entity graph (entity.addComponent(...), entity.createChild(...)). That single premise produces two defects:

  1. Silent invalid component graph. Transform-replacement dependency validation runs before the replacement is constructed, so components added by the replacement's own constructor are never validated. The call succeeds and the broken graph only surfaces later (e.g. Image._render unconditionally reads (entity.transform as UITransform).size).
  2. clone() is not isomorphic. Entity._createCloneEntity rebuilds an entity by replaying the source's component constructor list. A constructor that adds components produces an extra, unmapped component on the clone.

This is the root cause behind two review threads on #3073 and was deliberately deferred out of that PR (477f9a1b1).

Evidence

Probes against the current head 477f9a1b1 and base 2a4b86a, using core-level equivalents.

1. Silent invalid graph
class SubTransform extends Transform {}

@dependentComponents(SubTransform, DependentMode.CheckOnly)
class NeedsSub extends Script {}

class MutatingTransform extends Transform {
  constructor(entity: Entity) {
    super(entity);
    entity.addComponent(NeedsSub); // NeedsSub depends on SubTransform
  }
}

const entity = new Entity(engine, "x", SubTransform);
entity.addComponent(MutatingTransform);
version result
base 2a4b86a, immediate destroy throws Should remove NeedsSub before remove SubTransform, but leaves the replacement inside _components
base 2a4b86a, in-frame (deferred destroy) no throw — the slot swap happens before the deferred destroy validates
current 477f9a1b1 no throw — final _components = [MutatingTransform, NeedsSub], getComponent(SubTransform) === null

Also reachable during Entity construction: when the requested Transform's constructor triggers an AutoAdd of a Transform subtype, addComponent reads this._transform.constructor before _transform has been assigned, producing a TypeError instead of a meaningful error.

2. clone is not isomorphic
class Tail extends Script {}

class AddingTransform extends Transform {
  constructor(entity: Entity) {
    super(entity);
    entity.addComponent(Tail);
  }
}

const source = new Entity(engine, "src", AddingTransform);
const clone = source.clone();
version result
current 477f9a1b1 source ["AddingTransform","Tail"] → clone ["AddingTransform","Tail","Tail"]. The extra component has no source counterpart, so cloneMap / _parseCloneEntity never map or clone its fields
base 2a4b86a clone throws TypeError: Cannot set properties of undefined (setting '_onValueChanged') (index misalignment in ComponentCloner)

createChild() / addChild() in a constructor produce the same non-isomorphism for children, because _createCloneEntity runs the constructor first and then replays the source's child list.

Proposed rule

A component constructor must not mutate the entity graph — neither components (addComponent, component destroy) nor hierarchy (createChild / addChild). Do that work in onAwake() instead.

Why the constructor specifically

Both "validate before construction" and "replay constructors during clone" are only correct if construction cannot mutate the graph:

  • the pre-construction validation becomes authoritative and sufficient (no second post-construction check, no rollback);
  • clone replay is exact, so source/clone component lists are equal;
  • a rejected operation leaves zero residue.

Enforcement sketch

private _isConstructingComponent = false;

private _constructComponent<T extends ComponentConstructor>(type: T, args: ComponentArguments<T>): InstanceType<T> {
  this._isConstructingComponent = true;
  const component = new type(this, ...args) as InstanceType<T>;
  this._isConstructingComponent = false;
  return component;
}

addComponent<T extends ComponentConstructor>(type: T, ...args: ComponentArguments<T>): InstanceType<T> {
  if (this._isConstructingComponent) {
    throw `Cannot add ${type.name} from a component constructor; use onAwake() instead`;
  }
  // ...
}

The flag only spans new type(...); the Entity constructor's own installation calls happen between constructions and stay allowed. Guarding the removal path (_removeComponent) and hierarchy operations needs the same treatment if the rule is to be complete.

Migration

  • Move the work to onAwake() (or onEnterScene). Note the timing difference: _onAwake fires only when entity._isActiveInHierarchy is true, i.e. after the entity is attached to an active scene, whereas a constructor runs immediately.
  • Related precedent: #3021 — constructors registering native actors / transform listeners break clone and instantiate, and the fix direction there is also to do it on enter-scene.

In-repo impact

No engine component adds components from its constructor (checked), so only Entity changes. The #3073 fixture that currently blesses this pattern (allows component additions from a compatible Transform constructor) would be replaced by a rejection test.

Acceptance criteria

  • Adding/removing a component, or adding/removing a child, from a component constructor throws a clear error.
  • For every accepted input, source._components and clone._components are identical in content and order.
  • Transform replacement validation observes the final graph, so a pre-construction check is sufficient.
  • A rejected add leaves no residue: no constructed replacement and no constructor-added components.

Related

  • #3073 review threads: constructor as a second component producer; validation sees only the pre-construction snapshot.
  • #3021: same principle applied to constructor-side native/listener registration.
Lingua principale
TypeScript
Stelle
5.9k
Fork
413
Merge medio
16h 17m
PR unite (30g)
41

Preparare l'ambiente

  • Nessun Dockerfile né file Docker Compose
  • Ha un modello di pull request
  • Nessuna guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di galacean/engine

Tutte le issue di galacean/engine

Issue simili

Altre issue su TypeScript

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.