graphcore-kernel 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (343) hide show
  1. graphcore/__init__.py +5 -0
  2. graphcore/agent_frontend/__init__.py +8 -0
  3. graphcore/agent_frontend/api.py +69 -0
  4. graphcore/agent_frontend/base/__init__.py +11 -0
  5. graphcore/agent_frontend/base/views.py +167 -0
  6. graphcore/agent_frontend/client.py +31 -0
  7. graphcore/agent_frontend/context.py +157 -0
  8. graphcore/agent_frontend/errors.py +12 -0
  9. graphcore/agent_frontend/loading.py +54 -0
  10. graphcore/agent_frontend/registry.py +42 -0
  11. graphcore/agent_frontend/render.py +207 -0
  12. graphcore/agent_frontend/server.py +103 -0
  13. graphcore/agent_frontend/signatures.py +35 -0
  14. graphcore/agent_frontend/testing.py +45 -0
  15. graphcore/agent_frontend/tests/__init__.py +0 -0
  16. graphcore/agent_frontend/tests/fakes.py +114 -0
  17. graphcore/agent_frontend/tests/test_frontend.py +447 -0
  18. graphcore/agent_frontend/tests/test_loading.py +83 -0
  19. graphcore/agent_frontend/tests/test_server.py +109 -0
  20. graphcore/agent_frontend/tools.py +137 -0
  21. graphcore/api/__init__.py +4 -0
  22. graphcore/api/graph_api.py +378 -0
  23. graphcore/api/predicate_codec.py +81 -0
  24. graphcore/api/tests/__init__.py +0 -0
  25. graphcore/api/tests/test_changed_entities.py +109 -0
  26. graphcore/api/tests/test_graph_api.py +290 -0
  27. graphcore/api/tests/test_graph_api_access.py +94 -0
  28. graphcore/api/tests/test_graph_api_grants.py +90 -0
  29. graphcore/api/tests/test_predicate_codec.py +83 -0
  30. graphcore/api/tests/test_subtree_query.py +79 -0
  31. graphcore/apps.py +71 -0
  32. graphcore/auth/__init__.py +1 -0
  33. graphcore/auth/authn/README.md +178 -0
  34. graphcore/auth/authn/__init__.py +3 -0
  35. graphcore/auth/authn/authenticator.py +120 -0
  36. graphcore/auth/authn/onboarding.py +105 -0
  37. graphcore/auth/authn/principals.py +20 -0
  38. graphcore/auth/authn/resource_metadata.py +43 -0
  39. graphcore/auth/authn/service_accounts.py +96 -0
  40. graphcore/auth/authn/testing.py +96 -0
  41. graphcore/auth/authn/tests/__init__.py +0 -0
  42. graphcore/auth/authn/tests/test_authenticator.py +145 -0
  43. graphcore/auth/authn/tests/test_onboarding.py +145 -0
  44. graphcore/auth/authn/tests/test_service_accounts.py +180 -0
  45. graphcore/auth/authn/users.py +59 -0
  46. graphcore/auth/authz/__init__.py +0 -0
  47. graphcore/auth/authz/access_port.py +120 -0
  48. graphcore/auth/authz/adapter/__init__.py +0 -0
  49. graphcore/auth/authz/adapter/default_access_adapter.py +556 -0
  50. graphcore/auth/authz/adapter/tests/__init__.py +0 -0
  51. graphcore/auth/authz/adapter/tests/test_default_adapter.py +543 -0
  52. graphcore/auth/authz/adapter/tests/test_entity_write_hooks.py +207 -0
  53. graphcore/auth/authz/adapter/tests/test_group_types.py +70 -0
  54. graphcore/auth/authz/adapter/tests/test_sync_support.py +209 -0
  55. graphcore/auth/authz/defaults.py +26 -0
  56. graphcore/auth/authz/kernel_policy.py +191 -0
  57. graphcore/auth/authz/kernel_writes.py +31 -0
  58. graphcore/auth/authz/lookups.py +25 -0
  59. graphcore/auth/authz/policy.py +403 -0
  60. graphcore/auth/authz/tests/__init__.py +0 -0
  61. graphcore/auth/authz/tests/test_can_contain.py +150 -0
  62. graphcore/auth/authz/tests/test_contained_by.py +167 -0
  63. graphcore/auth/authz/tests/test_creation.py +391 -0
  64. graphcore/auth/authz/tests/test_delete_permission.py +82 -0
  65. graphcore/auth/authz/tests/test_granted_to_me.py +160 -0
  66. graphcore/auth/authz/tests/test_integration.py +637 -0
  67. graphcore/auth/authz/tests/test_invites.py +184 -0
  68. graphcore/auth/authz/tests/test_kernel_policy.py +140 -0
  69. graphcore/auth/authz/tests/test_lockout.py +132 -0
  70. graphcore/auth/authz/tests/test_policy.py +329 -0
  71. graphcore/auth/authz/tests/test_primitives.py +73 -0
  72. graphcore/auth/authz/tests/test_principal_creation.py +62 -0
  73. graphcore/bootstrap/__init__.py +0 -0
  74. graphcore/bootstrap/deployment.py +67 -0
  75. graphcore/bootstrap/signals.py +16 -0
  76. graphcore/bootstrap/tests/__init__.py +0 -0
  77. graphcore/bootstrap/tests/test_deployment_seed.py +154 -0
  78. graphcore/broadcast/__init__.py +4 -0
  79. graphcore/broadcast/broadcaster.py +201 -0
  80. graphcore/broadcast/channels.py +56 -0
  81. graphcore/broadcast/tests/__init__.py +0 -0
  82. graphcore/broadcast/tests/test_broadcaster.py +444 -0
  83. graphcore/celery.py +14 -0
  84. graphcore/docs/AGENT_FRONTEND_TDD.md +389 -0
  85. graphcore/docs/ARCHITECTURE_PRINCIPLES.md +152 -0
  86. graphcore/docs/AUTHORIZATION_TECHNICAL_TDD.md +1379 -0
  87. graphcore/docs/ENTITY_REFERENCE_TDD.md +561 -0
  88. graphcore/docs/GRAPHAPI_FRONT_DOOR.md +173 -0
  89. graphcore/docs/RUNTIME.md +90 -0
  90. graphcore/docs/SCHEDULING_TDD.md +244 -0
  91. graphcore/docs/STRATEGY_EXECUTION_TDD.md +1043 -0
  92. graphcore/docs/VIEW_ENTITY_TDD.md +522 -0
  93. graphcore/docs/VIEW_SYSTEM_TDD.md +307 -0
  94. graphcore/docs/__init__.py +0 -0
  95. graphcore/docs/doc_topics.py +97 -0
  96. graphcore/docs/docs_discovery.py +64 -0
  97. graphcore/docs/public_api.py +56 -0
  98. graphcore/domain/__init__.py +0 -0
  99. graphcore/domain/entity/Entity.py +204 -0
  100. graphcore/domain/entity/__init__.py +0 -0
  101. graphcore/domain/entity/deployment/Deployment.py +25 -0
  102. graphcore/domain/entity/deployment/__init__.py +0 -0
  103. graphcore/domain/entity/grant/Grant.py +31 -0
  104. graphcore/domain/entity/grant/__init__.py +0 -0
  105. graphcore/domain/entity/group/Group.py +48 -0
  106. graphcore/domain/entity/group/README.md +88 -0
  107. graphcore/domain/entity/group/__init__.py +0 -0
  108. graphcore/domain/entity/invite/Invite.py +31 -0
  109. graphcore/domain/entity/invite/__init__.py +0 -0
  110. graphcore/domain/entity/request_template/RequestTemplate.py +48 -0
  111. graphcore/domain/entity/request_template/__init__.py +0 -0
  112. graphcore/domain/entity/request_template/tests/__init__.py +0 -0
  113. graphcore/domain/entity/request_template/tests/test_request_template.py +52 -0
  114. graphcore/domain/entity/service_account/ServiceAccount.py +41 -0
  115. graphcore/domain/entity/service_account/__init__.py +0 -0
  116. graphcore/domain/entity/strategy_request/StrategyRequest.py +61 -0
  117. graphcore/domain/entity/strategy_request/__init__.py +0 -0
  118. graphcore/domain/entity/strategy_request/tests/__init__.py +0 -0
  119. graphcore/domain/entity/strategy_request/tests/test_strategy_request_entity.py +35 -0
  120. graphcore/domain/entity/tests/__init__.py +0 -0
  121. graphcore/domain/entity/tests/test_entity.py +227 -0
  122. graphcore/domain/entity/tests/test_grant_group_entities.py +36 -0
  123. graphcore/domain/entity/tests/test_write_once_fields.py +98 -0
  124. graphcore/domain/entity/user/User.py +39 -0
  125. graphcore/domain/entity/user/__init__.py +0 -0
  126. graphcore/domain/entity/user/tests/__init__.py +0 -0
  127. graphcore/domain/entity/user/tests/test_user_entity.py +33 -0
  128. graphcore/domain/entity/view/View.py +37 -0
  129. graphcore/domain/entity/view/__init__.py +0 -0
  130. graphcore/domain/entity/view/position.py +78 -0
  131. graphcore/domain/entity/view/tests/__init__.py +0 -0
  132. graphcore/domain/entity/view/tests/test_position.py +71 -0
  133. graphcore/domain/entity/view/tests/test_view_entity.py +134 -0
  134. graphcore/domain/strategy/BaseStrategy.py +759 -0
  135. graphcore/domain/strategy/DeploymentStrategies.py +55 -0
  136. graphcore/domain/strategy/GrantStrategies.py +189 -0
  137. graphcore/domain/strategy/GroupStrategies.py +193 -0
  138. graphcore/domain/strategy/InviteStrategies.py +84 -0
  139. graphcore/domain/strategy/RequestTemplateStrategies.py +126 -0
  140. graphcore/domain/strategy/ViewStrategies.py +219 -0
  141. graphcore/domain/strategy/__init__.py +0 -0
  142. graphcore/domain/strategy/runner.py +84 -0
  143. graphcore/domain/strategy/session.py +56 -0
  144. graphcore/domain/strategy/tests/BaseStrategyTest.py +167 -0
  145. graphcore/domain/strategy/tests/__init__.py +0 -0
  146. graphcore/domain/strategy/tests/test_BaseStrategies.py +870 -0
  147. graphcore/domain/strategy/tests/test_grant_strategies.py +245 -0
  148. graphcore/domain/strategy/tests/test_group_strategies.py +99 -0
  149. graphcore/domain/strategy/tests/test_runner.py +220 -0
  150. graphcore/domain/strategy/tests/test_strategy_locks.py +446 -0
  151. graphcore/domain/strategy/tests/test_utils.py +95 -0
  152. graphcore/domain/strategy/tests/test_view_strategies.py +436 -0
  153. graphcore/errors.py +145 -0
  154. graphcore/execution/README.md +97 -0
  155. graphcore/execution/StrategyExecutorService.py +333 -0
  156. graphcore/execution/__init__.py +0 -0
  157. graphcore/execution/dispatcher.py +19 -0
  158. graphcore/execution/environments/__init__.py +0 -0
  159. graphcore/execution/environments/celery.py +59 -0
  160. graphcore/execution/environments/in_process.py +55 -0
  161. graphcore/execution/local_session.py +117 -0
  162. graphcore/execution/redis_run_events.py +74 -0
  163. graphcore/execution/requests.py +22 -0
  164. graphcore/execution/run_events.py +85 -0
  165. graphcore/execution/strategy_context.py +54 -0
  166. graphcore/execution/tasks.py +34 -0
  167. graphcore/execution/tests/__init__.py +5 -0
  168. graphcore/execution/tests/contract.py +171 -0
  169. graphcore/execution/tests/support.py +310 -0
  170. graphcore/execution/tests/test_dispatchers.py +76 -0
  171. graphcore/execution/tests/test_executor.py +368 -0
  172. graphcore/execution/tests/test_local_session.py +95 -0
  173. graphcore/execution/tests/test_reconcile_runs.py +134 -0
  174. graphcore/execution/tests/test_run_events.py +106 -0
  175. graphcore/execution/tests/test_strategy_context.py +62 -0
  176. graphcore/gateway/__init__.py +1 -0
  177. graphcore/gateway/remote.py +35 -0
  178. graphcore/gateway/tests/__init__.py +0 -0
  179. graphcore/gateway/tests/test_remote.py +30 -0
  180. graphcore/graph/EntityService.py +710 -0
  181. graphcore/graph/__init__.py +0 -0
  182. graphcore/graph/entity_cache.py +152 -0
  183. graphcore/graph/tests/__init__.py +4 -0
  184. graphcore/graph/tests/test_EntityService.py +908 -0
  185. graphcore/graph/tests/test_EntityService_list.py +170 -0
  186. graphcore/graph/tests/test_EntityService_model_resolution.py +339 -0
  187. graphcore/graph/tests/test_EntityService_referrers.py +236 -0
  188. graphcore/graph/tests/test_EntityService_routing.py +119 -0
  189. graphcore/graph/tests/test_dependent_on.py +141 -0
  190. graphcore/graph/tests/test_engine_is_type_agnostic.py +25 -0
  191. graphcore/graph/tests/test_engine_resolves_read_permission.py +93 -0
  192. graphcore/graph/tests/test_entity_cache.py +159 -0
  193. graphcore/graph/tests/test_null_entity_cache.py +12 -0
  194. graphcore/management/__init__.py +0 -0
  195. graphcore/management/commands/__init__.py +0 -0
  196. graphcore/management/commands/dev_reset.py +18 -0
  197. graphcore/management/commands/graphcore_createadmin.py +65 -0
  198. graphcore/management/commands/graphcore_policy.py +59 -0
  199. graphcore/management/commands/graphcore_status.py +98 -0
  200. graphcore/management/tests/__init__.py +0 -0
  201. graphcore/management/tests/test_createadmin.py +78 -0
  202. graphcore/management/tests/test_policy_command.py +46 -0
  203. graphcore/management/tests/test_status_command.py +85 -0
  204. graphcore/migrations/0001_initial.py +186 -0
  205. graphcore/migrations/0002_invite.py +26 -0
  206. graphcore/migrations/__init__.py +0 -0
  207. graphcore/models.py +11 -0
  208. graphcore/persistence/ENTITY_REPOSITORY_TECHNICAL_TDD.md +396 -0
  209. graphcore/persistence/__init__.py +6 -0
  210. graphcore/persistence/django/__init__.py +0 -0
  211. graphcore/persistence/django/backends.py +43 -0
  212. graphcore/persistence/django/bindings.py +28 -0
  213. graphcore/persistence/django/cache.py +38 -0
  214. graphcore/persistence/django/compiler.py +214 -0
  215. graphcore/persistence/django/identity.py +18 -0
  216. graphcore/persistence/django/models.py +252 -0
  217. graphcore/persistence/django/repository.py +525 -0
  218. graphcore/persistence/django/tests/__init__.py +0 -0
  219. graphcore/persistence/django/tests/test_backends.py +68 -0
  220. graphcore/persistence/django/tests/test_compiler.py +269 -0
  221. graphcore/persistence/django/tests/test_repository.py +472 -0
  222. graphcore/persistence/django/tests/test_shared_column.py +120 -0
  223. graphcore/persistence/django/tests/test_threads.py +50 -0
  224. graphcore/persistence/django/tests/test_update_shape.py +175 -0
  225. graphcore/persistence/django/threads.py +38 -0
  226. graphcore/persistence/repository.py +172 -0
  227. graphcore/persistence/tests/__init__.py +0 -0
  228. graphcore/persistence/tests/contract.py +688 -0
  229. graphcore/persistence/tests/evaluate.py +51 -0
  230. graphcore/persistence/tests/fixtures.py +32 -0
  231. graphcore/persistence/tests/memory.py +263 -0
  232. graphcore/persistence/tests/test_memory_repository.py +10 -0
  233. graphcore/persistence/tests/test_query_types.py +127 -0
  234. graphcore/public/__init__.py +9 -0
  235. graphcore/public/api.py +9 -0
  236. graphcore/public/apps.py +10 -0
  237. graphcore/public/auth/__init__.py +1 -0
  238. graphcore/public/auth/grants.py +7 -0
  239. graphcore/public/auth/onboarding.py +8 -0
  240. graphcore/public/auth/perms.py +7 -0
  241. graphcore/public/auth/policy.py +10 -0
  242. graphcore/public/auth/roles.py +8 -0
  243. graphcore/public/auth/subjects.py +7 -0
  244. graphcore/public/entities/__init__.py +32 -0
  245. graphcore/public/errors.py +19 -0
  246. graphcore/public/persistence/__init__.py +44 -0
  247. graphcore/public/persistence/django.py +24 -0
  248. graphcore/public/scheduling.py +23 -0
  249. graphcore/public/strategies/__init__.py +85 -0
  250. graphcore/public/test_settings.py +16 -0
  251. graphcore/public/testing.py +47 -0
  252. graphcore/registry/EntityDirectory.py +246 -0
  253. graphcore/registry/README.md +147 -0
  254. graphcore/registry/StrategyDirectory.py +308 -0
  255. graphcore/registry/TYPE_METADATA_PLACEMENT.md +66 -0
  256. graphcore/registry/__init__.py +0 -0
  257. graphcore/registry/app_discovery.py +108 -0
  258. graphcore/registry/decorators.py +77 -0
  259. graphcore/registry/discovery.py +111 -0
  260. graphcore/registry/registry.py +79 -0
  261. graphcore/registry/tests/__init__.py +0 -0
  262. graphcore/registry/tests/test_agent_frontend_discovery.py +56 -0
  263. graphcore/registry/tests/test_app_config.py +36 -0
  264. graphcore/registry/tests/test_discovery.py +147 -0
  265. graphcore/registry/tests/test_entity_directory_storage.py +73 -0
  266. graphcore/registry/tests/test_import_package.py +87 -0
  267. graphcore/registry/tests/test_principal_flag.py +67 -0
  268. graphcore/registry/tests/test_strategy_directory.py +29 -0
  269. graphcore/routes/__init__.py +116 -0
  270. graphcore/routes/tests/__init__.py +0 -0
  271. graphcore/routes/tests/test_routes.py +90 -0
  272. graphcore/runtime.py +243 -0
  273. graphcore/scheduling/__init__.py +0 -0
  274. graphcore/scheduling/beat_scheduler.py +164 -0
  275. graphcore/scheduling/beat_tasks.py +63 -0
  276. graphcore/scheduling/scheduler.py +37 -0
  277. graphcore/scheduling/tests/__init__.py +0 -0
  278. graphcore/scheduling/tests/contract.py +136 -0
  279. graphcore/scheduling/tests/memory.py +42 -0
  280. graphcore/scheduling/tests/test_beat_scheduler.py +87 -0
  281. graphcore/scheduling/tests/test_memory_scheduler.py +15 -0
  282. graphcore/scheduling/tests/test_ticks.py +143 -0
  283. graphcore/tasks.py +9 -0
  284. graphcore/test_settings.py +78 -0
  285. graphcore/testing/__init__.py +0 -0
  286. graphcore/testing/case.py +112 -0
  287. graphcore/testing/runner.py +32 -0
  288. graphcore/testing/settings.py +26 -0
  289. graphcore/testing/tests/__init__.py +0 -0
  290. graphcore/testing/tests/agent_view_fixture.py +19 -0
  291. graphcore/testing/tests/test_case_and_runner.py +219 -0
  292. graphcore/testing/tests/test_settings_for_apps.py +50 -0
  293. graphcore/tests/__init__.py +0 -0
  294. graphcore/tests/ids.py +14 -0
  295. graphcore/tests/public_api_manifest.py +102 -0
  296. graphcore/tests/runs.py +7 -0
  297. graphcore/tests/test_app_discovery.py +90 -0
  298. graphcore/tests/test_composition_boundaries.py +231 -0
  299. graphcore/tests/test_docs_discovery.py +108 -0
  300. graphcore/tests/test_no_print.py +70 -0
  301. graphcore/tests/test_packaging.py +64 -0
  302. graphcore/tests/test_public_api_boundaries.py +229 -0
  303. graphcore/tests/test_public_api_contract.py +62 -0
  304. graphcore/tests/test_public_api_docs.py +28 -0
  305. graphcore/tests/test_runtime.py +42 -0
  306. graphcore/tests/test_shared_type_boundaries.py +128 -0
  307. graphcore/tests/test_shared_types.py +144 -0
  308. graphcore/tests/test_test_settings.py +45 -0
  309. graphcore/transport/__init__.py +0 -0
  310. graphcore/transport/agent_asgi.py +68 -0
  311. graphcore/transport/agent_client.py +85 -0
  312. graphcore/transport/channel_layer.py +68 -0
  313. graphcore/transport/consumers.py +507 -0
  314. graphcore/transport/routing.py +6 -0
  315. graphcore/transport/tests/__init__.py +0 -0
  316. graphcore/transport/tests/test_agent_client.py +31 -0
  317. graphcore/transport/tests/test_api_views.py +733 -0
  318. graphcore/transport/tests/test_channel_layer.py +96 -0
  319. graphcore/transport/tests/test_consumers.py +963 -0
  320. graphcore/transport/tests/test_resource_metadata.py +67 -0
  321. graphcore/transport/urls.py +29 -0
  322. graphcore/transport/views.py +358 -0
  323. graphcore/types/__init__.py +4 -0
  324. graphcore/types/access.py +114 -0
  325. graphcore/types/api.py +76 -0
  326. graphcore/types/entities.py +100 -0
  327. graphcore/types/entity_id.py +85 -0
  328. graphcore/types/execution.py +41 -0
  329. graphcore/types/identity.py +20 -0
  330. graphcore/types/onboarding.py +20 -0
  331. graphcore/types/query.py +116 -0
  332. graphcore/types/schedules.py +91 -0
  333. graphcore/types/strategy.py +73 -0
  334. graphcore/types/tests/__init__.py +0 -0
  335. graphcore/types/tests/test_entity_id.py +50 -0
  336. graphcore/urls.py +5 -0
  337. graphcore_kernel-0.1.0.dist-info/METADATA +94 -0
  338. graphcore_kernel-0.1.0.dist-info/RECORD +343 -0
  339. graphcore_kernel-0.1.0.dist-info/WHEEL +5 -0
  340. graphcore_kernel-0.1.0.dist-info/entry_points.txt +2 -0
  341. graphcore_kernel-0.1.0.dist-info/licenses/LICENSE +202 -0
  342. graphcore_kernel-0.1.0.dist-info/licenses/NOTICE +2 -0
  343. graphcore_kernel-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,759 @@
1
+ from abc import ABC, abstractmethod
2
+ from typing import Optional
3
+
4
+ from graphcore.domain.entity.Entity import Entity
5
+ from graphcore.domain.entity.strategy_request.StrategyRequest import StrategyRequest
6
+ from graphcore.domain.strategy.session import StrategySession
7
+ from graphcore.errors import ConcurrentModificationError, InvalidRequest, NotFound
8
+ from graphcore.registry.decorators import register_strategy
9
+ from graphcore.types.entity_id import is_entity_id
10
+ from graphcore.types.strategy import StrategyRequestPayload, Workload
11
+ import logging
12
+ import time
13
+
14
+
15
+ class Strategy(ABC):
16
+ """Domain code that fulfils one request. It reaches the graph only
17
+ through `self.session` (docs/STRATEGY_EXECUTION_TDD.md)."""
18
+
19
+ strategy_description = 'This is the base strategy class'
20
+ # The kind of environment apply() needs; the deployment maps it to one.
21
+ workload: Workload = Workload.IO
22
+ # Seconds per attempt; None means the deployment default.
23
+ timeout: Optional[int] = None
24
+ # True for strategies that never write. Their target is never saved after
25
+ # apply(), and the chokepoint refuses any write they attempt.
26
+ #
27
+ # Saving contract: after apply() the runner saves the returned target only
28
+ # if it differs from the state the session last loaded or saved, so a
29
+ # strategy that already saved its target, or never changed it, causes no
30
+ # second save. See `graphcore docs distro/writing-strategies`.
31
+ read_only_strategy = False
32
+ # Declarative param_config schema (JSON Schema). Set this instead of
33
+ # overriding get_request_schema() when a schema doesn't need computed
34
+ # logic — `graphcore frontend prepare` reads it to emit typed builders.
35
+ param_schema: Optional[dict] = None
36
+
37
+ logger = logging.getLogger(__name__)
38
+
39
+ def __init__(self, strategy_request: StrategyRequest, entity: Optional[Entity],
40
+ session: StrategySession, registry):
41
+ self.strategy_request = strategy_request
42
+ self.entity = entity
43
+ self.session = session
44
+ self.registry = registry
45
+ self.principal = session.principal
46
+ self.principal_entity_id = session.principal.principal_entity_id
47
+ self._held_locks = set()
48
+
49
+ async def execute_request(self, payload: StrategyRequestPayload, **kwargs):
50
+ """Run a nested strategy request as this strategy's principal."""
51
+ return await self.session.execute(payload, **kwargs)
52
+
53
+ @abstractmethod
54
+ async def apply(self) -> tuple:
55
+ """Apply the strategy to self.entity. Returns (strategy_request, entity)."""
56
+ pass
57
+
58
+ @classmethod
59
+ @abstractmethod
60
+ def request_constructor(cls, target_entity_id: str, *args, **kwargs) -> StrategyRequestPayload:
61
+ """Construct an un-executed request for this strategy. Only the
62
+ kernel turns it into a `StrategyRequest`."""
63
+ raise NotImplementedError
64
+
65
+ @classmethod
66
+ def _build_request(
67
+ cls,
68
+ target_entity_id: str,
69
+ param_config: Optional[dict] = None,
70
+ ) -> StrategyRequestPayload:
71
+ """Create a strategy request with consistent defaults across strategies."""
72
+ return StrategyRequestPayload(
73
+ strategy_name=cls.__name__,
74
+ param_config=param_config or {},
75
+ target_entity_id=target_entity_id,
76
+ )
77
+
78
+ def verify_executable(self):
79
+ """Base implementation that can be overridden by child classes"""
80
+ return True
81
+
82
+ @classmethod
83
+ def get_request_schema(cls):
84
+ """Return JSON Schema for param_config validation.
85
+
86
+ Returns `param_schema` if the subclass set one declaratively;
87
+ otherwise override this method for schemas that need computed logic.
88
+ Returns a JSON Schema object with type, properties, and required fields.
89
+ """
90
+ if cls.param_schema is not None:
91
+ return cls.param_schema
92
+ return {
93
+ "type": "object",
94
+ "properties": {},
95
+ "required": []
96
+ }
97
+
98
+ @classmethod
99
+ def serialize(cls):
100
+ return {
101
+ 'name': cls.__name__,
102
+ 'schema': cls.get_request_schema(),
103
+ 'description': cls.strategy_description,
104
+ }
105
+
106
+ async def cleanup(self):
107
+ """Called by the runner after apply() completes (success or failure).
108
+ Override to reset state, release locks, etc."""
109
+ pass
110
+
111
+ async def get_entity(self, entity_id: str) -> Entity:
112
+ return await self.session.get(entity_id)
113
+
114
+ async def save_entity(self, entity: Entity) -> Entity:
115
+ return await self.session.save(entity)
116
+
117
+ async def try_acquire_lock(self, flag_name: str, timeout_seconds: int = 600) -> bool:
118
+ """Atomically acquire an exclusive lock using optimistic locking with timeout.
119
+
120
+ If a lock is held but the timestamp is older than timeout_seconds, the lock
121
+ is considered stale (e.g., from a crashed process) and can be taken over.
122
+
123
+ Args:
124
+ flag_name: Name of the lock flag attribute
125
+ timeout_seconds: Seconds after which a lock is considered stale (default: 600 = 10 minutes)
126
+
127
+ Returns:
128
+ True if lock acquired, False if not acquired.
129
+
130
+ Note:
131
+ Tracks acquired locks in self._held_locks so release_lock() only releases
132
+ locks that this strategy instance actually acquired.
133
+ """
134
+ import time
135
+
136
+ self.entity = await self.get_entity(self.entity.entity_id)
137
+
138
+ timestamp_attr = f"{flag_name}_timestamp"
139
+
140
+ # Check if flag exists and is True (already locked)
141
+ if self.entity.has_attribute(flag_name) and self.entity.get_attribute(flag_name):
142
+ # Check if lock is stale
143
+ if self.entity.has_attribute(timestamp_attr):
144
+ lock_time = self.entity.get_attribute(timestamp_attr)
145
+ current_time = time.time()
146
+ if current_time - lock_time > timeout_seconds:
147
+ # Lock is stale - can take it over
148
+ self.logger.warning(
149
+ f"Taking over stale lock '{flag_name}' (age: {current_time - lock_time:.1f}s, "
150
+ f"timeout: {timeout_seconds}s)"
151
+ )
152
+ else:
153
+ # Lock is fresh - another process is actively using it
154
+ return False
155
+ else:
156
+ # Lock exists but no timestamp - be conservative and reject
157
+ return False
158
+
159
+ # Acquire lock with timestamp
160
+ self.entity.set_attribute(flag_name, True)
161
+ self.entity.set_attribute(timestamp_attr, time.time())
162
+
163
+ try:
164
+ self.entity = await self.save_entity(self.entity)
165
+ # Track that this instance holds the lock
166
+ self._held_locks.add(flag_name)
167
+ return True # Successfully acquired lock
168
+ except ConcurrentModificationError:
169
+ # Failed to save - did not acquire lock
170
+ # Refresh entity to latest state for caller
171
+ self.entity = await self.get_entity(self.entity.entity_id)
172
+ return False
173
+
174
+ async def release_lock(self, flag_name: str):
175
+ """Release an exclusive lock.
176
+
177
+ Only releases the lock if this strategy instance actually acquired it.
178
+ This prevents Strategy B from releasing Strategy A's lock when Strategy B
179
+ failed to acquire and its cleanup() is called.
180
+
181
+ Clears both the lock flag and its associated timestamp."""
182
+ # Only release if we actually hold this lock
183
+ if flag_name not in self._held_locks:
184
+ self.logger.debug(
185
+ f"Skipping release_lock('{flag_name}') - this strategy instance does not hold it"
186
+ )
187
+ return
188
+
189
+ self.entity = await self.get_entity(self.entity.entity_id)
190
+ self.entity.set_attribute(flag_name, False)
191
+
192
+ # Also clear the timestamp
193
+ timestamp_attr = f"{flag_name}_timestamp"
194
+ if self.entity.has_attribute(timestamp_attr):
195
+ self.entity.remove_attribute(timestamp_attr)
196
+
197
+ self.entity = await self.save_entity(self.entity)
198
+
199
+ # Remove from held locks
200
+ self._held_locks.discard(flag_name)
201
+ @register_strategy(Entity)
202
+ class CreateEntity(Strategy):
203
+ """Generic strategy for creating any entity type"""
204
+ strategy_description = 'Creates a new entity under the target, or at the top level when there is no target'
205
+
206
+ def verify_executable(self):
207
+ # Base class handles param_config type checking
208
+ super().verify_executable()
209
+ return 'entity_type_id' in self.strategy_request.param_config or 'entity_class' in self.strategy_request.param_config
210
+
211
+ async def apply(self) -> tuple:
212
+ """
213
+ Creates a new entity under the target, or at the top level when
214
+ there is no target
215
+
216
+ param_config requirements:
217
+ - entity_type_id: the type to create
218
+ - entity_uuid: (optional) full entity identifier to reuse for recreation
219
+ """
220
+ config = self.strategy_request.param_config
221
+ entity_type_id = config.get('entity_type_id')
222
+
223
+ entity_uuid = config.get('entity_uuid')
224
+ if entity_uuid is not None and not is_entity_id(entity_uuid):
225
+ raise InvalidRequest(
226
+ f"entity_uuid must be a full entity identifier (gc://<backend_id>/<local_id>), "
227
+ f"got {entity_uuid!r}"
228
+ )
229
+ new_entity = None
230
+ if entity_uuid is not None:
231
+ try:
232
+ new_entity = await self.get_entity(entity_uuid)
233
+ except NotFound:
234
+ pass
235
+
236
+
237
+ if new_entity is None:
238
+ entity_class = self.registry.entities.get_entity_class(entity_type_id)
239
+ if entity_class is None:
240
+ raise ValueError(f"Unknown entity_type_id: {entity_type_id}. Make sure the entity is registered with @register_entity()")
241
+
242
+ new_entity = (
243
+ entity_class(entity_id=entity_uuid) if entity_uuid is not None
244
+ else self.session.create(entity_class)
245
+ )
246
+ # Owner is stamped at the EntityService persistence chokepoint
247
+ # (reads the persisted parent for the creation-perm check).
248
+ # A group seeds its creator as the first roster member.
249
+ from graphcore.domain.entity.group.Group import Group
250
+
251
+ if isinstance(new_entity, Group):
252
+ new_entity.add_member(self.principal_entity_id)
253
+
254
+ if self.entity is None:
255
+ new_entity = await self.save_entity(new_entity)
256
+ else:
257
+ new_entity.set_parent(self.entity.entity_id)
258
+ new_entity = await self.save_entity(new_entity)
259
+
260
+ if config.get('initial_attributes') is not None:
261
+ set_initial_request = SetAttributes.request_constructor(target_entity_id=new_entity.entity_id, attribute_map=config.get("initial_attributes"))
262
+ set_initial_request, _ = await self.execute_request(set_initial_request)
263
+ new_entity = await self.get_entity(new_entity.entity_id)
264
+ request_list = new_entity.on_create(self.strategy_request.param_config)
265
+
266
+ if request_list:
267
+ for request in request_list:
268
+ request, _ = await self.execute_request(request)
269
+
270
+
271
+ self.strategy_request.ret_val['child_entity'] = new_entity.entity_id
272
+
273
+ return self.strategy_request, self.entity
274
+
275
+ @staticmethod
276
+ def get_request_schema():
277
+ """Return JSON Schema for CreateEntity param_config."""
278
+ return {
279
+ "type": "object",
280
+ "properties": {
281
+ "entity_type_id": {
282
+ "type": "string",
283
+ "description": "Fully qualified entity type ID (e.g., 'graphcore.Entity')"
284
+ },
285
+ "entity_uuid": {
286
+ "type": ["string", "null"],
287
+ "description": "Optional UUID to use for the new entity (for recreation)"
288
+ },
289
+ "initial_attributes": {
290
+ "type": ["object", "null"],
291
+ "description": "Optional initial attributes to set on the new entity",
292
+ "additionalProperties": True
293
+ }
294
+ },
295
+ "required": ["entity_type_id"]
296
+ }
297
+
298
+ @classmethod
299
+ def request_constructor(
300
+ cls,
301
+ target_entity_id,
302
+ entity_type_id: str,
303
+ entity_uuid: str = None,
304
+ initial_attributes: dict = None,
305
+ ):
306
+ """
307
+ Convenience constructor for CreateEntity requests.
308
+
309
+ Args:
310
+ target_entity_id: The parent entity ID, or None to create at the
311
+ top level
312
+ entity_type_id: The entity type ID to create
313
+ entity_uuid: Optional UUID for the new entity
314
+ initial_attributes: Optional initial attributes
315
+
316
+ Returns:
317
+ StrategyRequestPayload configured for this strategy
318
+ """
319
+ param_config = {
320
+ 'entity_type_id': entity_type_id,
321
+ 'entity_uuid': entity_uuid,
322
+ }
323
+ if initial_attributes is not None:
324
+ param_config['initial_attributes'] = initial_attributes
325
+ return cls._build_request(
326
+ target_entity_id=target_entity_id,
327
+ param_config=param_config,
328
+ )
329
+
330
+
331
+ @register_strategy(Entity)
332
+ class SetAttributes(Strategy):
333
+ """Generic strategy for setting attributes on an entity"""
334
+
335
+ strategy_description = 'Sets attributes on an entity'
336
+
337
+ async def apply(self) -> tuple:
338
+ for name, value in self.strategy_request.param_config['attribute_map'].items():
339
+ self.entity.set_attribute(name, value)
340
+ self.entity = await self.save_entity(self.entity)
341
+ return self.strategy_request, self.entity
342
+
343
+ @staticmethod
344
+ def get_request_schema():
345
+ return {
346
+ "type": "object",
347
+ "properties": {"attribute_map": {"type": "object", "additionalProperties": True}},
348
+ "required": ["attribute_map"],
349
+ "additionalProperties": False,
350
+ }
351
+
352
+ @classmethod
353
+ def request_constructor(cls, target_entity_id, attribute_map: dict):
354
+ return cls._build_request(
355
+ target_entity_id=target_entity_id,
356
+ param_config={"attribute_map": attribute_map},
357
+ )
358
+
359
+
360
+ @register_strategy(Entity)
361
+ class RemoveAttribute(Strategy):
362
+ """Generic strategy for removing attributes from an entity"""
363
+
364
+ strategy_description = 'Removes specified attributes from an entity'
365
+
366
+ async def apply(self) -> tuple:
367
+ """
368
+ Removes an attribute from an entity
369
+
370
+ param_config requirements:
371
+ - attribute_name: name of the attribute to remove
372
+ """
373
+ config = self.strategy_request.param_config
374
+ attribute_name = config.get('attribute_name')
375
+
376
+ if not attribute_name:
377
+ raise ValueError("Missing required parameter: attribute_name")
378
+
379
+ if self.entity.has_attribute(attribute_name):
380
+ # Remove the attribute from entity's internal storage
381
+ self.entity.remove_attribute(attribute_name)
382
+
383
+ self.entity = await self.save_entity(self.entity)
384
+ return self.strategy_request, self.entity
385
+
386
+ @staticmethod
387
+ def get_request_schema():
388
+ """Return JSON Schema for RemoveAttribute param_config."""
389
+ return {
390
+ "type": "object",
391
+ "properties": {
392
+ "attribute_name": {
393
+ "type": "string",
394
+ "description": "Name of the attribute to remove from the entity"
395
+ }
396
+ },
397
+ "required": ["attribute_name"]
398
+ }
399
+
400
+ @classmethod
401
+ def request_constructor(cls, target_entity_id, attribute_name: str):
402
+ return cls._build_request(
403
+ target_entity_id=target_entity_id,
404
+ param_config={"attribute_name": attribute_name},
405
+ )
406
+
407
+ @register_strategy(Entity)
408
+ class ReparentChild(Strategy):
409
+ """Move an entity to a new parent, or detach it by setting `parent_id`
410
+ to null. Targets the child being moved - the parent is never written
411
+ (containment is a field on the child, not a list on the parent)."""
412
+
413
+ strategy_description = 'Sets the target entity\'s parent (or detaches it when null)'
414
+
415
+ async def apply(self) -> tuple:
416
+ new_parent_id = self.strategy_request.param_config.get('parent_id')
417
+
418
+ if new_parent_id != self.entity.parent_id:
419
+ if new_parent_id:
420
+ await self.get_entity(new_parent_id)
421
+ self.entity.set_parent(new_parent_id or None)
422
+
423
+ self.strategy_request.ret_val['parent_id'] = self.entity.parent_id
424
+ return self.strategy_request, self.entity
425
+
426
+ @staticmethod
427
+ def get_request_schema():
428
+ """Return JSON Schema for ReparentChild param_config."""
429
+ return {
430
+ "type": "object",
431
+ "properties": {
432
+ "parent_id": {
433
+ "type": ["string", "null"],
434
+ "description": "New parent entity ID, or null to detach"
435
+ }
436
+ },
437
+ "required": ["parent_id"],
438
+ "additionalProperties": False
439
+ }
440
+
441
+ @classmethod
442
+ def request_constructor(
443
+ cls,
444
+ target_entity_id: str,
445
+ parent_id: Optional[str],
446
+ ):
447
+ return cls._build_request(
448
+ target_entity_id=target_entity_id,
449
+ param_config={"parent_id": parent_id},
450
+ )
451
+
452
+
453
+ @register_strategy(Entity)
454
+ class ReorderChild(Strategy):
455
+ """Reposition an entity among its siblings under its current parent.
456
+ Targets the child being moved and writes only its own
457
+ `sibling_position` - the parent is never touched (Ordering: see
458
+ docs/AUTHORIZATION_TECHNICAL_TDD.md)."""
459
+
460
+ strategy_description = 'Repositions the target entity among its siblings'
461
+
462
+ @staticmethod
463
+ def _midpoint_position(left: Optional[Entity], right: Optional[Entity]) -> Optional[float]:
464
+ """Float midpoint between two ordered siblings' `sibling_position`
465
+ values (either may be absent at a list boundary). `None` means the
466
+ gap between them has been exhausted and a rebalance is needed
467
+ instead of a midpoint insert."""
468
+ if left is None and right is None:
469
+ return time.time()
470
+ if left is None:
471
+ return right.sibling_position - 1.0
472
+ if right is None:
473
+ return left.sibling_position + 1.0
474
+ if right.sibling_position - left.sibling_position < 1e-9:
475
+ return None
476
+ return (left.sibling_position + right.sibling_position) / 2.0
477
+
478
+ async def _rebalance_positions(self, ordered_child_ids: list[str]) -> None:
479
+ """Rare O(n) fix-up: reassign integer positions 0..n-1 in the given
480
+ order, restoring midpoint room between every pair of siblings."""
481
+ for index, cid in enumerate(ordered_child_ids):
482
+ sibling = await self.get_entity(cid)
483
+ sibling.sibling_position = float(index)
484
+ await self.save_entity(sibling)
485
+
486
+ async def apply(self) -> tuple:
487
+ config = self.strategy_request.param_config
488
+ before_child_id = config.get('before_child_id')
489
+ after_child_id = config.get('after_child_id')
490
+ to_start = config.get('to_start', False)
491
+ to_end = config.get('to_end', False)
492
+
493
+ parent_id = self.entity.parent_id
494
+ if not parent_id:
495
+ raise ValueError(f"Cannot reorder entity {self.entity.entity_id}: it has no parent")
496
+
497
+ parent = await self.get_entity(parent_id)
498
+ siblings = [cid for cid in parent.children_ids if cid != self.entity.entity_id]
499
+
500
+ if to_start:
501
+ insert_index = 0
502
+ elif to_end:
503
+ insert_index = len(siblings)
504
+ else:
505
+ anchor_child_id = before_child_id or after_child_id
506
+ if anchor_child_id == self.entity.entity_id:
507
+ raise ValueError("Cannot move an entity relative to itself")
508
+ if anchor_child_id not in siblings:
509
+ raise ValueError(
510
+ f"Cannot move {self.entity.entity_id}: anchor {anchor_child_id} is not a "
511
+ f"sibling under parent {parent_id}"
512
+ )
513
+ anchor_index = siblings.index(anchor_child_id)
514
+ insert_index = anchor_index if before_child_id else anchor_index + 1
515
+
516
+ left_id = siblings[insert_index - 1] if insert_index > 0 else None
517
+ right_id = siblings[insert_index] if insert_index < len(siblings) else None
518
+ left = await self.get_entity(left_id) if left_id else None
519
+ right = await self.get_entity(right_id) if right_id else None
520
+
521
+ new_position = self._midpoint_position(left, right)
522
+ if new_position is None:
523
+ ordered = siblings[:insert_index] + [self.entity.entity_id] + siblings[insert_index:]
524
+ await self._rebalance_positions(ordered)
525
+ self.entity = await self.get_entity(self.entity.entity_id)
526
+ changed = True
527
+ elif self.entity.sibling_position == new_position:
528
+ changed = False
529
+ else:
530
+ self.entity.sibling_position = new_position
531
+ changed = True
532
+
533
+ self.strategy_request.ret_val['changed'] = changed
534
+ return self.strategy_request, self.entity
535
+
536
+ @staticmethod
537
+ def get_request_schema():
538
+ """Return JSON Schema for ReorderChild param_config."""
539
+ return {
540
+ "type": "object",
541
+ "oneOf": [
542
+ {
543
+ "properties": {
544
+ "before_child_id": {
545
+ "type": "string",
546
+ "minLength": 1,
547
+ "description": "Move before this existing sibling"
548
+ }
549
+ },
550
+ "required": ["before_child_id"],
551
+ "additionalProperties": False
552
+ },
553
+ {
554
+ "properties": {
555
+ "after_child_id": {
556
+ "type": "string",
557
+ "minLength": 1,
558
+ "description": "Move after this existing sibling"
559
+ }
560
+ },
561
+ "required": ["after_child_id"],
562
+ "additionalProperties": False
563
+ },
564
+ {
565
+ "properties": {
566
+ "to_start": {"type": "boolean", "enum": [True]}
567
+ },
568
+ "required": ["to_start"],
569
+ "additionalProperties": False
570
+ },
571
+ {
572
+ "properties": {
573
+ "to_end": {"type": "boolean", "enum": [True]}
574
+ },
575
+ "required": ["to_end"],
576
+ "additionalProperties": False
577
+ }
578
+ ]
579
+ }
580
+
581
+ @classmethod
582
+ def request_constructor(
583
+ cls,
584
+ target_entity_id: str,
585
+ before_child_id: Optional[str] = None,
586
+ after_child_id: Optional[str] = None,
587
+ to_start: bool = False,
588
+ to_end: bool = False,
589
+ ):
590
+ if before_child_id:
591
+ param_config = {"before_child_id": before_child_id}
592
+ elif after_child_id:
593
+ param_config = {"after_child_id": after_child_id}
594
+ elif to_start:
595
+ param_config = {"to_start": True}
596
+ elif to_end:
597
+ param_config = {"to_end": True}
598
+ else:
599
+ raise ValueError("Must specify one of before_child_id, after_child_id, to_start, to_end")
600
+
601
+ return cls._build_request(
602
+ target_entity_id=target_entity_id,
603
+ param_config=param_config,
604
+ )
605
+
606
+ @register_strategy(Entity)
607
+ class DeleteEntity(Strategy):
608
+ """Delete an entity and recursively delete descendants without external parents."""
609
+
610
+ strategy_description = (
611
+ 'Deletes an entity and any descendant whose remaining parents are also deleted'
612
+ )
613
+
614
+ async def apply(self) -> tuple:
615
+ # Mark entity as in deletion early so UI/other strategies can stop creating new children.
616
+ self.entity.set_attribute('is_deleting', True)
617
+ self.entity = await self.save_entity(self.entity)
618
+
619
+ # Deletion chokepoint: authorize once against the root, compute the
620
+ # containment closure internally, delete it with no per-descendant
621
+ # checks ("grants on nothing govern nothing").
622
+ await self.session.delete_tree(self.entity.entity_id)
623
+
624
+ self.strategy_request.ret_val['entity_id'] = self.entity.entity_id
625
+
626
+ return self.strategy_request, self.entity
627
+
628
+ @classmethod
629
+ def request_constructor(
630
+ cls,
631
+ target_entity_id,
632
+ ):
633
+ """Construct a StrategyRequest to delete an entity."""
634
+ return cls._build_request(
635
+ target_entity_id=target_entity_id,
636
+ param_config={},
637
+ )
638
+
639
+ @staticmethod
640
+ def get_request_schema():
641
+ """Return JSON Schema for DeleteEntity param_config."""
642
+ return {
643
+ "type": "object",
644
+ "properties": {},
645
+ "required": []
646
+ }
647
+
648
+
649
+ @register_strategy(Entity)
650
+ class FindAndReplace(Strategy):
651
+ """Strategy for finding and replacing substrings in entity string attributes"""
652
+
653
+ strategy_description = 'Finds and replaces substrings in a string attribute of an entity'
654
+
655
+ def verify_executable(self):
656
+ """Schema covers required keys; this checks entity state schema can't see."""
657
+ attribute_name = self.strategy_request.param_config['attribute_name']
658
+
659
+ if not self.entity.has_attribute(attribute_name):
660
+ raise ValueError(f"Entity does not have attribute '{attribute_name}'")
661
+
662
+ attribute_value = self.entity.get_attribute(attribute_name)
663
+ if not isinstance(attribute_value, str):
664
+ raise ValueError(
665
+ f"Attribute '{attribute_name}' must be a string, got {type(attribute_value).__name__}"
666
+ )
667
+
668
+ async def apply(self) -> tuple:
669
+ """
670
+ Finds and replaces substrings in the specified entity attribute
671
+
672
+ param_config requirements:
673
+ - attribute_name: Name of the string attribute to modify
674
+ - find_string: The substring to search for
675
+ - replace_string: The substring to replace with
676
+ - replace_all: (optional) If True, replace all occurrences; if False, replace only first (default: True)
677
+ """
678
+ config = self.strategy_request.param_config
679
+ attribute_name = config['attribute_name']
680
+ find_string = config['find_string']
681
+ replace_string = config['replace_string']
682
+ replace_all = config.get('replace_all', True)
683
+
684
+ # Get the current attribute value
685
+ current_value = self.entity.get_attribute(attribute_name)
686
+
687
+ # Perform the replacement
688
+ if replace_all:
689
+ # Replace all occurrences
690
+ new_value = current_value.replace(find_string, replace_string)
691
+ else:
692
+ # Replace only the first occurrence
693
+ new_value = current_value.replace(find_string, replace_string, 1)
694
+
695
+ # Set the updated value back to the entity
696
+ self.entity.set_attribute(attribute_name, new_value)
697
+
698
+ # Save entity and get updated version
699
+ self.entity = await self.save_entity(self.entity)
700
+
701
+ # Keep the return payload small; callers only need the replacement count.
702
+ self.strategy_request.ret_val['replacements_made'] = (
703
+ current_value.count(find_string) if replace_all else (1 if find_string in current_value else 0)
704
+ )
705
+
706
+ return self.strategy_request, self.entity
707
+
708
+ @staticmethod
709
+ def get_request_schema():
710
+ """Return JSON Schema for FindAndReplace param_config."""
711
+ return {
712
+ "type": "object",
713
+ "properties": {
714
+ "attribute_name": {
715
+ "type": "string",
716
+ "description": "Name of the string attribute to modify"
717
+ },
718
+ "find_string": {
719
+ "type": "string",
720
+ "description": "The substring to search for"
721
+ },
722
+ "replace_string": {
723
+ "type": "string",
724
+ "description": "The substring to replace with"
725
+ },
726
+ "replace_all": {
727
+ "type": "boolean",
728
+ "description": "If true, replace all occurrences; if false, replace only first",
729
+ "default": True
730
+ }
731
+ },
732
+ "required": ["attribute_name", "find_string", "replace_string"]
733
+ }
734
+
735
+ @classmethod
736
+ def request_constructor(cls, target_entity_id, attribute_name: str,
737
+ find_string: str, replace_string: str,
738
+ replace_all: bool = True):
739
+ """
740
+ Convenience method to construct a find-and-replace strategy request.
741
+
742
+ Args:
743
+ target_entity_id: The entity to operate on
744
+ attribute_name: Name of the string attribute to modify
745
+ find_string: The substring to search for
746
+ replace_string: The substring to replace with
747
+ replace_all: If True, replace all occurrences; if False, replace only first
748
+ """
749
+ return cls._build_request(
750
+ target_entity_id=target_entity_id,
751
+ param_config={
752
+ "attribute_name": attribute_name,
753
+ "find_string": find_string,
754
+ "replace_string": replace_string,
755
+ "replace_all": replace_all,
756
+ },
757
+ )
758
+
759
+