Skip to content

Data history: emit property Delete events on twin/relationship deletion (opt-in) #129

Done

Description

@nikoraes

User story

As a team that rebuilds the twin graph from Data History (AdtPropertyEvents + AdtTwinLifeCycleEvents + AdtRelationshipLifeCycleEvents), I want Konnektr Graph to emit a property Delete event for every property of a twin/relationship that gets deleted — behind an opt-in flag — so that a twin recreated with the same id can no longer inherit property values from its previous incarnation.

Requested by Arcadis. ADT does not emit property deletion events on twin deletion either, so this must be off by default and stay ADT-compatible.

Background & motivation

Data History currently emits only the lifecycle Delete event when an entity is deleted; the property series simply stops at the last Update. Verified in CloudEventFactory.CreateDataHistoryEvents (src/AgeDigitalTwins.Events/Core/Events/CloudEventFactory.cs:347, anchor: main @ 6d60bc8):

EventType.TwinCreate or EventType.TwinDelete => CreateTwinLifeCycleEvents(...),            // :357
EventType.RelationshipCreate or EventType.RelationshipDelete => CreateRelationshipLifeCycleEvents(...),
EventType.TwinUpdate or EventType.RelationshipUpdate => CreatePropertyEvents(...),         // :494

This is codified by a test that asserts exactly one event for a twin delete that still carries a property: src/AgeDigitalTwins.Events.Test/CloudEventFactoryTests.cs:262 (CreateDataHistoryEvents_HandlesTwinDeleteEventWithProperties). That test has to keep passing for the default (flag off) behaviour.

Why that leaves a hole

Any reconstruction that resolves node/edge property values from the latest property row per (Id, Key) — the documented LatestPropertyValues pattern (.summarize arg_max(TimeStamp, *) by Id, Key in ADX, DISTINCT ON/array_agg in Postgres) — keeps resolving to the pre-delete value after the entity is gone, because no newer row was ever written for those keys. Two symptoms follow:

  1. Resurrection on re-create with the same id. If the twin is re-created with only some of its old properties (partial create, PATCH-based re-creation, a property dropped by a model change, or a re-import that writes a subset), only the properties present on the new write get fresh Create rows. Every other key still resolves to the previous incarnation's value — exactly the reported defect: property events from before the deletion reappear in the recreated graph.
  2. Values for entities that no longer exist. After a plain delete (no re-create), the property series still answers for that Id at any targetTime after the delete; consumers that do not join against the lifecycle tables will happily read them.

The reporter's ADX helper is what surfaces (1). The lifecycle CTEs are correct — they drop the deleted entity — but the node properties are joined from AdtPropertyEvents, which has no terminal row:

.create-or-alter function with (skipvalidation = "true") AdtGraph() {
    let twins = materialize(AdtTwinLifeCycleEvents
    | summarize arg_max(TimeStamp, *) by TwinId
    | where Action != 'Delete');
    let twinIds = twins | project TwinId;
    let relationships = AdtRelationshipLifeCycleEvents
    | summarize arg_max(TimeStamp, *) by Source, Target
    | where Source in (twinIds) and Target in (twinIds)
    | where Action != 'Delete';
    relationships
    | make-graph Source-->Target with twins on TwinId
}

Emitting property Delete rows at deletion time makes the property series self-terminating: arg_max per (Id, Key) resolves to Delete at the moment of deletion, and a later Create (re-creation) wins again because it is strictly newer. No tombstones or purge logic on the consumer side.

Why opt-in (default false)

  • ADT parity. ADT emits only the twin/relationship lifecycle Delete; a client that counts or replays property events must not suddenly see an extra class of event.
  • Volume. One row per property per deleted entity. A bulk delete of 10k twins × 20 properties turns into 200k extra property rows — fine for the team's historization, not something to force on every deployment.

Proposed implementation

Small, contained change: one config flag, one new factory method, no sink changes and no table/schema change (both data-history sinks already map the action column — see §3).

1. Opt-in flag

Mirror the existing TrackLastUpdatedBy plumbing (src/AgeDigitalTwins.Events/Program.cs:67 → SharedEventConsumer → CloudEventFactory.CreateDataHistoryEvents):

  • Parameters:EmitPropertyEventsOnDelete (bool, default false), env Parameters__EmitPropertyEventsOnDelete=true.
  • Add a bool emitPropertyEventsOnDelete = false parameter to CreateDataHistoryEvents and thread it from SharedEventConsumer.ProcessSingleEventData (src/AgeDigitalTwins.Events/Core/Services/SharedEventConsumer.cs:256).
  • No KustoSinkOptions/PostgresSinkOptions property is needed for this one (unlike TrackLastUpdatedBy, it does not change any ingestion mapping) — keep the surface minimal.

2. Emit the events in the factory

Add CreatePropertyDeleteEvents(EventData, Uri source, Dictionary<SinkEventType,string> typeMapping, bool trackLastUpdatedBy) next to CreatePropertyEvents. Call it from CreateDataHistoryEvents in addition to (not instead of) the lifecycle event, when the flag is on and EventType is TwinDelete or RelationshipDelete:

EventType.TwinDelete => emitPropertyEventsOnDelete
    ? [.. CreateTwinLifeCycleEvents(...), .. CreatePropertyDeleteEvents(...)]
    : CreateTwinLifeCycleEvents(...),

(The existing CreatePropertyEvents requires both OldValue and NewValue; a delete has NewValue == null, so extending it would only add branches — a separate method keeps the delete path explicit.)

Source material: eventData.OldValue — the replication row's properties object (AgeDigitalTwinsReplication.ConvertRowToJsonAsync, src/AgeDigitalTwins.Events/Core/Services/AgeDigitalTwinsReplication.cs:572), for twins { "$dtId", "$metadata", <property>… }, for relationships { "$relationshipId", "$relationshipName", "$sourceId", "$targetId", "$metadata", <property>… }.

Per emitted event:

Field Value
action "Delete"
key the top-level property name (same convention as CreateCloudEventsFromPatch, :560 — one event per top-level property, object values kept whole, i.e. what a remove /prop patch produces today)
value the removed value from OldValue — mirrors the existing property-delete row shape (OperationType.Remove → action: "Delete" in CreatePropertyCloudEvent, :604)
id OldValue["$dtId"], or OldValue["$sourceId"] for a relationship (same resolution CreatePropertyCloudEvent does from NewValue, but read from OldValue)
modelId OldValue["$metadata"]["$model"]
relationshipId / relationshipTarget OldValue["$relationshipId"] / OldValue["$targetId"] (relationship deletes only)
timeStamp eventData.Timestamp — the delete transaction's ServerClock. Never a DateTime.UtcNow fallback: the ordering guarantee against the pre-delete rows and a later re-create depends on the commit clock
sourceTimeStamp omitted — a delete has no source write to attribute
updatedBy only when TrackLastUpdatedBy is on: the twin/relationship-level $metadata.$lastUpdatedBy written by the deleting update. Use the twin-level value, not $metadata.<prop>.lastUpdatedBy — per #127 / PR #128 the per-property entry is not trustworthy for a delete
subject <id> or <id>/relationships/<relationshipId>, matching the PropertyEvent convention

Rules:

  • Skip all keys starting with $ ($dtId, $etag, $version, $metadata, $relationshipId, $relationshipName, $sourceId, $targetId) — same rule as CreateCloudEventsFromPatch.
  • Zero properties (a twin that is only $dtId/$metadata) → zero extra events, no error.
  • OldValue empty or missing properties (replica identity not FULL on a table that predates the current client) → emit nothing and log; do not emit null-valued Delete rows, which would be indistinguishable from a real value change.
  • Do not throw when the flag is off: current behaviour and event count stay byte-identical.

3. Relationship deletes, timestamps and sinks

  • Relationship deletes are explicit, separate calls — by design. AGE rejects a plain DELETE of a vertex that still has edges, and the client deliberately issues exactly that (src/AgeDigitalTwins/AgeDigitalTwinsClient.DigitalTwins.cs:899 — MATCH (t:Twin {$dtId: $twinId}) DELETE t); the contract is that the caller deletes the relationships first, then the twin. Verified on a throwaway pod of this project's own image ghcr.io/konnektr-io/age-pgvector:16-1.6.0-standard-trixie (2026-12-02): MATCH (a:V {id:'a'}) DELETE a on a vertex with one edge → ERROR: Cannot delete a vertex that has edge(s). Delete the edge(s) first, or try DETACH DELETE.

    Consequence for this feature: there is no implicit cascade to piggyback on, so RelationshipDelete must be handled in its own right (§2) — that is the path that produces the edge property Delete rows, one transaction per relationship delete. A twin delete then emits property Delete rows for the twin's own properties only. Do not switch to DETACH DELETE as part of this issue: it would silently change a documented operating contract.

  • REPLICA IDENTITY FULL is set on Twin (src/AgeDigitalTwins/GraphInitialization.cs:23) and on every relationship table at creation (src/AgeDigitalTwins/AgeDigitalTwinsClient.Models.cs:467), so OldValue carries the full property set for both deletes.

  • Ordering. Each delete is its own transaction, so rows are stamped with that transaction's ServerClock: relationship property deletes precede the twin's lifecycle Delete and its property deletes. Within a transaction the events share one ServerClock, and cross-transaction ordering is monotonic (fixed in Rapid relationship delete→recreate emits lifecycle events in wrong TimeStamp order #111), so Delete(TimeStamp) < Create(TimeStamp) holds for a delete→re-create cycle. Test that invariant, not just the event shape.

  • No sink work, no schema change. Both sinks already map the column: KustoEventSink.BuildPropertyEventMappings → Action ← $.action (src/AgeDigitalTwins.Events/Sinks/Kusto/KustoEventSink.cs:214), PostgresEventSink.BuildPropertyEventColumns → action (src/AgeDigitalTwins.Events/Sinks/Postgres/PostgresEventSink.cs:520).

  • Pre-flight for the implementer: the ADX schema table in docs/how-to-guides/data-history-kusto.mdx (~line 129) omits Action, so a hand-created AdtPropertyEvents table might not have the column. Confirm what queued ingestion does with a mapped-but-missing column and, if needed, note the .alter table AdtPropertyEvents add Action:string step in the docs.

4. Tests

src/AgeDigitalTwins.Events.Test/CloudEventFactoryTests.cs (unit):

  • Flag off: twin delete with properties → still exactly 1 lifecycle event (existing :262 test unchanged).
  • Flag on: twin delete with 2 properties → 1 lifecycle Delete + 2 property events with action=Delete, correct key/value/id/modelId/subject, timeStamp == eventData.Timestamp.
  • System keys ($dtId, $metadata, $etag, …) never produce events.
  • Relationship delete variant: id == $sourceId, relationshipId/relationshipTarget set, relationship properties emitted.
  • TrackLastUpdatedBy on → updatedBy from twin/relationship-level $metadata.$lastUpdatedBy; off → omitted.
  • Twin with no properties → no extra events; OldValue without properties → no extra events, no throw.

src/AgeDigitalTwins.Events.Test (integration, EventsTestBase/TestingEventSink, live replication):

  • Create twin with 2 properties → delete it: captured events contain the lifecycle Delete and one Delete per property.
  • The actual defect: create twin with properties a + b, delete it, re-create it with a only → assert that resolving (Id, Key) by latest TimeStamp yields Delete for b, and Create for a; and that the re-create's TimeStamp is strictly greater than the delete's.
  • Relationship-first flow (the documented contract): twin with one relationship that carries a property → delete the relationship, then the twin → the captured stream contains the relationship's RelationshipDelete + one property Delete per edge property, then the twin's lifecycle Delete + one property Delete per twin property, with the relationship rows' TimeStamp earlier than the twin's, and nothing emitted twice.

5. Documentation

  • docs/how-to-guides/data-history-kusto.mdx + docs/how-to-guides/data-history-postgres.mdx: the new flag, what it emits, that it is opt-in and not ADT behaviour, and that LatestPropertyValues / point-in-time queries can drop their tombstone workaround when it is on (they must keep it when off). Add Action to the AdtPropertyEvents schema table while there.
  • CLAUDE.md: config surface (Parameters:EmitPropertyEventsOnDelete) and the event semantics for deletes, next to the existing TrackLastUpdatedBy / property-event notes.

Acceptance criteria

  • Parameters:EmitPropertyEventsOnDelete (default false) is threaded to the Data History factory; with it off the emitted event stream is unchanged (existing tests unmodified and green).
  • With it on, a twin delete emits one Delete property event per non-$ property of the deleted twin, in addition to the lifecycle Delete.
  • With it on, a relationship delete does the same for relationship properties — covered as its own event type, not relying on an implicit cascade (the contract is delete-relationships-first; DETACH DELETE is out of scope and stays unimplemented).
  • All synthesized rows carry the delete transaction's TimeStamp, action=Delete, the removed value, and the delete caller in updatedBy when TrackLastUpdatedBy is on.
  • Retained for delete→re-create: latest row per (Id, Key) is the Delete for properties the re-created twin does not set, and the re-create's Create for the ones it does.
  • Unit + integration tests from §4, running on the PG16/AGE 1.6 and PG18/AGE 1.8 matrix cells.
  • Docs updated (both data-history guides + CLAUDE.md).
  • No sink, table or migration change required — confirmed by the diff.

Open questions

  1. Flag name/scope — Parameters:EmitPropertyEventsOnDelete as a single global switch (recommended, matches TrackLastUpdatedBy and keeps one source of truth), or per-sink so one sink can opt in independently? Recommend global.
  2. Value on the delete row — the removed value (recommended, matches the existing remove-patch rows) or null? Recommend the removed value: point-in-time readers then see the last known value right up to the delete, and the Delete action is what carries the semantics.
  3. Event notifications — should EventFormat.EventNotification also gain anything here? Recommend no: ADT emits only the twin delete notification, and this issue is about Data History reconstruction.
  4. Out of scope, but worth naming — model deletion (DeleteModelsAsync issues MATCH (m:Model) DETACH DELETE m) and import-job replaces go through the same client methods, so whatever they emit follows from this change; they are not analysed separately here. A retroactive purge of already-historized property rows is not part of this issue.

Filed on Niko's behalf — Hermes

Activity

  1. added
    enhancement
    on Dec 2, 2026
  2. added
    in-progress
    on Dec 2, 2026
  3. nikoraes commented on Dec 2, 2026

    @nikoraes
    MemberAuthor

    Implemented — PR #130

    #130 (feat/emit-property-delete-events-129, head c5acd10)

    What it does. Parameters:EmitPropertyEventsOnDelete (Events service, default false) threads Program.cs → SharedEventConsumer → CloudEventFactory.CreateDataHistoryEvents, and with it on a twin/relationship delete emits one property Delete row per non-$ top-level property in addition to the lifecycle Delete. Rows are synthesized from the replication row's property image (OldValue), carry the delete's TimeStamp and the removed value, and use the twin/relationship-level $metadata.$lastUpdatedBy for updatedBy (the per-property entry still names the previous writer, #127). A missing/empty image emits nothing and logs a warning rather than a null-valued Delete row. No sink, table or migration change — both sinks already map action/Action.

    Aligned to the edited spec. The issue was updated at 13:01 while this was in flight: §3/§4/acceptance now say the delete-relationships-first contract stands and DETACH DELETE is out of scope. I had implemented, measured and test-covered the DETACH DELETE variant first; it is fully reverted — the PR touches no client code, and the relationship coverage is the explicit DeleteRelationshipAsync path (edge RelationshipDelete + one property Delete per edge property, then the twin's own delete rows in TimeStamp order). The measurement is still worth having on record: a plain MATCH … DELETE on a still-connected vertex fails with Cannot delete a vertex that has edge(s) on age-pgvector:16-1.6.0-standard-trixie, i.e. deleting edges first is genuinely mandatory, not merely conventional.

    One correction to the issue text (§3, "within a transaction the events share one ServerClock"): measured, they are clustered but not bit-identical — the relationship delete's lifecycle row came out at …32.078716Z while its edge property Delete row carried the same transaction's later per-row clock. The reconstruction invariant is ordering across transactions (Delete < Create), which holds; the integration test asserts a transaction window, not equality.

    Tests. 8 unit cases (flag off → exactly one event, i.e. the existing :262 test unchanged; flag on shape; $-keys; relationship variant; updatedBy source; empty image; delete→re-create ordering) and 3 integration cases over live replication (per-property deletes; latest-row-per-(Id, Key) terminates on Delete after a partial re-create; relationship-then-twin delete ordering). Verified locally on ghcr.io/konnektr-io/age-pgvector:16-1.6.0-standard-trixie (PG 16.15 / AGE 1.6.0): AgeDigitalTwins.Events.Test 117 passed / 0 failed, AgeDigitalTwins.Test 358 passed / 8 skipped / 0 failed. The PG18 + apache/AGE cells are CI's.

    Docs. Both data-history guides (opt-in section + the reconstruction-query caveat), configuration.mdx (Events service key), CLAUDE.md. While there: the AdtPropertyEvents schema table omitted Action although the sink has always mapped it — added, with the .alter-merge table AdtPropertyEvents add Action:string step for hand-created tables. I could not exercise ADX queued ingestion here, so the doc states the requirement rather than guessing at ingestion behaviour.

    Leaving this open for the PR's Closes; card is In review.

    — Hermes

  4. added a commit that references this issue on Dec 2, 2026
  5. removed
    in-progress
    on Dec 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementwork-request

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions