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.

feat(properties): cross-entity bulk option/tag update endpoint + AI tool (#5070)

gbirman5c13bdb6570a
diff --git a/apps/web/src/lib/core/component/AI/component/tool/Properties.tsx b/apps/web/src/lib/core/component/AI/component/tool/Properties.tsx
index c5f2ed005b..c412beef4e 100644
--- a/apps/web/src/lib/core/component/AI/component/tool/Properties.tsx
+++ b/apps/web/src/lib/core/component/AI/component/tool/Properties.tsx
@@ -23,5 +23,25 @@ const setHandler = createToolRenderer({
),
});
+const bulkSetHandler = createToolRenderer({
+ name: 'BulkSetEntityPropertyOptions',
+ render: (ctx) => {
+ const count = ctx.tool.data.entities.length;
+ return (
+ <BaseTool
+ icon={PencilSimple}
+ renderContext={ctx.renderContext}
+ type="call"
+ >
+ Update a property on{' '}
+ <span class="text-ink">
+ {count} {count === 1 ? 'item' : 'items'}
+ </span>
+ </BaseTool>
+ );
+ },
+});
+
export const getEntityPropertiesHandler = getHandler;
export const setEntityPropertyHandler = setHandler;
+export const bulkSetEntityPropertyOptionsHandler = bulkSetHandler;
diff --git a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx b/apps/web/src/lib/core/component/AI/component/tool/handler.tsx
index 97b66b9741..827b17e6d3 100644
--- a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx
+++ b/apps/web/src/lib/core/component/AI/component/tool/handler.tsx
@@ -26,6 +26,7 @@ import {
markNotificationsSeenHandler,
} from './Notifications';
import {
+ bulkSetEntityPropertyOptionsHandler,
getEntityPropertiesHandler,
setEntityPropertyHandler,
} from './Properties';
@@ -96,6 +97,7 @@ const toolHandlers: ToolHandlerMap<RenderContext> = {
SendChannelMessage: sendChannelMessageHandler,
SendEmail: sendEmailHandler,
SetEntityProperty: setEntityPropertyHandler,
+ BulkSetEntityPropertyOptions: bulkSetEntityPropertyOptionsHandler,
Subagent: subagentHandler,
TextEditorCodeExecution: textEditorCodeExecutionHandler,
UpdateThreadLabels: updateThreadLabelsHandler,
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
index 5ee0134d56..63a19071dc 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
@@ -71,6 +71,41 @@ export const BashCodeExecutionResponse = z.object({
tool_use_id: z.string(),
});
+export const BulkSetEntityPropertyOptions = z.object({
+ add_option_ids: z.union([z.array(z.string().uuid()), z.null()]).default(null),
+ entities: z.array(
+ z.object({
+ entity_id: z.string(),
+ entity_type: z.enum([
+ 'document',
+ 'project',
+ 'chat',
+ 'thread',
+ 'channel',
+ 'call',
+ 'user',
+ 'company',
+ ]),
+ })
+ ),
+ property_definition_id: z.string().uuid(),
+ remove_option_ids: z
+ .union([z.array(z.string().uuid()), z.null()])
+ .default(null),
+});
+
+export const BulkSetEntityPropertyOptionsResponse = z.object({
+ results: z.array(
+ z.object({
+ entityId: z.string(),
+ entityType: z.string(),
+ error: z.union([z.string(), z.null()]).optional(),
+ status: z.string(),
+ })
+ ),
+ summary: z.string(),
+});
+
export const ContentSearch = z.object({
entityTypes: z
.array(
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts
index 6b11dcc4c5..8f6a24fec5 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts
@@ -12,6 +12,10 @@ type ToolParserMap = {
call: types.BashCodeExecution;
response: types.BashCodeExecutionResponse;
};
+ BulkSetEntityPropertyOptions: {
+ call: types.BulkSetEntityPropertyOptions;
+ response: types.BulkSetEntityPropertyOptionsResponse;
+ };
ContentSearch: {
call: types.ContentSearch;
response: types.SearchToolResponse;
@@ -129,6 +133,10 @@ const toolParserMap = {
call: schemas.BashCodeExecution,
response: schemas.BashCodeExecutionResponse,
},
+ BulkSetEntityPropertyOptions: {
+ call: schemas.BulkSetEntityPropertyOptions,
+ response: schemas.BulkSetEntityPropertyOptionsResponse,
+ },
ContentSearch: {
call: schemas.ContentSearch,
response: schemas.SearchToolResponse,
@@ -272,6 +280,10 @@ type ToolDataMap = {
call: types.BashCodeExecution;
response: types.BashCodeExecutionResponse;
};
+ BulkSetEntityPropertyOptions: {
+ call: types.BulkSetEntityPropertyOptions;
+ response: types.BulkSetEntityPropertyOptionsResponse;
+ };
ContentSearch: {
call: types.ContentSearch;
response: types.SearchToolResponse;
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
index dfa6afd2db..efe34fdb87 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
@@ -37,6 +37,18 @@ export type CodeExecutionErrorCode =
| 'too_many_requests'
| 'file_not_found'
| 'string_not_found';
+/**
+ * Canonical entity type accepted when an AI tool targets an entity's properties.
+ */
+export type ToolPropertyTargetEntityType =
+ | 'document'
+ | 'project'
+ | 'chat'
+ | 'thread'
+ | 'channel'
+ | 'call'
+ | 'user'
+ | 'company';
/**
* Viewer-relative attendance status for a call record.
* Serializes as `ATTENDED`, `MISSED`, or `UNATTENDED`.
@@ -315,18 +327,6 @@ export type EntityItem =
};
type: 'foreignEntity';
};
-/**
- * Canonical entity type accepted when an AI tool targets an entity's properties.
- */
-export type ToolPropertyTargetEntityType =
- | 'document'
- | 'project'
- | 'chat'
- | 'thread'
- | 'channel'
- | 'call'
- | 'user'
- | 'company';
/**
* Entity types that can be returned by the list entities AI tool.
*/
@@ -591,6 +591,77 @@ export interface BashCodeExecutionResponse {
content: BashCodeExecutionContent;
tool_use_id: string;
}
+/**
+ * Apply one multi-select option delta — most often a tag — to many entities in a single call. Use this instead of calling SetEntityProperty once per entity when the user asks to tag or label a set of items at once (e.g. "tag the last 50 emails as Follow-up"). Provide the property_definition_id (a tag set's propertyDefinitionId from ListTags) and the option ids to add and/or remove (a tag's option id from ListTags). The same add_option_ids/remove_option_ids delta is applied to every entity, composing atomically with concurrent edits per entity.
+ *
+ * Only for multi-select or tag properties; for other value types, or a single entity, use SetEntityProperty. Up to 200 entities per call — split larger sets across multiple calls.
+ *
+ * Best-effort: each entity is handled independently. Entities you don't have edit access to are reported with status 'skipped_no_permission' and left unchanged, entities that can't take the property are 'failed', and the rest are 'applied' — one call never fails wholesale because a few entities were not editable. Inspect the per-entity results and the summary to see what happened.
+ */
+export interface BulkSetEntityPropertyOptions {
+ /**
+ * Options to add to every entity (e.g. a tag's option id from ListTags),
+ * deduped against each entity's current value.
+ */
+ add_option_ids?: string[] | null;
+ /**
+ * The entities to update (up to 200). Entities the user can't edit are skipped.
+ */
+ entities: BulkTargetEntity[];
+ /**
+ * The multi-select property definition id changed on every entity — e.g. a
+ * tag set's propertyDefinitionId from ListTags.
+ */
+ property_definition_id: string;
+ /**
+ * Options to remove from every entity. Removing an absent option is a no-op.
+ */
+ remove_option_ids?: string[] | null;
+}
+/**
+ * One entity targeted by a bulk option update.
+ */
+export interface BulkTargetEntity {
+ /**
+ * The id of the entity.
+ */
+ entity_id: string;
+ entity_type: ToolPropertyTargetEntityType;
+}
+/**
+ * Response from the BulkSetEntityPropertyOptions tool.
+ */
+export interface BulkSetEntityPropertyOptionsResponse {
+ /**
+ * Per-entity results, aligned to the requested entities' order.
+ */
+ results: BulkSetEntityPropertyOptionsResult[];
+ /**
+ * Human-readable summary of how many entities were applied/skipped/failed.
+ */
+ summary: string;
+}
+/**
+ * One entity's result in the tool response.
+ */
+export interface BulkSetEntityPropertyOptionsResult {
+ /**
+ * The entity's id this result is for.
+ */
+ entityId: string;
+ /**
+ * The entity's type this result is for.
+ */
+ entityType: string;
+ /**
+ * A human-readable reason, present only when the status is failed.
+ */
+ error?: string | null;
+ /**
+ * One of: applied, skipped_no_permission, failed.
+ */
+ status: string;
+}
export interface CallRecordMetadata {
attended: boolean;
channel_name?: string | null;
diff --git a/apps/web/src/lib/service-clients/service-properties/generated/schemas/bulkEntityOptionUpdateResult.ts b/apps/web/src/lib/service-clients/service-properties/generated/schemas/bulkEntityOptionUpdateResult.ts
new file mode 100644
index 0000000000..dbf7b258bc
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-properties/generated/schemas/bulkEntityOptionUpdateResult.ts
@@ -0,0 +1,27 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * properties_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+import type { BulkEntityOptionUpdateResultError } from './bulkEntityOptionUpdateResultError';
+import type { BulkEntityOptionUpdateResultOptionIds } from './bulkEntityOptionUpdateResultOptionIds';
+import type { BulkEntityOptionUpdateStatus } from './bulkEntityOptionUpdateStatus';
+import type { PropertyTargetEntityType } from './propertyTargetEntityType';
+
+/**
+ * One entity's result in a cross-entity bulk option update.
+ */
+export interface BulkEntityOptionUpdateResult {
+ /** The entity's id this result is for. */
+ entity_id: string;
+ /** The entity's type this result is for. */
+ entity_type: PropertyTargetEntityType;
+ /** A human-readable reason, present only when `failed`. */
+ error?: BulkEntityOptionUpdateResultError;
+ /** The entity's reconciled final option ids, present only when `applied`. */
+ option_ids?: BulkEntityOptionUpdateResultOptionIds;
+ /** Whether the delta was applied, skipped, or failed for this entity. */
+ status: BulkEntityOptionUpdateStatus;
+}
diff --git a/apps/web/src/lib/service-clients/service-properties/generated/schemas/bulkEntityOptionUpdateResultError.ts b/apps/web/src/lib/service-clients/service-properties/generated/schemas/bulkEntityOptionUpdateResultError.ts
new file mode 100644
index 0000000000..5ecafb07ff
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-properties/generated/schemas/bulkEntityOptionUpdateResultError.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * properties_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * A human-readable reason, present only when `failed`.
+ */
+export type BulkEntityOptionUpdateResultError = string | null;
diff --git a/apps/web/src/lib/service-clients/service-properties/generated/schemas/bulkEntityOptionUpdateResultOptionIds.ts b/apps/web/src/lib/service-clients/service-properties/generated/schemas/bulkEntityOptionUpdateResultOptionIds.ts
new file mode 100644
index 0000000000..3af58e8d52
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-properties/generated/schemas/bulkEntityOptionUpdateResultOptionIds.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * properties_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The entity's reconciled final option ids, present only when `applied`.
+ */
+export type BulkEntityOptionUpdateResultOptionIds = string[] | null;
diff --git a/apps/web/src/lib/service-clients/service-properties/generated/schemas/bulkEntityOptionUpdateStatus.ts b/apps/web/src/lib/service-clients/service-properties/generated/schemas/bulkEntityOptionUpdateStatus.ts
new file mode 100644
index 0000000000..9ef70cdfec
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-properties/generated/schemas/bulkEntityOptionUpdateStatus.ts
@@ -0,0 +1,19 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * properties_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Per-entity outcome of a cross-entity bulk option update.
+ */
+export type BulkEntityOptionUpdateStatus =
+ (typeof BulkEntityOptionUpdateStatus)[keyof typeof BulkEntityOptionUpdateStatus];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const BulkEntityOptionUpdateStatus = {
+ applied: 'applied',
+ skipped_no_permission: 'skipped_no_permission',
+ failed: 'failed',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-properties/generated/schemas/bulkUpdateEntitiesPropertyOptionsRequest.ts b/apps/web/src/lib/service-clients/service-properties/generated/schemas/bulkUpdateEntitiesPropertyOptionsRequest.ts
new file mode 100644
index 0000000000..12a50a8bf4
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-properties/generated/schemas/bulkUpdateEntitiesPropertyOptionsRequest.ts
@@ -0,0 +1,23 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * properties_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { PropertyTargetReference } from './propertyTargetReference';
+
+/**
+ * Request to apply one shared option delta across several entities in a single
+call. Mirrors the per-entity bulk endpoint's delta semantics, applied to
+every listed entity (e.g. tag N emails with one label in one request).
+ */
+export interface BulkUpdateEntitiesPropertyOptionsRequest {
+ /** Options to add to each entity's current value (deduped). */
+ add_option_ids?: string[];
+ /** The entities to update. Entities the caller cannot edit are skipped. */
+ entities: PropertyTargetReference[];
+ /** The multi-select property definition changed on every entity. */
+ property_id: string;
+ /** Options to remove from each entity's current value (a no-op if absent). */
+ remove_option_ids?: string[];
+}
diff --git a/apps/web/src/lib/service-clients/service-properties/generated/schemas/bulkUpdateEntitiesPropertyOptionsResponse.ts b/apps/web/src/lib/service-clients/service-properties/generated/schemas/bulkUpdateEntitiesPropertyOptionsResponse.ts
new file mode 100644
index 0000000000..ef2a2068cf
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-properties/generated/schemas/bulkUpdateEntitiesPropertyOptionsResponse.ts
@@ -0,0 +1,16 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * properties_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { BulkEntityOptionUpdateResult } from './bulkEntityOptionUpdateResult';
+
+/**
+ * Response for a cross-entity bulk option update: one result per requested
+entity, in request order.
+ */
+export interface BulkUpdateEntitiesPropertyOptionsResponse {
+ /** Per-entity results, aligned to the request's `entities` order. */
+ results: BulkEntityOptionUpdateResult[];
+}
diff --git a/apps/web/src/lib/service-clients/service-properties/generated/zod.ts b/apps/web/src/lib/service-clients/service-properties/generated/zod.ts
index 3d41c44e4b..fe64f7e556 100644
--- a/apps/web/src/lib/service-clients/service-properties/generated/zod.ts
+++ b/apps/web/src/lib/service-clients/service-properties/generated/zod.ts
@@ -1424,6 +1424,113 @@ export const deleteEntityPropertyParams = zod.object({
entity_property_id: zod.uuid().describe('Entity Property ID'),
});
+/**
+ * Best-effort per entity: one edit receipt is minted per entity, entities the
+caller can't edit are reported as `skipped_no_permission` (mirroring the
+read path, which silently drops entities the caller can't view), and each
+permitted entity is updated in its own transaction so one entity failing
+does not roll back the others. Returns one result per requested entity in
+request order, with the reconciled final option ids for the successes.
+ * @summary Apply one shared option delta (add / remove option ids on a single
+multi-select property) to many entities in one request — e.g. tag a set of
+emails with one label.
+ */
+export const bulkUpdateEntitiesPropertyOptionsBody = zod
+ .object({
+ add_option_ids: zod
+ .array(zod.uuid())
+ .optional()
+ .describe("Options to add to each entity's current value (deduped)."),
+ entities: zod
+ .array(
+ zod
+ .object({
+ entity_id: zod.string().describe('Entity identifier.'),
+ entity_type: zod
+ .enum([
+ 'CALL_RECORD',
+ 'CHANNEL',
+ 'CHAT',
+ 'COMPANY',
+ 'DOCUMENT',
+ 'PROJECT',
+ 'THREAD',
+ 'USER',
+ ])
+ .describe(
+ 'Canonical type of an entity receiving properties.\n\nTasks are documents at API boundaries. `Task` intentionally does not exist\nhere; task classification is resolved by the properties domain from the\ndocument subtype.'
+ ),
+ })
+ .describe('Canonical reference to an entity receiving properties.')
+ )
+ .describe(
+ 'The entities to update. Entities the caller cannot edit are skipped.'
+ ),
+ property_id: zod
+ .uuid()
+ .describe(
+ 'The multi-select property definition changed on every entity.'
+ ),
+ remove_option_ids: zod
+ .array(zod.uuid())
+ .optional()
+ .describe(
+ "Options to remove from each entity's current value (a no-op if absent)."
+ ),
+ })
+ .describe(
+ "Request to apply one shared option delta across several entities in a single\ncall. Mirrors the per-entity bulk endpoint's delta semantics, applied to\nevery listed entity (e.g. tag N emails with one label in one request)."
+ );
+
+export const bulkUpdateEntitiesPropertyOptionsResponse = zod
+ .object({
+ results: zod
+ .array(
+ zod
+ .object({
+ entity_id: zod
+ .string()
+ .describe("The entity's id this result is for."),
+ entity_type: zod
+ .enum([
+ 'CALL_RECORD',
+ 'CHANNEL',
+ 'CHAT',
+ 'COMPANY',
+ 'DOCUMENT',
+ 'PROJECT',
+ 'THREAD',
+ 'USER',
+ ])
+ .describe(
+ 'Canonical type of an entity receiving properties.\n\nTasks are documents at API boundaries. `Task` intentionally does not exist\nhere; task classification is resolved by the properties domain from the\ndocument subtype.'
+ ),
+ error: zod
+ .string()
+ .nullish()
+ .describe('A human-readable reason, present only when `failed`.'),
+ option_ids: zod
+ .array(zod.uuid())
+ .nullish()
+ .describe(
+ "The entity's reconciled final option ids, present only when `applied`."
+ ),
+ status: zod
+ .enum(['applied', 'skipped_no_permission', 'failed'])
+ .describe(
+ 'Per-entity outcome of a cross-entity bulk option update.'
+ ),
+ })
+ .describe("One entity's result in a cross-entity bulk option update.")
+ )
+ .describe(
+ "Per-entity results, aligned to the request's `entities` order."
+ ),
+ })
+ .describe(
+ 'Response for a cross-entity bulk option update: one result per requested\nentity, in request order.'
+ );
+
/**
* @summary List the caller's tag sets: their personal set, plus their team's set when on a team.
Pure read - a scope with no provisioned definition yet returns an empty set.
diff --git a/apps/web/src/lib/service-clients/service-properties/openapi.json b/apps/web/src/lib/service-clients/service-properties/openapi.json
index 3b031314bf..e21f02d1c6 100644
--- a/apps/web/src/lib/service-clients/service-properties/openapi.json
+++ b/apps/web/src/lib/service-clients/service-properties/openapi.json
@@ -721,6 +721,45 @@
}
}
},
+ "/properties/options/bulk": {
+ "post": {
+ "tags": ["Properties"],
+ "summary": "Apply one shared option delta (add / remove option ids on a single\nmulti-select property) to many entities in one request — e.g. tag a set of\nemails with one label.",
+ "description": "Best-effort per entity: one edit receipt is minted per entity, entities the\ncaller can't edit are reported as `skipped_no_permission` (mirroring the\nread path, which silently drops entities the caller can't view), and each\npermitted entity is updated in its own transaction so one entity failing\ndoes not roll back the others. Returns one result per requested entity in\nrequest order, with the reconciled final option ids for the successes.",
+ "operationId": "bulk_update_entities_property_options",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/BulkUpdateEntitiesPropertyOptionsRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "Per-entity results: each entity applied, skipped, or failed",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/BulkUpdateEntitiesPropertyOptionsResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid request, the property is not multi-select, or an option does not belong to the property"
+ },
+ "401": {
+ "description": "Unauthenticated"
+ },
+ "500": {
+ "description": "Internal server error"
+ }
+ }
+ }
+ },
"/properties/tags": {
"get": {
"tags": ["Properties"],
@@ -847,6 +886,42 @@
}
}
},
+ "BulkEntityOptionUpdateResult": {
+ "type": "object",
+ "description": "One entity's result in a cross-entity bulk option update.",
+ "required": ["entity_type", "entity_id", "status"],
+ "properties": {
+ "entity_id": {
+ "type": "string",
+ "description": "The entity's id this result is for."
+ },
+ "entity_type": {
+ "$ref": "#/components/schemas/PropertyTargetEntityType",
+ "description": "The entity's type this result is for."
+ },
+ "error": {
+ "type": ["string", "null"],
+ "description": "A human-readable reason, present only when `failed`."
+ },
+ "option_ids": {
+ "type": ["array", "null"],
+ "items": {
+ "type": "string",
+ "format": "uuid"
+ },
+ "description": "The entity's reconciled final option ids, present only when `applied`."
+ },
+ "status": {
+ "$ref": "#/components/schemas/BulkEntityOptionUpdateStatus",
+ "description": "Whether the delta was applied, skipped, or failed for this entity."
+ }
+ }
+ },
+ "BulkEntityOptionUpdateStatus": {
+ "type": "string",
+ "description": "Per-entity outcome of a cross-entity bulk option update.",
+ "enum": ["applied", "skipped_no_permission", "failed"]
+ },
"BulkEntityPropertiesRequest": {
"type": "object",
"description": "Request for getting properties for multiple entities in bulk",
@@ -869,6 +944,55 @@
}
}
},
+ "BulkUpdateEntitiesPropertyOptionsRequest": {
+ "type": "object",
+ "description": "Request to apply one shared option delta across several entities in a single\ncall. Mirrors the per-entity bulk endpoint's delta semantics, applied to\nevery listed entity (e.g. tag N emails with one label in one request).",
+ "required": ["entities", "property_id"],
+ "properties": {
+ "add_option_ids": {
+ "type": "array",
+ "items": {
+ "type": "string",
+ "format": "uuid"
+ },
+ "description": "Options to add to each entity's current value (deduped)."
+ },
+ "entities": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/PropertyTargetReference"
+ },
+ "description": "The entities to update. Entities the caller cannot edit are skipped."
+ },
+ "property_id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The multi-select property definition changed on every entity."
+ },
+ "remove_option_ids": {
+ "type": "array",
+ "items": {
+ "type": "string",
+ "format": "uuid"
+ },
+ "description": "Options to remove from each entity's current value (a no-op if absent)."
+ }
+ }
+ },
+ "BulkUpdateEntitiesPropertyOptionsResponse": {
+ "type": "object",
+ "description": "Response for a cross-entity bulk option update: one result per requested\nentity, in request order.",
+ "required": ["results"],
+ "properties": {
+ "results": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/BulkEntityOptionUpdateResult"
+ },
+ "description": "Per-entity results, aligned to the request's `entities` order."
+ }
+ }
+ },
"BulkUpdateEntityPropertyOptionsRequest": {
"type": "object",
"description": "Request to apply option deltas across one or more of an entity's multi-select\nproperties in a single transaction.",
diff --git a/crates/properties/src/domain/model.rs b/crates/properties/src/domain/model.rs
index fd1653a14b..c02c8e05fb 100644
--- a/crates/properties/src/domain/model.rs
+++ b/crates/properties/src/domain/model.rs
@@ -203,6 +203,29 @@ pub struct EntityPropertyOptionSelection {
pub option_ids: Vec<Uuid>,
}
+/// The outcome of applying one shared option delta to a single entity in a
+/// cross-entity bulk update.
+///
+/// The batch is best-effort per entity: each entity gets its own transaction,
+/// so one entity failing does not roll back the others. An entity the caller
+/// could not edit never reaches the domain (its receipt was never minted), so
+/// the "skipped, no permission" case lives only at the transport/tool boundary
+/// and is not represented here.
+#[derive(Debug, Clone)]
+pub enum EntityOptionUpdateOutcome {
+ /// The delta was applied; carries the entity's reconciled final option ids.
+ Applied {
+ /// The final option ids stored for the entity's property, in stored order.
+ option_ids: Vec<Uuid>,
+ },
+ /// The delta was not applied to this entity (the property does not apply to
+ /// its type, or the write failed). Carries a human-readable reason.
+ Failed {
+ /// Why the delta was not applied.
+ message: String,
+ },
+}
+
/// Outcome of an in-place property option update.
#[derive(Debug, Clone)]
pub enum UpdatePropertyOptionOutcome {
diff --git a/crates/properties/src/domain/service.rs b/crates/properties/src/domain/service.rs
index 5dea08ebad..a42ccc1400 100644
--- a/crates/properties/src/domain/service.rs
+++ b/crates/properties/src/domain/service.rs
@@ -27,8 +27,8 @@ use uuid::Uuid;
use super::error::PropertiesErr;
use super::model::{
- EditReceipt, EntityPropertyInfo, EntityPropertyOptionSelection, EntityPropertyOptionUpdate,
- PropertyTargetKey, TagScope, TagSet, ViewReceipt,
+ EditReceipt, EntityOptionUpdateOutcome, EntityPropertyInfo, EntityPropertyOptionSelection,
+ EntityPropertyOptionUpdate, PropertyTargetKey, TagScope, TagSet, ViewReceipt,
};
/// The caller's team-membership proof, used to scope definition/option/tag
@@ -121,6 +121,26 @@ pub trait PropertiesService: Send + Sync + 'static {
updates: Vec<EntityPropertyOptionUpdate>,
) -> impl Future<Output = Result<Vec<EntityPropertyOptionSelection>, PropertiesErr>> + Send;
+ /// Apply one shared option delta to several entities at once, returning a
+ /// per-entity outcome aligned to `access` (same length and order).
+ ///
+ /// The shared delta (`add_option_ids` / `remove_option_ids` on one
+ /// multi-select `property_definition_id`) is validated once up front; a bad
+ /// property or option fails the whole call. Each entity is then updated in
+ /// its own transaction, so the batch is best-effort: an entity whose type
+ /// does not accept the property, or whose write fails, is reported as
+ /// [`EntityOptionUpdateOutcome::Failed`] without aborting the rest. Callers
+ /// mint one [`EditReceipt`] per entity at the edge and pass only the
+ /// entities the caller may edit; entities the caller cannot edit are handled
+ /// there, not here.
+ fn bulk_update_entities_property_options(
+ &self,
+ access: &[EditReceipt],
+ property_definition_id: Uuid,
+ add_option_ids: Vec<Uuid>,
+ remove_option_ids: Vec<Uuid>,
+ ) -> impl Future<Output = Result<Vec<EntityOptionUpdateOutcome>, PropertiesErr>> + Send;
+
/// List property definitions owned by the given team and/or user, sorted by
/// display name. Set `include_system` to true to also include system properties.
/// When `for_entity_type` is provided, definitions that cannot be attached to
diff --git a/crates/properties/src/domain/service_impl/mod.rs b/crates/properties/src/domain/service_impl/mod.rs
index 73a3d07143..da85b8afb0 100644
--- a/crates/properties/src/domain/service_impl/mod.rs
+++ b/crates/properties/src/domain/service_impl/mod.rs
@@ -31,9 +31,10 @@ use std::sync::Arc;
use super::error::PropertiesErr;
use super::metadata;
use super::model::{
- EditReceipt, EntityPropertyInfo, EntityPropertyOptionSelection, EntityPropertyOptionUpdate,
- PropertyAccessReceiptExt, PropertyDefinitionOwner, PropertyTargetKey, ResolvedPropertySubject,
- TagScope, TagSet, UpdatePropertyOptionOutcome, ViewReceipt,
+ EditReceipt, EntityOptionUpdateOutcome, EntityPropertyInfo, EntityPropertyOptionSelection,
+ EntityPropertyOptionUpdate, PropertyAccessReceiptExt, PropertyDefinitionOwner,
+ PropertyTargetKey, ResolvedPropertySubject, TagScope, TagSet, UpdatePropertyOptionOutcome,
+ ViewReceipt,
};
use super::ports::{NotificationService, PermissionService, PropertiesRepo, PropertySearchIndexer};
use super::service::{PropertiesService, TeamReceipt, team_id_from_receipt};
@@ -641,6 +642,128 @@ where
Ok(selections)
}
+ #[tracing::instrument(
+ skip(self, access, add_option_ids, remove_option_ids),
+ fields(
+ entity_count = access.len(),
+ property_definition_id = %property_definition_id,
+ add_count = add_option_ids.len(),
+ remove_count = remove_option_ids.len(),
+ ),
+ err
+ )]
+ async fn bulk_update_entities_property_options(
+ &self,
+ access: &[EditReceipt],
+ property_definition_id: Uuid,
+ add_option_ids: Vec<Uuid>,
+ remove_option_ids: Vec<Uuid>,
+ ) -> Result<Vec<EntityOptionUpdateOutcome>, PropertiesErr> {
+ // Validate the shared delta once. A missing property, a single-select
+ // property, or an invalid added option is a client error in the request
+ // itself, so it fails the whole call rather than producing per-entity
+ // failures.
+ let property_definition = self
+ .repository
+ .get_property_definition(property_definition_id)
+ .await
+ .map_err(anyhow::Error::from)?
+ .ok_or_else(|| {
+ PropertiesErr::Validation(format!(
+ "Property definition not found: {}",
+ property_definition_id
+ ))
+ })?;
+
+ if !property_definition.is_multi_select {
+ return Err(PropertiesErr::Validation(
+ "Option add/remove is only supported for multi-select properties".to_string(),
+ ));
+ }
+
+ // Only additions need option validation; removing an unknown id is a
+ // harmless no-op. Dedupe first so a repeated id is not miscounted.
+ let mut validated_add_ids = add_option_ids.clone();
+ validated_add_ids.sort();
+ validated_add_ids.dedup();
+ self.validate_property_options(property_definition_id, &validated_add_ids)
+ .await?;
+
+ // Resolve every subject in one batch (one document-subtype lookup).
+ let subjects = self.resolve_subjects(access).await?;
+
+ let update = EntityPropertyOptionUpdate {
+ property_definition_id,
+ add_option_ids,
+ remove_option_ids,
+ };
+
+ // Acquire per-entity row locks in a consistent order across callers so
+ // two cross-entity updates touching overlapping entities can't deadlock.
+ // Each entity is its own transaction, so outcomes are still returned
+ // aligned to the input order.
+ let mut order: Vec<usize> = (0..subjects.len()).collect();
+ order.sort_by_key(|&index| {
+ (
+ subjects[index].canonical_key.entity_id.clone(),
+ format!("{:?}", subjects[index].storage_entity_type),
+ )
+ });
+
+ let mut outcomes: Vec<Option<EntityOptionUpdateOutcome>> =
+ (0..subjects.len()).map(|_| None).collect();
+ for index in order {
+ let subject = &subjects[index];
+ let entity_id = subject.canonical_key.entity_id.as_str();
+ let entity_type = subject.storage_entity_type;
+
+ if !is_property_applicable_to(property_definition_id, entity_type) {
+ outcomes[index] = Some(EntityOptionUpdateOutcome::Failed {
+ message: "This property cannot be attached to this entity type".to_string(),
+ });
+ continue;
+ }
+
+ // Convert the repo error to a Send type up front so the raw
+ // `R::Err` is never held across the reindex await below.
+ let update_result = self
+ .repository
+ .bulk_update_entity_property_options(
+ entity_id,
+ entity_type,
+ std::slice::from_ref(&update),
+ )
+ .await
+ .map_err(anyhow::Error::from);
+
+ match update_result {
+ Ok(mut selections) => {
+ let option_ids = selections
+ .pop()
+ .map(|selection| selection.option_ids)
+ .unwrap_or_default();
+ self.enqueue_property_upsert(entity_id, entity_type).await;
+ outcomes[index] = Some(EntityOptionUpdateOutcome::Applied { option_ids });
+ }
+ Err(error) => {
+ tracing::warn!(
+ error = ?error,
+ entity_id = %entity_id,
+ "failed to apply bulk option delta to entity"
+ );
+ outcomes[index] = Some(EntityOptionUpdateOutcome::Failed {
+ message: error.to_string(),
+ });
+ }
+ }
+ }
+
+ Ok(outcomes
+ .into_iter()
+ .map(|outcome| outcome.expect("every subject yields an outcome"))
+ .collect())
+ }
+
#[tracing::instrument(skip(self, team), err)]
async fn list_property_definitions(
&self,
diff --git a/crates/properties/src/domain/test.rs b/crates/properties/src/domain/test.rs
index 4f53776eb9..20d00ed06b 100644
--- a/crates/properties/src/domain/test.rs
+++ b/crates/properties/src/domain/test.rs
@@ -1681,3 +1681,255 @@ async fn test_bulk_update_entity_property_options_dedupes_added_options() {
.await
.unwrap();
}
+
+// ============================================================================
+// Cross-entity bulk option updates - bulk_update_entities_property_options
+// ============================================================================
+
+#[tokio::test]
+async fn test_bulk_update_entities_applies_delta_in_input_order() {
+ use crate::domain::model::{EntityOptionUpdateOutcome, EntityPropertyOptionSelection};
+
+ let def_id = Uuid::from_u128(0xA1);
+ let add_id = Uuid::from_u128(0xB2);
+ // Distinct stored marker per entity so alignment to input order is provable.
+ let final_c = Uuid::from_u128(0xC0);
+ let final_a = Uuid::from_u128(0xC1);
+ let final_b = Uuid::from_u128(0xC2);
+
+ let mut repo = MockPropertiesRepo::new();
+ repo.expect_get_property_definition().returning(move |_| {
+ Box::pin(async move { Ok(Some(multi_select_definition(def_id, true))) })
+ });
+ repo.expect_count_valid_property_options()
+ .returning(|_, _| Box::pin(async { Ok(1) }));
+ repo.expect_get_document_sub_types()
+ .returning(|_| Box::pin(async { Ok(HashMap::new()) }));
+ repo.expect_bulk_update_entity_property_options()
+ .times(3)
+ .returning(move |entity_id, _, _| {
+ let final_id = match entity_id {
+ "cid" => final_c,
+ "aid" => final_a,
+ "bid" => final_b,
+ other => panic!("unexpected entity {other}"),
+ };
+ Box::pin(async move {
+ Ok(vec![EntityPropertyOptionSelection {
+ property_definition_id: def_id,
+ option_ids: vec![final_id],
+ }])
+ })
+ });
+
+ let service = PropertiesServiceImpl::new(
+ repo,
+ Some(create_mock_permission_service()),
+ None::<MockNotificationService>,
+ );
+
+ // Input order (cid, aid, bid) differs from the sorted lock order (aid, bid,
+ // cid); outcomes must still come back aligned to the input.
+ let receipts = vec![
+ edit_receipt("cid", EntityType::Document),
+ edit_receipt("aid", EntityType::Document),
+ edit_receipt("bid", EntityType::Document),
+ ];
+ let outcomes = service
+ .bulk_update_entities_property_options(&receipts, def_id, vec![add_id], vec![])
+ .await
+ .unwrap();
+
+ assert_eq!(outcomes.len(), 3);
+ assert!(matches!(
+ &outcomes[0],
+ EntityOptionUpdateOutcome::Applied { option_ids } if *option_ids == vec![final_c]
+ ));
+ assert!(matches!(
+ &outcomes[1],
+ EntityOptionUpdateOutcome::Applied { option_ids } if *option_ids == vec![final_a]
+ ));
+ assert!(matches!(
+ &outcomes[2],
+ EntityOptionUpdateOutcome::Applied { option_ids } if *option_ids == vec![final_b]
+ ));
+}
+
+#[tokio::test]
+async fn test_bulk_update_entities_is_best_effort_on_per_entity_write_failure() {
+ use crate::domain::model::{EntityOptionUpdateOutcome, EntityPropertyOptionSelection};
+
+ let def_id = Uuid::from_u128(0xA1);
+ let add_id = Uuid::from_u128(0xB2);
+
+ let mut repo = MockPropertiesRepo::new();
+ repo.expect_get_property_definition().returning(move |_| {
+ Box::pin(async move { Ok(Some(multi_select_definition(def_id, true))) })
+ });
+ repo.expect_count_valid_property_options()
+ .returning(|_, _| Box::pin(async { Ok(1) }));
+ repo.expect_get_document_sub_types()
+ .returning(|_| Box::pin(async { Ok(HashMap::new()) }));
+ // One entity's write fails; the other must still be attempted and succeed.
+ repo.expect_bulk_update_entity_property_options()
+ .times(2)
+ .returning(move |entity_id, _, _| {
+ if entity_id == "doc-bad" {
+ Box::pin(async { Err(anyhow!("write blew up")) })
+ } else {
+ Box::pin(async move {
+ Ok(vec![EntityPropertyOptionSelection {
+ property_definition_id: def_id,
+ option_ids: vec![add_id],
+ }])
+ })
+ }
+ });
+
+ let service = PropertiesServiceImpl::new(
+ repo,
+ Some(create_mock_permission_service()),
+ None::<MockNotificationService>,
+ );
+
+ let receipts = vec![
+ edit_receipt("doc-good", EntityType::Document),
+ edit_receipt("doc-bad", EntityType::Document),
+ ];
+ let outcomes = service
+ .bulk_update_entities_property_options(&receipts, def_id, vec![add_id], vec![])
+ .await
+ .unwrap();
+
+ assert!(matches!(
+ &outcomes[0],
+ EntityOptionUpdateOutcome::Applied { option_ids } if *option_ids == vec![add_id]
+ ));
+ assert!(matches!(
+ &outcomes[1],
+ EntityOptionUpdateOutcome::Failed { .. }
+ ));
+}
+
+#[tokio::test]
+async fn test_bulk_update_entities_fails_entity_that_rejects_property_type() {
+ use crate::domain::model::{EntityOptionUpdateOutcome, EntityPropertyOptionSelection};
+
+ // A company-only property (Stage) applies to a company but not a document.
+ let def_id = SystemPropertyKey::STAGE_UUID;
+ let add_id = Uuid::from_u128(0xB2);
+
+ let mut repo = MockPropertiesRepo::new();
+ repo.expect_get_property_definition().returning(move |_| {
+ Box::pin(async move { Ok(Some(multi_select_definition(def_id, true))) })
+ });
+ repo.expect_count_valid_property_options()
+ .returning(|_, _| Box::pin(async { Ok(1) }));
+ repo.expect_get_document_sub_types()
+ .returning(|_| Box::pin(async { Ok(HashMap::new()) }));
+ // Only the company is a valid target, so exactly one write is attempted.
+ repo.expect_bulk_update_entity_property_options()
+ .times(1)
+ .withf(|entity_id, _, _| entity_id == "company1")
+ .returning(move |_, _, _| {
+ Box::pin(async move {
+ Ok(vec![EntityPropertyOptionSelection {
+ property_definition_id: def_id,
+ option_ids: vec![add_id],
+ }])
+ })
+ });
+
+ let service = PropertiesServiceImpl::new(
+ repo,
+ Some(create_mock_permission_service()),
+ None::<MockNotificationService>,
+ );
+
+ let receipts = vec![
+ edit_receipt("company1", EntityType::Company),
+ edit_receipt("doc1", EntityType::Document),
+ ];
+ let outcomes = service
+ .bulk_update_entities_property_options(&receipts, def_id, vec![add_id], vec![])
+ .await
+ .unwrap();
+
+ assert!(matches!(
+ &outcomes[0],
+ EntityOptionUpdateOutcome::Applied { .. }
+ ));
+ assert!(matches!(
+ &outcomes[1],
+ EntityOptionUpdateOutcome::Failed { .. }
+ ));
+}
+
+#[tokio::test]
+async fn test_bulk_update_entities_rejects_single_select_wholesale() {
+ let def_id = Uuid::from_u128(0xA1);
+
+ let mut repo = MockPropertiesRepo::new();
+ repo.expect_get_property_definition().returning(move |_| {
+ Box::pin(async move { Ok(Some(multi_select_definition(def_id, false))) })
+ });
+ // A bad shared delta must abort before any entity is touched.
+ repo.expect_bulk_update_entity_property_options().never();
+
+ let service = PropertiesServiceImpl::new(
+ repo,
+ Some(create_mock_permission_service()),
+ None::<MockNotificationService>,
+ );
+
+ let receipts = vec![edit_receipt("doc1", EntityType::Document)];
+ let err = service
+ .bulk_update_entities_property_options(
+ &receipts,
+ def_id,
+ vec![Uuid::from_u128(0xB2)],
+ vec![],
+ )
+ .await
+ .unwrap_err();
+
+ assert!(matches!(
+ err,
+ crate::domain::error::PropertiesErr::Validation(_)
+ ));
+}
+
+#[tokio::test]
+async fn test_bulk_update_entities_rejects_invalid_option_wholesale() {
+ let def_id = Uuid::from_u128(0xA1);
+
+ let mut repo = MockPropertiesRepo::new();
+ repo.expect_get_property_definition().returning(move |_| {
+ Box::pin(async move { Ok(Some(multi_select_definition(def_id, true))) })
+ });
+ repo.expect_count_valid_property_options()
+ .returning(|_, _| Box::pin(async { Ok(0) }));
+ repo.expect_bulk_update_entity_property_options().never();
+
+ let service = PropertiesServiceImpl::new(
+ repo,
+ Some(create_mock_permission_service()),
+ None::<MockNotificationService>,
+ );
+
+ let receipts = vec![edit_receipt("doc1", EntityType::Document)];
+ let err = service
+ .bulk_update_entities_property_options(
+ &receipts,
+ def_id,
+ vec![Uuid::from_u128(0xB2)],
+ vec![],
+ )
+ .await
+ .unwrap_err();
+
+ assert!(matches!(
+ err,
+ crate::domain::error::PropertiesErr::Validation(_)
+ ));
+}
diff --git a/crates/properties/src/inbound/axum_router.rs b/crates/properties/src/inbound/axum_router.rs
index 380d76b62e..f7892f74ad 100644
--- a/crates/properties/src/inbound/axum_router.rs
+++ b/crates/properties/src/inbound/axum_router.rs
@@ -161,6 +161,12 @@ where
"/entities/{entity_type}/{entity_id}/options/bulk",
post(entities::bulk_update_entity_property_options::<S, A, Auth>),
)
+ // Cross-entity option delta: one shared delta applied to many entities
+ // (e.g. tag N emails with one label), best-effort per entity
+ .route(
+ "/options/bulk",
+ post(entities::bulk_update_entities_property_options::<S, A, Auth>),
+ )
.route(
"/entity_properties/{entity_property_id}",
delete(entities::delete_entity_property::<S, A, Auth>),
diff --git a/crates/properties/src/inbound/axum_router/entities.rs b/crates/properties/src/inbound/axum_router/entities.rs
index 56d0838665..4fd85e9422 100644
--- a/crates/properties/src/inbound/axum_router/entities.rs
+++ b/crates/properties/src/inbound/axum_router/entities.rs
@@ -27,8 +27,8 @@ use super::extract::{EditReceiptExtractor, ViewReceiptExtractor};
use super::extract::{mint_authenticated_receipt, mint_view_receipt, target_entity_type};
use super::{PropertiesRouterState, properties_err_status};
use crate::domain::error::PropertiesErr;
-use crate::domain::model::EntityPropertyOptionUpdate;
use crate::domain::model::PropertyAccessReceiptExt;
+use crate::domain::model::{EditReceipt, EntityOptionUpdateOutcome, EntityPropertyOptionUpdate};
use crate::domain::service::PropertiesService;
#[cfg(test)]
@@ -667,6 +667,229 @@ pub async fn bulk_update_entity_property_options<
}))
}
+/// Request to apply one shared option delta across several entities in a single
+/// call. Mirrors the per-entity bulk endpoint's delta semantics, applied to
+/// every listed entity (e.g. tag N emails with one label in one request).
+#[derive(Debug, Serialize, Deserialize, ToSchema)]
+pub struct BulkUpdateEntitiesPropertyOptionsRequest {
+ /// The entities to update. Entities the caller cannot edit are skipped.
+ pub entities: Vec<PropertyTargetReference>,
+ /// The multi-select property definition changed on every entity.
+ pub property_id: Uuid,
+ /// Options to add to each entity's current value (deduped).
+ #[serde(default)]
+ pub add_option_ids: Vec<Uuid>,
+ /// Options to remove from each entity's current value (a no-op if absent).
+ #[serde(default)]
+ pub remove_option_ids: Vec<Uuid>,
+}
+
+/// Per-entity outcome of a cross-entity bulk option update.
+#[derive(Debug, Serialize, Deserialize, ToSchema, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum BulkEntityOptionUpdateStatus {
+ /// The delta was applied to the entity.
+ Applied,
+ /// The caller lacks edit access to the entity; it was left unchanged.
+ SkippedNoPermission,
+ /// The delta could not be applied (wrong entity type, or a write failure).
+ Failed,
+}
+
+/// One entity's result in a cross-entity bulk option update.
+#[derive(Debug, Serialize, Deserialize, ToSchema)]
+pub struct BulkEntityOptionUpdateResult {
+ /// The entity's type this result is for.
+ pub entity_type: PropertyTargetEntityType,
+ /// The entity's id this result is for.
+ pub entity_id: String,
+ /// Whether the delta was applied, skipped, or failed for this entity.
+ pub status: BulkEntityOptionUpdateStatus,
+ /// The entity's reconciled final option ids, present only when `applied`.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub option_ids: Option<Vec<Uuid>>,
+ /// A human-readable reason, present only when `failed`.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub error: Option<String>,
+}
+
+/// Response for a cross-entity bulk option update: one result per requested
+/// entity, in request order.
+#[derive(Debug, Serialize, Deserialize, ToSchema)]
+pub struct BulkUpdateEntitiesPropertyOptionsResponse {
+ /// Per-entity results, aligned to the request's `entities` order.
+ pub results: Vec<BulkEntityOptionUpdateResult>,
+}
+
+#[derive(Debug, Error)]
+pub enum BulkUpdateEntitiesPropertyOptionsErr {
+ #[error(transparent)]
+ Properties(#[from] PropertiesErr),
+ #[error("Cannot update more than {MAX_BULK_ENTITIES} entities at once")]
+ TooManyEntities,
+ #[error("Cannot change more than {MAX_OPTION_IDS_PER_PROPERTY} options at once")]
+ TooManyOptions,
+}
+
+impl IntoResponse for BulkUpdateEntitiesPropertyOptionsErr {
+ fn into_response(self) -> Response {
+ let status_code = match &self {
+ BulkUpdateEntitiesPropertyOptionsErr::Properties(e) => properties_err_status(e),
+ BulkUpdateEntitiesPropertyOptionsErr::TooManyEntities
+ | BulkUpdateEntitiesPropertyOptionsErr::TooManyOptions => StatusCode::BAD_REQUEST,
+ };
+
+ if status_code.is_server_error() {
+ tracing::error!(
+ error = ?self,
+ error_type = "BulkUpdateEntitiesPropertyOptionsErr",
+ "Internal server error"
+ );
+ }
+
+ (status_code, self.to_string()).into_response()
+ }
+}
+
+/// Reject oversized requests before any permission checks or database work, so
+/// one authenticated call can't force unbounded receipt-minting and lock work.
+fn validate_bulk_entities_option_request(
+ request: &BulkUpdateEntitiesPropertyOptionsRequest,
+) -> Result<(), BulkUpdateEntitiesPropertyOptionsErr> {
+ if request.entities.len() > MAX_BULK_ENTITIES {
+ return Err(BulkUpdateEntitiesPropertyOptionsErr::TooManyEntities);
+ }
+ if request.add_option_ids.len() + request.remove_option_ids.len() > MAX_OPTION_IDS_PER_PROPERTY
+ {
+ return Err(BulkUpdateEntitiesPropertyOptionsErr::TooManyOptions);
+ }
+ Ok(())
+}
+
+/// Apply one shared option delta (add / remove option ids on a single
+/// multi-select property) to many entities in one request — e.g. tag a set of
+/// emails with one label.
+///
+/// Best-effort per entity: one edit receipt is minted per entity, entities the
+/// caller can't edit are reported as `skipped_no_permission` (mirroring the
+/// read path, which silently drops entities the caller can't view), and each
+/// permitted entity is updated in its own transaction so one entity failing
+/// does not roll back the others. Returns one result per requested entity in
+/// request order, with the reconciled final option ids for the successes.
+#[utoipa::path(
+ post,
+ path = "/properties/options/bulk",
+ request_body = BulkUpdateEntitiesPropertyOptionsRequest,
+ responses(
+ (status = 200, description = "Per-entity results: each entity applied, skipped, or failed", body = BulkUpdateEntitiesPropertyOptionsResponse),
+ (status = 400, description = "Invalid request, the property is not multi-select, or an option does not belong to the property"),
+ (status = 401, description = "Unauthenticated"),
+ (status = 500, description = "Internal server error")
+ ),
+ tags = ["Properties"]
+)]
+#[tracing::instrument(skip(state, request, user), fields(entity_count = request.entities.len(), property_id = %request.property_id), err)]
+pub async fn bulk_update_entities_property_options<
+ S: PropertiesService,
+ A: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<PropertiesRouterState<S, A, Auth>>,
+ MacroAuthorizationExtractor {
+ macro_user_id: user,
+ ..
+ }: MacroAuthorizationExtractor<Auth>,
+ Json(request): Json<BulkUpdateEntitiesPropertyOptionsRequest>,
+) -> Result<Json<BulkUpdateEntitiesPropertyOptionsResponse>, BulkUpdateEntitiesPropertyOptionsErr> {
+ tracing::info!("bulk updating property options across entities");
+
+ validate_bulk_entities_option_request(&request)?;
+
+ let BulkUpdateEntitiesPropertyOptionsRequest {
+ entities,
+ property_id,
+ add_option_ids,
+ remove_option_ids,
+ } = request;
+
+ // Mint one edit receipt per entity. Entities the caller can't edit are
+ // recorded as skipped and never handed to the service.
+ let mut results: Vec<Option<BulkEntityOptionUpdateResult>> =
+ (0..entities.len()).map(|_| None).collect();
+ let mut receipts: Vec<EditReceipt> = Vec::new();
+ let mut granted_indices: Vec<usize> = Vec::new();
+
+ for (index, entity_ref) in entities.iter().enumerate() {
+ match mint_authenticated_receipt::<EditAccessLevel, A>(
+ state.entity_access_service.as_ref(),
+ &user,
+ &entity_ref.entity_id,
+ target_entity_type(entity_ref.entity_type),
+ )
+ .await
+ {
+ Ok(receipt) => {
+ receipts.push(receipt);
+ granted_indices.push(index);
+ }
+ Err(error) => {
+ tracing::debug!(
+ entity_id = %entity_ref.entity_id,
+ entity_type = ?entity_ref.entity_type,
+ error = ?error,
+ "user lacks edit permission, skipping entity"
+ );
+ results[index] = Some(BulkEntityOptionUpdateResult {
+ entity_type: entity_ref.entity_type,
+ entity_id: entity_ref.entity_id.clone(),
+ status: BulkEntityOptionUpdateStatus::SkippedNoPermission,
+ option_ids: None,
+ error: None,
+ });
+ }
+ }
+ }
+
+ if !receipts.is_empty() {
+ let outcomes = state
+ .properties_service
+ .bulk_update_entities_property_options(
+ &receipts,
+ property_id,
+ add_option_ids,
+ remove_option_ids,
+ )
+ .await?;
+
+ for (index, outcome) in granted_indices.into_iter().zip(outcomes) {
+ let entity_ref = &entities[index];
+ results[index] = Some(match outcome {
+ EntityOptionUpdateOutcome::Applied { option_ids } => BulkEntityOptionUpdateResult {
+ entity_type: entity_ref.entity_type,
+ entity_id: entity_ref.entity_id.clone(),
+ status: BulkEntityOptionUpdateStatus::Applied,
+ option_ids: Some(option_ids),
+ error: None,
+ },
+ EntityOptionUpdateOutcome::Failed { message } => BulkEntityOptionUpdateResult {
+ entity_type: entity_ref.entity_type,
+ entity_id: entity_ref.entity_id.clone(),
+ status: BulkEntityOptionUpdateStatus::Failed,
+ option_ids: None,
+ error: Some(message),
+ },
+ });
+ }
+ }
+
+ let results = results
+ .into_iter()
+ .map(|result| result.expect("every entity yields a result"))
+ .collect();
+
+ Ok(Json(BulkUpdateEntitiesPropertyOptionsResponse { results }))
+}
+
#[derive(Debug, Error)]
pub enum DeleteEntityPropertyErr {
#[error(transparent)]
diff --git a/crates/properties/src/inbound/axum_router/entities/test.rs b/crates/properties/src/inbound/axum_router/entities/test.rs
index 39740f7474..7d04dbe183 100644
--- a/crates/properties/src/inbound/axum_router/entities/test.rs
+++ b/crates/properties/src/inbound/axum_router/entities/test.rs
@@ -51,3 +51,47 @@ fn validate_bulk_option_request_rejects_too_many_options() {
Err(BulkUpdateEntityPropertyOptionsErr::TooManyOptions)
));
}
+
+fn entity_ref() -> PropertyTargetReference {
+ PropertyTargetReference {
+ entity_id: Uuid::new_v4().to_string(),
+ entity_type: PropertyTargetEntityType::Document,
+ }
+}
+
+fn entities_request(
+ entities: usize,
+ add: usize,
+ remove: usize,
+) -> BulkUpdateEntitiesPropertyOptionsRequest {
+ BulkUpdateEntitiesPropertyOptionsRequest {
+ entities: (0..entities).map(|_| entity_ref()).collect(),
+ property_id: Uuid::new_v4(),
+ add_option_ids: (0..add).map(|_| Uuid::new_v4()).collect(),
+ remove_option_ids: (0..remove).map(|_| Uuid::new_v4()).collect(),
+ }
+}
+
+#[test]
+fn validate_bulk_entities_option_request_accepts_bounded() {
+ let request = entities_request(MAX_BULK_ENTITIES, 3, 2);
+ assert!(validate_bulk_entities_option_request(&request).is_ok());
+}
+
+#[test]
+fn validate_bulk_entities_option_request_rejects_too_many_entities() {
+ let request = entities_request(MAX_BULK_ENTITIES + 1, 1, 0);
+ assert!(matches!(
+ validate_bulk_entities_option_request(&request),
+ Err(BulkUpdateEntitiesPropertyOptionsErr::TooManyEntities)
+ ));
+}
+
+#[test]
+fn validate_bulk_entities_option_request_rejects_too_many_options() {
+ let request = entities_request(1, MAX_OPTION_IDS_PER_PROPERTY, 1);
+ assert!(matches!(
+ validate_bulk_entities_option_request(&request),
+ Err(BulkUpdateEntitiesPropertyOptionsErr::TooManyOptions)
+ ));
+}
diff --git a/crates/properties/src/inbound/axum_router/test.rs b/crates/properties/src/inbound/axum_router/test.rs
index e3d4be148b..d3d7b29afb 100644
--- a/crates/properties/src/inbound/axum_router/test.rs
+++ b/crates/properties/src/inbound/axum_router/test.rs
@@ -93,6 +93,12 @@ impl EntityAccessService for FakeEntityAccessService {
entity_type,
});
+ // Entities whose id contains "denied" model the caller lacking access,
+ // so receipt-minting fails for them (used by the bulk skip test).
+ if entity_id.contains("denied") {
+ return Err(AccessError::Unauthorized);
+ }
+
let user_id = MacroUserIdStr::try_from(user_id.as_ref().to_string())
.expect("authorized test user id should be valid");
Ok(EntityAccessReceipt::dangerously_assert_authenticated_user(
@@ -459,3 +465,103 @@ async fn malformed_typed_path_is_rejected_before_missing_authentication() {
"Missing or invalid entity_type / entity_id in path"
);
}
+
+fn multi_select_def(
+ id: Uuid,
+) -> models_properties::service::property_definition::PropertyDefinition {
+ models_properties::service::property_definition::PropertyDefinition {
+ id,
+ owner: models_properties::PropertyOwner::System,
+ display_name: "Tags".to_string(),
+ data_type: models_properties::DataType::SelectString,
+ is_multi_select: true,
+ specific_entity_type: None,
+ created_at: chrono::Utc::now(),
+ updated_at: chrono::Utc::now(),
+ is_system: false,
+ is_metadata: false,
+ }
+}
+
+/// Builds the full properties router over a mock-repo service so the bulk
+/// cross-entity endpoint can be exercised end to end.
+fn properties_router(
+ service: TestPropertiesService,
+ entity_access_service: FakeEntityAccessService,
+) -> Router {
+ let state = PropertiesRouterState::new(
+ Arc::new(service),
+ Arc::new(entity_access_service),
+ authorization_state(),
+ );
+ super::router::<TestPropertiesService, FakeEntityAccessService, TestAuthorizationService>()
+ .with_state(state)
+}
+
+#[tokio::test]
+async fn bulk_options_across_entities_skips_denied_and_applies_granted() {
+ use crate::domain::model::EntityPropertyOptionSelection;
+
+ let property_id = Uuid::new_v4();
+ let option_id = Uuid::new_v4();
+
+ let mut repo = MockPropertiesRepo::new();
+ repo.expect_get_property_definition()
+ .returning(move |_| Box::pin(async move { Ok(Some(multi_select_def(property_id))) }));
+ repo.expect_count_valid_property_options()
+ .returning(|_, _| Box::pin(async { Ok(1) }));
+ // Only the granted entity reaches the write path.
+ repo.expect_bulk_update_entity_property_options()
+ .times(1)
+ .withf(|entity_id, _, _| entity_id == "doc-granted")
+ .returning(move |_, _, _| {
+ Box::pin(async move {
+ Ok(vec![EntityPropertyOptionSelection {
+ property_definition_id: property_id,
+ option_ids: vec![option_id],
+ }])
+ })
+ });
+
+ let service = PropertiesServiceImpl::new(
+ repo,
+ None::<MockPermissionService>,
+ None::<MockNotificationService>,
+ );
+ let router = properties_router(service, FakeEntityAccessService::default());
+
+ let body = serde_json::json!({
+ "entities": [
+ {"entity_type": "DOCUMENT", "entity_id": "doc-denied"},
+ {"entity_type": "DOCUMENT", "entity_id": "doc-granted"},
+ ],
+ "property_id": property_id,
+ "add_option_ids": [option_id],
+ "remove_option_ids": [],
+ });
+ let request = Request::builder()
+ .method("POST")
+ .uri("/options/bulk")
+ .header(header::AUTHORIZATION, "Bearer valid")
+ .header(header::CONTENT_TYPE, "application/json")
+ .body(Body::from(body.to_string()))
+ .expect("request should be valid");
+
+ let response = router
+ .oneshot(request)
+ .await
+ .expect("request should complete");
+ assert_eq!(response.status(), StatusCode::OK);
+
+ let json: serde_json::Value =
+ serde_json::from_str(&response_body(response).await).expect("json body");
+ let results = json["results"].as_array().expect("results array");
+ assert_eq!(results.len(), 2, "one result per requested entity");
+
+ // Results are returned in request order.
+ assert_eq!(results[0]["entity_id"], "doc-denied");
+ assert_eq!(results[0]["status"], "skipped_no_permission");
+ assert_eq!(results[1]["entity_id"], "doc-granted");
+ assert_eq!(results[1]["status"], "applied");
+ assert_eq!(results[1]["option_ids"], serde_json::json!([option_id]));
+}
diff --git a/crates/properties/src/inbound/toolset/bulk_set_entity_property_options.rs b/crates/properties/src/inbound/toolset/bulk_set_entity_property_options.rs
new file mode 100644
index 0000000000..6938d07c40
--- /dev/null
+++ b/crates/properties/src/inbound/toolset/bulk_set_entity_property_options.rs
@@ -0,0 +1,225 @@
+//! BulkSetEntityPropertyOptions tool: apply one option delta (e.g. a tag) to
+//! many entities in a single call.
+
+use crate::domain::model::{EditReceipt, EntityOptionUpdateOutcome};
+use crate::domain::service::PropertiesService;
+use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};
+use async_trait::async_trait;
+use entity_access::domain::models::EditAccessLevel;
+use entity_access::domain::ports::EntityAccessService;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+use super::PropertiesToolContext;
+use super::get_entity_properties::ToolPropertyTargetEntityType;
+
+/// The most entities one call may target. Mirrors the HTTP endpoint's cap.
+const MAX_BULK_ENTITIES: usize = 200;
+
+/// One entity targeted by a bulk option update.
+#[derive(Debug, Clone, Deserialize, JsonSchema)]
+#[serde(rename_all = "snake_case")]
+pub struct BulkTargetEntity {
+ /// The type of entity. Tasks are targeted as 'document'.
+ pub entity_type: ToolPropertyTargetEntityType,
+ /// The id of the entity.
+ pub entity_id: String,
+}
+
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(
+ title = "BulkSetEntityPropertyOptions",
+ description = "Apply one multi-select option delta — most often a tag — to many entities in a single call. Use this instead of calling SetEntityProperty once per entity when the user asks to tag or label a set of items at once (e.g. \"tag the last 50 emails as Follow-up\"). Provide the property_definition_id (a tag set's propertyDefinitionId from ListTags) and the option ids to add and/or remove (a tag's option id from ListTags). The same add_option_ids/remove_option_ids delta is applied to every entity, composing atomically with concurrent edits per entity.
+
+Only for multi-select or tag properties; for other value types, or a single entity, use SetEntityProperty. Up to 200 entities per call — split larger sets across multiple calls.
+
+Best-effort: each entity is handled independently. Entities you don't have edit access to are reported with status 'skipped_no_permission' and left unchanged, entities that can't take the property are 'failed', and the rest are 'applied' — one call never fails wholesale because a few entities were not editable. Inspect the per-entity results and the summary to see what happened."
+)]
+#[serde(rename_all = "snake_case")]
+pub struct BulkSetEntityPropertyOptions {
+ /// The entities to update (up to 200). Entities the user can't edit are skipped.
+ pub entities: Vec<BulkTargetEntity>,
+
+ /// The multi-select property definition id changed on every entity — e.g. a
+ /// tag set's propertyDefinitionId from ListTags.
+ pub property_definition_id: Uuid,
+
+ /// Options to add to every entity (e.g. a tag's option id from ListTags),
+ /// deduped against each entity's current value.
+ #[serde(default)]
+ pub add_option_ids: Option<Vec<Uuid>>,
+
+ /// Options to remove from every entity. Removing an absent option is a no-op.
+ #[serde(default)]
+ pub remove_option_ids: Option<Vec<Uuid>>,
+}
+
+/// One entity's result in the tool response.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct BulkSetEntityPropertyOptionsResult {
+ /// The entity's type this result is for.
+ pub entity_type: String,
+ /// The entity's id this result is for.
+ pub entity_id: String,
+ /// One of: applied, skipped_no_permission, failed.
+ pub status: String,
+ /// A human-readable reason, present only when the status is failed.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub error: Option<String>,
+}
+
+/// Response from the BulkSetEntityPropertyOptions tool.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct BulkSetEntityPropertyOptionsResponse {
+ /// Per-entity results, aligned to the requested entities' order.
+ pub results: Vec<BulkSetEntityPropertyOptionsResult>,
+ /// Human-readable summary of how many entities were applied/skipped/failed.
+ pub summary: String,
+}
+
+fn entity_type_label(entity_type: ToolPropertyTargetEntityType) -> &'static str {
+ match entity_type {
+ ToolPropertyTargetEntityType::Document => "document",
+ ToolPropertyTargetEntityType::Project => "project",
+ ToolPropertyTargetEntityType::Chat => "chat",
+ ToolPropertyTargetEntityType::Thread => "thread",
+ ToolPropertyTargetEntityType::Channel => "channel",
+ ToolPropertyTargetEntityType::Call => "call",
+ ToolPropertyTargetEntityType::User => "user",
+ ToolPropertyTargetEntityType::Company => "company",
+ }
+}
+
+#[async_trait]
+impl<T, A> AsyncTool<PropertiesToolContext<T, A>> for BulkSetEntityPropertyOptions
+where
+ T: PropertiesService,
+ A: EntityAccessService,
+{
+ type Output = BulkSetEntityPropertyOptionsResponse;
+
+ #[tracing::instrument(
+ skip_all,
+ fields(
+ user_id = ?request_context.user_id,
+ entity_count = self.entities.len(),
+ property_definition_id = %self.property_definition_id
+ ),
+ err
+ )]
+ async fn call(
+ &self,
+ service_context: ServiceContext<PropertiesToolContext<T, A>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ tracing::info!("Bulk set entity property options");
+
+ if self.entities.len() > MAX_BULK_ENTITIES {
+ return Err(ToolCallError {
+ description: format!(
+ "Too many entities: {} provided, at most {MAX_BULK_ENTITIES} allowed per call. Split the request into smaller batches.",
+ self.entities.len()
+ ),
+ internal_error: anyhow::anyhow!("bulk option update entity cap exceeded"),
+ });
+ }
+
+ let add_option_ids = self.add_option_ids.clone().unwrap_or_default();
+ let remove_option_ids = self.remove_option_ids.clone().unwrap_or_default();
+ if add_option_ids.is_empty() && remove_option_ids.is_empty() {
+ return Err(ToolCallError {
+ description: "Provide at least one of add_option_ids or remove_option_ids."
+ .to_string(),
+ internal_error: anyhow::anyhow!("bulk option update with no delta"),
+ });
+ }
+
+ // Mint one edit receipt per entity. Entities the caller can't edit are
+ // recorded as skipped and never sent to the service.
+ let mut results: Vec<Option<BulkSetEntityPropertyOptionsResult>> =
+ (0..self.entities.len()).map(|_| None).collect();
+ let mut receipts: Vec<EditReceipt> = Vec::new();
+ let mut granted_indices: Vec<usize> = Vec::new();
+
+ for (index, entity) in self.entities.iter().enumerate() {
+ let entity_type = model_entity::EntityType::from(entity.entity_type);
+ match service_context
+ .entity_access_service
+ .generate_entity_access_receipt::<EditAccessLevel>(
+ &request_context.user_id,
+ None,
+ &entity.entity_id,
+ entity_type,
+ )
+ .await
+ {
+ Ok(receipt) => {
+ receipts.push(receipt);
+ granted_indices.push(index);
+ }
+ Err(error) => {
+ tracing::debug!(entity_id = %entity.entity_id, error = ?error, "no edit access, skipping entity");
+ results[index] = Some(BulkSetEntityPropertyOptionsResult {
+ entity_type: entity_type_label(entity.entity_type).to_string(),
+ entity_id: entity.entity_id.clone(),
+ status: "skipped_no_permission".to_string(),
+ error: None,
+ });
+ }
+ }
+ }
+
+ if !receipts.is_empty() {
+ let outcomes = service_context
+ .service
+ .bulk_update_entities_property_options(
+ &receipts,
+ self.property_definition_id,
+ add_option_ids,
+ remove_option_ids,
+ )
+ .await
+ .map_err(|e| ToolCallError {
+ description: format!("Failed to update property options: {e}"),
+ internal_error: e.into(),
+ })?;
+
+ for (index, outcome) in granted_indices.into_iter().zip(outcomes) {
+ let entity = &self.entities[index];
+ let (status, error) = match outcome {
+ EntityOptionUpdateOutcome::Applied { .. } => ("applied".to_string(), None),
+ EntityOptionUpdateOutcome::Failed { message } => {
+ ("failed".to_string(), Some(message))
+ }
+ };
+ results[index] = Some(BulkSetEntityPropertyOptionsResult {
+ entity_type: entity_type_label(entity.entity_type).to_string(),
+ entity_id: entity.entity_id.clone(),
+ status,
+ error,
+ });
+ }
+ }
+
+ let results: Vec<BulkSetEntityPropertyOptionsResult> = results
+ .into_iter()
+ .map(|result| result.expect("every entity yields a result"))
+ .collect();
+
+ let applied = results.iter().filter(|r| r.status == "applied").count();
+ let skipped = results
+ .iter()
+ .filter(|r| r.status == "skipped_no_permission")
+ .count();
+ let failed = results.iter().filter(|r| r.status == "failed").count();
+ let summary = format!(
+ "{applied} applied, {skipped} skipped (no permission), {failed} failed out of {} entities.",
+ results.len()
+ );
+
+ Ok(BulkSetEntityPropertyOptionsResponse { results, summary })
+ }
+}
diff --git a/crates/properties/src/inbound/toolset/mod.rs b/crates/properties/src/inbound/toolset/mod.rs
index e940b24d76..b9ae0da8d5 100644
--- a/crates/properties/src/inbound/toolset/mod.rs
+++ b/crates/properties/src/inbound/toolset/mod.rs
@@ -1,5 +1,6 @@
//! Toolset inbound adapter for the Properties service.
+mod bulk_set_entity_property_options;
mod create_tag;
mod delete_tag;
mod edit_tag;
@@ -19,6 +20,9 @@ use entity_access::domain::models::{
use entity_access::domain::ports::EntityAccessService;
use std::sync::Arc;
+pub use bulk_set_entity_property_options::{
+ BulkSetEntityPropertyOptions, BulkSetEntityPropertyOptionsResponse,
+};
pub use create_tag::{CreateTag, CreateTagResponse};
pub use delete_tag::{DeleteTag, DeleteTagResponse};
pub use edit_tag::{EditTag, EditTagResponse};
@@ -104,6 +108,7 @@ where
AsyncToolCollection::new()
.add_tool::<GetEntityProperties, PropertiesToolContext<T, A>>()
.add_tool::<SetEntityProperty, PropertiesToolContext<T, A>>()
+ .add_tool::<BulkSetEntityPropertyOptions, PropertiesToolContext<T, A>>()
.add_tool::<ListTags, PropertiesToolContext<T, A>>()
.add_tool::<CreateTag, PropertiesToolContext<T, A>>()
.add_tool::<EditTag, PropertiesToolContext<T, A>>()
diff --git a/crates/properties/src/inbound/toolset/test.rs b/crates/properties/src/inbound/toolset/test.rs
index 792492921f..b0a78866f3 100644
--- a/crates/properties/src/inbound/toolset/test.rs
+++ b/crates/properties/src/inbound/toolset/test.rs
@@ -46,6 +46,27 @@ fn test_set_entity_property_schema_documents_delta_options() {
);
}
+#[test]
+fn test_bulk_set_entity_property_options_schema_validation() {
+ let result = generate_validated_input_schema::<BulkSetEntityPropertyOptions>();
+ assert!(result.is_ok(), "{:?}", result);
+
+ let validated = result.unwrap();
+ assert_eq!(validated.name, "BulkSetEntityPropertyOptions");
+ assert!(
+ validated.description.contains("many entities"),
+ "Description should explain the multi-entity apply"
+ );
+
+ let schema_json = serde_json::to_string(&validated.schema).unwrap();
+ assert!(
+ schema_json.contains("entities")
+ && schema_json.contains("add_option_ids")
+ && schema_json.contains("remove_option_ids"),
+ "schema should expose entities and the add/remove option deltas"
+ );
+}
+
#[test]
fn test_list_tags_schema_validation() {
let result = generate_validated_input_schema::<ListTags>();
diff --git a/crates/properties/src/outbound/test.rs b/crates/properties/src/outbound/test.rs
index 8eb7ee32e7..e5a19fff23 100644
--- a/crates/properties/src/outbound/test.rs
+++ b/crates/properties/src/outbound/test.rs
@@ -1,10 +1,15 @@
//! Integration tests for PropertiesPgRepo using sqlx and real migrations.
use super::properties_pg_repo::PropertiesPgRepo;
-use crate::domain::ports::PropertiesRepo;
+use crate::PropertiesServiceImpl;
+use crate::domain::model::{EditReceipt, canonical_entity_type};
+use crate::domain::ports::{MockNotificationService, MockPermissionService, PropertiesRepo};
+use crate::domain::service::PropertiesService;
use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use macro_user_id::user_id::MacroUserIdStr;
use models_properties::EntityType;
use sqlx::{Pool, Postgres};
+use std::sync::Arc;
use system_properties::SystemPropertyKey;
use uuid::Uuid;
@@ -1033,3 +1038,149 @@ async fn bulk_update_options_removal_only_on_unattached_is_noop(
Ok(())
}
+
+/// Seeds a select option for the definition and returns its id, so the
+/// domain's option validation (which checks `property_options`) accepts it.
+async fn seed_option(pool: &Pool<Postgres>, def_id: Uuid, value: &str) -> Uuid {
+ PropertiesPgRepo::new(pool.clone())
+ .create_property_option(
+ def_id,
+ 0,
+ models_properties::service::property_option::PropertyOptionValue::String(
+ value.to_string(),
+ ),
+ None,
+ )
+ .await
+ .expect("seed option")
+ .id
+}
+
+/// A cross-entity bulk service over the live repo, with no permission,
+/// notification, or search-indexer collaborators (unused by the option path).
+fn cross_entity_service(
+ pool: Pool<Postgres>,
+) -> PropertiesServiceImpl<PropertiesPgRepo, MockPermissionService, MockNotificationService> {
+ PropertiesServiceImpl::new(
+ PropertiesPgRepo::new(pool),
+ None::<MockPermissionService>,
+ None::<MockNotificationService>,
+ )
+}
+
+/// An edit receipt for a document entity, minted without an access check.
+fn doc_edit_receipt(entity_id: &str) -> EditReceipt {
+ let user = MacroUserIdStr::parse_from_str("macro|[email protected]").expect("valid test user id");
+ EditReceipt::dangerously_assert_authenticated_user(
+ user,
+ entity_id,
+ canonical_entity_type(EntityType::Document),
+ )
+}
+
+/// Two cross-entity bulk updates race on the same two entities, listed in
+/// opposite orders: one removes A, the other adds B. The service's consistent
+/// per-entity lock ordering avoids deadlock and each entity's row lock avoids a
+/// lost update, so both entities end at {B} regardless of interleaving.
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("properties_seed"))
+)]
+async fn cross_entity_bulk_update_concurrent_no_lost_update(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let def_id = seed_multi_select_definition(&pool, "Cross Entity Concurrent").await;
+ let entity_one = "cross-entity-1";
+ let entity_two = "cross-entity-2";
+ let opt_a = seed_option(&pool, def_id, "A").await;
+ let opt_b = seed_option(&pool, def_id, "B").await;
+
+ let service = Arc::new(cross_entity_service(pool.clone()));
+
+ // Both entities start from {A}.
+ service
+ .bulk_update_entities_property_options(
+ &[doc_edit_receipt(entity_one), doc_edit_receipt(entity_two)],
+ def_id,
+ vec![opt_a],
+ vec![],
+ )
+ .await?;
+
+ let remover = {
+ let service = service.clone();
+ tokio::spawn(async move {
+ service
+ .bulk_update_entities_property_options(
+ &[doc_edit_receipt(entity_one), doc_edit_receipt(entity_two)],
+ def_id,
+ vec![],
+ vec![opt_a],
+ )
+ .await
+ })
+ };
+ let adder = {
+ let service = service.clone();
+ tokio::spawn(async move {
+ service
+ .bulk_update_entities_property_options(
+ &[doc_edit_receipt(entity_two), doc_edit_receipt(entity_one)],
+ def_id,
+ vec![opt_b],
+ vec![],
+ )
+ .await
+ })
+ };
+
+ remover.await??;
+ adder.await??;
+
+ for entity in [entity_one, entity_two] {
+ assert_eq!(
+ select_option_ids(&read_select_value(&pool, entity, def_id).await),
+ vec![opt_b.to_string()],
+ "entity {entity} should have A removed and B added"
+ );
+ }
+
+ Ok(())
+}
+
+/// The cross-entity path applies the shared delta and persists it against the
+/// live DB for a permitted entity. Per-entity failures can't be provoked here:
+/// `entity_properties.entity_id` carries no existence/foreign-key constraint (the
+/// entity lives in another database), and the one real FK — `property_definition_id`
+/// — is shared, so violating it fails the whole call up front (covered by
+/// `bulk_update_options_partial_failure_rolls_back`). Best-effort continuation
+/// past a per-entity failure is covered at the service level by
+/// `crate::domain::test::test_bulk_update_entities_is_best_effort_on_per_entity_write_failure`.
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("properties_seed"))
+)]
+async fn cross_entity_bulk_update_applies_and_persists_via_live_db(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let def_id = seed_multi_select_definition(&pool, "Cross Entity Best Effort").await;
+ let good = "cross-entity-good";
+ let opt = seed_option(&pool, def_id, "opt").await;
+
+ let service = cross_entity_service(pool.clone());
+ let outcomes = service
+ .bulk_update_entities_property_options(&[doc_edit_receipt(good)], def_id, vec![opt], vec![])
+ .await?;
+
+ assert_eq!(outcomes.len(), 1);
+ assert!(matches!(
+ &outcomes[0],
+ crate::domain::model::EntityOptionUpdateOutcome::Applied { option_ids } if *option_ids == vec![opt]
+ ));
+ assert_eq!(
+ select_option_ids(&read_select_value(&pool, good, def_id).await),
+ vec![opt.to_string()]
+ );
+
+ Ok(())
+}
diff --git a/crates/properties_service/src/api/swagger.rs b/crates/properties_service/src/api/swagger.rs
index 3288c4261a..0d518dfdc9 100644
--- a/crates/properties_service/src/api/swagger.rs
+++ b/crates/properties_service/src/api/swagger.rs
@@ -2,10 +2,11 @@ use models_properties::api;
use properties::inbound::axum_router::{
definitions::{ListPropertiesQuery, PropertyDefinitionResponse},
entities::{
- BulkEntityPropertiesRequest, BulkUpdateEntityPropertyOptionsRequest,
- BulkUpdateEntityPropertyOptionsResponse, EntityPropertiesResponse,
- EntityPropertyOptionSelectionResponse, EntityPropertyOptionUpdateRequest,
- EntityQueryParams, SetEntityPropertyRequest,
+ BulkEntityOptionUpdateResult, BulkEntityOptionUpdateStatus, BulkEntityPropertiesRequest,
+ BulkUpdateEntitiesPropertyOptionsRequest, BulkUpdateEntitiesPropertyOptionsResponse,
+ BulkUpdateEntityPropertyOptionsRequest, BulkUpdateEntityPropertyOptionsResponse,
+ EntityPropertiesResponse, EntityPropertyOptionSelectionResponse,
+ EntityPropertyOptionUpdateRequest, EntityQueryParams, SetEntityPropertyRequest,
},
tags::{EnsureTagSetRequest, TagScope, TagSetResponse},
};
@@ -35,6 +36,7 @@ use utoipa::OpenApi;
properties::inbound::axum_router::entities::add_entity_property_option,
properties::inbound::axum_router::entities::remove_entity_property_option,
properties::inbound::axum_router::entities::bulk_update_entity_property_options,
+ properties::inbound::axum_router::entities::bulk_update_entities_property_options,
properties::inbound::axum_router::entities::delete_entity_property,
),
components(
@@ -55,6 +57,10 @@ use utoipa::OpenApi;
BulkUpdateEntityPropertyOptionsResponse,
EntityPropertyOptionUpdateRequest,
EntityPropertyOptionSelectionResponse,
+ BulkUpdateEntitiesPropertyOptionsRequest,
+ BulkUpdateEntitiesPropertyOptionsResponse,
+ BulkEntityOptionUpdateResult,
+ BulkEntityOptionUpdateStatus,
api::SetPropertyValue,
models_properties::EntityReference,
api::AddPropertyOptionRequest,