Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

add [properties-be] - link parent and subtasks (#610)

Daniel Kweonebe46baf9ba2
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index e893a2ed1f..aaa87c115c 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -2635,6 +2635,7 @@ dependencies = [
"models_permissions",
"models_soup",
"ordered-float",
+ "properties",
"rayon",
"redis",
"regex",
diff --git a/rust/cloud-storage/document_storage_service/Cargo.toml b/rust/cloud-storage/document_storage_service/Cargo.toml
index 1339b93e8e..ef45fad092 100644
--- a/rust/cloud-storage/document_storage_service/Cargo.toml
+++ b/rust/cloud-storage/document_storage_service/Cargo.toml
@@ -77,6 +77,7 @@ models_bulk_upload = { path = "../models_bulk_upload" }
models_opensearch = { path = "../models_opensearch" }
models_pagination = { path = "../models_pagination", features = ["axum"] }
models_permissions = { path = "../models_permissions" }
+properties = { path = "../properties" }
models_soup = { path = "../models_soup", features = ["schema"] }
rayon = "1.10.0"
redis = { workspace = true, features = [
diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rs
index aee0856966..537582d216 100644
--- a/rust/cloud-storage/document_storage_service/src/api/context.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs
@@ -8,6 +8,7 @@ use frecency::{domain::services::FrecencyQueryServiceImpl, outbound::postgres::F
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_env_var::env_var;
use macro_redis_cluster_client::Redis;
+use properties::{PropertiesPgRepo, PropertiesServiceImpl};
use soup::{
domain::service::SoupImpl, inbound::axum_router::SoupRouterState,
outbound::pg_soup_repo::PgSoupRepo,
@@ -32,6 +33,7 @@ type DssSoupState = SoupRouterState<
>;
type SystemPropertiesService = SystemPropertiesServiceImpl<PgSystemPropertiesRepository>;
+type PropertiesService = PropertiesServiceImpl<PropertiesPgRepo>;
#[derive(Clone, FromRef)]
pub(crate) struct ApiContext {
@@ -48,6 +50,7 @@ pub(crate) struct ApiContext {
pub conn_gateway_client: Arc<ConnectionGatewayClient>,
pub sync_service_client: Arc<SyncServiceClient>,
pub system_properties_service: Arc<SystemPropertiesService>,
+ pub properties_service: Arc<PropertiesService>,
pub jwt_validation_args: JwtValidationArgs,
pub config: Arc<Config>,
pub dss_auth_key: DocumentStorageServiceAuthKey,
diff --git a/rust/cloud-storage/document_storage_service/src/api/documents/delete_document.rs b/rust/cloud-storage/document_storage_service/src/api/documents/delete_document.rs
index 119414adae..f735858e01 100644
--- a/rust/cloud-storage/document_storage_service/src/api/documents/delete_document.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/documents/delete_document.rs
@@ -13,8 +13,10 @@ use model::response::{
};
use model::user::UserContext;
use models_permissions::share_permission::access_level::OwnerAccessLevel;
+use properties::PropertiesService;
use serde::Deserialize;
use sqs_client::search::{SearchQueueMessage, document::DocumentId};
+use uuid::Uuid;
#[derive(Deserialize)]
pub struct Params {
@@ -46,6 +48,7 @@ pub async fn delete_document_handler(
doc: Extension<DocumentBasic>,
) -> impl IntoResponse {
tracing::info!("delete document");
+
// soft delete the document, this will remove the history and pins and mark the document as deleted
if let Err(e) = macro_db_client::document::soft_delete_document(&state.db, &document_id).await {
tracing::error!(error=?e, document_id=?document_id, "unable to soft delete document");
@@ -55,6 +58,24 @@ pub async fn delete_document_handler(
.send(StatusCode::INTERNAL_SERVER_ERROR);
}
+ // Unlink task parent/subtasks if this is a task (no-op for non-tasks)
+ if let Ok(task_id) = Uuid::parse_str(&document_id) {
+ if let Err(e) = state
+ .properties_service
+ .link_parent_task(task_id, None)
+ .await
+ {
+ tracing::warn!(error = ?e, "failed to unlink parent task on delete");
+ }
+ if let Err(e) = state
+ .properties_service
+ .link_subtasks(task_id, vec![])
+ .await
+ {
+ tracing::warn!(error = ?e, "failed to unlink subtasks on delete");
+ }
+ }
+
let response_data = GenericSuccessResponse { success: true };
macro_project_utils::update_project_modified(
diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rs
index 63fb92186e..d5efec44a7 100644
--- a/rust/cloud-storage/document_storage_service/src/main.rs
+++ b/rust/cloud-storage/document_storage_service/src/main.rs
@@ -16,6 +16,7 @@ use macro_entrypoint::MacroEntrypoint;
use macro_env_var::env_var;
use macro_middleware::auth::internal_access::InternalApiSecretKey;
use macro_redis_cluster_client::Redis;
+use properties::{PropertiesPgRepo, PropertiesServiceImpl};
use secretsmanager_client::SecretManager;
use soup::{
domain::service::SoupImpl, inbound::axum_router::SoupRouterState,
@@ -187,6 +188,7 @@ async fn main() -> anyhow::Result<()> {
EmailServiceImpl::new(EmailPgRepo::new(db.clone()), frecency_service.clone());
let system_properties_service =
SystemPropertiesServiceImpl::new(PgSystemPropertiesRepository::new(db.clone()));
+ let properties_service = PropertiesServiceImpl::new(PropertiesPgRepo::new(db.clone()));
let api_context = ApiContext {
soup_router_state: SoupRouterState::new(
SoupImpl::new(
@@ -213,6 +215,7 @@ async fn main() -> anyhow::Result<()> {
conn_gateway_client: Arc::new(conn_gateway_client),
sync_service_client: Arc::new(sync_service_client),
system_properties_service: Arc::new(system_properties_service),
+ properties_service: Arc::new(properties_service),
config: Arc::new(config),
jwt_validation_args,
dss_auth_key,
diff --git a/rust/cloud-storage/properties/.sqlx/query-1435acbba365796ddcb6ddbef86f4ebf664cffc44082996f6b60a60373c28f75.json b/rust/cloud-storage/properties/.sqlx/query-1435acbba365796ddcb6ddbef86f4ebf664cffc44082996f6b60a60373c28f75.json
new file mode 100644
index 0000000000..d2b084cf10
--- /dev/null
+++ b/rust/cloud-storage/properties/.sqlx/query-1435acbba365796ddcb6ddbef86f4ebf664cffc44082996f6b60a60373c28f75.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)\n SELECT \n u.id,\n u.entity_id,\n 'TASK'::property_entity_type,\n u.property_definition_id,\n u.values\n FROM UNNEST(\n $1::UUID[],\n $2::TEXT[],\n $3::UUID[],\n $4::JSONB[]\n ) AS u(id, entity_id, property_definition_id, values)\n ON CONFLICT (entity_id, entity_type, property_definition_id)\n DO UPDATE SET \n values = EXCLUDED.values,\n updated_at = NOW()\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "UuidArray",
+ "TextArray",
+ "UuidArray",
+ "JsonbArray"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "1435acbba365796ddcb6ddbef86f4ebf664cffc44082996f6b60a60373c28f75"
+}
diff --git a/rust/cloud-storage/properties/.sqlx/query-4123b0f2a6fa02a9191a87f2484cb27fd4220b15126fd010acbf4b954a9afb68.json b/rust/cloud-storage/properties/.sqlx/query-4123b0f2a6fa02a9191a87f2484cb27fd4220b15126fd010acbf4b954a9afb68.json
new file mode 100644
index 0000000000..1990ecc0d6
--- /dev/null
+++ b/rust/cloud-storage/properties/.sqlx/query-4123b0f2a6fa02a9191a87f2484cb27fd4220b15126fd010acbf4b954a9afb68.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT elem->>'entity_id' as \"subtask_id!\"\n FROM entity_properties,\n jsonb_array_elements(values->'value') elem\n WHERE entity_id = $1\n AND entity_type = 'TASK'\n AND property_definition_id = $2\n AND values IS NOT NULL\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "subtask_id!",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "4123b0f2a6fa02a9191a87f2484cb27fd4220b15126fd010acbf4b954a9afb68"
+}
diff --git a/rust/cloud-storage/properties/.sqlx/query-63492b018803ce26db5891964a0f52f37d2f54bd8243265c6561f4423af8617c.json b/rust/cloud-storage/properties/.sqlx/query-63492b018803ce26db5891964a0f52f37d2f54bd8243265c6561f4423af8617c.json
new file mode 100644
index 0000000000..6d97183829
--- /dev/null
+++ b/rust/cloud-storage/properties/.sqlx/query-63492b018803ce26db5891964a0f52f37d2f54bd8243265c6561f4423af8617c.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)\n SELECT \n u.id,\n u.entity_id,\n 'TASK'::property_entity_type,\n u.property_definition_id,\n NULL\n FROM UNNEST(\n $1::UUID[],\n $2::TEXT[],\n $3::UUID[]\n ) AS u(id, entity_id, property_definition_id)\n ON CONFLICT (entity_id, entity_type, property_definition_id)\n DO NOTHING\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "UuidArray",
+ "TextArray",
+ "UuidArray"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "63492b018803ce26db5891964a0f52f37d2f54bd8243265c6561f4423af8617c"
+}
diff --git a/rust/cloud-storage/properties/.sqlx/query-805150c1a22fe4cee95588606be11c6419a2e25f66201dfefc8a87a586150d26.json b/rust/cloud-storage/properties/.sqlx/query-805150c1a22fe4cee95588606be11c6419a2e25f66201dfefc8a87a586150d26.json
new file mode 100644
index 0000000000..1211597670
--- /dev/null
+++ b/rust/cloud-storage/properties/.sqlx/query-805150c1a22fe4cee95588606be11c6419a2e25f66201dfefc8a87a586150d26.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT values->'value'->0->>'entity_id' as \"parent_id\"\n FROM entity_properties\n WHERE entity_id = $1\n AND entity_type = 'TASK'\n AND property_definition_id = $2\n AND values IS NOT NULL\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "parent_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "805150c1a22fe4cee95588606be11c6419a2e25f66201dfefc8a87a586150d26"
+}
diff --git a/rust/cloud-storage/properties/.sqlx/query-9cd40fbb1ade51e9e0d49792839d1a363cada017252a6f653c2272608189bcc4.json b/rust/cloud-storage/properties/.sqlx/query-9cd40fbb1ade51e9e0d49792839d1a363cada017252a6f653c2272608189bcc4.json
new file mode 100644
index 0000000000..9d717fa5f9
--- /dev/null
+++ b/rust/cloud-storage/properties/.sqlx/query-9cd40fbb1ade51e9e0d49792839d1a363cada017252a6f653c2272608189bcc4.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT property_definition_id, values\n FROM entity_properties\n WHERE entity_id = $1\n AND entity_type = 'TASK'\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "property_definition_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "values",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ true
+ ]
+ },
+ "hash": "9cd40fbb1ade51e9e0d49792839d1a363cada017252a6f653c2272608189bcc4"
+}
diff --git a/rust/cloud-storage/properties/.sqlx/query-7d52ef19ac1655037ce18444b549c7394c851e67f211888194b09fc234731e2a.json b/rust/cloud-storage/properties/.sqlx/query-bf308be1e802f2f6552a6bd0282ae985dfb1a3fc738532eca74c6b098c6772c0.json
similarity index 64%
rename from rust/cloud-storage/properties/.sqlx/query-7d52ef19ac1655037ce18444b549c7394c851e67f211888194b09fc234731e2a.json
rename to rust/cloud-storage/properties/.sqlx/query-bf308be1e802f2f6552a6bd0282ae985dfb1a3fc738532eca74c6b098c6772c0.json
index f5068aa5c5..2c1ef9427c 100644
--- a/rust/cloud-storage/properties/.sqlx/query-7d52ef19ac1655037ce18444b549c7394c851e67f211888194b09fc234731e2a.json
+++ b/rust/cloud-storage/properties/.sqlx/query-bf308be1e802f2f6552a6bd0282ae985dfb1a3fc738532eca74c6b098c6772c0.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\n AND entity_type = $2\n AND property_definition_id = $3\n ",
+ "query": "\n UPDATE entity_properties\n SET values = $4, updated_at = NOW()\n WHERE entity_id = $1\n AND entity_type = $2\n AND property_definition_id = $3\n ",
"describe": {
"columns": [],
"parameters": {
@@ -29,5 +29,5 @@
},
"nullable": []
},
- "hash": "7d52ef19ac1655037ce18444b549c7394c851e67f211888194b09fc234731e2a"
+ "hash": "bf308be1e802f2f6552a6bd0282ae985dfb1a3fc738532eca74c6b098c6772c0"
}
diff --git a/rust/cloud-storage/properties/.sqlx/query-f2d5d7aea9918978cd69c14f8afe24156c2fa387e001ee8eaf57e4a70a106069.json b/rust/cloud-storage/properties/.sqlx/query-f2d5d7aea9918978cd69c14f8afe24156c2fa387e001ee8eaf57e4a70a106069.json
new file mode 100644
index 0000000000..182e0858ba
--- /dev/null
+++ b/rust/cloud-storage/properties/.sqlx/query-f2d5d7aea9918978cd69c14f8afe24156c2fa387e001ee8eaf57e4a70a106069.json
@@ -0,0 +1,18 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)\n SELECT \n u.id,\n u.entity_id,\n u.entity_type::property_entity_type,\n u.property_definition_id,\n u.values\n FROM UNNEST(\n $1::UUID[],\n $2::TEXT[],\n $3::TEXT[],\n $4::UUID[],\n $5::JSONB[]\n ) AS u(id, entity_id, entity_type, property_definition_id, values)\n ON CONFLICT (entity_id, entity_type, property_definition_id)\n DO UPDATE SET \n values = EXCLUDED.values,\n updated_at = NOW()\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "UuidArray",
+ "TextArray",
+ "TextArray",
+ "UuidArray",
+ "JsonbArray"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "f2d5d7aea9918978cd69c14f8afe24156c2fa387e001ee8eaf57e4a70a106069"
+}
diff --git a/rust/cloud-storage/properties/fixtures/task_linking_seed.sql b/rust/cloud-storage/properties/fixtures/task_linking_seed.sql
new file mode 100644
index 0000000000..f0bc001edd
--- /dev/null
+++ b/rust/cloud-storage/properties/fixtures/task_linking_seed.sql
@@ -0,0 +1,190 @@
+-- Test fixture for task parent/subtask bidirectional linking tests
+--
+-- Parent Task UUID: 00000001-0000-0000-0000-000000000005
+-- Subtasks UUID: 00000001-0000-0000-0000-000000000006
+--
+-- Task IDs (as UUIDs converted to strings):
+-- task-parent-a = 20000001-0000-0000-0000-000000000001
+-- task-parent-b = 20000001-0000-0000-0000-000000000002
+-- task-child-1 = 20000001-0000-0000-0000-000000000003
+-- task-child-2 = 20000001-0000-0000-0000-000000000004
+-- task-child-3 = 20000001-0000-0000-0000-000000000005
+-- task-orphan = 20000001-0000-0000-0000-000000000006
+-- task-standalone = 20000001-0000-0000-0000-000000000007
+--
+-- Task hierarchy for tests:
+-- task-parent-a
+-- └── task-child-1 (subtask of task-parent-a)
+-- └── task-child-2 (subtask of task-parent-a)
+-- task-parent-b
+-- └── task-child-3 (subtask of task-parent-b)
+-- task-orphan (no parent, no subtasks)
+-- task-standalone (has properties attached but empty values)
+
+-- Task: task-parent-a with Subtasks = [task-child-1, task-child-2]
+INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values, created_at, updated_at)
+VALUES (
+ '10000001-0000-0000-0000-000000000001',
+ '20000001-0000-0000-0000-000000000001', -- task-parent-a
+ 'TASK',
+ '00000001-0000-0000-0000-000000000006', -- Subtasks
+ '{"type": "EntityReference", "value": [{"entity_id": "20000001-0000-0000-0000-000000000003", "entity_type": "TASK"}, {"entity_id": "20000001-0000-0000-0000-000000000004", "entity_type": "TASK"}]}'::jsonb,
+ NOW(),
+ NOW()
+);
+
+-- Task: task-parent-a with Parent Task = NULL (attached but empty)
+INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values, created_at, updated_at)
+VALUES (
+ '10000001-0000-0000-0000-000000000002',
+ '20000001-0000-0000-0000-000000000001', -- task-parent-a
+ 'TASK',
+ '00000001-0000-0000-0000-000000000005', -- Parent Task
+ NULL,
+ NOW(),
+ NOW()
+);
+
+-- Task: task-child-1 with Parent Task = task-parent-a
+INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values, created_at, updated_at)
+VALUES (
+ '10000001-0000-0000-0000-000000000003',
+ '20000001-0000-0000-0000-000000000003', -- task-child-1
+ 'TASK',
+ '00000001-0000-0000-0000-000000000005', -- Parent Task
+ '{"type": "EntityReference", "value": [{"entity_id": "20000001-0000-0000-0000-000000000001", "entity_type": "TASK"}]}'::jsonb,
+ NOW(),
+ NOW()
+);
+
+-- Task: task-child-1 with Subtasks = [] (attached but empty)
+INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values, created_at, updated_at)
+VALUES (
+ '10000001-0000-0000-0000-000000000004',
+ '20000001-0000-0000-0000-000000000003', -- task-child-1
+ 'TASK',
+ '00000001-0000-0000-0000-000000000006', -- Subtasks
+ NULL,
+ NOW(),
+ NOW()
+);
+
+-- Task: task-child-2 with Parent Task = task-parent-a
+INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values, created_at, updated_at)
+VALUES (
+ '10000001-0000-0000-0000-000000000005',
+ '20000001-0000-0000-0000-000000000004', -- task-child-2
+ 'TASK',
+ '00000001-0000-0000-0000-000000000005', -- Parent Task
+ '{"type": "EntityReference", "value": [{"entity_id": "20000001-0000-0000-0000-000000000001", "entity_type": "TASK"}]}'::jsonb,
+ NOW(),
+ NOW()
+);
+
+-- Task: task-child-2 with Subtasks = [] (attached but empty)
+INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values, created_at, updated_at)
+VALUES (
+ '10000001-0000-0000-0000-000000000006',
+ '20000001-0000-0000-0000-000000000004', -- task-child-2
+ 'TASK',
+ '00000001-0000-0000-0000-000000000006', -- Subtasks
+ NULL,
+ NOW(),
+ NOW()
+);
+
+-- Task: task-parent-b with Subtasks = [task-child-3]
+INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values, created_at, updated_at)
+VALUES (
+ '10000001-0000-0000-0000-000000000007',
+ '20000001-0000-0000-0000-000000000002', -- task-parent-b
+ 'TASK',
+ '00000001-0000-0000-0000-000000000006', -- Subtasks
+ '{"type": "EntityReference", "value": [{"entity_id": "20000001-0000-0000-0000-000000000005", "entity_type": "TASK"}]}'::jsonb,
+ NOW(),
+ NOW()
+);
+
+-- Task: task-parent-b with Parent Task = NULL
+INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values, created_at, updated_at)
+VALUES (
+ '10000001-0000-0000-0000-000000000008',
+ '20000001-0000-0000-0000-000000000002', -- task-parent-b
+ 'TASK',
+ '00000001-0000-0000-0000-000000000005', -- Parent Task
+ NULL,
+ NOW(),
+ NOW()
+);
+
+-- Task: task-child-3 with Parent Task = task-parent-b
+INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values, created_at, updated_at)
+VALUES (
+ '10000001-0000-0000-0000-000000000009',
+ '20000001-0000-0000-0000-000000000005', -- task-child-3
+ 'TASK',
+ '00000001-0000-0000-0000-000000000005', -- Parent Task
+ '{"type": "EntityReference", "value": [{"entity_id": "20000001-0000-0000-0000-000000000002", "entity_type": "TASK"}]}'::jsonb,
+ NOW(),
+ NOW()
+);
+
+-- Task: task-child-3 with Subtasks = []
+INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values, created_at, updated_at)
+VALUES (
+ '10000001-0000-0000-0000-000000000010',
+ '20000001-0000-0000-0000-000000000005', -- task-child-3
+ 'TASK',
+ '00000001-0000-0000-0000-000000000006', -- Subtasks
+ NULL,
+ NOW(),
+ NOW()
+);
+
+-- Task: task-orphan with Parent Task = NULL (no parent)
+INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values, created_at, updated_at)
+VALUES (
+ '10000001-0000-0000-0000-000000000011',
+ '20000001-0000-0000-0000-000000000006', -- task-orphan
+ 'TASK',
+ '00000001-0000-0000-0000-000000000005', -- Parent Task
+ NULL,
+ NOW(),
+ NOW()
+);
+
+-- Task: task-orphan with Subtasks = []
+INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values, created_at, updated_at)
+VALUES (
+ '10000001-0000-0000-0000-000000000012',
+ '20000001-0000-0000-0000-000000000006', -- task-orphan
+ 'TASK',
+ '00000001-0000-0000-0000-000000000006', -- Subtasks
+ NULL,
+ NOW(),
+ NOW()
+);
+
+-- Task: task-standalone with Parent Task attached (empty)
+INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values, created_at, updated_at)
+VALUES (
+ '10000001-0000-0000-0000-000000000013',
+ '20000001-0000-0000-0000-000000000007', -- task-standalone
+ 'TASK',
+ '00000001-0000-0000-0000-000000000005', -- Parent Task
+ NULL,
+ NOW(),
+ NOW()
+);
+
+-- Task: task-standalone with Subtasks attached (empty)
+INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values, created_at, updated_at)
+VALUES (
+ '10000001-0000-0000-0000-000000000014',
+ '20000001-0000-0000-0000-000000000007', -- task-standalone
+ 'TASK',
+ '00000001-0000-0000-0000-000000000006', -- Subtasks
+ NULL,
+ NOW(),
+ NOW()
+);
diff --git a/rust/cloud-storage/properties/src/domain/ports.rs b/rust/cloud-storage/properties/src/domain/ports.rs
index 7c82e335b6..3d26bd4e6c 100644
--- a/rust/cloud-storage/properties/src/domain/ports.rs
+++ b/rust/cloud-storage/properties/src/domain/ports.rs
@@ -24,4 +24,31 @@ pub trait PropertiesRepo: Send + Sync + 'static {
property_definition_id: Uuid,
value: Option<PropertyValue>,
) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
+ /// Atomically link or unlink a task's parent (for Parent Task property).
+ ///
+ /// When `parent_task_id` is `Some(parent)`:
+ /// - Sets task's Parent Task = parent
+ /// - Adds task to parent's Subtasks
+ /// - Removes task from old parent's Subtasks (if different)
+ ///
+ /// When `parent_task_id` is `None`:
+ /// - Clears task's Parent Task
+ /// - Removes task from old parent's Subtasks
+ fn link_parent_task(
+ &self,
+ task_id: Uuid,
+ parent_task_id: Option<Uuid>,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
+ /// Atomically set a task's subtasks (for Subtasks property).
+ ///
+ /// - Sets task's Subtasks to the new list
+ /// - For added subtasks: sets their Parent Task = task
+ /// - For removed subtasks: clears their Parent Task
+ fn link_subtasks(
+ &self,
+ task_id: Uuid,
+ subtask_ids: Vec<Uuid>,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
}
diff --git a/rust/cloud-storage/properties/src/domain/service.rs b/rust/cloud-storage/properties/src/domain/service.rs
index 08ce33bb91..f1a0a56f18 100644
--- a/rust/cloud-storage/properties/src/domain/service.rs
+++ b/rust/cloud-storage/properties/src/domain/service.rs
@@ -1,6 +1,7 @@
//! Service trait for properties.
use models_properties::EntityType;
+use uuid::Uuid;
/// Service trait for property operations.
pub trait PropertiesService: Send + Sync + 'static {
@@ -13,4 +14,31 @@ pub trait PropertiesService: Send + Sync + 'static {
entity_id: &str,
entity_type: EntityType,
) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
+ /// Bidirectionally link or unlink a task's parent.
+ ///
+ /// When `parent_task_id` is `Some(parent)`:
+ /// - Sets task's Parent Task = parent
+ /// - Adds task to parent's Subtasks
+ /// - Removes task from old parent's Subtasks (if different)
+ ///
+ /// When `parent_task_id` is `None`:
+ /// - Clears task's Parent Task
+ /// - Removes task from old parent's Subtasks
+ fn link_parent_task(
+ &self,
+ task_id: Uuid,
+ parent_task_id: Option<Uuid>,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
+ /// Bidirectionally set a task's subtasks.
+ ///
+ /// - Sets task's Subtasks to the new list
+ /// - For added subtasks: sets their Parent Task = task
+ /// - For removed subtasks: clears their Parent Task
+ fn link_subtasks(
+ &self,
+ task_id: Uuid,
+ subtask_ids: Vec<Uuid>,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
}
diff --git a/rust/cloud-storage/properties/src/domain/service_impl.rs b/rust/cloud-storage/properties/src/domain/service_impl.rs
index bd3520ffdb..5c6858b6fc 100644
--- a/rust/cloud-storage/properties/src/domain/service_impl.rs
+++ b/rust/cloud-storage/properties/src/domain/service_impl.rs
@@ -5,6 +5,7 @@ use std::fmt::Debug;
use models_properties::EntityType;
use models_properties::service::property_value::PropertyValue;
use system_properties::{StatusOption, SystemPropertyKey};
+use uuid::Uuid;
use super::ports::PropertiesRepo;
use super::service::PropertiesService;
@@ -56,4 +57,20 @@ where
Ok(())
}
+
+ #[tracing::instrument(skip(self))]
+ async fn link_parent_task(
+ &self,
+ task_id: Uuid,
+ parent_task_id: Option<Uuid>,
+ ) -> Result<(), Self::Err> {
+ self.repository
+ .link_parent_task(task_id, parent_task_id)
+ .await
+ }
+
+ #[tracing::instrument(skip(self))]
+ async fn link_subtasks(&self, task_id: Uuid, subtask_ids: Vec<Uuid>) -> Result<(), Self::Err> {
+ self.repository.link_subtasks(task_id, subtask_ids).await
+ }
}
diff --git a/rust/cloud-storage/properties/src/domain/test.rs b/rust/cloud-storage/properties/src/domain/test.rs
index a1a6d2d589..f27c8b21b6 100644
--- a/rust/cloud-storage/properties/src/domain/test.rs
+++ b/rust/cloud-storage/properties/src/domain/test.rs
@@ -5,6 +5,7 @@ use crate::domain::{ports::MockPropertiesRepo, service::PropertiesService};
use anyhow::anyhow;
use models_properties::{EntityType, service::property_value::PropertyValue};
use system_properties::{StatusOption, SystemPropertyKey};
+use uuid::Uuid;
#[tokio::test]
async fn test_set_system_property_status_complete_happy_path() {
@@ -58,3 +59,116 @@ async fn test_set_system_property_status_complete_error_path() {
assert_eq!(err.to_string(), "boom");
}
+
+// ============================================================================
+// link_parent_task unit tests
+// ============================================================================
+
+#[tokio::test]
+async fn test_link_parent_task_delegates_to_repo() {
+ let mut repo = MockPropertiesRepo::new();
+
+ let task_id = Uuid::from_u128(0x12345678_1234_1234_1234_123456789abc);
+ let parent_id = Uuid::from_u128(0xabcdef01_2345_6789_abcd_ef0123456789);
+
+ repo.expect_link_parent_task()
+ .withf(move |t, p| *t == task_id && *p == Some(parent_id))
+ .returning(|_, _| Box::pin(async { Ok(()) }));
+
+ let service = PropertiesServiceImpl::new(repo);
+
+ service
+ .link_parent_task(task_id, Some(parent_id))
+ .await
+ .unwrap();
+}
+
+#[tokio::test]
+async fn test_link_parent_task_clear_parent() {
+ let mut repo = MockPropertiesRepo::new();
+
+ let task_id = Uuid::from_u128(0x12345678_1234_1234_1234_123456789abc);
+
+ repo.expect_link_parent_task()
+ .withf(move |t, p| *t == task_id && p.is_none())
+ .returning(|_, _| Box::pin(async { Ok(()) }));
+
+ let service = PropertiesServiceImpl::new(repo);
+
+ service.link_parent_task(task_id, None).await.unwrap();
+}
+
+#[tokio::test]
+async fn test_link_parent_task_error_propagates() {
+ let mut repo = MockPropertiesRepo::new();
+
+ repo.expect_link_parent_task()
+ .returning(|_, _| Box::pin(async { Err(anyhow!("link failed")) }));
+
+ let service = PropertiesServiceImpl::new(repo);
+
+ let err = service
+ .link_parent_task(Uuid::nil(), Some(Uuid::nil()))
+ .await
+ .unwrap_err();
+
+ assert_eq!(err.to_string(), "link failed");
+}
+
+// ============================================================================
+// link_subtasks unit tests
+// ============================================================================
+
+#[tokio::test]
+async fn test_link_subtasks_delegates_to_repo() {
+ let mut repo = MockPropertiesRepo::new();
+
+ let task_id = Uuid::from_u128(0x12345678_1234_1234_1234_123456789abc);
+ let subtask_1 = Uuid::from_u128(0xaaaaaaaa_aaaa_aaaa_aaaa_aaaaaaaaaaaa);
+ let subtask_2 = Uuid::from_u128(0xbbbbbbbb_bbbb_bbbb_bbbb_bbbbbbbbbbbb);
+
+ repo.expect_link_subtasks()
+ .withf(move |t, s| {
+ *t == task_id && s.len() == 2 && s.contains(&subtask_1) && s.contains(&subtask_2)
+ })
+ .returning(|_, _| Box::pin(async { Ok(()) }));
+
+ let service = PropertiesServiceImpl::new(repo);
+
+ service
+ .link_subtasks(task_id, vec![subtask_1, subtask_2])
+ .await
+ .unwrap();
+}
+
+#[tokio::test]
+async fn test_link_subtasks_clear_all() {
+ let mut repo = MockPropertiesRepo::new();
+
+ let task_id = Uuid::from_u128(0x12345678_1234_1234_1234_123456789abc);
+
+ repo.expect_link_subtasks()
+ .withf(move |t, s| *t == task_id && s.is_empty())
+ .returning(|_, _| Box::pin(async { Ok(()) }));
+
+ let service = PropertiesServiceImpl::new(repo);
+
+ service.link_subtasks(task_id, vec![]).await.unwrap();
+}
+
+#[tokio::test]
+async fn test_link_subtasks_error_propagates() {
+ let mut repo = MockPropertiesRepo::new();
+
+ repo.expect_link_subtasks()
+ .returning(|_, _| Box::pin(async { Err(anyhow!("subtask link failed")) }));
+
+ let service = PropertiesServiceImpl::new(repo);
+
+ let err = service
+ .link_subtasks(Uuid::nil(), vec![Uuid::nil()])
+ .await
+ .unwrap_err();
+
+ assert_eq!(err.to_string(), "subtask link failed");
+}
diff --git a/rust/cloud-storage/properties/src/outbound.rs b/rust/cloud-storage/properties/src/outbound.rs
index a5b981b231..be2005a853 100644
--- a/rust/cloud-storage/properties/src/outbound.rs
+++ b/rust/cloud-storage/properties/src/outbound.rs
@@ -1,3 +1,5 @@
+pub mod entity_property_queries;
pub mod properties_pg_repo;
+pub mod task_property_queries;
#[cfg(test)]
pub mod test;
diff --git a/rust/cloud-storage/properties/src/outbound/entity_property_queries.rs b/rust/cloud-storage/properties/src/outbound/entity_property_queries.rs
new file mode 100644
index 0000000000..9be659bb63
--- /dev/null
+++ b/rust/cloud-storage/properties/src/outbound/entity_property_queries.rs
@@ -0,0 +1,49 @@
+//! General entity property query helpers.
+
+use models_properties::EntityType;
+use models_properties::service::property_value::PropertyValue;
+use sqlx::{Pool, Postgres};
+use uuid::Uuid;
+
+/// Atomically update a property value if the property is attached to the entity.
+/// No-op if the property is not attached.
+pub async fn update_entity_property_value_if_exists(
+ pool: &Pool<Postgres>,
+ entity_id: &str,
+ entity_type: EntityType,
+ property_definition_id: Uuid,
+ value: Option<PropertyValue>,
+) -> anyhow::Result<()> {
+ // Serialize PropertyValue to JSONB (or NULL if None)
+ let value_json = match value {
+ Some(v) => serde_json::to_value(&v)?,
+ None => serde_json::Value::Null,
+ };
+
+ tracing::debug!(value_json = ?value_json, "updating entity property if exists");
+
+ // Atomic update - only updates if the property is already attached
+ let result = sqlx::query!(
+ r#"
+ UPDATE entity_properties
+ SET values = $4, updated_at = NOW()
+ WHERE entity_id = $1
+ AND entity_type = $2
+ AND property_definition_id = $3
+ "#,
+ entity_id,
+ entity_type as EntityType,
+ property_definition_id,
+ value_json
+ )
+ .execute(pool)
+ .await?;
+
+ if result.rows_affected() > 0 {
+ tracing::debug!("successfully updated entity property");
+ } else {
+ tracing::debug!("entity property not attached, no-op");
+ }
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/properties/src/outbound/properties_pg_repo.rs b/rust/cloud-storage/properties/src/outbound/properties_pg_repo.rs
index 571c334026..5b0be4ebbf 100644
--- a/rust/cloud-storage/properties/src/outbound/properties_pg_repo.rs
+++ b/rust/cloud-storage/properties/src/outbound/properties_pg_repo.rs
@@ -1,11 +1,11 @@
//! PostgreSQL implementation for properties repository.
-use anyhow::Context;
use models_properties::EntityType;
use models_properties::service::property_value::PropertyValue;
use sqlx::{Pool, Postgres};
use uuid::Uuid;
+use super::{entity_property_queries, task_property_queries};
use crate::domain::ports::PropertiesRepo;
/// PostgreSQL implementation of PropertiesRepo.
@@ -32,38 +32,27 @@ impl PropertiesRepo for PropertiesPgRepo {
property_definition_id: Uuid,
value: Option<PropertyValue>,
) -> Result<(), Self::Err> {
- // Serialize PropertyValue to JSONB (or NULL if None)
- let value_json = match value {
- Some(v) => serde_json::to_value(&v).context("failed to serialize property value")?,
- None => serde_json::Value::Null,
- };
-
- tracing::debug!(value_json = ?value_json, "updating entity property if exists");
-
- // Atomic update - only updates if the property is already attached
- let result = sqlx::query!(
- r#"
- UPDATE entity_properties
- SET values = $4, updated_at = NOW()
- WHERE entity_id = $1
- AND entity_type = $2
- AND property_definition_id = $3
- "#,
+ entity_property_queries::update_entity_property_value_if_exists(
+ &self.pool,
entity_id,
- entity_type as EntityType,
+ entity_type,
property_definition_id,
- value_json
+ value,
)
- .execute(&self.pool)
.await
- .context("failed to update entity property")?;
+ }
- if result.rows_affected() > 0 {
- tracing::info!("successfully updated entity property");
- } else {
- tracing::debug!("entity property not attached, no-op");
- }
+ #[tracing::instrument(skip(self))]
+ async fn link_parent_task(
+ &self,
+ task_id: Uuid,
+ parent_task_id: Option<Uuid>,
+ ) -> Result<(), Self::Err> {
+ task_property_queries::link_parent_task(&self.pool, task_id, parent_task_id).await
+ }
- Ok(())
+ #[tracing::instrument(skip(self))]
+ async fn link_subtasks(&self, task_id: Uuid, subtask_ids: Vec<Uuid>) -> Result<(), Self::Err> {
+ task_property_queries::link_subtasks(&self.pool, task_id, subtask_ids).await
}
}
diff --git a/rust/cloud-storage/properties/src/outbound/task_property_queries.rs b/rust/cloud-storage/properties/src/outbound/task_property_queries.rs
new file mode 100644
index 0000000000..b7075d5bdc
--- /dev/null
+++ b/rust/cloud-storage/properties/src/outbound/task_property_queries.rs
@@ -0,0 +1,303 @@
+//! Helper functions for bidirectional task parent/subtask linking.
+
+use std::collections::HashSet;
+
+use models_properties::EntityReference;
+use models_properties::EntityType;
+use models_properties::service::property_value::PropertyValue;
+use sqlx::{PgConnection, Pool, Postgres};
+use system_properties::SystemPropertyKey;
+use uuid::Uuid;
+
+// ============================================================================
+// Main linking functions
+// ============================================================================
+
+/// Link or unlink a task's parent (for Parent Task property).
+pub async fn link_parent_task(
+ pool: &Pool<Postgres>,
+ task_id: Uuid,
+ parent_task_id: Option<Uuid>,
+) -> anyhow::Result<()> {
+ // Validate: can't set self as parent
+ if parent_task_id == Some(task_id) {
+ anyhow::bail!("a task cannot be its own parent");
+ }
+
+ let mut tx = pool.begin().await?;
+
+ // Validate: can't set a subtask as parent (would create mutual reference)
+ if let Some(parent_id) = parent_task_id {
+ let current_subtasks = get_task_subtasks(&mut tx, task_id).await?;
+ if current_subtasks.contains(&parent_id) {
+ anyhow::bail!("cannot set a subtask as parent (would create circular reference)");
+ }
+ }
+
+ // 1. Get old parent
+ let old_parent = get_task_parent(&mut tx, task_id).await?;
+ tracing::debug!(old_parent = ?old_parent, "fetched current parent");
+
+ // 2. Remove from old parent if changed
+ if let Some(old_parent_id) = old_parent
+ && Some(old_parent_id) != parent_task_id
+ {
+ remove_from_parent_subtasks(&mut tx, old_parent_id, task_id).await?;
+ tracing::debug!(old_parent = %old_parent_id, "removed task from old parent's Subtasks");
+ }
+
+ // 3. Set new parent (returns true if task exists)
+ let task_exists = set_task_parent(&mut tx, task_id, parent_task_id).await?;
+
+ // 4. Add to new parent's subtasks (only if task exists)
+ if task_exists {
+ if let Some(parent_id) = parent_task_id {
+ add_to_parent_subtasks(&mut tx, parent_id, task_id).await?;
+ tracing::debug!("added task to parent's Subtasks");
+ }
+ } else {
+ tracing::debug!("task does not exist, skipping subtasks update");
+ }
+
+ tx.commit().await?;
+ tracing::info!("successfully linked parent task");
+ Ok(())
+}
+
+/// Set a task's subtasks (for Subtasks property).
+pub async fn link_subtasks(
+ pool: &Pool<Postgres>,
+ task_id: Uuid,
+ subtask_ids: Vec<Uuid>,
+) -> anyhow::Result<()> {
+ // Validate: can't include self as subtask
+ if subtask_ids.contains(&task_id) {
+ anyhow::bail!("a task cannot be its own subtask");
+ }
+
+ // Dedupe subtask IDs
+ let subtask_ids: Vec<Uuid> = subtask_ids
+ .into_iter()
+ .collect::<HashSet<_>>()
+ .into_iter()
+ .collect();
+
+ let mut tx = pool.begin().await?;
+
+ // Validate: can't include parent as subtask (would create mutual reference)
+ if let Some(current_parent) = get_task_parent(&mut tx, task_id).await?
+ && subtask_ids.contains(&current_parent)
+ {
+ anyhow::bail!("cannot set parent as subtask (would create circular reference)");
+ }
+
+ // 1. Get current subtasks & compute diff
+ let current_subtasks = get_task_subtasks(&mut tx, task_id).await?;
+
+ let added: Vec<Uuid> = subtask_ids
+ .iter()
+ .copied()
+ .filter(|id| !current_subtasks.contains(id))
+ .collect();
+ let removed: Vec<Uuid> = current_subtasks
+ .iter()
+ .copied()
+ .filter(|id| !subtask_ids.contains(id))
+ .collect();
+
+ tracing::debug!(
+ current = ?current_subtasks,
+ added = ?added,
+ removed = ?removed,
+ "computed subtasks diff"
+ );
+
+ // 2. Set task's subtasks to new list
+ set_task_subtasks(&mut tx, task_id, subtask_ids).await?;
+
+ // 3. For added subtasks: remove from old parent, set new parent
+ for subtask_id in &added {
+ if let Some(old_parent_id) = get_task_parent(&mut tx, *subtask_id).await?
+ && old_parent_id != task_id
+ {
+ remove_from_parent_subtasks(&mut tx, old_parent_id, *subtask_id).await?;
+ tracing::debug!(
+ subtask = %subtask_id,
+ old_parent = %old_parent_id,
+ "removed subtask from old parent's Subtasks"
+ );
+ }
+ let _ = set_task_parent(&mut tx, *subtask_id, Some(task_id)).await?;
+ }
+
+ // 4. For removed subtasks: clear their parent
+ for subtask_id in &removed {
+ let _ = set_task_parent(&mut tx, *subtask_id, None).await?;
+ }
+
+ tx.commit().await?;
+ tracing::info!(
+ added_count = added.len(),
+ removed_count = removed.len(),
+ "successfully linked subtasks"
+ );
+ Ok(())
+}
+
+// ============================================================================
+// Helper functions
+// ============================================================================
+
+/// Get a task's current parent task ID.
+async fn get_task_parent(tx: &mut PgConnection, task_id: Uuid) -> anyhow::Result<Option<Uuid>> {
+ let parent_task_prop_id = SystemPropertyKey::PARENT_TASK_UUID;
+ let task_id_str = task_id.to_string();
+
+ let parent_str: Option<Option<String>> = sqlx::query_scalar!(
+ r#"
+ SELECT values->'value'->0->>'entity_id' as "parent_id"
+ FROM entity_properties
+ WHERE entity_id = $1
+ AND entity_type = 'TASK'
+ AND property_definition_id = $2
+ AND values IS NOT NULL
+ "#,
+ task_id_str,
+ parent_task_prop_id
+ )
+ .fetch_optional(&mut *tx)
+ .await?;
+
+ Ok(parent_str
+ .flatten()
+ .and_then(|s: String| Uuid::parse_str(&s).ok()))
+}
+
+/// Get a task's current subtask IDs.
+async fn get_task_subtasks(tx: &mut PgConnection, task_id: Uuid) -> anyhow::Result<Vec<Uuid>> {
+ let subtasks_prop_id = SystemPropertyKey::SUBTASKS_UUID;
+ let task_id_str = task_id.to_string();
+
+ let subtask_strs: Vec<String> = sqlx::query_scalar!(
+ r#"
+ SELECT elem->>'entity_id' as "subtask_id!"
+ FROM entity_properties,
+ jsonb_array_elements(values->'value') elem
+ WHERE entity_id = $1
+ AND entity_type = 'TASK'
+ AND property_definition_id = $2
+ AND values IS NOT NULL
+ "#,
+ task_id_str,
+ subtasks_prop_id
+ )
+ .fetch_all(&mut *tx)
+ .await?;
+
+ Ok(subtask_strs
+ .into_iter()
+ .filter_map(|s: String| Uuid::parse_str(&s).ok())
+ .collect())
+}
+
+/// Remove a task from a parent's subtasks array.
+async fn remove_from_parent_subtasks(
+ tx: &mut PgConnection,
+ parent_id: Uuid,
+ task_id: Uuid,
+) -> anyhow::Result<()> {
+ let current = get_task_subtasks(&mut *tx, parent_id).await?;
+ let updated: Vec<Uuid> = current.into_iter().filter(|id| *id != task_id).collect();
+ set_task_subtasks(&mut *tx, parent_id, updated).await
+}
+
+/// Set a task's parent task property. Returns true if the task exists (row was updated).
+async fn set_task_parent(
+ tx: &mut PgConnection,
+ task_id: Uuid,
+ parent_task_id: Option<Uuid>,
+) -> anyhow::Result<bool> {
+ let parent_task_prop_id = SystemPropertyKey::PARENT_TASK_UUID;
+ let task_id_str = task_id.to_string();
+
+ let parent_value = match parent_task_id {
+ Some(parent_id) => {
+ let entity_ref = EntityReference::new(parent_id.to_string(), EntityType::Task);
+ serde_json::to_value(PropertyValue::EntityRef(vec![entity_ref]))?
+ }
+ None => serde_json::Value::Null,
+ };
+
+ let result = sqlx::query!(
+ r#"
+ UPDATE entity_properties
+ SET values = $4, updated_at = NOW()
+ WHERE entity_id = $1
+ AND entity_type = $2
+ AND property_definition_id = $3
+ "#,
+ task_id_str,
+ EntityType::Task as EntityType,
+ parent_task_prop_id,
+ parent_value
+ )
+ .execute(&mut *tx)
+ .await?;
+
+ Ok(result.rows_affected() > 0)
+}
+
+/// Add a task to a parent's subtasks array (if not already present).
+async fn add_to_parent_subtasks(
+ tx: &mut PgConnection,
+ parent_id: Uuid,
+ task_id: Uuid,
+) -> anyhow::Result<()> {
+ let current = get_task_subtasks(&mut *tx, parent_id).await?;
+
+ if !current.contains(&task_id) {
+ let mut updated = current;
+ updated.push(task_id);
+ set_task_subtasks(&mut *tx, parent_id, updated).await?;
+ }
+
+ Ok(())
+}
+
+/// Set a task's subtasks property to a new list.
+async fn set_task_subtasks(
+ tx: &mut PgConnection,
+ task_id: Uuid,
+ subtask_ids: Vec<Uuid>,
+) -> anyhow::Result<()> {
+ let subtasks_prop_id = SystemPropertyKey::SUBTASKS_UUID;
+ let task_id_str = task_id.to_string();
+
+ let subtasks_value = if subtask_ids.is_empty() {
+ serde_json::Value::Null
+ } else {
+ let refs: Vec<EntityReference> = subtask_ids
+ .iter()
+ .map(|id| EntityReference::new(id.to_string(), EntityType::Task))
+ .collect();
+ serde_json::to_value(PropertyValue::EntityRef(refs))?
+ };
+
+ sqlx::query!(
+ r#"
+ UPDATE entity_properties
+ SET values = $4, updated_at = NOW()
+ WHERE entity_id = $1
+ AND entity_type = $2
+ AND property_definition_id = $3
+ "#,
+ task_id_str,
+ EntityType::Task as EntityType,
+ subtasks_prop_id,
+ subtasks_value
+ )
+ .execute(&mut *tx)
+ .await?;
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/properties/src/outbound/test.rs b/rust/cloud-storage/properties/src/outbound/test.rs
index d2fecdb8f4..09e2eccd03 100644
--- a/rust/cloud-storage/properties/src/outbound/test.rs
+++ b/rust/cloud-storage/properties/src/outbound/test.rs
@@ -6,6 +6,7 @@ use macro_db_migrator::MACRO_DB_MIGRATIONS;
use models_properties::{EntityType, service::property_value::PropertyValue};
use sqlx::{Pool, Postgres};
use system_properties::{StatusOption, SystemPropertyKey};
+use uuid::Uuid;
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
@@ -122,3 +123,699 @@ async fn idempotent_when_already_completed(pool: Pool<Postgres>) -> anyhow::Resu
Ok(())
}
+
+// ============================================================================
+// Task linking tests - link_parent_task
+// ============================================================================
+
+/// Helper to get a task's parent from the database
+async fn get_parent(pool: &Pool<Postgres>, task_id: &str) -> Option<String> {
+ sqlx::query_scalar::<_, Option<String>>(
+ r#"
+ SELECT values->'value'->0->>'entity_id'
+ FROM entity_properties
+ WHERE entity_id = $1
+ AND entity_type = 'TASK'
+ AND property_definition_id = $2
+ AND values IS NOT NULL
+ "#,
+ )
+ .bind(task_id)
+ .bind(SystemPropertyKey::PARENT_TASK_UUID)
+ .fetch_optional(pool)
+ .await
+ .ok()
+ .flatten()
+ .flatten()
+}
+
+/// Helper to get a task's subtasks from the database
+async fn get_subtasks(pool: &Pool<Postgres>, task_id: &str) -> Vec<String> {
+ sqlx::query_scalar::<_, String>(
+ r#"
+ SELECT elem->>'entity_id'
+ FROM entity_properties,
+ jsonb_array_elements(values->'value') elem
+ WHERE entity_id = $1
+ AND entity_type = 'TASK'
+ AND property_definition_id = $2
+ AND values IS NOT NULL
+ "#,
+ )
+ .bind(task_id)
+ .bind(SystemPropertyKey::SUBTASKS_UUID)
+ .fetch_all(pool)
+ .await
+ .unwrap_or_default()
+}
+
+/// Helper to parse task ID string to UUID
+fn task_uuid(task_id: &str) -> Uuid {
+ // For test fixtures, we use predictable UUIDs based on task name
+ match task_id {
+ "task-parent-a" => Uuid::from_u128(0x20000001_0000_0000_0000_000000000001),
+ "task-parent-b" => Uuid::from_u128(0x20000001_0000_0000_0000_000000000002),
+ "task-child-1" => Uuid::from_u128(0x20000001_0000_0000_0000_000000000003),
+ "task-child-2" => Uuid::from_u128(0x20000001_0000_0000_0000_000000000004),
+ "task-child-3" => Uuid::from_u128(0x20000001_0000_0000_0000_000000000005),
+ "task-orphan" => Uuid::from_u128(0x20000001_0000_0000_0000_000000000006),
+ "task-standalone" => Uuid::from_u128(0x20000001_0000_0000_0000_000000000007),
+ _ => panic!("Unknown test task: {}", task_id),
+ }
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("task_linking_seed"))
+)]
+async fn link_parent_task_set_parent_on_orphan(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = PropertiesPgRepo::new(pool.clone());
+
+ // task-orphan has no parent, set it to task-parent-a
+ let orphan_id = task_uuid("task-orphan");
+ let parent_a_id = task_uuid("task-parent-a");
+
+ // Verify initial state
+ let initial_parent = get_parent(&pool, &orphan_id.to_string()).await;
+ assert_eq!(initial_parent, None);
+
+ let initial_subtasks = get_subtasks(&pool, &parent_a_id.to_string()).await;
+ assert!(!initial_subtasks.contains(&orphan_id.to_string()));
+
+ // Set parent
+ repo.link_parent_task(orphan_id, Some(parent_a_id)).await?;
+
+ // Verify: task-orphan's parent is now task-parent-a
+ let parent = get_parent(&pool, &orphan_id.to_string()).await;
+ assert_eq!(parent, Some(parent_a_id.to_string()));
+
+ // Verify: task-parent-a's subtasks now includes task-orphan
+ let subtasks = get_subtasks(&pool, &parent_a_id.to_string()).await;
+ assert!(subtasks.contains(&orphan_id.to_string()));
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("task_linking_seed"))
+)]
+async fn link_parent_task_change_parent(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = PropertiesPgRepo::new(pool.clone());
+
+ // task-child-1 has parent task-parent-a, change to task-parent-b
+ let child_1_id = task_uuid("task-child-1");
+ let parent_a_id = task_uuid("task-parent-a");
+ let parent_b_id = task_uuid("task-parent-b");
+
+ // Verify initial state
+ let initial_parent = get_parent(&pool, &child_1_id.to_string()).await;
+ assert_eq!(initial_parent, Some(parent_a_id.to_string()));
+
+ let initial_a_subtasks = get_subtasks(&pool, &parent_a_id.to_string()).await;
+ assert!(initial_a_subtasks.contains(&child_1_id.to_string()));
+
+ // Change parent
+ repo.link_parent_task(child_1_id, Some(parent_b_id)).await?;
+
+ // Verify: task-child-1's parent is now task-parent-b
+ let new_parent = get_parent(&pool, &child_1_id.to_string()).await;
+ assert_eq!(new_parent, Some(parent_b_id.to_string()));
+
+ // Verify: task-parent-a's subtasks no longer includes task-child-1
+ let a_subtasks = get_subtasks(&pool, &parent_a_id.to_string()).await;
+ assert!(!a_subtasks.contains(&child_1_id.to_string()));
+
+ // Verify: task-parent-b's subtasks now includes task-child-1
+ let b_subtasks = get_subtasks(&pool, &parent_b_id.to_string()).await;
+ assert!(b_subtasks.contains(&child_1_id.to_string()));
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("task_linking_seed"))
+)]
+async fn link_parent_task_clear_parent(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = PropertiesPgRepo::new(pool.clone());
+
+ // task-child-1 has parent task-parent-a, clear it
+ let child_1_id = task_uuid("task-child-1");
+ let parent_a_id = task_uuid("task-parent-a");
+
+ // Verify initial state
+ let initial_parent = get_parent(&pool, &child_1_id.to_string()).await;
+ assert_eq!(initial_parent, Some(parent_a_id.to_string()));
+
+ let initial_a_subtasks = get_subtasks(&pool, &parent_a_id.to_string()).await;
+ assert!(initial_a_subtasks.contains(&child_1_id.to_string()));
+
+ // Clear parent
+ repo.link_parent_task(child_1_id, None).await?;
+
+ // Verify: task-child-1's parent is now None
+ let new_parent = get_parent(&pool, &child_1_id.to_string()).await;
+ assert_eq!(new_parent, None);
+
+ // Verify: task-parent-a's subtasks no longer includes task-child-1
+ let a_subtasks = get_subtasks(&pool, &parent_a_id.to_string()).await;
+ assert!(!a_subtasks.contains(&child_1_id.to_string()));
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("task_linking_seed"))
+)]
+async fn link_parent_task_set_same_parent_is_noop(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = PropertiesPgRepo::new(pool.clone());
+
+ // task-child-1 has parent task-parent-a, set same parent
+ let child_1_id = task_uuid("task-child-1");
+ let parent_a_id = task_uuid("task-parent-a");
+
+ // Verify initial state
+ let initial_parent = get_parent(&pool, &child_1_id.to_string()).await;
+ assert_eq!(initial_parent, Some(parent_a_id.to_string()));
+
+ let initial_subtasks = get_subtasks(&pool, &parent_a_id.to_string()).await;
+ assert!(initial_subtasks.contains(&child_1_id.to_string()));
+ let initial_count = initial_subtasks.len();
+
+ // Set same parent
+ repo.link_parent_task(child_1_id, Some(parent_a_id)).await?;
+
+ // Verify: parent unchanged
+ let parent = get_parent(&pool, &child_1_id.to_string()).await;
+ assert_eq!(parent, Some(parent_a_id.to_string()));
+
+ // Verify: subtasks count unchanged (no duplicates)
+ let subtasks = get_subtasks(&pool, &parent_a_id.to_string()).await;
+ assert_eq!(subtasks.len(), initial_count);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("task_linking_seed"))
+)]
+async fn link_parent_task_nonexistent_task_is_noop(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = PropertiesPgRepo::new(pool.clone());
+
+ // Try to set parent on a task that doesn't exist
+ let nonexistent_id = Uuid::from_u128(0x99999999_9999_9999_9999_999999999999);
+ let parent_a_id = task_uuid("task-parent-a");
+
+ // Verify initial state
+ let initial_subtasks = get_subtasks(&pool, &parent_a_id.to_string()).await;
+ assert!(!initial_subtasks.contains(&nonexistent_id.to_string()));
+
+ // Should not error, just no-op
+ repo.link_parent_task(nonexistent_id, Some(parent_a_id))
+ .await?;
+
+ // Verify: task-parent-a's subtasks unchanged
+ let subtasks = get_subtasks(&pool, &parent_a_id.to_string()).await;
+ assert!(!subtasks.contains(&nonexistent_id.to_string()));
+
+ Ok(())
+}
+
+// ============================================================================
+// Task linking tests - link_subtasks
+// ============================================================================
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("task_linking_seed"))
+)]
+async fn link_subtasks_add_subtask(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = PropertiesPgRepo::new(pool.clone());
+
+ // task-parent-b has subtasks [task-child-3], add task-orphan
+ let parent_b_id = task_uuid("task-parent-b");
+ let child_3_id = task_uuid("task-child-3");
+ let orphan_id = task_uuid("task-orphan");
+
+ // Verify initial state
+ let initial_subtasks = get_subtasks(&pool, &parent_b_id.to_string()).await;
+ assert_eq!(initial_subtasks.len(), 1);
+ assert!(initial_subtasks.contains(&child_3_id.to_string()));
+
+ let initial_orphan_parent = get_parent(&pool, &orphan_id.to_string()).await;
+ assert_eq!(initial_orphan_parent, None);
+
+ // Add subtask
+ repo.link_subtasks(parent_b_id, vec![child_3_id, orphan_id])
+ .await?;
+
+ // Verify: task-parent-b's subtasks now includes both
+ let subtasks = get_subtasks(&pool, &parent_b_id.to_string()).await;
+ assert!(subtasks.contains(&child_3_id.to_string()));
+ assert!(subtasks.contains(&orphan_id.to_string()));
+
+ // Verify: task-orphan's parent is now task-parent-b
+ let orphan_parent = get_parent(&pool, &orphan_id.to_string()).await;
+ assert_eq!(orphan_parent, Some(parent_b_id.to_string()));
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("task_linking_seed"))
+)]
+async fn link_subtasks_remove_subtask(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = PropertiesPgRepo::new(pool.clone());
+
+ // task-parent-a has subtasks [task-child-1, task-child-2], remove task-child-1
+ let parent_a_id = task_uuid("task-parent-a");
+ let child_1_id = task_uuid("task-child-1");
+ let child_2_id = task_uuid("task-child-2");
+
+ // Verify initial state
+ let initial_subtasks = get_subtasks(&pool, &parent_a_id.to_string()).await;
+ assert_eq!(initial_subtasks.len(), 2);
+ assert!(initial_subtasks.contains(&child_1_id.to_string()));
+ assert!(initial_subtasks.contains(&child_2_id.to_string()));
+
+ let initial_child_1_parent = get_parent(&pool, &child_1_id.to_string()).await;
+ assert_eq!(initial_child_1_parent, Some(parent_a_id.to_string()));
+
+ // Remove subtask
+ repo.link_subtasks(parent_a_id, vec![child_2_id]).await?;
+
+ // Verify: task-parent-a's subtasks only has task-child-2
+ let subtasks = get_subtasks(&pool, &parent_a_id.to_string()).await;
+ assert!(!subtasks.contains(&child_1_id.to_string()));
+ assert!(subtasks.contains(&child_2_id.to_string()));
+
+ // Verify: task-child-1's parent is now None
+ let child_1_parent = get_parent(&pool, &child_1_id.to_string()).await;
+ assert_eq!(child_1_parent, None);
+
+ // Verify: task-child-2's parent is still task-parent-a
+ let child_2_parent = get_parent(&pool, &child_2_id.to_string()).await;
+ assert_eq!(child_2_parent, Some(parent_a_id.to_string()));
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("task_linking_seed"))
+)]
+async fn link_subtasks_clear_all(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = PropertiesPgRepo::new(pool.clone());
+
+ // task-parent-a has subtasks [task-child-1, task-child-2], clear all
+ let parent_a_id = task_uuid("task-parent-a");
+ let child_1_id = task_uuid("task-child-1");
+ let child_2_id = task_uuid("task-child-2");
+
+ // Verify initial state
+ let initial_subtasks = get_subtasks(&pool, &parent_a_id.to_string()).await;
+ assert_eq!(initial_subtasks.len(), 2);
+ assert!(initial_subtasks.contains(&child_1_id.to_string()));
+ assert!(initial_subtasks.contains(&child_2_id.to_string()));
+
+ // Clear all subtasks
+ repo.link_subtasks(parent_a_id, vec![]).await?;
+
+ // Verify: task-parent-a's subtasks is empty
+ let subtasks = get_subtasks(&pool, &parent_a_id.to_string()).await;
+ assert!(subtasks.is_empty());
+
+ // Verify: both children's parent is now None
+ let child_1_parent = get_parent(&pool, &child_1_id.to_string()).await;
+ assert_eq!(child_1_parent, None);
+
+ let child_2_parent = get_parent(&pool, &child_2_id.to_string()).await;
+ assert_eq!(child_2_parent, None);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("task_linking_seed"))
+)]
+async fn link_subtasks_steal_from_other_parent(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = PropertiesPgRepo::new(pool.clone());
+
+ // task-child-3 belongs to task-parent-b
+ // Move it to task-parent-a
+ let parent_a_id = task_uuid("task-parent-a");
+ let parent_b_id = task_uuid("task-parent-b");
+ let child_1_id = task_uuid("task-child-1");
+ let child_2_id = task_uuid("task-child-2");
+ let child_3_id = task_uuid("task-child-3");
+
+ // Verify initial state
+ let initial_child_3_parent = get_parent(&pool, &child_3_id.to_string()).await;
+ assert_eq!(initial_child_3_parent, Some(parent_b_id.to_string()));
+
+ let initial_b_subtasks = get_subtasks(&pool, &parent_b_id.to_string()).await;
+ assert!(initial_b_subtasks.contains(&child_3_id.to_string()));
+
+ let initial_a_subtasks = get_subtasks(&pool, &parent_a_id.to_string()).await;
+ assert!(!initial_a_subtasks.contains(&child_3_id.to_string()));
+
+ // Set task-parent-a's subtasks to include task-child-3 (stealing it)
+ repo.link_subtasks(parent_a_id, vec![child_1_id, child_2_id, child_3_id])
+ .await?;
+
+ // Verify: task-child-3's parent is now task-parent-a
+ let child_3_parent = get_parent(&pool, &child_3_id.to_string()).await;
+ assert_eq!(child_3_parent, Some(parent_a_id.to_string()));
+
+ // Verify: task-parent-b's subtasks no longer includes task-child-3
+ let b_subtasks = get_subtasks(&pool, &parent_b_id.to_string()).await;
+ assert!(!b_subtasks.contains(&child_3_id.to_string()));
+
+ // Verify: task-parent-a's subtasks includes all three
+ let a_subtasks = get_subtasks(&pool, &parent_a_id.to_string()).await;
+ assert!(a_subtasks.contains(&child_1_id.to_string()));
+ assert!(a_subtasks.contains(&child_2_id.to_string()));
+ assert!(a_subtasks.contains(&child_3_id.to_string()));
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("task_linking_seed"))
+)]
+async fn link_subtasks_replace_all(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = PropertiesPgRepo::new(pool.clone());
+
+ // task-parent-a has subtasks [task-child-1, task-child-2]
+ // Replace with [task-orphan, task-standalone]
+ let parent_a_id = task_uuid("task-parent-a");
+ let child_1_id = task_uuid("task-child-1");
+ let child_2_id = task_uuid("task-child-2");
+ let orphan_id = task_uuid("task-orphan");
+ let standalone_id = task_uuid("task-standalone");
+
+ // Verify initial state
+ let initial_subtasks = get_subtasks(&pool, &parent_a_id.to_string()).await;
+ assert_eq!(initial_subtasks.len(), 2);
+ assert!(initial_subtasks.contains(&child_1_id.to_string()));
+ assert!(initial_subtasks.contains(&child_2_id.to_string()));
+
+ let initial_orphan_parent = get_parent(&pool, &orphan_id.to_string()).await;
+ assert_eq!(initial_orphan_parent, None);
+
+ let initial_standalone_parent = get_parent(&pool, &standalone_id.to_string()).await;
+ assert_eq!(initial_standalone_parent, None);
+
+ // Replace all subtasks
+ repo.link_subtasks(parent_a_id, vec![orphan_id, standalone_id])
+ .await?;
+
+ // Verify: task-parent-a's subtasks is [task-orphan, task-standalone]
+ let subtasks = get_subtasks(&pool, &parent_a_id.to_string()).await;
+ assert!(!subtasks.contains(&child_1_id.to_string()));
+ assert!(!subtasks.contains(&child_2_id.to_string()));
+ assert!(subtasks.contains(&orphan_id.to_string()));
+ assert!(subtasks.contains(&standalone_id.to_string()));
+
+ // Verify: old children's parent is now None
+ let child_1_parent = get_parent(&pool, &child_1_id.to_string()).await;
+ assert_eq!(child_1_parent, None);
+
+ let child_2_parent = get_parent(&pool, &child_2_id.to_string()).await;
+ assert_eq!(child_2_parent, None);
+
+ // Verify: new children's parent is task-parent-a
+ let orphan_parent = get_parent(&pool, &orphan_id.to_string()).await;
+ assert_eq!(orphan_parent, Some(parent_a_id.to_string()));
+
+ let standalone_parent = get_parent(&pool, &standalone_id.to_string()).await;
+ assert_eq!(standalone_parent, Some(parent_a_id.to_string()));
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("task_linking_seed"))
+)]
+async fn link_subtasks_set_same_is_noop(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = PropertiesPgRepo::new(pool.clone());
+
+ // task-parent-a has subtasks [task-child-1, task-child-2], set same
+ let parent_a_id = task_uuid("task-parent-a");
+ let child_1_id = task_uuid("task-child-1");
+ let child_2_id = task_uuid("task-child-2");
+
+ // Verify initial state
+ let initial_subtasks = get_subtasks(&pool, &parent_a_id.to_string()).await;
+ assert_eq!(initial_subtasks.len(), 2);
+ assert!(initial_subtasks.contains(&child_1_id.to_string()));
+ assert!(initial_subtasks.contains(&child_2_id.to_string()));
+
+ // Set same subtasks
+ repo.link_subtasks(parent_a_id, vec![child_1_id, child_2_id])
+ .await?;
+
+ // Verify: subtasks unchanged
+ let subtasks = get_subtasks(&pool, &parent_a_id.to_string()).await;
+ assert_eq!(subtasks.len(), 2);
+ assert!(subtasks.contains(&child_1_id.to_string()));
+ assert!(subtasks.contains(&child_2_id.to_string()));
+
+ // Verify: children's parent unchanged
+ let child_1_parent = get_parent(&pool, &child_1_id.to_string()).await;
+ assert_eq!(child_1_parent, Some(parent_a_id.to_string()));
+
+ let child_2_parent = get_parent(&pool, &child_2_id.to_string()).await;
+ assert_eq!(child_2_parent, Some(parent_a_id.to_string()));
+
+ Ok(())
+}
+
+// ============================================================================
+// Validation tests - circular reference prevention
+// ============================================================================
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("task_linking_seed"))
+)]
+async fn link_parent_task_rejects_self_as_parent(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = PropertiesPgRepo::new(pool.clone());
+
+ let task_id = task_uuid("task-orphan");
+
+ // Try to set self as parent - should fail
+ let result = repo.link_parent_task(task_id, Some(task_id)).await;
+ assert!(result.is_err());
+ assert!(
+ result
+ .unwrap_err()
+ .to_string()
+ .contains("cannot be its own parent")
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("task_linking_seed"))
+)]
+async fn link_subtasks_rejects_self_as_subtask(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = PropertiesPgRepo::new(pool.clone());
+
+ let task_id = task_uuid("task-orphan");
+
+ // Try to include self in subtasks - should fail
+ let result = repo.link_subtasks(task_id, vec![task_id]).await;
+ assert!(result.is_err());
+ assert!(
+ result
+ .unwrap_err()
+ .to_string()
+ .contains("cannot be its own subtask")
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("task_linking_seed"))
+)]
+async fn link_parent_task_rejects_subtask_as_parent(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = PropertiesPgRepo::new(pool.clone());
+
+ // task-parent-a has subtasks [task-child-1, task-child-2]
+ let parent_a_id = task_uuid("task-parent-a");
+ let child_1_id = task_uuid("task-child-1");
+
+ // Try to set a subtask as parent - should fail
+ let result = repo.link_parent_task(parent_a_id, Some(child_1_id)).await;
+ assert!(result.is_err());
+ assert!(
+ result
+ .unwrap_err()
+ .to_string()
+ .contains("circular reference")
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("task_linking_seed"))
+)]
+async fn link_subtasks_rejects_parent_as_subtask(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = PropertiesPgRepo::new(pool.clone());
+
+ // task-child-1 has parent task-parent-a
+ let parent_a_id = task_uuid("task-parent-a");
+ let child_1_id = task_uuid("task-child-1");
+
+ // Try to set parent as subtask - should fail
+ let result = repo.link_subtasks(child_1_id, vec![parent_a_id]).await;
+ assert!(result.is_err());
+ assert!(
+ result
+ .unwrap_err()
+ .to_string()
+ .contains("circular reference")
+ );
+
+ Ok(())
+}
+
+// Tests for dynamically created mutual references
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("task_linking_seed"))
+)]
+async fn link_parent_then_add_as_subtask_fails(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = PropertiesPgRepo::new(pool.clone());
+
+ // Use two unrelated tasks
+ let task_orphan = task_uuid("task-orphan");
+ let task_standalone = task_uuid("task-standalone");
+
+ // Step 1: Set task-standalone as parent of task-orphan
+ // This means: task-orphan.parent = task-standalone, task-standalone.subtasks = [task-orphan]
+ repo.link_parent_task(task_orphan, Some(task_standalone))
+ .await?;
+
+ // Step 2: Now try to add task-standalone as a subtask of task-orphan
+ // This should fail because task-standalone is already task-orphan's parent
+ let result = repo.link_subtasks(task_orphan, vec![task_standalone]).await;
+ assert!(result.is_err());
+ assert!(
+ result
+ .unwrap_err()
+ .to_string()
+ .contains("circular reference")
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("task_linking_seed"))
+)]
+async fn link_subtask_then_set_as_parent_fails(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = PropertiesPgRepo::new(pool.clone());
+
+ // Use two unrelated tasks
+ let task_orphan = task_uuid("task-orphan");
+ let task_standalone = task_uuid("task-standalone");
+
+ // Step 1: Add task-standalone as a subtask of task-orphan
+ // This means: task-orphan.subtasks = [task-standalone], task-standalone.parent = task-orphan
+ repo.link_subtasks(task_orphan, vec![task_standalone])
+ .await?;
+
+ // Step 2: Now try to set task-standalone as parent of task-orphan
+ // This should fail because task-standalone is already task-orphan's subtask
+ let result = repo
+ .link_parent_task(task_orphan, Some(task_standalone))
+ .await;
+ assert!(result.is_err());
+ assert!(
+ result
+ .unwrap_err()
+ .to_string()
+ .contains("circular reference")
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("task_linking_seed"))
+)]
+async fn mutual_parent_link_fails(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = PropertiesPgRepo::new(pool.clone());
+
+ // Use two unrelated tasks
+ let task_orphan = task_uuid("task-orphan");
+ let task_standalone = task_uuid("task-standalone");
+
+ // Step 1: Set task-standalone as parent of task-orphan
+ // This means: task-orphan.parent = task-standalone, task-standalone.subtasks = [task-orphan]
+ repo.link_parent_task(task_orphan, Some(task_standalone))
+ .await?;
+
+ // Step 2: Now try to set task-orphan as parent of task-standalone
+ // This should fail because task-orphan is already in task-standalone's subtasks
+ let result = repo
+ .link_parent_task(task_standalone, Some(task_orphan))
+ .await;
+ assert!(result.is_err());
+ assert!(
+ result
+ .unwrap_err()
+ .to_string()
+ .contains("circular reference")
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("task_linking_seed"))
+)]
+async fn mutual_subtask_link_fails(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let repo = PropertiesPgRepo::new(pool.clone());
+
+ // Use two unrelated tasks
+ let task_orphan = task_uuid("task-orphan");
+ let task_standalone = task_uuid("task-standalone");
+
+ // Step 1: Add task-standalone as subtask of task-orphan
+ // This means: task-orphan.subtasks = [task-standalone], task-standalone.parent = task-orphan
+ repo.link_subtasks(task_orphan, vec![task_standalone])
+ .await?;
+
+ // Step 2: Now try to add task-orphan as subtask of task-standalone
+ // This should fail because task-orphan is already task-standalone's parent
+ let result = repo.link_subtasks(task_standalone, vec![task_orphan]).await;
+ assert!(result.is_err());
+ assert!(
+ result
+ .unwrap_err()
+ .to_string()
+ .contains("circular reference")
+ );
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/properties_service/src/api/properties/entities/set.rs b/rust/cloud-storage/properties_service/src/api/properties/entities/set.rs
index 77d2a3744f..c3e0871d6a 100644
--- a/rust/cloud-storage/properties_service/src/api/properties/entities/set.rs
+++ b/rust/cloud-storage/properties_service/src/api/properties/entities/set.rs
@@ -5,6 +5,7 @@ use axum::{
response::{IntoResponse, Response},
};
use std::collections::HashSet;
+use system_properties::SystemPropertyKey;
use thiserror::Error;
use uuid::Uuid;
@@ -12,6 +13,7 @@ use crate::api::{context::ApiContext, properties::entities::types::SetEntityProp
use model::user::UserContext;
use models_properties::service::property_value::PropertyValue;
use models_properties::{EntityReference, EntityType, api::SetPropertyValue};
+use properties::PropertiesService;
use properties_db_client::{
entity_properties::upsert as entity_properties_upsert, error::PropertiesDatabaseError,
property_definitions::get as property_definitions_get,
@@ -160,6 +162,89 @@ pub async fn set_entity_property(
tracing::debug!(has_value = has_value, "setting property in database");
+ // Handle bidirectional linking for task Parent Task / Subtasks properties
+ if entity_type == EntityType::Task
+ && (property_uuid == SystemPropertyKey::PARENT_TASK_UUID
+ || property_uuid == SystemPropertyKey::SUBTASKS_UUID)
+ {
+ let task_id = Uuid::parse_str(&entity_id)
+ .map_err(|_| SetEntityPropertyErr::InvalidRequest("Invalid task ID".to_string()))?;
+
+ if property_uuid == SystemPropertyKey::PARENT_TASK_UUID {
+ // Extract parent task ID (None to clear)
+ let parent_task_id = match &request.value {
+ None => None,
+ Some(SetPropertyValue::EntityReference { reference }) => {
+ if reference.entity_type != EntityType::Task {
+ return Err(SetEntityPropertyErr::InvalidRequest(
+ "Parent Task must reference a Task entity".to_string(),
+ ));
+ }
+ Some(Uuid::parse_str(&reference.entity_id).map_err(|_| {
+ SetEntityPropertyErr::InvalidRequest("Invalid task ID".to_string())
+ })?)
+ }
+ _ => {
+ return Err(SetEntityPropertyErr::InvalidRequest(
+ "Parent Task requires a single entity reference".to_string(),
+ ));
+ }
+ };
+
+ context
+ .properties_service
+ .link_parent_task(task_id, parent_task_id)
+ .await
+ .map_err(|e| {
+ tracing::error!(error = ?e, "failed to link parent task");
+ SetEntityPropertyErr::InternalError(anyhow::anyhow!(
+ "Failed to link parent task: {}",
+ e
+ ))
+ })?;
+ tracing::info!("successfully linked parent task");
+ } else {
+ // Extract subtask IDs (empty to clear)
+ let subtask_ids = match &request.value {
+ None => vec![],
+ Some(SetPropertyValue::MultiEntityReference { references }) => {
+ let mut ids = Vec::with_capacity(references.len());
+ for reference in references {
+ if reference.entity_type != EntityType::Task {
+ return Err(SetEntityPropertyErr::InvalidRequest(
+ "Subtasks must reference Task entities".to_string(),
+ ));
+ }
+ ids.push(Uuid::parse_str(&reference.entity_id).map_err(|_| {
+ SetEntityPropertyErr::InvalidRequest("Invalid task ID".to_string())
+ })?);
+ }
+ ids
+ }
+ _ => {
+ return Err(SetEntityPropertyErr::InvalidRequest(
+ "Subtasks requires multiple entity references".to_string(),
+ ));
+ }
+ };
+
+ context
+ .properties_service
+ .link_subtasks(task_id, subtask_ids)
+ .await
+ .map_err(|e| {
+ tracing::error!(error = ?e, "failed to link subtasks");
+ SetEntityPropertyErr::InternalError(anyhow::anyhow!(
+ "Failed to link subtasks: {}",
+ e
+ ))
+ })?;
+ tracing::info!("successfully linked subtasks");
+ }
+
+ return Ok(StatusCode::NO_CONTENT);
+ }
+
entity_properties_upsert::upsert_entity_property_values(
&context.db,
&entity_id,