diff --git a/RUNTIME_GUIDE.md b/RUNTIME_GUIDE.md index ce58c219..1c139669 100644 --- a/RUNTIME_GUIDE.md +++ b/RUNTIME_GUIDE.md @@ -262,3 +262,22 @@ approval, audit propagation, and zero-write denial evidence. --- To run test validations and business logic simulations locally, simply run `pytest` in the project root. + +## Explicit business operations + +For a business command spanning independent entity graphs, use a trusted +`BusinessOperation` registration. Its handler receives an explicit context; +existing generated `.save(context)` calls made through that context retain +independent ledgers while participating in one operation transaction. Ordinary +saves on the original context remain independent and cannot re-enter an active +operation. Register reviewed authorization, preparation, input schema and final +invariant validation; the runtime runs them and coordinates durable idempotency. + +The first provider qualification is file SQLite (`BEGIN IMMEDIATE`). Explicitly +initialize the operation tables with `service.ensure_business_operation_schema()` +at startup. Other providers fail closed until their concurrency protocol is +qualified. Commit uncertainty requires recovery with the original key; postcommit +sink errors must not be treated as a rolled-back write. + +See [`examples/business-operation/README.md`](examples/business-operation/README.md) +and its executable shipping example for the supported operation contract. diff --git a/examples/business-operation/README.md b/examples/business-operation/README.md new file mode 100644 index 00000000..40410a00 --- /dev/null +++ b/examples/business-operation/README.md @@ -0,0 +1,66 @@ +# Business operation: inventory shipping + +`BusinessOperation` groups independent entity graph saves into a single Python +runtime transaction. The provider qualified here is **file SQLite**. + +Run from the repository using its installed dependencies: + +```bash +PYTHONPATH=src python examples/business-operation/warehouse.py +python -m pytest tests/runtime/test_business_operation.py -q +``` + +`BusinessOperation` is a trusted server registration containing a complete typed +scalar input schema, authorization, preparation, handler, and invariant validator. +Every input field enters a versioned fingerprint. The validator runs even when +the handler forgets to enforce the reviewed domain contract. Review and protect +these registrations like application policy; the runtime cannot infer missing +business rules or defend against arbitrary code with raw database credentials. + +The handler receives an explicit operation context. Native graph saves and +existing generated entity `.save(context)` calls made through that context join +one database transaction. Ordinary independent saves keep their existing separate +transaction boundaries. Context supplies services, not a shared mutation ledger. +Each graph retains its Checker, Fix, mutation policy, trace, rollback and commit +callbacks. A caught graph error marks the whole operation rollback-only. + +The shipping handler changes stock and order through native TeaQL graph APIs. +It contains no transaction or idempotency protocol. A reviewed postcondition +requires exact inventory/order deltas and the correct returned business result. +The acceptance suite also uses real generated `WorkItem.save()` calls to verify +that the coordinator works with existing generated entities without patching +their source. + +At explicit startup, call `ensure_schema()` for domain metadata, then +`service.ensure_business_operation_schema()` for replay and committed-operation +audit tables. No DDL runs implicitly during a business operation. SQLite +`BEGIN IMMEDIATE` protects the complete read/decision/write interval across +processes. This trades write concurrency for a small, testable initial guarantee; +MySQL and PostgreSQL transactions alone are not automatically qualified. + +Successful business effects, replay snapshot and operation audit commit together. +An identical key and parameters return the original JSON result even after other +operations change the order. Different business parameters or operation version +with that key conflict. Keys are scoped by trusted active-root identity and +operation name. Authorization runs again before replay. No keys expire in v1; +retention/compaction, quotas and encryption policy remain production work. + +External audit sinks remain post-commit delivery. Sink failure is reported as +`GraphCommittedError(committed=True)`; the durable operation-audit row still +exists. Automatic outbox delivery and external side effects are outside this +minimal implementation. A commit exception is conservatively +`OPERATION_COMMIT_UNKNOWN`, never a claim of rollback; recover with the original +key and newly loaded state. Other failures retain their cause and report +`rolled_back` only if rollback succeeded. There is no automatic handler retry. + +Supported input fields are exactly `str`, `int`, and `bool`; missing/extra fields +and Python `bool` where `int` is required are rejected. Complex objects, +normalization and nullable input schemas require a separately reviewed extension. +Results must be JSON-serializable. Use one task per operation context; parallel +or escaped context use, nested operations and provider replacement are rejected. + +This example covers shipping, not complete transfer creation/receive/cancel. +Full schema-level inventory constraints, operation registry governance, arbitrary +provider routing, other databases, retention, and full harness/Assist rollout +remain outside its qualified scope. Strict independent delivery checks remain +necessary. diff --git a/examples/business-operation/warehouse.py b/examples/business-operation/warehouse.py new file mode 100644 index 00000000..0547ac12 --- /dev/null +++ b/examples/business-operation/warehouse.py @@ -0,0 +1,169 @@ +"""A small DDD shipping example using native TeaQL graph APIs. + +This is a hand-written domain facade, not a claim of generated operation APIs. +The runtime supplies transaction, idempotency and serialized SQLite execution. +""" + +import argparse +import asyncio +import json +from pathlib import Path +import tempfile + +from teaql.core.entity import EntityKey, EntityRoot +from teaql.core.expr import Expr +from teaql.core.meta import EntityDescriptor, PropertyDescriptor +from teaql.core.mutation import InsertCommand, UpdateCommand +from teaql.core.query import SelectQuery +from teaql.core.value import Value +from teaql.data_service import QueryRequest +from teaql.provider.sqlite import create_sqlite_service, SimpleSchemaProvider +from teaql.runtime import BusinessOperation, BusinessOperationError, ContextEntityRef, RuntimeModule + + +def descriptors(): + result = [] + for name, fields in ( + ('Stock', ('tenant', 'on_hand', 'reserved')), + ('TransferOrder', ('tenant', 'stock', 'quantity', 'shipped', 'received', 'cancelled')), + ): + entity = EntityDescriptor(name).table_name(name.lower() + '_data') + entity.property(PropertyDescriptor('id', 'i64').is_id().required()) + entity.property(PropertyDescriptor('version', 'i64').is_version().required()) + for field in fields: + entity.property(PropertyDescriptor(field, 'i64').required()) + result.append(entity) + return result + + +def context_for(path, tenant=1): + schema = SimpleSchemaProvider() + module = RuntimeModule.new() + for entity in descriptors(): + schema.register_entity(entity) + module.entity(entity) + service = create_sqlite_service(str(path), schema) + context = module.into_context().insert_resource('dataService', service) + context.with_schema_provider(service).with_active_root(ContextEntityRef('Tenant', tenant)) + context.with_user_identifier('warehouse-operator') + context.disable_sql_log() + return context + + +async def load(context, entity, identity): + tenant = context.require_active_root('Tenant').id + query = SelectQuery(entity).filter(Expr.new_and(Expr.eq('id', identity), Expr.eq('tenant', tenant))) + query.comment('load shipping state').purpose('validate and execute warehouse operation') + rows = (await context.require_resource('dataService').query(context, QueryRequest(query))).rows + if len(rows) != 1: + raise BusinessOperationError('REFERENCE_NOT_FOUND', f'{entity} is absent from the active tenant') + return rows[0] + + +async def save_command(context, command): + """One graph per command; the explicit operation coordinates their commit.""" + async def work(graph): + graph.context.preflight_mutation(command) + key = EntityKey(command.entity, command.values['id'].val if isinstance(command, InsertCommand) else command.id.val) + ledger = EntityRoot() + for field, value in command.values.items(): + ledger.set(key, field, value) + result = await graph.transaction.mutate( + graph.context, graph.request(command, graph.scope(key), ledger, key)) + if result.affected_rows != 1 or result.persisted_record is None: + raise BusinessOperationError('VERSION_CONFLICT', 'shipping state changed; retry the whole operation') + graph.after_commit(ledger.clear_committed) + return result.persisted_record + return await context.execute_graph_save(work, comment='persist shipping domain change') + + +async def ship(context, params): + q = params['quantity'] + if q <= 0: + raise BusinessOperationError('INVALID_QUANTITY', 'shipping quantity must be positive') + order = await load(context, 'TransferOrder', params['order_id']) + stock = await load(context, 'Stock', order['stock']) + if (q > order['quantity'] - order['shipped'] - order['cancelled'] + or stock['reserved'] < q or stock['on_hand'] < q): + raise BusinessOperationError('EXCEEDS_UNSHIPPED', 'quantity exceeds remaining order or reserved stock') + if not (0 <= stock['reserved'] <= stock['on_hand'] and + 0 <= order['received'] <= order['shipped'] <= order['quantity'] - order['cancelled']): + raise BusinessOperationError('INVALID_STATE', 'stored shipping state violates the declared invariants') + + # Domain behavior; no BEGIN, COMMIT, idempotency lookup, or retry protocol. + await save_command(context, UpdateCommand.new('Stock', stock['id']).expected_version(stock['version']) + .value('on_hand', stock['on_hand'] - q).value('reserved', stock['reserved'] - q)) + updated = await save_command(context, UpdateCommand.new('TransferOrder', order['id']).expected_version(order['version']) + .value('shipped', order['shipped'] + q)) + return {'order_id': updated['id'], 'shipped': updated['shipped'], 'quantity': q} + + +async def shipping_snapshot(context, params): + order = await load(context, 'TransferOrder', params['order_id']) + stock = await load(context, 'Stock', order['stock']) + return {'order': order, 'stock': stock} + + +async def validate_shipping(context, params, before, result): + """Reviewed domain contract, invoked by runtime even if handler omits checks.""" + after = await shipping_snapshot(context, params) + order, stock = before['order'], before['stock'] + q = params['quantity'] + if not (q > 0 and q <= order['quantity'] - order['shipped'] - order['cancelled'] + and 0 <= order['received'] <= order['shipped'] + and stock['on_hand'] >= stock['reserved'] >= q): + return False + expected_stock = dict(stock, on_hand=stock['on_hand'] - q, reserved=stock['reserved'] - q, + version=stock['version'] + 1) + expected_order = dict(order, shipped=order['shipped'] + q, version=order['version'] + 1) + return (after['stock'] == expected_stock and after['order'] == expected_order + and result == {'order_id': order['id'], 'shipped': order['shipped'] + q, 'quantity': q}) + + +SHIP = BusinessOperation( + name='ShipTransfer', version='1', root_type='Tenant', + parameters={'order_id': int, 'quantity': int}, + authorize=lambda context, params: context.user_identifier() == 'warehouse-operator', + prepare=shipping_snapshot, handler=ship, validate=validate_shipping, +) + + +async def initialize(path): + context = context_for(path) + await context.ensure_schema() + await context.require_resource('dataService').ensure_business_operation_schema() + await save_command(context, InsertCommand.new('Stock').value('id', 1).value('version', 1) + .value('tenant', 1).value('on_hand', 100).value('reserved', 30)) + await save_command(context, InsertCommand.new('TransferOrder').value('id', 1).value('version', 1) + .value('tenant', 1).value('stock', 1).value('quantity', 30) + .value('shipped', 0).value('received', 0).value('cancelled', 0)) + return context + + +async def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--worker', type=Path) + parser.add_argument('--key') + parser.add_argument('--quantity', type=int, default=10) + args = parser.parse_args() + if args.worker: + try: + result = await SHIP.execute(context_for(args.worker), key=args.key, + parameters={'order_id': 1, 'quantity': args.quantity}, comment='ship transfer') + print(json.dumps({'ok': True, 'result': result})) + except BusinessOperationError as error: + print(json.dumps({'ok': False, 'code': error.code, 'outcome': error.outcome})) + return + with tempfile.TemporaryDirectory() as directory: + context = await initialize(Path(directory) / 'stock.db') + first = await SHIP.execute(context, key='SHIP-1', parameters={'order_id': 1, 'quantity': 10}, comment='ship transfer') + replay = await SHIP.execute(context_for(Path(directory) / 'stock.db'), key='SHIP-1', + parameters={'order_id': 1, 'quantity': 10}, comment='retry ship transfer') + assert first == replay == {'order_id': 1, 'shipped': 10, 'quantity': 10} + stock = await load(context, 'Stock', 1) + assert (stock['on_hand'], stock['reserved']) == (90, 20) + print(json.dumps({'smoke': 'passed', 'result': first, 'replay_equal': True})) + + +if __name__ == '__main__': + asyncio.run(main()) diff --git a/scripts/verify-examples.sh b/scripts/verify-examples.sh index 6b5419dc..c756a876 100755 --- a/scripts/verify-examples.sh +++ b/scripts/verify-examples.sh @@ -2,7 +2,7 @@ set -euo pipefail repo="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -expected=(business-clock business-id conformance context-derived expression-profiles facet-trace fix-e-alignment internal-id mutation-policy natural-messages object-storage opaque-entity-reference order-management query-policy scalar-type-probe school-management task_board trace-chain typed-extension-spi) +expected=(business-clock business-id business-operation conformance context-derived expression-profiles facet-trace fix-e-alignment internal-id mutation-policy natural-messages object-storage opaque-entity-reference order-management query-policy scalar-type-probe school-management task_board trace-chain typed-extension-spi) mapfile -t actual < <(find "$repo/examples" -mindepth 1 -maxdepth 1 -type d -printf '%f\n' | sort) if [[ "${actual[*]}" != "${expected[*]}" ]]; then echo "example inventory changed; update scripts/verify-examples.sh: ${actual[*]}" >&2 @@ -42,6 +42,8 @@ TEAQL_CONTEXT_FIX_EVIDENCE_DIR="$evidence_directory/context-derived" python "$re TEAQL_NATURAL_MESSAGES_EVIDENCE_DIR="$evidence_directory/natural-messages" python "$repo/examples/natural-messages/verify-local.py" TEAQL_GENERATED_E_PROFILE_EVIDENCE_DIR="$evidence_directory/expression-profiles" \ python "$repo/examples/expression-profiles/verify-local.py" +PYTHONPATH="$repo/src" python "$repo/examples/business-operation/warehouse.py" +PYTHONPATH="$repo/src" python -m pytest -q "$repo/tests/runtime/test_business_operation.py" PYTHONPATH="$repo/examples/conformance:$repo/src" python -m app.main PYTHONPATH="$repo/src" python "$repo/examples/conformance/app/managed_creation.py" PYTHONPATH="$repo/src" python "$repo/examples/conformance/app/managed_sqlite.py" diff --git a/src/teaql/provider/sqlite/transport.py b/src/teaql/provider/sqlite/transport.py index faea75e6..48668a75 100644 --- a/src/teaql/provider/sqlite/transport.py +++ b/src/teaql/provider/sqlite/transport.py @@ -32,6 +32,8 @@ def _soundex(value: Optional[str]) -> str: return result.ljust(4, "0") class SqliteTransport(SqlTransactionTransport): + # BEGIN IMMEDIATE serializes the entire read/decision/write interval. + serializes_business_operations = True def __init__(self, db_path: str): self.db_path = db_path self._soundex_enabled = False @@ -167,8 +169,12 @@ async def execute_sql(self, query: CompiledQuery) -> tuple[int, int]: async def begin_sql(self) -> 'SqlTransactionTransportTx': db = await self._connect() - await self._prepare(db) - await db.execute("BEGIN IMMEDIATE") + try: + await self._prepare(db) + await db.execute("BEGIN IMMEDIATE") + except BaseException: + await db.close() + raise return _SqliteTransaction(db, self._bind_values, self._decode_value) diff --git a/src/teaql/runtime/__init__.py b/src/teaql/runtime/__init__.py index 5a17534e..3102ea09 100644 --- a/src/teaql/runtime/__init__.py +++ b/src/teaql/runtime/__init__.py @@ -11,6 +11,7 @@ from .logging import RuntimeLogger, RuntimeLoggingError from .context_fix import ContextFix, ContextFixInput from .graph_session import GraphMutationSession, GraphCommittedError +from .business_operation import BusinessOperation, BusinessOperationError, BusinessOperationCommitUnknown from .store import DataStore from .audit import RawAuditEvent, SafeAuditEvent, MutationAuditKind from .business_clock import BusinessClock, FixedBusinessClock, SystemBusinessClock @@ -78,6 +79,7 @@ "CheckerMessageRequest", "standard_checker_message_renderer", "EntityJSONError", "EntityJSONField", "EntityJSONSchema", "ExpressionPath", "TeaQLNotLoadedError", + "BusinessOperation", "BusinessOperationError", "BusinessOperationCommitUnknown", "Checker", "CheckerRegistry", "DiagnosticTelemetryAdapter", "RequestPolicy", "RequestPolicyInput", "RuntimeTelemetryAdapter", "RuntimeTelemetryInput", "SafeAuditEventSink", "SchemaCapability", diff --git a/src/teaql/runtime/business_operation.py b/src/teaql/runtime/business_operation.py new file mode 100644 index 00000000..178fafaf --- /dev/null +++ b/src/teaql/runtime/business_operation.py @@ -0,0 +1,221 @@ +"""Explicit single-database business operations, initially qualified on SQLite. + +Graphs keep independent ledgers. Only saves made through the context passed to +the registered handler participate in this operation's one database transaction. +""" + +from __future__ import annotations + +import asyncio +from copy import copy +from dataclasses import dataclass +import hashlib +from inspect import isawaitable +import json +from types import MappingProxyType +from typing import Callable, Mapping + +from teaql.core.request_intent import MutationIntent +from .graph_session import GraphCommittedError, GraphMutationSession +from .i18n import CheckException + + +class BusinessOperationError(RuntimeError): + def __init__(self, code, message, *, outcome="not_started"): + self.code = code + self.outcome = outcome + super().__init__(message) + + +class BusinessOperationCommitUnknown(BusinessOperationError): + def __init__(self): + super().__init__( + "OPERATION_COMMIT_UNKNOWN", + "Commit outcome is unknown; recover using the original idempotency key", + outcome="unknown", + ) + + +def _json(value): + return json.dumps(value, ensure_ascii=False, sort_keys=True, + separators=(",", ":"), allow_nan=False) + + +@dataclass(frozen=True) +class BusinessOperation: + """Trusted registration, not a descriptor supplied by a remote caller. + + ``parameters`` is the complete, scalar-only v1 business input schema. Every + field participates in the fingerprint. Authorization is mandatory and runs + on every invocation, including replay. Successful results must be JSON data. + """ + + name: str + version: str + root_type: str + parameters: Mapping[str, type] + authorize: Callable + prepare: Callable + handler: Callable + validate: Callable + + def __post_init__(self): + for value in (self.name, self.version, self.root_type): + if not isinstance(value, str) or not value.strip() or len(value) > 128: + raise ValueError("operation name, version and root type are required (max 128)") + schema = dict(self.parameters) + if (not schema or any(not isinstance(key, str) or not key or + kind not in (str, int, bool) for key, kind in schema.items())): + raise ValueError("v1 parameters require named str, int or bool fields") + if not all(callable(value) for value in (self.authorize, self.prepare, self.handler, self.validate)): + raise TypeError("authorization, preparation, handler and invariant validator are required") + object.__setattr__(self, "parameters", MappingProxyType(schema)) + + async def execute(self, context, *, key: str, parameters: Mapping, comment: str): + intent = MutationIntent(comment) + if not isinstance(key, str) or not key.strip() or len(key) > 256: + raise BusinessOperationError("OPERATION_INPUT_INVALID", "idempotency key required (max 256)") + if (not isinstance(parameters, Mapping) or set(parameters) != set(self.parameters) + or any(type(parameters[name]) is not kind for name, kind in self.parameters.items())): + raise BusinessOperationError("OPERATION_INPUT_INVALID", "parameters must match the complete registered schema") + # Values are scalars; freeze caller input before the first await. + params = MappingProxyType(dict(parameters)) + root = context.require_active_root(self.root_type) + if type(root.id) is not int or root.id <= 0: + raise BusinessOperationError("OPERATION_SCOPE_INVALID", "active root must have a valid identity") + if context._graph_session is not None or context._business_operation is not None: + raise BusinessOperationError("OPERATION_NESTING_UNSUPPORTED", "business operations cannot nest") + guard = context._graph_save_guard.get() + if guard is not None and guard['active']: + raise BusinessOperationError("OPERATION_NESTING_UNSUPPORTED", "an explicit operation cannot enter an active graph") + permission = self.authorize(context, params) + if isawaitable(permission): + permission = await permission + if permission is not True: + raise BusinessOperationError("OPERATION_DENIED", "business operation authorization denied") + fingerprint = hashlib.sha256(_json({"version": self.version, "parameters": dict(params)}).encode()).hexdigest() + scope = _json([root.entity, root.id]) + provider = context.require_resource("dataService") + begin = getattr(provider, "begin_business_operation", None) + if not callable(begin): + raise BusinessOperationError("OPERATION_UNSUPPORTED", "provider does not support business operations") + async with context._graph_save_lock: + transaction = await begin(context) + session = _BusinessOperationSession(context, transaction) + guard = {'active': True} + token = context._graph_save_guard.set(guard) + try: + stored = await transaction.lookup_business_result(scope, self.name, key) + if stored is not None: + if stored["fingerprint"] != fingerprint: + raise BusinessOperationError("IDEMPOTENCY_CONFLICT", "same key has different business parameters or operation version") + # A replay has no writes. End its read transaction before return. + replay = json.loads(stored["result"]) + await transaction.rollback(session.context) + return replay + before = await self.prepare(session.context, params) + result = await self.handler(session.context, params) + session.require_active() + if session.failed: + raise BusinessOperationError("OPERATION_ROLLBACK_ONLY", "a participating graph failed; the operation cannot commit") + if await self.validate(session.context, params, before, result) is not True: + raise BusinessOperationError("OPERATION_INVARIANT_FAILED", "registered business postconditions rejected the operation") + session.require_active() + if session.failed: + raise BusinessOperationError("OPERATION_ROLLBACK_ONLY", "validation cannot hide a failed graph") + encoded = _json(result) + await transaction.store_business_result(scope, self.name, key, fingerprint, encoded, + context.user_identifier()) + try: + await transaction.commit(session.context) + except BaseException as error: + # A provider exception does not prove COMMIT did not happen. + raise BusinessOperationCommitUnknown() from error + except BaseException as error: + rollback_failed = False + recovery_failures = [] + try: + await transaction.rollback(session.context) + except BaseException: + rollback_failed = True + for graph in reversed(session.graphs): + recovery_failures.extend(await graph.rolled_back()) + if isinstance(error, BusinessOperationError) and error.outcome != "unknown": + error.outcome = "unknown" if rollback_failed else "rolled_back" + if isinstance(error, BusinessOperationError): + error.state_recovery_failures = tuple(recovery_failures) + if isinstance(error, Exception) and not isinstance(error, BusinessOperationError): + failure = BusinessOperationError( + "OPERATION_EXECUTION_FAILED", str(error), + outcome="unknown" if rollback_failed else "rolled_back", + ) + failure.state_recovery_failures = tuple(recovery_failures) + raise failure from error + raise + else: + failures = [] + for graph in session.graphs: + try: + await graph.committed() + except GraphCommittedError as error: + failures.extend(error.failures) + if failures: + raise GraphCommittedError(failures) + # Detach the response as well as persisting its original snapshot. + return json.loads(encoded) + finally: + session.close() + guard['active'] = False + context._graph_save_guard.reset(token) + + +class _BusinessOperationSession: + def __init__(self, context, transaction): + self.transaction = transaction + self.graphs = [] + self.failed = False + self.active = True + self.saving = False + self.owner = asyncio.current_task() + self.context = copy(context) + self.context._resources = dict(context._resources) + self.context._resources['dataService'] = transaction + self.context._business_operation = self + + def require_active(self): + if not self.active or asyncio.current_task() is not self.owner: + raise BusinessOperationError("OPERATION_CONTEXT_INVALID", "operation context is closed or used by another task") + + async def save_graph(self, work, *, comment, prepare=None): + self.require_active() + if self.saving or self.failed: + raise BusinessOperationError("OPERATION_ROLLBACK_ONLY", "operation graph is reentrant or has already failed") + self.saving = True + try: + graph = GraphMutationSession(self.context, self.transaction, MutationIntent(comment)) + self.graphs.append(graph) + try: + if prepare is not None: + graph._preparing = True + try: + await prepare(graph) + finally: + graph._preparing = False + result = await work(graph) + graph.context._mutation_policy.ensure_graph_complete() + return result + except CheckException as failure: + failure.refresh_presentation(graph.context.render_checker_graph_results( + failure.violations, graph._checker_messages, + (graph._checker_messages.model, graph._checker_origin))) + raise + except BaseException: + self.failed = True + raise + finally: + self.saving = False + + def close(self): + self.active = False + for graph in self.graphs: + graph.close() diff --git a/src/teaql/runtime/context.py b/src/teaql/runtime/context.py index deb8e935..2f6e0756 100644 --- a/src/teaql/runtime/context.py +++ b/src/teaql/runtime/context.py @@ -129,6 +129,7 @@ def __init__(self, *, runtime_logger=None, log_name=None, model_names=()): f"teaql_graph_save_guard_{id(self)}", default=None ) self._graph_session = None + self._business_operation = None self._audit_journal = None self._fix_evidence_current: List[FixEvidence] = [] self._fix_evidence_last: List[FixEvidence] = [] @@ -234,6 +235,8 @@ def decode_entity_reference( async def execute_graph_save(self, work, *, comment=None, prepare=None): """Run ``work(session)``; never implicitly join another root save.""" + if self._business_operation is not None and self._graph_session is None: + return await self._business_operation.save_graph(work, comment=comment, prepare=prepare) from teaql.core.request_intent import MutationIntent from .graph_session import GraphMutationSession intent = MutationIntent(comment) @@ -422,6 +425,8 @@ def with_metadata(self, metadata: Any) -> 'UserContext': return self def insert_resource(self, resource_type: str, resource: Any): + if self._business_operation is not None and resource_type in ('dataService', 'schema_provider', 'active_root'): + raise RuntimeError('business operation cannot change its database participant') inferred_schema = None if resource_type == "request_policy": resource = validate_request_policy(resource) @@ -443,10 +448,12 @@ def insert_resource(self, resource_type: str, resource: Any): return self def get_resource(self, resource_type: str) -> Optional[Any]: + if self._business_operation is not None and resource_type == 'dataService': + self._business_operation.require_active() return self._resources.get(resource_type) def require_resource(self, resource_type: str) -> Any: - res = self._resources.get(resource_type) + res = self.get_resource(resource_type) if res is None: raise Exception(f"Resource {resource_type} not found") return res @@ -646,6 +653,8 @@ async def ensure_business_id( ) def with_schema_provider(self, provider: SchemaCapability) -> 'UserContext': + if self._business_operation is not None: + raise RuntimeError('business operation cannot change its database participant') self._resources["schema_provider"] = validate_schema_capability(provider) self._explicit_schema_provider = True return self @@ -654,6 +663,8 @@ def set_schema_provider(self, provider: SchemaCapability): self.with_schema_provider(provider) async def ensure_schema(self): + if self._business_operation is not None: + raise RuntimeError('schema changes are not business transaction participants') provider = self.get_resource("schema_provider") if provider: from ._schema_capability import SCHEMA_CAPABILITY @@ -1160,6 +1171,10 @@ def mutation_policy_execution(self, request: Any): return scope def _require_mutation_invocation(self): + if self._business_operation is not None: + self._business_operation.require_active() + if self._graph_session is None: + raise RuntimeError('business mutations require an explicit graph save') if self._audit_journal is not None: self._audit_journal.require_active() if self._graph_session is not None: diff --git a/src/teaql/sql/business_operation.py b/src/teaql/sql/business_operation.py new file mode 100644 index 00000000..81c64bb8 --- /dev/null +++ b/src/teaql/sql/business_operation.py @@ -0,0 +1,43 @@ +"""SQLite-only durable replay store; all SQL runs on the owning transaction.""" + +from teaql.core.value import Value +from .types import CompiledQuery + + +SCHEMAS = ("""CREATE TABLE IF NOT EXISTS teaql_operation_results ( + scope TEXT NOT NULL, + operation TEXT NOT NULL, + idempotency_key TEXT NOT NULL, + fingerprint TEXT NOT NULL, + result TEXT NOT NULL, + PRIMARY KEY (scope, operation, idempotency_key) +)""", """CREATE TABLE IF NOT EXISTS teaql_operation_audit ( + scope TEXT NOT NULL, + operation TEXT NOT NULL, + idempotency_key TEXT NOT NULL, + fingerprint TEXT NOT NULL, + actor TEXT NOT NULL, + PRIMARY KEY (scope, operation, idempotency_key) +)""") + + +async def lookup(transport, scope, operation, key): + rows = await transport.fetch_all_sql(CompiledQuery( + "SELECT fingerprint, result FROM teaql_operation_results " + "WHERE scope = ? AND operation = ? AND idempotency_key = ?", + [Value.from_any(value) for value in (scope, operation, key)], + )) + return rows[0] if rows else None + + +async def store(transport, scope, operation, key, fingerprint, result, actor): + await transport.execute_sql(CompiledQuery( + "INSERT INTO teaql_operation_results " + "(scope, operation, idempotency_key, fingerprint, result) VALUES (?, ?, ?, ?, ?)", + [Value.from_any(value) for value in (scope, operation, key, fingerprint, result)], + )) + await transport.execute_sql(CompiledQuery( + "INSERT INTO teaql_operation_audit " + "(scope, operation, idempotency_key, fingerprint, actor) VALUES (?, ?, ?, ?, ?)", + [Value.from_any(value) for value in (scope, operation, key, fingerprint, actor)], + )) diff --git a/src/teaql/sql/executor.py b/src/teaql/sql/executor.py index bd3981c2..86dca75e 100644 --- a/src/teaql/sql/executor.py +++ b/src/teaql/sql/executor.py @@ -379,7 +379,7 @@ def capabilities(self) -> DataServiceCapabilities: return DataServiceCapabilities( query=True, mutation=True, - transaction=False, # Could be determined from transport + transaction=isinstance(self.transport, SqlTransactionTransport), schema=True, id_generation=True, batch_mutation=True, @@ -1468,6 +1468,25 @@ async def begin(self, context: 'UserContext') -> 'teaql.data_service.Transaction tx = await self.transport.begin_sql() return SqlDataServiceTransaction(self.dialect, tx, self.schema_provider) + def _require_business_operations(self): + from teaql.runtime.business_operation import BusinessOperationError + path = getattr(self.transport, 'db_path', '') + if (not getattr(self.transport, 'serializes_business_operations', False) + or not path or path == ':memory:' or 'mode=memory' in path or path.startswith('file::memory:')): + raise BusinessOperationError('OPERATION_UNSUPPORTED', + 'business operations require a qualified file-SQLite provider') + + async def ensure_business_operation_schema(self): + """Explicit startup step, never implicit DDL in a business operation.""" + from .business_operation import SCHEMAS + self._require_business_operations() + for statement in SCHEMAS: + await self.transport.execute_sql(CompiledQuery(statement, [])) + + async def begin_business_operation(self, context): + self._require_business_operations() + return await self.begin(context) + class SqlDataServiceTransaction(QueryExecutor, MutationExecutor): def __init__(self, dialect: SqlDialect, transport: SqlTransactionTransportTx, schema_provider: SchemaProvider): self.dialect = dialect @@ -1515,6 +1534,14 @@ async def next_id(self, entity: str) -> int: executor = SqlDataServiceExecutor(self.dialect, self.transport, self.schema_provider) return await executor.next_id(entity) + async def lookup_business_result(self, scope, operation, key): + from .business_operation import lookup + return await lookup(self.transport, scope, operation, key) + + async def store_business_result(self, scope, operation, key, fingerprint, result, actor): + from .business_operation import store + await store(self.transport, scope, operation, key, fingerprint, result, actor) + async def ensure_id_floor(self, entity: str, floor: int) -> None: executor = SqlDataServiceExecutor(self.dialect, self.transport, self.schema_provider) await executor.ensure_id_floor(entity, floor) diff --git a/tests/runtime/test_business_operation.py b/tests/runtime/test_business_operation.py new file mode 100644 index 00000000..0d12d9d4 --- /dev/null +++ b/tests/runtime/test_business_operation.py @@ -0,0 +1,490 @@ +"""Independent file-SQLite acceptance for the shipping operation boundary.""" + +import asyncio +from dataclasses import replace +import importlib.util +import json +import os +from pathlib import Path +import sqlite3 +import sys + +import pytest + +from teaql.runtime import BusinessOperationError, BusinessOperationCommitUnknown, GraphCommittedError + + +ROOT = Path(__file__).resolve().parents[2] +EXAMPLE = ROOT / 'examples' / 'business-operation' +spec = importlib.util.spec_from_file_location('shipping_example', EXAMPLE / 'warehouse.py') +warehouse = importlib.util.module_from_spec(spec) +spec.loader.exec_module(warehouse) + + +@pytest.fixture +async def shipping(tmp_path): + path = tmp_path / 'warehouse.db' + context = await warehouse.initialize(path) + return path, context + + +def state(path): + # Independent connection, not the application's response or cached entities. + with sqlite3.connect(path) as db: + return { + 'stock': db.execute('SELECT on_hand,reserved,version FROM stock_data WHERE id=1').fetchone(), + 'order': db.execute('SELECT quantity,shipped,received,cancelled,version FROM transferorder_data WHERE id=1').fetchone(), + 'results': db.execute('SELECT COUNT(*) FROM teaql_operation_results').fetchone()[0], + 'audit': db.execute('SELECT COUNT(*) FROM teaql_operation_audit').fetchone()[0], + } + + +async def execute(context, key='SHIP-1', quantity=10, order_id=1, operation=None): + return await (operation or warehouse.SHIP).execute( + context, key=key, parameters={'order_id': order_id, 'quantity': quantity}, comment='ship inventory') + + +@pytest.mark.asyncio +async def test_ship_replay_restart_and_immutable_historical_result(shipping): + path, context = shipping + assert context.require_resource('dataService').capabilities().transaction is True + first = await execute(context) + assert first == {'order_id': 1, 'shipped': 10, 'quantity': 10} + assert state(path) == {'stock': (90, 20, 2), 'order': (30, 10, 0, 0, 2), 'results': 1, 'audit': 1} + first['shipped'] = 999 + await execute(context, key='SHIP-2') + # A genuinely new process must replay the original snapshot, not current shipped=20. + replay = await worker(path, 'SHIP-1', 10) + assert replay == {'ok': True, 'result': {'order_id': 1, 'shipped': 10, 'quantity': 10}} + assert state(path) == {'stock': (80, 10, 3), 'order': (30, 20, 0, 0, 3), 'results': 2, 'audit': 2} + + +@pytest.mark.asyncio +@pytest.mark.parametrize('parameters', [ + {'order_id': 1, 'quantity': 11}, {'order_id': 2, 'quantity': 10}, +]) +async def test_same_key_different_parameters_rejected(shipping, parameters): + path, context = shipping + await execute(context) + before = state(path) + with pytest.raises(BusinessOperationError) as caught: + await warehouse.SHIP.execute(context, key='SHIP-1', parameters=parameters, comment='retry') + assert caught.value.code == 'IDEMPOTENCY_CONFLICT' + assert caught.value.outcome == 'rolled_back' + assert state(path) == before + + +@pytest.mark.asyncio +async def test_version_change_cannot_reexecute_existing_key(shipping): + path, context = shipping + await execute(context) + before = state(path) + with pytest.raises(BusinessOperationError, match='different business parameters'): + await execute(context, operation=replace(warehouse.SHIP, version='2')) + assert state(path) == before + + +@pytest.mark.asyncio +@pytest.mark.parametrize('quantity,order_id', [(0, 1), (-1, 1), (31, 1), (10, 0), (10, 999)]) +async def test_domain_rejection_changes_nothing(shipping, quantity, order_id): + path, context = shipping + before = state(path) + with pytest.raises(BusinessOperationError): + await execute(context, quantity=quantity, order_id=order_id) + assert state(path) == before + + +@pytest.mark.asyncio +@pytest.mark.parametrize('parameters', [ + {'order_id': 1}, {'order_id': 1, 'quantity': True}, + {'order_id': 1, 'quantity': '10'}, {'order_id': 1, 'quantity': 10, 'shipped': 10}, +]) +async def test_complete_typed_input_required(shipping, parameters): + path, context = shipping + before = state(path) + with pytest.raises(BusinessOperationError) as caught: + await warehouse.SHIP.execute(context, key='SHIP-1', parameters=parameters, comment='invalid input') + assert caught.value.code == 'OPERATION_INPUT_INVALID' + assert state(path) == before + + +@pytest.mark.asyncio +async def test_authorization_is_required_on_replay_and_tenant_reference_is_scoped(shipping): + path, context = shipping + await execute(context) + before = state(path) + denied = replace(warehouse.SHIP, authorize=lambda context, params: False) + with pytest.raises(BusinessOperationError) as caught: + await execute(context, operation=denied) + assert caught.value.code == 'OPERATION_DENIED' + with pytest.raises(BusinessOperationError) as caught: + await execute(warehouse.context_for(path, tenant=2), key='SHIP-2') + assert caught.value.code == 'REFERENCE_NOT_FOUND' + assert state(path) == before + + +@pytest.mark.asyncio +@pytest.mark.parametrize('table,verb', [ + ('stock_data', 'UPDATE'), ('transferorder_data', 'UPDATE'), + ('teaql_operation_results', 'INSERT'), ('teaql_operation_audit', 'INSERT'), +]) +async def test_real_database_failure_rolls_back_every_participant(shipping, table, verb): + path, context = shipping + before = state(path) + with sqlite3.connect(path) as db: + db.execute(f"CREATE TRIGGER reject_write BEFORE {verb} ON {table} BEGIN SELECT RAISE(ABORT, 'INDEPENDENT_INJECTED_FAILURE'); END") + with pytest.raises(Exception, match='INDEPENDENT_INJECTED_FAILURE'): + await execute(context) + assert state(path) == before + # Same context and key can be retried; no poisoned transaction or partial data. + with sqlite3.connect(path) as db: + db.execute('DROP TRIGGER reject_write') + assert (await execute(context))['shipped'] == 10 + assert state(path)['stock'] == (90, 20, 2) + + +@pytest.mark.asyncio +async def test_caught_graph_error_still_forces_whole_operation_rollback(shipping): + path, context = shipping + before = state(path) + with sqlite3.connect(path) as db: + db.execute("CREATE TRIGGER reject_order BEFORE UPDATE ON transferorder_data BEGIN SELECT RAISE(ABORT, 'MUST_ROLL_BACK'); END") + + async def broken_handler(context, params): + try: + await warehouse.ship(context, params) + except Exception: + return {'ok': True} # A model must not be able to turn a failed graph into success. + + with pytest.raises(BusinessOperationError) as caught: + await execute(context, operation=replace(warehouse.SHIP, handler=broken_handler)) + assert caught.value.code == 'OPERATION_ROLLBACK_ONLY' + assert state(path) == before + + +@pytest.mark.asyncio +async def test_runtime_enforces_registered_rules_when_handler_omits_order_write(shipping): + path, context = shipping + before = state(path) + async def incomplete_handler(context, params): + stock = await warehouse.load(context, 'Stock', 1) + await warehouse.save_command(context, warehouse.UpdateCommand.new('Stock', 1) + .expected_version(stock['version']).value('on_hand', 90).value('reserved', 20)) + return {'order_id': 1, 'shipped': 10, 'quantity': 10} + with pytest.raises(BusinessOperationError) as caught: + await execute(context, operation=replace(warehouse.SHIP, handler=incomplete_handler)) + assert caught.value.code == 'OPERATION_INVARIANT_FAILED' + assert state(path) == before + + +@pytest.mark.asyncio +async def test_ordinary_independent_saves_do_not_implicitly_become_business_transaction(shipping): + path, context = shipping + with sqlite3.connect(path) as db: + db.execute("CREATE TRIGGER reject_order BEFORE UPDATE ON transferorder_data BEGIN SELECT RAISE(ABORT, 'BASELINE_FAILURE'); END") + with pytest.raises(Exception, match='BASELINE_FAILURE'): + await warehouse.ship(context, {'order_id': 1, 'quantity': 10}) + # Retained unsafe baseline: demonstrates exactly why an explicit operation is needed. + assert state(path) == {'stock': (90, 20, 2), 'order': (30, 0, 0, 0, 1), 'results': 0, 'audit': 0} + + +async def subprocess_code(code, *args): + paths = [str(ROOT / 'src'), str(EXAMPLE)] + if extra_paths := os.environ.get('PYTHONPATH'): + paths.append(extra_paths) + env = dict(os.environ, PYTHONPATH=os.pathsep.join(paths)) + process = await asyncio.create_subprocess_exec( + sys.executable, '-c', code, *(str(arg) for arg in args), env=env, + stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) + stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=30) + return process.returncode, stdout.decode(), stderr.decode() + + +async def worker(path, key, quantity, gate=None): + if gate is not None: + code = ''' +import asyncio, json, os, sys +from pathlib import Path +import warehouse +from teaql.runtime import BusinessOperationError +async def main(): + context = warehouse.context_for(sys.argv[1]) + transport = context.require_resource('dataService').transport + begin = transport.begin_sql + gate = Path(sys.argv[4]) + async def barrier_begin(): + gate.with_name(gate.name + '.ready.' + str(os.getpid())).touch() + while not gate.exists(): await asyncio.sleep(0.01) + return await begin() + transport.begin_sql = barrier_begin + try: + result = await warehouse.SHIP.execute(context, key=sys.argv[2], parameters={'order_id':1,'quantity':int(sys.argv[3])}, comment='concurrent ship') + print(json.dumps({'ok':True,'result':result})) + except BusinessOperationError as error: + print(json.dumps({'ok':False,'code':error.code,'outcome':error.outcome})) +asyncio.run(main()) +''' + status, stdout, stderr = await subprocess_code(code, path, key, quantity, gate) + assert status == 0, stderr + return json.loads(stdout) + process = await asyncio.create_subprocess_exec( + sys.executable, str(EXAMPLE / 'warehouse.py'), '--worker', str(path), '--key', key, + '--quantity', str(quantity), stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) + stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=30) + assert process.returncode == 0, stderr.decode() + return json.loads(stdout) + + +async def concurrent_workers(path, requests): + gate = path.with_name('start-gate') + tasks = [asyncio.create_task(worker(path, key, quantity, gate)) for key, quantity in requests] + try: + async def wait_ready(): + while len(list(path.parent.glob('start-gate.ready.*'))) != len(tasks): + await asyncio.sleep(0.01) + await asyncio.wait_for(wait_ready(), timeout=15) + gate.touch() + return await asyncio.gather(*tasks) + finally: + gate.touch() + await asyncio.gather(*tasks, return_exceptions=True) + + +@pytest.mark.asyncio +async def test_concurrent_processes_same_key_execute_once(shipping): + path, _ = shipping + results = await concurrent_workers(path, [('SAME', 10)] * 4) + assert results == [{'ok': True, 'result': {'order_id': 1, 'shipped': 10, 'quantity': 10}}] * 4 + assert state(path) == {'stock': (90, 20, 2), 'order': (30, 10, 0, 0, 2), 'results': 1, 'audit': 1} + + +@pytest.mark.asyncio +async def test_concurrent_processes_different_keys_cannot_overship(shipping): + path, _ = shipping + results = await concurrent_workers(path, [('A', 20), ('B', 20)]) + assert sorted(result['ok'] for result in results) == [False, True] + assert [result['code'] for result in results if not result['ok']] == ['EXCEEDS_UNSHIPPED'] + current = state(path) + assert current == {'stock': (80, 10, 2), 'order': (30, 20, 0, 0, 2), 'results': 1, 'audit': 1} + assert current['stock'][0] + current['order'][1] - current['order'][2] == 100 + + +@pytest.mark.asyncio +@pytest.mark.parametrize('after_commit,exit_code', [(False, 21), (True, 22)]) +async def test_process_exit_before_or_after_commit_recovers_by_same_key(shipping, after_commit, exit_code): + path, context = shipping + code = ''' +import asyncio, os, sys +from dataclasses import replace +import warehouse +async def main(): + context = warehouse.context_for(sys.argv[1]) + if sys.argv[2] == 'True': + transport = context.require_resource('dataService').transport + begin = transport.begin_sql + async def observed_begin(): + tx = await begin() + commit = tx.commit_sql + async def die_after_commit(): + await commit() + os._exit(22) + tx.commit_sql = die_after_commit + return tx + transport.begin_sql = observed_begin + operation = warehouse.SHIP + else: + save = warehouse.save_command + async def die_after_stock(context, command): + result = await save(context, command) + if command.entity == 'Stock': os._exit(21) + return result + warehouse.save_command = die_after_stock + operation = warehouse.SHIP + await operation.execute(context, key='CRASH', parameters={'order_id':1,'quantity':10}, comment='crash probe') +asyncio.run(main()) +''' + status, stdout, stderr = await subprocess_code(code, path, after_commit) + assert status == exit_code, (stdout, stderr) + assert state(path)['results'] == (1 if after_commit else 0) + assert state(path)['stock'] == ((90, 20, 2) if after_commit else (100, 30, 1)) + assert (await execute(context, key='CRASH'))['shipped'] == 10 + assert state(path)['stock'] == (90, 20, 2) + + +@pytest.mark.asyncio +async def test_commit_exception_is_unknown_and_original_key_recovers(shipping, monkeypatch): + path, context = shipping + transport = context.require_resource('dataService').transport + begin = transport.begin_sql + + async def observed_begin(): + tx = await begin() + commit = tx.commit_sql + async def lost_acknowledgement(): + await commit() + raise ConnectionError('commit acknowledgement lost') + tx.commit_sql = lost_acknowledgement + return tx + + monkeypatch.setattr(transport, 'begin_sql', observed_begin) + with pytest.raises(BusinessOperationCommitUnknown) as caught: + await execute(context) + assert caught.value.outcome == 'unknown' + assert state(path)['stock'] == (90, 20, 2) + assert (await execute(warehouse.context_for(path)))['shipped'] == 10 + assert state(path)['results'] == state(path)['audit'] == 1 + + +@pytest.mark.asyncio +async def test_postcommit_sink_failure_is_committed_and_replay_is_safe(shipping): + path, context = shipping + class Sink: + def on_safe_event(self, context, event): + raise RuntimeError('sink unavailable') + context.with_app_audit_event_sink(Sink()) + with pytest.raises(GraphCommittedError) as caught: + await execute(context) + assert caught.value.committed is True + assert state(path)['stock'] == (90, 20, 2) + assert (await execute(context))['shipped'] == 10 + + +@pytest.mark.asyncio +async def test_explicit_operation_context_cannot_escape_or_change_provider(shipping): + path, context = shipping + captured = [] + async def handler(owned, params): + captured.append(owned) + with pytest.raises(RuntimeError, match='participant'): + owned.insert_resource('dataService', context.require_resource('dataService')) + with pytest.raises(RuntimeError, match='participant'): + owned.with_schema_provider(context.require_resource('dataService')) + with pytest.raises(RuntimeError, match='participant'): + owned.with_active_root(warehouse.ContextEntityRef('Tenant', 2)) + with pytest.raises(RuntimeError, match='schema changes'): + await owned.ensure_schema() + async def child(): + with pytest.raises(BusinessOperationError, match='another task'): + await warehouse.load(owned, 'Stock', 1) + await asyncio.create_task(child()) + return await warehouse.ship(owned, params) + await execute(context, operation=replace(warehouse.SHIP, handler=handler)) + with pytest.raises(BusinessOperationError, match='closed'): + await warehouse.load(captured[0], 'Stock', 1) + assert state(path)['results'] == 1 + + +@pytest.mark.asyncio +async def test_cancelled_handler_rolls_back_and_keeps_original_key_retryable(shipping): + path, context = shipping + before = state(path) + staged = asyncio.Event() + async def handler(owned, params): + await warehouse.ship(owned, params) + staged.set() + await asyncio.Future() + task = asyncio.create_task(execute(context, operation=replace(warehouse.SHIP, handler=handler))) + await asyncio.wait_for(staged.wait(), timeout=5) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + assert state(path) == before + assert (await execute(context))['shipped'] == 10 + + +@pytest.mark.asyncio +async def test_unqualified_provider_rejects_before_handler(shipping): + _, context = shipping + service = context.require_resource('dataService') + service.transport.serializes_business_operations = False + async def handler(context, params): + pytest.fail('handler must not run without qualified serialization') + with pytest.raises(BusinessOperationError) as caught: + await execute(context, operation=replace(warehouse.SHIP, handler=handler)) + assert caught.value.code == 'OPERATION_UNSUPPORTED' + + +@pytest.mark.asyncio +async def test_nested_operation_and_original_context_save_are_rejected(shipping): + path, context = shipping + async def handler(owned, params): + with pytest.raises(BusinessOperationError) as caught: + await execute(owned, key='NESTED') + assert caught.value.code == 'OPERATION_NESTING_UNSUPPORTED' + with pytest.raises(RuntimeError, match='re-enter'): + await warehouse.ship(context, params) + return await warehouse.ship(owned, params) + await execute(context, operation=replace(warehouse.SHIP, handler=handler)) + assert state(path)['stock'] == (90, 20, 2) + assert state(path)['results'] == 1 + + +@pytest.mark.asyncio +async def test_independent_operations_on_same_context_serialize(shipping): + path, context = shipping + result = await asyncio.gather(execute(context, key='ONE'), execute(context, key='TWO')) + assert sorted(row['shipped'] for row in result) == [10, 20] + assert state(path)['stock'] == (80, 10, 3) + assert state(path)['results'] == state(path)['audit'] == 2 + + +@pytest.mark.asyncio +async def test_real_generated_entities_join_only_explicit_operation_context(tmp_path): + # Isolate generated Q/models imports from other generated fixtures in this suite. + code = ''' +import asyncio, json, sqlite3, sys +from dataclasses import replace +from pathlib import Path +sys.path.insert(0, sys.argv[2]) +from runtime_module import GENERATED_RUNTIME_MODULE +from Q import Q +from teaql.data_service import SQLiteTeaQLClient +from teaql.runtime import UserContext, ContextEntityRef, BusinessOperation, BusinessOperationError +async def main(): + path = sys.argv[1] + client = SQLiteTeaQLClient(path) + context = UserContext.new().install(GENERATED_RUNTIME_MODULE).insert_resource('dataService', client) + context.disable_sql_log() + await context.ensure_schema() + await client.ensure_business_operation_schema() + context.with_active_root(ContextEntityRef('Platform', 1)) + captured = [] + async def prepare(ctx, params): return None + async def validate(ctx, params, before, result): return True + async def create_work_item(ctx, title): + item = await (Q.work_items().comment('Allocate work item') + .purpose('Create a graph in the business operation').new_entity(ctx)) + return item.update_title(title).update_platform(1) + async def handler(ctx, params): + first = await create_work_item(ctx, 'first') + captured.append(first) + await first.audit_as('create first graph').save(ctx) + second = await create_work_item(ctx, params['title']) + await second.audit_as('create second graph').save(ctx) + return {'ids':[first.id,second.id]} + operation = BusinessOperation('CreatePair','1','Platform',{'title':str},lambda c,p:True,prepare,handler,validate) + with sqlite3.connect(path) as db: + db.execute("CREATE TRIGGER reject_second BEFORE INSERT ON work_item_data WHEN NEW.title='reject' BEGIN SELECT RAISE(ABORT,'GENERATED_SECOND_FAILED'); END") + try: + await operation.execute(context,key='PAIR',parameters={'title':'reject'},comment='create pair') + raise AssertionError('must fail') + except BusinessOperationError as error: + assert 'GENERATED_SECOND_FAILED' in str(error) + with sqlite3.connect(path) as db: + assert db.execute('SELECT COUNT(*) FROM work_item_data').fetchone()[0] == 0 + assert db.execute('SELECT COUNT(*) FROM teaql_operation_results').fetchone()[0] == 0 + # The generated graph must retain the intent of its reserved entity after rollback. + assert captured[0].id is not None and captured[0]._action == 'Create' + assert captured[0]._entity_root.has_pending(captured[0]._teaql_entity_key()) + with sqlite3.connect(path) as db: db.execute('DROP TRIGGER reject_second') + result = await operation.execute(context,key='PAIR',parameters={'title':'second'},comment='create pair') + with sqlite3.connect(path) as db: + assert db.execute('SELECT COUNT(*) FROM work_item_data').fetchone()[0] == 2 + assert len(set(result['ids'])) == 2 + assert not captured[-1]._entity_root.has_pending(captured[-1]._teaql_entity_key()) + print(json.dumps({'generated_graphs':2,'rollback':True,'retry':True,'ledger_cleanup':True})) +asyncio.run(main()) +''' + status, stdout, stderr = await subprocess_code(code, tmp_path / 'generated.db', ROOT / 'examples' / 'conformance') + assert status == 0, (stdout, stderr) + assert json.loads(stdout)['ledger_cleanup'] is True