Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(properties): carry the previous value on property update events (#5596)
teo36afe7c559cc
diff --git a/.sqlx/query-e3ccac58c457d255e4af2af8f97f4e155410c45baa5a63b9420e8448317bf825.json b/.sqlx/query-339ed96279e420f9f18f5152d5c64b8c77fe7dae968c4ddf29e3acbedc6afae6.jsonsimilarity index 63%rename from .sqlx/query-e3ccac58c457d255e4af2af8f97f4e155410c45baa5a63b9420e8448317bf825.jsonrename to .sqlx/query-339ed96279e420f9f18f5152d5c64b8c77fe7dae968c4ddf29e3acbedc6afae6.jsonindex d1e11cbb40..174d16dbfc 100644--- a/.sqlx/query-e3ccac58c457d255e4af2af8f97f4e155410c45baa5a63b9420e8448317bf825.json+++ b/.sqlx/query-339ed96279e420f9f18f5152d5c64b8c77fe7dae968c4ddf29e3acbedc6afae6.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n UPDATE entity_properties\n SET values = jsonb_set(\n values,\n '{value}',\n COALESCE(\n (\n SELECT jsonb_agg(elem)\n FROM jsonb_array_elements(values -> 'value') AS elem\n WHERE elem <> to_jsonb($4::text)\n ),\n '[]'::jsonb\n )\n ),\n updated_at = NOW()\n WHERE entity_id = $1\n AND entity_type = $2\n AND property_definition_id = $3\n AND values ->> 'type' = 'SelectOption'\n AND values -> 'value' @> jsonb_build_array($4::text)\n RETURNING\n id,\n entity_id,\n entity_type as \"entity_type: EntityType\",\n property_definition_id,\n values as \"value: serde_json::Value\",\n created_at,\n updated_at\n ",+ "query": "\n WITH previous AS (\n SELECT values FROM entity_properties\n WHERE entity_id = $2 AND entity_type = $3 AND property_definition_id = $4\n )\n INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)\n VALUES ($1, $2, $3, $4, $5)\n ON CONFLICT (entity_id, entity_type, property_definition_id)\n DO UPDATE SET\n values = EXCLUDED.values,\n updated_at = NOW()\n RETURNING\n id,\n entity_id,\n entity_type as \"entity_type: EntityType\",\n property_definition_id,\n values as \"value: serde_json::Value\",\n (SELECT values FROM previous) as \"previous: serde_json::Value\",\n created_at,\n updated_at\n ","describe": {"columns": [{@@ -48,17 +48,23 @@},{"ordinal": 5,+ "name": "previous: serde_json::Value",+ "type_info": "Jsonb"+ },+ {+ "ordinal": 6,"name": "created_at","type_info": "Timestamptz"},{- "ordinal": 6,+ "ordinal": 7,"name": "updated_at","type_info": "Timestamptz"}],"parameters": {"Left": [+ "Uuid","Text",{"Custom": {@@ -80,7 +86,7 @@}},"Uuid",- "Text"+ "Jsonb"]},"nullable": [@@ -89,9 +95,10 @@false,false,true,+ null,false,false]},- "hash": "e3ccac58c457d255e4af2af8f97f4e155410c45baa5a63b9420e8448317bf825"+ "hash": "339ed96279e420f9f18f5152d5c64b8c77fe7dae968c4ddf29e3acbedc6afae6"}diff --git a/.sqlx/query-bee9a8c6f98a24b798c0a60184002169fde0953aa9371dc56a9481e4b8526110.json b/.sqlx/query-5426870d4de50026ecdc17a7369e3bc375958d3556b33f318c7ef44814bcc96c.jsonsimilarity index 56%rename from .sqlx/query-bee9a8c6f98a24b798c0a60184002169fde0953aa9371dc56a9481e4b8526110.jsonrename to .sqlx/query-5426870d4de50026ecdc17a7369e3bc375958d3556b33f318c7ef44814bcc96c.jsonindex bf2feb76b0..316415477c 100644--- a/.sqlx/query-bee9a8c6f98a24b798c0a60184002169fde0953aa9371dc56a9481e4b8526110.json+++ b/.sqlx/query-5426870d4de50026ecdc17a7369e3bc375958d3556b33f318c7ef44814bcc96c.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)\n VALUES (\n $1, $2, $3, $4,\n jsonb_build_object('type', 'SelectOption', 'value', jsonb_build_array($5::text))\n )\n ON CONFLICT (entity_id, entity_type, property_definition_id)\n DO UPDATE SET\n values = CASE\n WHEN entity_properties.values ->> 'type' = 'SelectOption'\n AND entity_properties.values -> 'value' @> jsonb_build_array($5::text)\n THEN entity_properties.values\n WHEN entity_properties.values ->> 'type' = 'SelectOption'\n THEN jsonb_set(\n entity_properties.values,\n '{value}',\n (entity_properties.values -> 'value') || jsonb_build_array($5::text)\n )\n ELSE jsonb_build_object('type', 'SelectOption', 'value', jsonb_build_array($5::text))\n END,\n updated_at = NOW()\n RETURNING\n id,\n entity_id,\n entity_type as \"entity_type: EntityType\",\n property_definition_id,\n values as \"value: serde_json::Value\",\n created_at,\n updated_at\n ",+ "query": "\n WITH previous AS (\n SELECT values FROM entity_properties\n WHERE entity_id = $1 AND entity_type = $2 AND property_definition_id = $3\n )\n UPDATE entity_properties\n SET values = jsonb_set(\n values,\n '{value}',\n COALESCE(\n (\n SELECT jsonb_agg(elem)\n FROM jsonb_array_elements(values -> 'value') AS elem\n WHERE elem <> to_jsonb($4::text)\n ),\n '[]'::jsonb\n )\n ),\n updated_at = NOW()\n WHERE entity_id = $1\n AND entity_type = $2\n AND property_definition_id = $3\n AND values ->> 'type' = 'SelectOption'\n AND values -> 'value' @> jsonb_build_array($4::text)\n RETURNING\n id,\n entity_id,\n entity_type as \"entity_type: EntityType\",\n property_definition_id,\n values as \"value: serde_json::Value\",\n (SELECT values FROM previous) as \"previous: serde_json::Value\",\n created_at,\n updated_at\n ","describe": {"columns": [{@@ -48,18 +48,22 @@},{"ordinal": 5,+ "name": "previous: serde_json::Value",+ "type_info": "Jsonb"+ },+ {+ "ordinal": 6,"name": "created_at","type_info": "Timestamptz"},{- "ordinal": 6,+ "ordinal": 7,"name": "updated_at","type_info": "Timestamptz"}],"parameters": {"Left": [- "Uuid","Text",{"Custom": {@@ -90,9 +94,10 @@false,false,true,+ null,false,false]},- "hash": "bee9a8c6f98a24b798c0a60184002169fde0953aa9371dc56a9481e4b8526110"+ "hash": "5426870d4de50026ecdc17a7369e3bc375958d3556b33f318c7ef44814bcc96c"}diff --git a/.sqlx/query-6645d947e0e4f0c75e6a34b49690b22130ff90a6af5659837e2202381be03393.json b/.sqlx/query-6645d947e0e4f0c75e6a34b49690b22130ff90a6af5659837e2202381be03393.jsonnew file mode 100644index 0000000000..af19313955--- /dev/null+++ b/.sqlx/query-6645d947e0e4f0c75e6a34b49690b22130ff90a6af5659837e2202381be03393.json@@ -0,0 +1,104 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH previous AS (\n SELECT values FROM entity_properties\n WHERE entity_id = $2 AND entity_type = $3 AND property_definition_id = $4\n )\n INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)\n VALUES (\n $1, $2, $3, $4,\n jsonb_build_object('type', 'SelectOption', 'value', jsonb_build_array($5::text))\n )\n ON CONFLICT (entity_id, entity_type, property_definition_id)\n DO UPDATE SET\n values = CASE\n WHEN entity_properties.values ->> 'type' = 'SelectOption'\n AND entity_properties.values -> 'value' @> jsonb_build_array($5::text)\n THEN entity_properties.values\n WHEN entity_properties.values ->> 'type' = 'SelectOption'\n THEN jsonb_set(\n entity_properties.values,\n '{value}',\n (entity_properties.values -> 'value') || jsonb_build_array($5::text)\n )\n ELSE jsonb_build_object('type', 'SelectOption', 'value', jsonb_build_array($5::text))\n END,\n updated_at = NOW()\n RETURNING\n id,\n entity_id,\n entity_type as \"entity_type: EntityType\",\n property_definition_id,\n values as \"value: serde_json::Value\",\n (SELECT values FROM previous) as \"previous: serde_json::Value\",\n created_at,\n updated_at\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "entity_id",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "entity_type: EntityType",+ "type_info": {+ "Custom": {+ "name": "property_entity_type",+ "kind": {+ "Enum": [+ "CHANNEL",+ "CHAT",+ "DOCUMENT",+ "PROJECT",+ "THREAD",+ "USER",+ "COMPANY",+ "TASK",+ "CALL_RECORD",+ "CALENDAR_EVENT"+ ]+ }+ }+ }+ },+ {+ "ordinal": 3,+ "name": "property_definition_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 4,+ "name": "value: serde_json::Value",+ "type_info": "Jsonb"+ },+ {+ "ordinal": 5,+ "name": "previous: serde_json::Value",+ "type_info": "Jsonb"+ },+ {+ "ordinal": 6,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 7,+ "name": "updated_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ {+ "Custom": {+ "name": "property_entity_type",+ "kind": {+ "Enum": [+ "CHANNEL",+ "CHAT",+ "DOCUMENT",+ "PROJECT",+ "THREAD",+ "USER",+ "COMPANY",+ "TASK",+ "CALL_RECORD",+ "CALENDAR_EVENT"+ ]+ }+ }+ },+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ true,+ null,+ false,+ false+ ]+ },+ "hash": "6645d947e0e4f0c75e6a34b49690b22130ff90a6af5659837e2202381be03393"+}diff --git a/.sqlx/query-986f4ee0a4640ce34411c18ca60bf1194b616eac28e7258b1dc16b892d21afc0.json b/.sqlx/query-986f4ee0a4640ce34411c18ca60bf1194b616eac28e7258b1dc16b892d21afc0.jsondeleted file mode 100644index e4c1b6f559..0000000000--- a/.sqlx/query-986f4ee0a4640ce34411c18ca60bf1194b616eac28e7258b1dc16b892d21afc0.json+++ /dev/null@@ -1,92 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)\n VALUES ($1, $2, $3, $4, $5)\n ON CONFLICT (entity_id, entity_type, property_definition_id)\n DO UPDATE SET\n values = EXCLUDED.values,\n updated_at = NOW()\n RETURNING\n id,\n entity_id,\n entity_type as \"entity_type: EntityType\",\n property_definition_id,\n created_at,\n updated_at\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "id",- "type_info": "Uuid"- },- {- "ordinal": 1,- "name": "entity_id",- "type_info": "Text"- },- {- "ordinal": 2,- "name": "entity_type: EntityType",- "type_info": {- "Custom": {- "name": "property_entity_type",- "kind": {- "Enum": [- "CHANNEL",- "CHAT",- "DOCUMENT",- "PROJECT",- "THREAD",- "USER",- "COMPANY",- "TASK",- "CALL_RECORD",- "CALENDAR_EVENT"- ]- }- }- }- },- {- "ordinal": 3,- "name": "property_definition_id",- "type_info": "Uuid"- },- {- "ordinal": 4,- "name": "created_at",- "type_info": "Timestamptz"- },- {- "ordinal": 5,- "name": "updated_at",- "type_info": "Timestamptz"- }- ],- "parameters": {- "Left": [- "Uuid",- "Text",- {- "Custom": {- "name": "property_entity_type",- "kind": {- "Enum": [- "CHANNEL",- "CHAT",- "DOCUMENT",- "PROJECT",- "THREAD",- "USER",- "COMPANY",- "TASK",- "CALL_RECORD",- "CALENDAR_EVENT"- ]- }- }- },- "Uuid",- "Jsonb"- ]- },- "nullable": [- false,- false,- false,- false,- false,- false- ]- },- "hash": "986f4ee0a4640ce34411c18ca60bf1194b616eac28e7258b1dc16b892d21afc0"-}diff --git a/.sqlx/query-58cd7976a97a33c2adf0720fd3f17b6ae46476eaf83e1886db10ee3a799855c9.json b/.sqlx/query-9c7cf0202d59d6a1d07ba2254b99d316468775a153e273437ef05bbae2c6f346.jsonsimilarity index 91%rename from .sqlx/query-58cd7976a97a33c2adf0720fd3f17b6ae46476eaf83e1886db10ee3a799855c9.jsonrename to .sqlx/query-9c7cf0202d59d6a1d07ba2254b99d316468775a153e273437ef05bbae2c6f346.jsonindex 01375e14c2..7efe085d5e 100644--- a/.sqlx/query-58cd7976a97a33c2adf0720fd3f17b6ae46476eaf83e1886db10ee3a799855c9.json+++ b/.sqlx/query-9c7cf0202d59d6a1d07ba2254b99d316468775a153e273437ef05bbae2c6f346.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)\n SELECT\n source.id,\n source.entity_id,\n source.entity_type,\n $4,\n jsonb_build_object('type', 'SelectOption', 'value', jsonb_build_array($5::text))\n FROM UNNEST($1::uuid[], $2::text[], $3::property_entity_type[])\n AS source(id, entity_id, entity_type)\n ON CONFLICT (entity_id, entity_type, property_definition_id)\n DO UPDATE SET\n values = CASE\n WHEN entity_properties.values ->> 'type' = 'SelectOption'\n AND entity_properties.values -> 'value' @> jsonb_build_array($5::text)\n THEN entity_properties.values\n WHEN entity_properties.values ->> 'type' = 'SelectOption'\n THEN jsonb_set(\n entity_properties.values,\n '{value}',\n (entity_properties.values -> 'value') || jsonb_build_array($5::text)\n )\n ELSE jsonb_build_object('type', 'SelectOption', 'value', jsonb_build_array($5::text))\n END,\n updated_at = NOW()\n RETURNING\n id,\n entity_id,\n entity_type as \"entity_type: EntityType\",\n property_definition_id,\n values as \"value: serde_json::Value\",\n created_at,\n updated_at\n ",+ "query": "\n INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)\n SELECT\n source.id,\n source.entity_id,\n source.entity_type,\n $4,\n jsonb_build_object('type', 'SelectOption', 'value', jsonb_build_array($5::text))\n FROM UNNEST($1::uuid[], $2::text[], $3::property_entity_type[])\n AS source(id, entity_id, entity_type)\n ON CONFLICT (entity_id, entity_type, property_definition_id)\n DO UPDATE SET\n values = CASE\n WHEN entity_properties.values ->> 'type' = 'SelectOption'\n AND entity_properties.values -> 'value' @> jsonb_build_array($5::text)\n THEN entity_properties.values\n WHEN entity_properties.values ->> 'type' = 'SelectOption'\n THEN jsonb_set(\n entity_properties.values,\n '{value}',\n (entity_properties.values -> 'value') || jsonb_build_array($5::text)\n )\n ELSE jsonb_build_object('type', 'SelectOption', 'value', jsonb_build_array($5::text))\n END,\n updated_at = NOW()\n RETURNING\n id,\n entity_id,\n entity_type as \"entity_type: EntityType\",\n property_definition_id,\n values as \"value: serde_json::Value\",\n NULL as \"previous: serde_json::Value\",\n created_at,\n updated_at\n ","describe": {"columns": [{@@ -48,11 +48,16 @@},{"ordinal": 5,+ "name": "previous: serde_json::Value",+ "type_info": "Text"+ },+ {+ "ordinal": 6,"name": "created_at","type_info": "Timestamptz"},{- "ordinal": 6,+ "ordinal": 7,"name": "updated_at","type_info": "Timestamptz"}@@ -97,9 +102,10 @@false,false,true,+ null,false,false]},- "hash": "58cd7976a97a33c2adf0720fd3f17b6ae46476eaf83e1886db10ee3a799855c9"+ "hash": "9c7cf0202d59d6a1d07ba2254b99d316468775a153e273437ef05bbae2c6f346"}diff --git a/.sqlx/query-55299a8cfe6d8e27bdd1f419daa0acc0f3dbaf2b8b4c88c4cac9aa4447664009.json b/.sqlx/query-b069a57e11e7ed107a8495a4eb2d739b9751e8c1c7703fe2513b14c0ad0e42c2.jsonsimilarity index 86%rename from .sqlx/query-55299a8cfe6d8e27bdd1f419daa0acc0f3dbaf2b8b4c88c4cac9aa4447664009.jsonrename to .sqlx/query-b069a57e11e7ed107a8495a4eb2d739b9751e8c1c7703fe2513b14c0ad0e42c2.jsonindex fc162172ba..85f814cdf2 100644--- a/.sqlx/query-55299a8cfe6d8e27bdd1f419daa0acc0f3dbaf2b8b4c88c4cac9aa4447664009.json+++ b/.sqlx/query-b069a57e11e7ed107a8495a4eb2d739b9751e8c1c7703fe2513b14c0ad0e42c2.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n UPDATE entity_properties\n SET values = $4, updated_at = NOW()\n WHERE entity_id = $1 AND entity_type = $2 AND property_definition_id = $3\n RETURNING\n id,\n entity_id,\n entity_type as \"entity_type: EntityType\",\n property_definition_id,\n values as \"value: serde_json::Value\",\n created_at,\n updated_at\n ",+ "query": "\n UPDATE entity_properties\n SET values = $4, updated_at = NOW()\n WHERE entity_id = $1 AND entity_type = $2 AND property_definition_id = $3\n RETURNING\n id,\n entity_id,\n entity_type as \"entity_type: EntityType\",\n property_definition_id,\n values as \"value: serde_json::Value\",\n NULL as \"previous: serde_json::Value\",\n created_at,\n updated_at\n ","describe": {"columns": [{@@ -48,11 +48,16 @@},{"ordinal": 5,+ "name": "previous: serde_json::Value",+ "type_info": "Text"+ },+ {+ "ordinal": 6,"name": "created_at","type_info": "Timestamptz"},{- "ordinal": 6,+ "ordinal": 7,"name": "updated_at","type_info": "Timestamptz"}@@ -89,9 +94,10 @@false,false,true,+ null,false,false]},- "hash": "55299a8cfe6d8e27bdd1f419daa0acc0f3dbaf2b8b4c88c4cac9aa4447664009"+ "hash": "b069a57e11e7ed107a8495a4eb2d739b9751e8c1c7703fe2513b14c0ad0e42c2"}diff --git a/crates/properties/src/domain/activity.rs b/crates/properties/src/domain/activity.rsindex fceca8fe3b..719d68aab4 100644--- a/crates/properties/src/domain/activity.rs+++ b/crates/properties/src/domain/activity.rs@@ -70,10 +70,16 @@ impl ActivitySource for PropertyTopicEvent {&m.entity_id,CommonAction::PropertyChanged(PropertyChange {property: m.property_definition_id.to_string(),- // The event carries only the new value today.- from: None,- // None means cleared; a serialization failure must not- // masquerade as one, so it stores an explicit JSON null.+ // None means unknown/newly-attached for `from` and+ // cleared for `to`; a serialization failure must not+ // masquerade as either, so it stores an explicit JSON+ // null.+ from: m.previous_value.as_ref().map(|value| {+ serde_json::to_value(value).unwrap_or_else(|e| {+ tracing::error!(error=?e, "unserializable property value");+ serde_json::Value::Null+ })+ }),to: m.value.as_ref().map(|value| {serde_json::to_value(value).unwrap_or_else(|e| {tracing::error!(error=?e, "unserializable property value");diff --git a/crates/properties/src/domain/activity/test.rs b/crates/properties/src/domain/activity/test.rsindex 3e7d79c819..8707fb1504 100644--- a/crates/properties/src/domain/activity/test.rs+++ b/crates/properties/src/domain/activity/test.rs@@ -5,6 +5,7 @@ use model_entity::EntityType as ActivityEntityType;use uuid::Uuid;use macro_event_broker::Event;+use models_properties::service::property_value::PropertyValue;use super::*;use crate::domain::events::EntityPropertyUpdatedMetadata;@@ -25,10 +26,33 @@ fn update(actor: Option<MacroUserIdStr<'static>>) -> EntityPropertyUpdatedMetadaproperty_definition_id: Uuid::from_u128(3),actor_user_id: actor,value: None,+ previous_value: None,updated_at: Utc::now(),}}+#[test]+fn property_update_carries_the_previous_value_as_the_transition_from() {+ let previous = PropertyValue::SelectOption(vec![Uuid::from_u128(7)]);+ let mut metadata = update(Some(user("macro|[email protected]")));+ metadata.previous_value = Some(previous.clone());+ let event = envelope(PropertyTopicEvent::EntityPropertyUpdated(metadata));++ let Ingest::Insert(activities) = event.event.ingest(event.event_id) else {+ panic!("expected activities");+ };+ match &activities[0].action {+ Action::PropertyChanged(change) => {+ assert_eq!(+ change.from,+ Some(serde_json::to_value(&previous).expect("serializable"))+ );+ assert_eq!(change.to, None);+ }+ other => panic!("expected property_changed, got {other:?}"),+ }+}+#[test]fn task_property_update_maps_to_property_changed_on_the_document() {let event = envelope(PropertyTopicEvent::EntityPropertyUpdated(update(Some(diff --git a/crates/properties/src/domain/events.rs b/crates/properties/src/domain/events.rsindex b634cb16a1..255c32d61f 100644--- a/crates/properties/src/domain/events.rs+++ b/crates/properties/src/domain/events.rs@@ -114,6 +114,11 @@ pub struct EntityPropertyUpdatedMetadata {pub actor_user_id: Option<MacroUserIdStr<'static>>,/// Full value after the update, or `None` when cleared without deleting the row.pub value: Option<PropertyValue>,+ /// Full value before the update: `None` when the property was newly+ /// attached, when the writer couldn't capture it, or on events published+ /// before this field existed (hence the serde default).+ #[serde(default)]+ pub previous_value: Option<PropertyValue>,/// Time the entity-property row was updated.pub updated_at: DateTime<Utc>,}diff --git a/crates/properties/src/domain/events/test.rs b/crates/properties/src/domain/events/test.rsindex 305940cde0..2af9c06536 100644--- a/crates/properties/src/domain/events/test.rs+++ b/crates/properties/src/domain/events/test.rs@@ -161,6 +161,7 @@ fn topic_events(property_definition_id: uuid(PROPERTY_DEFINITION_ID),actor_user_id: actor_user_id.clone(),value: Some(PropertyValue::SelectOption(vec![uuid(OPTION_ID)])),+ previous_value: None,updated_at: timestamp(UPDATED_AT),}),json!({@@ -175,6 +176,7 @@ fn topic_events("type": "SelectOption","value": [OPTION_ID]},+ "previous_value": null,"updated_at": UPDATED_AT}}),diff --git a/crates/properties/src/domain/model.rs b/crates/properties/src/domain/model.rsindex 7fa6f91cda..de62426bba 100644--- a/crates/properties/src/domain/model.rs+++ b/crates/properties/src/domain/model.rs@@ -235,6 +235,11 @@ pub struct EntityPropertyMutationSnapshot {pub property: EntityProperty,/// The complete value after the mutation.pub value: Option<PropertyValue>,+ /// The complete value before the mutation: `None` when the property was+ /// not previously attached (or the stored value didn't decode). Captured+ /// in the same statement/transaction as the write, so it feeds the+ /// "changed X from A to B" activity transition.+ pub previous_value: Option<PropertyValue>,}/// The reconciled final option ids for one property after a bulk update. Thediff --git a/crates/properties/src/domain/ports.rs b/crates/properties/src/domain/ports.rsindex 987259ec8b..db9e9cf68b 100644--- a/crates/properties/src/domain/ports.rs+++ b/crates/properties/src/domain/ports.rs@@ -195,14 +195,15 @@ pub trait PropertiesRepo: Send + Sync + 'static {/// Upsert an entity property value (insert or update)./// If the property doesn't exist, it will be created and attached to the entity.- /// If it exists, the value will be updated. Returns the persisted assignment.+ /// If it exists, the value will be updated. Returns the persisted+ /// assignment together with the pre-write value.fn upsert_entity_property(&self,entity_id: &str,entity_type: EntityType,property_definition_id: Uuid,value: Option<PropertyValue>,- ) -> impl Future<Output = Result<EntityProperty, Self::Err>> + Send;+ ) -> impl Future<Output = Result<EntityPropertyMutationSnapshot, Self::Err>> + Send;/// Atomically add one option to a multi-select entity property value,/// attaching the property if needed. Re-adding a present option is deduped.diff --git a/crates/properties/src/domain/service_impl/mod.rs b/crates/properties/src/domain/service_impl/mod.rsindex 0407eb376a..412f8d0a3d 100644--- a/crates/properties/src/domain/service_impl/mod.rs+++ b/crates/properties/src/domain/service_impl/mod.rs@@ -178,6 +178,7 @@ wherefn entity_property_updated_event(property: &EntityProperty,value: &Option<PropertyValue>,+ previous_value: &Option<PropertyValue>,access: &EditReceipt,) -> PropertyMacroEvent {PropertyMacroEvent::entity_property_updated(EntityPropertyUpdatedMetadata {@@ -187,6 +188,7 @@ whereproperty_definition_id: property.property_definition_id,actor_user_id: access.authenticated_user().cloned(),value: value.clone(),+ previous_value: previous_value.clone(),updated_at: property.updated_at,})}@@ -204,6 +206,7 @@ whereself.publish_property_event(Self::entity_property_updated_event(&mutation.property,&mutation.value,+ &mutation.previous_value,access,));}@@ -390,6 +393,7 @@ whereproperty_definition_id: mutation.property.property_definition_id,actor_user_id: Some(actor.clone().into_owned()),value: mutation.value.clone(),+ previous_value: mutation.previous_value.clone(),updated_at: mutation.property.updated_at,},));@@ -620,6 +624,9 @@ whereself.publish_property_event(Self::entity_property_updated_event(&property,&property_value,+ // The relationship transaction doesn't capture the pre-write+ // value; the activity transition simply omits its "from" side.+ &None,access,));return Ok(EntityPropertyWithDefinition {@@ -637,7 +644,7 @@ where.await?;}- let property = self+ let snapshot = self.repository.upsert_entity_property(entity_id,@@ -649,13 +656,14 @@ where.map_err(anyhow::Error::from)?;self.publish_property_event(Self::entity_property_updated_event(- &property,+ &snapshot.property,&property_value,+ &snapshot.previous_value,access,));Ok(EntityPropertyWithDefinition {- property,+ property: snapshot.property,definition: property_definition,value: property_value,options: None,@@ -719,6 +727,7 @@ whereself.publish_property_event(Self::entity_property_updated_event(&mutation.property,&mutation.value,+ &mutation.previous_value,access,));@@ -756,6 +765,7 @@ whereself.publish_property_event(Self::entity_property_updated_event(&mutation.property,&mutation.value,+ &mutation.previous_value,access,));}diff --git a/crates/properties/src/domain/test.rs b/crates/properties/src/domain/test.rsindex cc07bb1190..ff134cc5da 100644--- a/crates/properties/src/domain/test.rs+++ b/crates/properties/src/domain/test.rs@@ -79,6 +79,7 @@ fn entity_property_mutation(EntityPropertyMutationSnapshot {property: entity_property(entity_id, entity_type, property_definition_id),value,+ previous_value: None,}}@@ -101,6 +102,7 @@ fn entity_property_option_selection_for_event(event_timestamp(),),value: Some(PropertyValue::SelectOption(option_ids)),+ previous_value: None,}),}}@@ -1084,7 +1086,15 @@ async fn entity_property_event_set_publishes_null_authoritative_snapshot() {&& *definition_id == property_definition_id&& value.is_none()})- .return_once(move |_, _, _, _| Box::pin(async move { Ok(assignment) }));+ .return_once(move |_, _, _, _| {+ Box::pin(async move {+ Ok(EntityPropertyMutationSnapshot {+ property: assignment,+ value: None,+ previous_value: None,+ })+ })+ });let event_broker = RecordingEventBroker::default();let service = service_with_event_broker(repo, event_broker.clone());@@ -1109,6 +1119,7 @@ async fn entity_property_event_set_publishes_null_authoritative_snapshot() {"entity_type": "DOCUMENT","property_definition_id": property_definition_id,"actor_user_id": caller_user_id(),+ "previous_value": null,"value": null,"updated_at": updated_at,})@@ -1209,7 +1220,15 @@ async fn entity_property_event_actor_is_only_an_authenticated_user() {)});repo.expect_upsert_entity_property()- .return_once(move |_, _, _, _| Box::pin(async move { Ok(assignment) }));+ .return_once(move |_, _, _, _| {+ Box::pin(async move {+ Ok(EntityPropertyMutationSnapshot {+ property: assignment,+ value: None,+ previous_value: None,+ })+ })+ });let event_broker = RecordingEventBroker::default();let service = service_with_event_broker(repo, event_broker.clone());@@ -1297,7 +1316,13 @@ async fn test_set_status_complete_through_general_property_mutation() {}).returning(|entity_id, entity_type, property_definition_id, _| {let property = entity_property(entity_id, entity_type, property_definition_id);- Box::pin(async move { Ok(property) })+ Box::pin(async move {+ Ok(EntityPropertyMutationSnapshot {+ property,+ value: None,+ previous_value: None,+ })+ })});let service = PropertiesServiceImpl::new(@@ -1437,6 +1462,7 @@ async fn entity_property_event_parent_task_uses_primary_task_snapshot_only() {"entity_type": "TASK","property_definition_id": SystemPropertyKey::PARENT_TASK_UUID,"actor_user_id": caller_user_id(),+ "previous_value": null,"value": {"type": "EntityReference","value": [{@@ -2584,6 +2610,7 @@ async fn entity_property_event_add_option_uses_full_mutation_snapshot() {existing_option_id,added_option_id,])),+ previous_value: None,};let mut repo = MockPropertiesRepo::new();repo.expect_get_property_definition().returning(move |_| {@@ -2622,6 +2649,7 @@ async fn entity_property_event_add_option_uses_full_mutation_snapshot() {"entity_type": "DOCUMENT","property_definition_id": def_id,"actor_user_id": caller_user_id(),+ "previous_value": null,"value": {"type": "SelectOption","value": [existing_option_id, added_option_id],@@ -2710,6 +2738,7 @@ async fn entity_property_event_remove_option_uses_full_mutation_snapshot() {updated_at,),value: Some(PropertyValue::SelectOption(vec![remaining_option_id])),+ previous_value: None,};let mut repo = MockPropertiesRepo::new();repo.expect_remove_entity_property_option()@@ -2809,7 +2838,13 @@ async fn canonical_document_task_write_uses_task_storage_type() {}).returning(|entity_id, entity_type, property_definition_id, _| {let property = entity_property(entity_id, entity_type, property_definition_id);- Box::pin(async move { Ok(property) })+ Box::pin(async move {+ Ok(EntityPropertyMutationSnapshot {+ property,+ value: None,+ previous_value: None,+ })+ })});let service = PropertiesServiceImpl::new(@@ -2874,7 +2909,13 @@ async fn canonical_document_task_assignee_write_grants_permissions() {}).returning(|entity_id, entity_type, property_definition_id, _| {let property = entity_property(entity_id, entity_type, property_definition_id);- Box::pin(async move { Ok(property) })+ Box::pin(async move {+ Ok(EntityPropertyMutationSnapshot {+ property,+ value: None,+ previous_value: None,+ })+ })});let mut permission_service = MockPermissionService::new();@@ -3188,6 +3229,7 @@ async fn bulk_entity_property_event_publishes_every_property_snapshot() {"entity_type": "DOCUMENT","property_definition_id": first_definition_id,"actor_user_id": caller_user_id(),+ "previous_value": null,"value": {"type": "SelectOption","value": first_final_option_ids,@@ -3203,6 +3245,7 @@ async fn bulk_entity_property_event_publishes_every_property_snapshot() {"entity_type": "DOCUMENT","property_definition_id": second_definition_id,"actor_user_id": caller_user_id(),+ "previous_value": null,"value": {"type": "SelectOption","value": second_final_option_ids,diff --git a/crates/properties/src/outbound/entity_property_queries.rs b/crates/properties/src/outbound/entity_property_queries.rsindex 7effd1620b..0cc6dfb238 100644--- a/crates/properties/src/outbound/entity_property_queries.rs+++ b/crates/properties/src/outbound/entity_property_queries.rs@@ -15,6 +15,7 @@ pub(super) struct EntityPropertyMutationRow {pub(super) entity_type: EntityType,pub(super) property_definition_id: Uuid,pub(super) value: Option<serde_json::Value>,+ pub(super) previous: Option<serde_json::Value>,pub(super) created_at: chrono::DateTime<chrono::Utc>,pub(super) updated_at: chrono::DateTime<chrono::Utc>,}@@ -25,6 +26,12 @@ impl EntityPropertyMutationRow {Some(value) if !value.is_null() => Some(serde_json::from_value(value)?),Some(_) | None => None,};+ // The pre-write value is display metadata; a row whose stored shape+ // no longer decodes must not fail the mutation that fixes it.+ let previous_value = self+ .previous+ .filter(|value| !value.is_null())+ .and_then(|value| serde_json::from_value(value).ok());Ok(EntityPropertyMutationSnapshot {property: EntityProperty {@@ -36,20 +43,23 @@ impl EntityPropertyMutationRow {updated_at: self.updated_at,},value,+ previous_value,})}}/// Upsert an entity property value (insert or update)./// If the property doesn't exist, it will be created and attached to the entity.-/// If it exists, the value will be updated.+/// If it exists, the value will be updated. The returned snapshot carries the+/// pre-write value (snapshotted by the CTE in the same statement) for+/// activity's "changed X from A to B" transitions.pub async fn upsert_entity_property(pool: &Pool<Postgres>,entity_id: &str,entity_type: EntityType,property_definition_id: Uuid,value: Option<PropertyValue>,-) -> anyhow::Result<EntityProperty> {+) -> anyhow::Result<EntityPropertyMutationSnapshot> {let id = macro_uuid::generate_uuid_v7();// Serialize PropertyValue to JSONB (or NULL if None)@@ -61,10 +71,15 @@ pub async fn upsert_entity_property(tracing::debug!(value_json = ?value_json, "upserting entity property");// Single UPSERT operation - handles both INSERT and UPDATE cases.- // RETURNING yields the canonical assignment for both branches without a second query.- let property = sqlx::query_as!(- EntityProperty,+ // RETURNING yields the canonical assignment for both branches without a+ // second query; the CTE snapshots the pre-statement value.+ let row = sqlx::query_as!(+ EntityPropertyMutationRow,r#"+ WITH previous AS (+ SELECT values FROM entity_properties+ WHERE entity_id = $2 AND entity_type = $3 AND property_definition_id = $4+ )INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)VALUES ($1, $2, $3, $4, $5)ON CONFLICT (entity_id, entity_type, property_definition_id)@@ -76,6 +91,8 @@ pub async fn upsert_entity_property(entity_id,entity_type as "entity_type: EntityType",property_definition_id,+ values as "value: serde_json::Value",+ (SELECT values FROM previous) as "previous: serde_json::Value",created_at,updated_at"#,@@ -90,7 +107,7 @@ pub async fn upsert_entity_property(tracing::debug!("successfully upserted entity property");- Ok(property)+ row.into_snapshot()}/// Atomically add one option to a multi-select entity property value, creating@@ -111,6 +128,10 @@ pub async fn add_entity_property_option(let row = sqlx::query_as!(EntityPropertyMutationRow,r#"+ WITH previous AS (+ SELECT values FROM entity_properties+ WHERE entity_id = $2 AND entity_type = $3 AND property_definition_id = $4+ )INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)VALUES ($1, $2, $3, $4,@@ -137,6 +158,7 @@ pub async fn add_entity_property_option(entity_type as "entity_type: EntityType",property_definition_id,values as "value: serde_json::Value",+ (SELECT values FROM previous) as "previous: serde_json::Value",created_at,updated_at"#,@@ -166,6 +188,10 @@ pub async fn remove_entity_property_option(let row = sqlx::query_as!(EntityPropertyMutationRow,r#"+ WITH previous AS (+ SELECT values FROM entity_properties+ WHERE entity_id = $1 AND entity_type = $2 AND property_definition_id = $3+ )UPDATE entity_propertiesSET values = jsonb_set(values,@@ -191,6 +217,7 @@ pub async fn remove_entity_property_option(entity_type as "entity_type: EntityType",property_definition_id,values as "value: serde_json::Value",+ (SELECT values FROM previous) as "previous: serde_json::Value",created_at,updated_at"#,@@ -272,12 +299,14 @@ pub async fn bulk_update_entity_property_options(.await?;let row_exists = existing.is_some();- let current_ids = match existing.flatten() {- Some(value) => match serde_json::from_value::<PropertyValue>(value) {- Ok(PropertyValue::SelectOption(ids)) => ids,- _ => Vec::new(),- },- None => Vec::new(),+ // The locked pre-write value doubles as the activity transition's+ // "from" side.+ let previous_value: Option<PropertyValue> = existing+ .flatten()+ .and_then(|value| serde_json::from_value(value).ok());+ let current_ids = match &previous_value {+ Some(PropertyValue::SelectOption(ids)) => ids.clone(),+ _ => Vec::new(),};let final_ids = apply_option_delta(@@ -304,6 +333,7 @@ pub async fn bulk_update_entity_property_options(entity_type as "entity_type: EntityType",property_definition_id,values as "value: serde_json::Value",+ NULL as "previous: serde_json::Value",created_at,updated_at"#,@@ -314,7 +344,11 @@ pub async fn bulk_update_entity_property_options().fetch_one(&mut *tx).await?;- Some(row.into_snapshot()?)+ // The FOR UPDATE read above is the authoritative pre-write value;+ // the query returns a NULL placeholder for it.+ let mut snapshot = row.into_snapshot()?;+ snapshot.previous_value = previous_value;+ Some(snapshot)} else {None};diff --git a/crates/properties/src/outbound/properties_pg_repo.rs b/crates/properties/src/outbound/properties_pg_repo.rsindex 4f85321828..0db28af78c 100644--- a/crates/properties/src/outbound/properties_pg_repo.rs+++ b/crates/properties/src/outbound/properties_pg_repo.rs@@ -290,7 +290,7 @@ impl PropertiesRepo for PropertiesPgRepo {entity_type: EntityType,property_definition_id: Uuid,value: Option<PropertyValue>,- ) -> Result<models_properties::service::entity_property::EntityProperty, Self::Err> {+ ) -> Result<EntityPropertyMutationSnapshot, Self::Err> {entity_property_queries::upsert_entity_property(&self.pool,entity_id,diff --git a/crates/properties/src/outbound/tag_promotion_queries.rs b/crates/properties/src/outbound/tag_promotion_queries.rsindex 34f6316d74..58912fc880 100644--- a/crates/properties/src/outbound/tag_promotion_queries.rs+++ b/crates/properties/src/outbound/tag_promotion_queries.rs@@ -324,6 +324,7 @@ async fn remap_entity_values(entity_type as "entity_type: EntityType",property_definition_id,values as "value: serde_json::Value",+ NULL as "previous: serde_json::Value",created_at,updated_at"#,diff --git a/crates/soup_realtime/src/inbound/kafka_consumer/test.rs b/crates/soup_realtime/src/inbound/kafka_consumer/test.rsindex 1443fe44fd..17c12083ce 100644--- a/crates/soup_realtime/src/inbound/kafka_consumer/test.rs+++ b/crates/soup_realtime/src/inbound/kafka_consumer/test.rs@@ -294,6 +294,7 @@ fn task_property_updates_map_to_document_updates() {property_definition_id: Uuid::now_v7(),actor_user_id: Some(user()),value: None,+ previous_value: None,updated_at: Utc::now(),});diff --git a/services/search_processing_service/src/inbound/kafka_consumer/test.rs b/services/search_processing_service/src/inbound/kafka_consumer/test.rsindex d99dfd3797..f0b03cd5f5 100644--- a/services/search_processing_service/src/inbound/kafka_consumer/test.rs+++ b/services/search_processing_service/src/inbound/kafka_consumer/test.rs@@ -1199,6 +1199,7 @@ fn property_event_cases() -> Vec<(PropertyTopicEvent, PropertyEventDescription<'property_definition_id: PROPERTY_DEFINITION_ID,actor_user_id: actor_user_id.clone(),value: None,+ previous_value: None,updated_at: Utc::now(),}),PropertyEventDescription {