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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -458,6 +458,7 @@ This mutation rule does not change the tolerant unknown-field search behavior.
- [Opaque reference example](examples/opaque-entity-reference)
- [Binary object storage and temporary S3 URLs](examples/object-storage/README.md)
- [Generated scalar probe and exact SQLite Decimal](examples/scalar-type-probe/README.md)
- [Supplier onboarding in 15 locales](examples/supplier-onboarding-i18n/README.md)

## Safe troubleshooting

Expand Down
98 changes: 98 additions & 0 deletions examples/supplier-onboarding-i18n/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
# Supplier onboarding in 15 locales with TeaQL Python

The [KSML model](model.xml) describes a warehouse and its suppliers. The
[semantic model](semantics.json) supplies two registrations to the generated
console. One lacks a supplier name. The other sets the minimum order quantity
to 3, below the model's limit of 10. The app makes real audited saves against
SQLite and reads the supplier table back through generated Q.

## Run and select a locale

Use Python 3.10 or newer and install this checkout's Python dependencies from
the repository root with `python3 -m pip install -e .`. The runner uses the
TeaQL 0.6.0 source in this checkout and the sibling generated domain library.

```sh
bash examples/supplier-onboarding-i18n/run.sh
bash examples/supplier-onboarding-i18n/run.sh --locale fr
bash examples/supplier-onboarding-i18n/run.sh --all
bash examples/supplier-onboarding-i18n/run.sh --edge-cases
```

Output is UTF-8 JSON Lines. Look at `effectiveLocale`, `messageKey`,
`location`, `arguments`, and `message` on each validation row. `--all`
switches through all 15 locales in one process. Add `--repeat 2` to run the
same mode twice against one temporary database. `PYTHON` selects the Python
executable and defaults to `python3`. An empty `PYTHON` also uses that default.

The app uses `context.set_locale_code(code)` before validation and reads
`context.language().value`. With no selection a fresh context uses `en`.
`ZH_hant` normalizes to `zh-TW`. Both the empty string and an unknown code
raise `UnsupportedLocaleError` and leave the previous locale in place. Single
locale mode reports the rejection and exits 2. The example selects locale
only through the CLI and trusted context wiring. Business input and process
locale variables supply no locale configuration.

## How the message is produced

1. The generated model is installed on a `UserContext` with a SQLite provider.
The setter parses and normalizes the requested locale before recording it.
2. The generated save checks the model. `CheckException.violations` contains
the rule, canonical location and parameters. The example reports
`checker.required` and `checker.min` with the source rule IDs alongside them.
3. The checker renderer chooses a template for the locale and location shape,
then binds the field label and the applicable parameters, such as
`{system}` for the lower bound. The generated presentation metadata
supplies field names where available.
4. The example explicitly installs its generated application catalog with
`I18nCatalog.from_dict(payload, I18nCatalog.builtin())`. That catalog lacks
these Vietnamese message overrides, so the two rendered messages stay
identical to the built-in Vietnamese results. The legacy catalog's
`message` method tries application and built-in entries in the selected
locale, then application and built-in English, then returns the key.
The natural checker renderer also supports per-shape templates and
generic `checker.invalid` when the rule has no natural template.

The independent context stays French while the main context changes from
Japanese to Arabic and back. The sample's localized sentence templates can
include English domain labels when no translated label is present.
[Context source](../../src/teaql/runtime/context.py) · [Locale and catalog source](../../src/teaql/runtime/i18n.py) · [Checker rendering source](../../src/teaql/runtime/checker_messages.py)

## Run the same scene in another runtime

Use the corresponding example in a sibling checkout. Keep the KSML,
semantic input, rule keys and field paths. Follow the other example's build
and context wiring for its host language.

[Java](../../../java/examples/supplier-onboarding-i18n/) ·
[Rust](../../../rust/examples/supplier-onboarding-i18n/) ·
[TypeScript](../../../typescript/examples/supplier-onboarding-i18n/) ·
[Go](../../../go/examples/supplier-onboarding-i18n/) ·
[Python](./) ·
[C#/.NET](../../../dotnet/examples/supplier-onboarding-i18n/) ·
[Swift](../../../swift/Examples/SupplierOnboardingI18n/)

## Add a locale

For a new runtime locale such as Italian, register `ITALIAN = "it"` in
`Locale` in `src/teaql/runtime/i18n.py` and add aliases in `_ALIASES` as
needed. Extend the legacy and natural built-ins and the per-locale checker
presentation defaults used in `checker_messages.py`. The legacy entry keeps
the key and placeholder.

```json
{
"it": {
"messages": {"checker.required": "Il campo {location} è obbligatorio"},
"vocabulary": {}
}
}
```

For natural checker messages supply the appropriate `one`, `two` and
`deep` templates in `src/teaql/runtime/natural-messages-v1.json`, preserving
placeholders such as `{field}` and `{system}`. Update the shared locale model
and generator locale list before regenerating the examples. Verify alias
selection, both real saves and missing-translation fallback, plus the
separation of locale state between contexts. For overrides of an already
supported locale, explicitly attach the application catalog instead.
48 changes: 48 additions & 0 deletions examples/supplier-onboarding-i18n/generated-files.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
{
"library": {
"scope": "python-lib-core",
"sha256": {
"E.py": "4feb2016d23c5f664122f11921814bb52645cfa51b2eb201204f9ea6231d6b75",
"Q.py": "a962f69c512c902e901b903b14c1dffaa92755e7443b6877cb122a5289b0c51e",
"generated_search_models.py": "bb6b6aaeabbc8bda3c42ba1445212f00ef1f9a9c952c6892c31783b00c477594",
"models/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"models/supplier.py": "03cb7101f03365edd970f2758ebc6ea58b1d693b8cd2d49bc8132f79c4c3fc7c",
"models/warehouse.py": "1f11e4254cc939a68c49758cbc8f4fc789484ca38807f52c292594ae7247d8df",
"pyproject.toml": "16eb65d80bf164747491ae65289e5b4511c40a600d81b7bc5569fc1f161657b5",
"requests/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"requests/supplier_request.py": "0ab10d5469ab426546f82f07803fc7af145fd281dd14ce57db6b304b7d8c9508",
"requests/warehouse_request.py": "c9062219b6972e79e93d974a96a56fdefc74001b1b302e51b8babb4c28f99009",
"runtime_module.py": "7db3980bc0ef3ef0120a4003ee3d84bd6b3d7c0bb7676fa7867850267b20f2e9",
"teaql-i18n.json": "f848093c0785f2730eaa74f8a9e175e1f90943f056d84666bc964d56668e298c",
"teaql/checker-model.json": "0c70836b868047e6bbf8c5a4b167343ef9425e5c535c59ee388b634a79f2b144",
"teaql/model-provenance.json": "94ae1b99943275455fce8de247c97f10a81cdb09fef91ada0ae924b26e572759"
}
},
"schema": "teaql.i18n-showcase-generation/v1",
"workspace": {
"applicationEntry": "app/main.py",
"domainSourcesFromSibling": true,
"scope": "python-app-console",
"sha256": {
"AGENTS.md": "c448ef9b56f4bda7dd534e666b77fde33b72d2ad9f987edd82fe83b3604f6bbc",
"E.py": "4feb2016d23c5f664122f11921814bb52645cfa51b2eb201204f9ea6231d6b75",
"Q.py": "a962f69c512c902e901b903b14c1dffaa92755e7443b6877cb122a5289b0c51e",
"README.md": "4463e00b120c1af3b6951fc43c19689b389d64b1989e0c41f66b8b5c140cd18e",
"STANDARD_TELEMETRY.md": "03391e8a7ff96c207269a3374437d7a95a16ac6563c58d6b054ab38e3bda3712",
"app/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"app/main.py": "1e019f8857f5aec33632b3b47b370832b90d1de9ecf260e0912c449ba3b23d46",
"generated_search_models.py": "bb6b6aaeabbc8bda3c42ba1445212f00ef1f9a9c952c6892c31783b00c477594",
"models/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"models/supplier.py": "03cb7101f03365edd970f2758ebc6ea58b1d693b8cd2d49bc8132f79c4c3fc7c",
"models/warehouse.py": "1f11e4254cc939a68c49758cbc8f4fc789484ca38807f52c292594ae7247d8df",
"pyproject.toml": "16eb65d80bf164747491ae65289e5b4511c40a600d81b7bc5569fc1f161657b5",
"requests/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"requests/supplier_request.py": "0ab10d5469ab426546f82f07803fc7af145fd281dd14ce57db6b304b7d8c9508",
"requests/warehouse_request.py": "c9062219b6972e79e93d974a96a56fdefc74001b1b302e51b8babb4c28f99009",
"runtime_module.py": "7db3980bc0ef3ef0120a4003ee3d84bd6b3d7c0bb7676fa7867850267b20f2e9",
"teaql-i18n.json": "f848093c0785f2730eaa74f8a9e175e1f90943f056d84666bc964d56668e298c",
"teaql/checker-model.json": "0c70836b868047e6bbf8c5a4b167343ef9425e5c535c59ee388b634a79f2b144",
"teaql/model-provenance.json": "94ae1b99943275455fce8de247c97f10a81cdb09fef91ada0ae924b26e572759"
}
}
}
7 changes: 7 additions & 0 deletions examples/supplier-onboarding-i18n/model.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<root name="supplier-onboarding-service" org="teaql" data_service="sqlite">
<warehouse _name="Warehouse" _zh_CN="仓库" name="Central Warehouse"/>
<supplier _name="Supplier" _zh_CN="供应商" warehouse="warehouse()"
name="Supplier Name|[1,80]"
minimum_order_quantity="integer()|[10,10000]"/>
</root>
46 changes: 46 additions & 0 deletions examples/supplier-onboarding-i18n/python-app-console/AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# supplier-onboarding-service application instructions

## TeaQL workspace rules

- Work in application-owned files. Keep the generated domain library read-only.
- Discover API names and signatures through model-aware Assist only.
Do not read or search generated library source for API discovery. Use the
original evaluated KSML file or directory and its exact entity and field names.
- Ask for the current entity and action first. Request field-level query help
only for the fields you use. If Assist lacks the operation, report
`MISSING_ASSIST` with the entity, action, and relevant field or diagnostic.

```text
cargo teaql --input [model] python-assist-[action]/[entity]
cargo teaql --input [model] python-assist-query/[entity].[field]
```

Replace the bracketed values with the actual model path, action, entity, and
field. Actions include `query`, `list-page`, `create`, `update`, `delete`, and
`expression`. Validate API usage by compiling and testing the application.

- Use the trusted `UserContext` as the only runtime argument for generated query
execution and saves. Resolve tenant, actor, authorization, and provider
resources from trusted application setup.
- Keep queries bounded and provide a non-empty purpose and comment. Supply a
non-empty audit reason for writes through the API shown by Assist.

## Application entry and context

Start in `app/main.py`. Use `create_context()` to install the generated
Runtime Module and configure the provider before calling `context.ensure_schema()`.

Every query is bounded and has non-blank comment and purpose. Use generated Q
for loading and E for loaded traversal. Load all scalar fields before mutation;
mark_for_deletion() and save(context) the composed graph with a non-blank audit_as
reason. Child reasons remain local; unannotated children inherit their parent.
Public execution accepts only UserContext. Schema changes are explicit through
context.ensure_schema(), with generated bootstrap intact.

Verify twice on one SQLite file without database cleanup. Use unique test labels,
keep generated library hashes unchanged, and retain commands, exit statuses and
skipped/unverified checks. Local source tests do not prove a published artifact.

## Optional standard telemetry

See [STANDARD_TELEMETRY.md](STANDARD_TELEMETRY.md) for the selected runtime's optional module, trusted activation variables and safe startup diagnostics.
12 changes: 12 additions & 0 deletions examples/supplier-onboarding-i18n/python-app-console/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# supplier-onboarding-service Python console

Run `python -m app.main`. Installing the generated Runtime Module is passive;
schema reconciliation remains an explicit application action.
The console main() explicitly awaits `context.ensure_schema()` after `create_context()`
and before reporting readiness. Importing the console or calling `create_context()`
does not reconcile schema.


## Optional standard telemetry

See [STANDARD_TELEMETRY.md](STANDARD_TELEMETRY.md) for the selected runtime's optional module, trusted activation variables and safe startup diagnostics.
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
## Standard OpenTelemetry module

Use the optional standard module supplied by the selected TeaQL runtime. Match
its version to the runtime dependency selected by the model and workspace;
keep local source or internal Registry overrides during development. Do not
upgrade to an unrelated public release just to enable telemetry. A runtime
without this module reports `module_unavailable`; package installation alone
does not enable export.

On a supported backend, configure these trusted process variables before startup, never
through a query, JSON or TFP payload:

```bash
export TEAQL_TELEMETRY_ENABLED=true
export TEAQL_TELEMETRY_SERVICE_NAME=payment-service
export TEAQL_TELEMETRY_OTLP_ENDPOINT=http://localhost:4318
```

Without enablement, startup reports `disabled` and all three activation variables;
no SDK export resources are created. Enabled startup reports safe effective
settings, full recording and masking. Invalid settings produce a fixed safe
diagnostic, not a claim of successful export. Never print credentials or raw
configuration values.

The module automatically records supported Q, graph mutation and physical SQL
operations as traces, logs and metrics. SQL is expanded with masked parameters;
plaintext debugging never authorizes plaintext telemetry export. Full recording
does not promise lossless delivery when bounded queues or exporters fail.
Do not add per-method spans or replace the customer's global SDK providers.

Keep schema reconciliation explicit. Run the generated ensure-schema and seed
flow through the same configured runtime to observe startup settings and audited,
idempotent seeding. Telemetry setup must not run ensure-schema implicitly.
Flush and shut down the owned pipeline at application shutdown, not per query.
Exporter failures do not change business results; durable business audit remains
an independent path.


### Python assembly

Select the `telemetry` extra on the application's existing `teaql` dependency
(`teaql[telemetry]`), retaining the version and source or Registry selected by the
workspace. UserContext startup loads the module only when enabled. No application
SDK initialization or per-method spans are required; set the three variables
before starting the process.
Empty file.
87 changes: 87 additions & 0 deletions examples/supplier-onboarding-i18n/python-app-console/app/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
"""Run supplier registration through the generated Python workspace."""

import asyncio
import json
from pathlib import Path
import sys

from teaql.data_service import SQLiteTeaQLClient
from teaql.runtime import UserContext
from teaql.runtime.i18n import CheckException, I18nCatalog, UnsupportedLocaleError

from Q import Q
from runtime_module import GENERATED_RUNTIME_MODULE


def create_context(client):
return UserContext.new().install(GENERATED_RUNTIME_MODULE).insert_resource("dataService", client)


def emit(step, context, event_type, **details):
result = {"type": event_type, "context": step["context"],
"effectiveLocale": context.language().value, **details}
print("TEAQL_I18N_SHOWCASE " + json.dumps(result, ensure_ascii=False))


async def register_supplier(context, warehouse_id, values):
supplier = (Q.suppliers().comment("Prepare supplier registration")
.purpose("Register a supplier for warehouse purchasing").new_entity(context))
supplier.update_warehouse(warehouse_id)
supplier.update_name(values["name"])
supplier.update_minimum_order_quantity(values["minimum_order_quantity"])
await supplier.audit_as("Register the supplier for purchasing").save(context)


async def verify_failure(step, context, warehouse_id):
try:
await register_supplier(context, warehouse_id, step["input"])
except CheckException as error:
if len(error.violations) != 1:
raise AssertionError(f"Expected one native checker result, received {error}") from error
violation, = error.violations
wire = violation.to_wire()
key = {"required": "checker.required", "min": "checker.min"}[violation.rule_id.lower()]
arguments = {"minimum": int(wire["systemValue"])} if key == "checker.min" else {}
emit(step, context, "validation", case=step["case"], messageKey=key,
nativeRule=violation.rule_id, location=violation.location.model_path,
arguments=arguments, message=wire["message"],
nativeArguments={name: wire[name] for name in ("inputValue", "systemValue") if name in wire})
else:
raise AssertionError(f"Invalid supplier registration was stored: {step['case']}")


async def main():
plan = json.load(sys.stdin)
client = SQLiteTeaQLClient(plan["database"])
try:
contexts = {name: create_context(client) for name in ("main", "independent")}
await contexts["main"].ensure_schema()
for step in plan["steps"]:
context = contexts[step["context"]]
operation = step["operation"]
if operation == "select":
try:
context.set_locale_code(step["locale"])
except UnsupportedLocaleError as error:
emit(step, context, "locale", requestedLocale=error.locale_code,
accepted=False, nativeError=type(error).__name__)
else:
emit(step, context, "locale", requestedLocale=step["locale"], accepted=True)
elif operation == "validate":
await verify_failure(step, context, plan["warehouse"]["id"])
elif operation == "install-catalog":
catalog = json.loads(Path(step["path"]).read_text(encoding="utf-8"))
context.install_i18n_catalog(I18nCatalog.from_dict(catalog, I18nCatalog.builtin()))
emit(step, context, "catalog-installed")
elif operation == "verify-unchanged":
rows = await (Q.suppliers_minimal().limit(1).comment("Check the rejected registrations")
.purpose("Verify no invalid supplier was stored").execute_for_list(context))
emit(step, context, "storage", supplierCount=len(rows))
else:
raise ValueError(f"Unsupported example operation: {operation}")
finally:
await client.close()


if __name__ == "__main__":
asyncio.run(main())
Loading
Loading