Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions RUNTIME_GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
66 changes: 66 additions & 0 deletions examples/business-operation/README.md
Original file line number Diff line number Diff line change
@@ -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.
169 changes: 169 additions & 0 deletions examples/business-operation/warehouse.py
Original file line number Diff line number Diff line change
@@ -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())
4 changes: 3 additions & 1 deletion scripts/verify-examples.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"
Expand Down
10 changes: 8 additions & 2 deletions src/teaql/provider/sqlite/transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)


Expand Down
2 changes: 2 additions & 0 deletions src/teaql/runtime/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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",
Expand Down
Loading
Loading