Skip to content

Commit 86ef1d3

Browse files
authored
Merge pull request #203 from teaql/feature/request-trace-chain
Align request-owned intent and typed graph Trace Chain
2 parents 416f9ac + 9b0156f commit 86ef1d3

183 files changed

Lines changed: 17731 additions & 1200 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎DIALECT_INTEGRATION_GUIDE.md‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ TeaQL 的架构分为两层:
1010
- **`teaql-data-service-sql` (JDBC 适配层)**:基于 `SqlExecutionAdapter` 实现的与数据库真实通信的通道。
1111

1212
## 2. 如何实现 `ensureSchema` (表结构同步)
13-
你**不需要**去手工遍历所有列、对比类型、拼接 CREATE/ALTER 语句,这些在 `PortableSQLRepository.ensureSchema()` 中已经完美实现。
13+
你**不需要**去手工遍历所有列、对比类型、拼接 CREATE/ALTER 语句,这些由 `PortableSQLRepository.ensurePhysicalSchema()` 统一实现。
1414

1515
在具体的数据库方言执行器(例如 `PostgresDataServiceExecutor`)中,只需执行以下 3 步:
1616

@@ -50,7 +50,7 @@ TeaQLDatabase dbAdapter = new TeaQLDatabase() {
5050
```
5151

5252
### Step 3: 交给 Portable 引擎执行 DDL
53-
针对每个 `EntityDescriptor`,实例化一个带有该伪装 Adapter 的 PortableRepository,并调用其 `ensureSchema` 方法:
53+
针对每个 `EntityDescriptor`,实例化一个带有该伪装 Adapter 的 PortableRepository,并调用其 `ensurePhysicalSchema` 方法:
5454
```java
5555
for (EntityDescriptor descriptor : descriptors) {
5656
// 实例化方言的 PortableSQLRepository(例如 PostgresPortableSQLRepository,如果没有则用基类)
@@ -63,6 +63,12 @@ for (EntityDescriptor descriptor : descriptors) {
6363
不能顺带修改生产数据库。新方言的最小验证应包含两个独立 context/metadata 实例,
6464
证明它们只处理自己的实体,再对目标数据库执行 live schema、查询和审计写入测试。
6565

66+
`ensurePhysicalSchema` 只处理数据库结构,不解释根对象或常量的候选值。
67+
数据播种由 context 调用已安装的 `GeneratedSchemaBootstrap`,使用带有
68+
comment/purpose 的 Q API 和 audited save,经过 Checker、Mutation Policy、
69+
乐观锁及提交后的审计链。旧的 Portable `ensureSchema` / `ensureInitData`
70+
直写数据入口已移除;不要在方言中重建这条绕过路径。
71+
6672
## 3. 核心纪律
6773
1. **彻底解耦 Spring**:在方言模块中,严禁直接使用 `JdbcTemplate` 或任何 `org.springframework` 包。全部通过 `SqlExecutionAdapter` 委托。
6874
2. **职责极简**:方言层(后端层)只负责提供“查询数据字典的原生 SQL”和“JDBC 链接”,表结构的 Diff 对比和通用 DDL 必须收口在 Portable 引擎。

‎README.md‎

Lines changed: 109 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -110,29 +110,130 @@ Mutations declare an audit action:
110110
task.auditAs("Move task to Done").save(userContext);
111111
```
112112

113+
### Request owned intent on the development branch
114+
115+
The `feature/request-trace-chain` branch makes non-blank `comment` part of both
116+
`QueryRequest` and `MutationRequest`. Query also requires non-blank `purpose`.
117+
Existing generated `.comment(...).purpose(...)` and `.auditAs(...)` spelling
118+
does not change. Low-level provider requests now expose an immutable validated
119+
`QueryIntent` or `MutationIntent`; custom SPI implementations must adopt this
120+
contract. These changes are not a claim about published Maven artifacts.
121+
122+
Missing or Unicode-whitespace-only comment fails with
123+
`REQUEST_COMMENT_REQUIRED` at `comment`; missing Query purpose fails with
124+
`QUERY_PURPOSE_REQUIRED` at `purpose`. Validation happens before policy and
125+
provider execution, including direct runtime calls and disabled logging.
126+
Neither a Context default nor a fabricated trace supplies missing intent.
127+
128+
List, aggregate, relation and streaming execution no longer push or pop query
129+
frames on Context. Streaming providers now accept the same validated
130+
`QueryRequest` envelope as materialized providers instead of a bare
131+
`SearchRequest`. A custom `StreamingQueryExecutor` must migrate that SPI
132+
signature; generated `.executeForStream(context)` calls remain unchanged.
133+
The captured intent survives Policy changes to a builder and delayed cursor
134+
consumption. SQL providers snapshot source paths and redaction provenance for
135+
the invocation, including inherited internal streams. Legacy unbound direct SQL
136+
diagnostics can still use explicitly supplied Context frames; those compatibility
137+
calls are not the runtime query ownership contract.
138+
139+
Derived relation, Facet and materialized relation-predicate queries carry their
140+
validated originating intent instead of asking callers to repeat it. Mutation
141+
reason is captured before policy and retained in provider requests and committed
142+
audit facts. Graph saves now use immutable parent-linked mutation scopes, rather
143+
than a Context push/pop stack. Each persistence request carries its own typed
144+
lineage through SQL writes, authoritative readback and committed safe audit.
145+
`TraceNode` includes entity type and assigned ID; Entity and Ledger trace setters
146+
now accept immutable `List<TraceNode>`, not flattened strings. Custom callers
147+
using the old string API must migrate; this is a local source change, not a
148+
released API. SQL `tracePath` remains separate from `mutationLineage`.
149+
150+
The local runtime tests cover branch reasons, deleted children, same numeric ID
151+
across types, assigned IDs, complete ledger overrides and concurrent saves sharing
152+
one Context. Actual SQLite tests cover SQL/audit propagation, provider rollback,
153+
readback failure/retry and masking. Native batch diagnostics distinguish the
154+
batch call's `batchOutcome` from an individual member's possibly unknown
155+
`executionOutcome`. Same-type graph inserts now use a validated
156+
`MutationBatchRequest` and the optional `BatchMutationExecutor` capability.
157+
Physical JDBC rows retain separate immutable trace bindings, including failure
158+
and readback diagnostics; incompatible insert column layouts are grouped separately.
159+
Root intent remains required even if children are annotated or logs are disabled.
160+
Providers without the capability retain individual command execution.
161+
162+
Internal reverse-list attachment-key projection preserves an explicitly requested
163+
nested forward load. It must not use the public scalar selection operation that
164+
removes a same-named relation load. Native SQLite tests cover root/nested graphs,
165+
window/probe plans and logging on/off; the example gate runs these tests too.
166+
Java retains an ID-only reference when its forward query has no matching target:
167+
non-loaded fields remain guarded by `TeaQLNotLoadedException`, while list
168+
membership and independent counts survive. This is not a claim of null-valued
169+
reference parity with other runtimes.
170+
171+
Bootstrap follows the same request and audit boundary. Call
172+
`context.ensureSchema()` with the generated Runtime Module installed: providers
173+
perform physical DDL, then generated Q and audited Mutation reconcile roots and
174+
constants. The legacy Portable `ensureSchema(context, type)` and repository
175+
`ensureInitData(context)` data-write APIs have been removed. The
176+
[School example](examples/school-management/README.md) verifies real bootstrap
177+
SQL intent, committed lineage, fixed IDs, no-op reseeding and versioned constant
178+
reconciliation on two starts of the same database.
179+
180+
The generated [Trace Chain example](examples/trace-chain/README.md) proves the
181+
normative graph, overlapping three-level Q/E queries, late-consumed streams,
182+
nested Facets with the original root and complete relation paths,
183+
prepared insert grouping and complete ledger replacement, plus prepared
184+
update/delete/recover batches with independent
185+
optimistic versions. It now also runs real overlapping generated Checkers and
186+
independent graph saves with one Context, observing per-item SQL and committed
187+
audit lineage. Temporary check results, visited objects, Fix evidence and the
188+
captured graph clock belong to each synchronous Checker invocation. Nested saves
189+
restore the outer invocation while preserving the original custom Context and
190+
its service hooks. `lastFixEvidence()` is the last completed check's diagnostic
191+
receipt on the calling execution thread; it is not an async propagation API.
192+
Read-only loaded relations retain their private ledger when reused by independent
193+
graphs. Graph composition imports only pending mutations of explicitly visited
194+
related entity keys, not every pending key from a foreign reference's ledger.
195+
The provider-route guard also belongs to each mutation plan, not a retained
196+
Context attribute. Independent graphs may use different providers on one
197+
Context. A single atomic graph with writes to different routes is rejected
198+
before mutation execution; read-only references do not count as writes.
199+
Native tests cover separate SQLite databases and actual overlapping threads.
200+
201+
Native dynamic-aggregation tests also retain the original root through nested
202+
relations, preserve inherited masking provenance and avoid fabricated relation
203+
nodes for numeric partitions. They are separate from generated Facet acceptance.
204+
205+
Complete entry-point/privacy coverage, legacy unbound SQL diagnostic migration, asynchronous
206+
handoff/cancellation and immutable internal Registry replay remain separate open
207+
gates. The tested SQLite writer transactions serialize while the generated
208+
Checkers overlap. This is local source evidence, not a merge or release claim.
209+
113210
Applications can replace runtime services such as `QueryPolicy`, the
114211
`MutationPolicyRegistry`, `MutationPolicyApprovalProvider`, `RuntimeLogSink`,
115212
`DataServiceRegistry`, `InternalIdGenerationService`, and `EntityMetaFactory`
116213
in their integration layer.
117214

118215
Query and Mutation execution logs are enabled by default. The built-in default
119216
sink is safe for ordinary operator output: it includes intent, trace, elapsed
120-
time, outcome, and parameterized SQL, but excludes bind values and rendered
121-
Debug SQL. Enable copy/paste SQL only for a controlled troubleshooting surface:
217+
time, outcome, and SQL with safely rendered parameters. Sensitive values follow
218+
the field's masking policy; an unsafe statement is omitted with a reason rather
219+
than printed as plaintext. Select an additional diagnostic destination only for
220+
controlled troubleshooting:
122221

123222
```java
124223
TeaQLRuntime runtime = TeaQLRuntime.builder()
125224
.metadata(metadata)
126225
.queryExecutionLogging(true)
127226
.mutationExecutionLogging(true)
128-
.diagnosticSqlLogging(true) // values and Debug SQL; apply restricted retention
227+
.diagnosticSqlLogging(true) // selecting a destination alone does not authorize plaintext
129228
.build();
130229
```
131230

132231
The Query and Mutation switches remain independent. Selecting diagnostic SQL
133232
changes the built-in destination; it does not enable or disable either family.
134-
Custom `RuntimeLogSink` implementations receive only parameterized SQL unless
135-
they explicitly override `requiresSensitiveSqlData()` to return `true`.
233+
Custom `RuntimeLogSink` implementations receive safe SQL projections too.
234+
Plaintext requires both an explicitly sensitive destination and the exact
235+
`TEAQL_ALLOW_SENSITIVE_PLAINTEXT_LOGS=I_UNDERSTAND_SENSITIVE_DATA_MAY_BE_WRITTEN_TO_DISK`
236+
acknowledgement. Debug records are individually labeled; credentials remain protected.
136237
Custom `UserContext` implementations must also explicitly delegate or override
137238
`requiresSensitiveSqlLogData()` when they enable a diagnostic sink.
138239
The optional file-backed `LogManager` requests value-bearing SQL only with
@@ -143,9 +244,9 @@ The optional file-backed `LogManager` requests value-bearing SQL only with
143244
TeaQL Java is a server-side security reference runtime:
144245

145246
- ordinary Query and Mutation logs are enabled by default and retain intent,
146-
trace, parameterized SQL, timing, and outcome without bind values;
147-
- copy/paste SQL and parameter values require an explicitly selected sensitive
148-
diagnostic sink;
247+
typed trace, safely expanded SQL, timing, and outcome;
248+
- ordinary SQL remains copy/paste-readable with masked values; plaintext requires
249+
a sensitive diagnostic sink and the exact environment acknowledgement;
149250
- the TFP endpoint applies trusted server policy, bounded queries, writable-field
150251
rules, tenant scope, and optimistic version in the provider operation;
151252
- boundary-facing entity references can be issued and verified through

‎examples/school-management/README.md‎

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,15 @@
22

33
This generated example retains `models/school-model.xml`. It explicitly calls
44
SQLite `ensureSchema` twice and verifies Platform `id=1` plus SchoolType constants
5-
`1001`/`1002` are present exactly once with version 1.
5+
`1001`/`1002` are present exactly once. Fresh rows start at version 1.
6+
7+
The application-owned `BootstrapTraceVerifier` observes the generated bootstrap's
8+
real SQL intent and committed audit lineage, without injecting trace frames.
9+
It changes PRIMARY's name through audited Mutation, then calls ensureSchema to
10+
restore the model-defined name. Each edit/repair advances the version once;
11+
SECONDARY remains unchanged. Repeated ensureSchema performs lookups only, emits
12+
no mutation audit, and restores the caller's bootstrap audit attributes. Both
13+
fresh and already-seeded databases are exercised by the two-start verifier.
614

715
The application-owned `SchoolLifecycleVerifier` also checks a missing required
816
name is rejected by Checker before mutation or schema SQL during `save`,
@@ -11,16 +19,24 @@ loaded E traversal, full-field update, mark-for-deletion plus save, and normal-q
1119
absence. The example gate runs with a fresh SQLite database; running it a
1220
second time against the same database is supported.
1321

22+
`RequestIntentVerifier` proves generated Q requests and graph saves reject
23+
missing comment/purpose before policy or SQL. It covers Unicode whitespace,
24+
fabricated ambient intent and root intent inheritance through both forward
25+
relations. Unit tests separately prove the gate is independent of logging.
26+
1427
For updates, load the complete scalar entity. A read projection that includes
1528
only selected fields of related entities is useful for E/display, but should
1629
not be reused as the mutation graph: Checker correctly rejects those partial
1730
related entities as `NotLoaded`.
1831

1932
Before publication, install the repository's local runtime and then run the
20-
generated workspace. The portable SQL runtime test separately changes a constant
21-
and verifies optimistic, single-version reconciliation.
33+
generated workspace. Portable provider tests forbid the removed raw seed APIs
34+
and prove physical DDL never inserts/reconciles root or constant data. Typed
35+
constant reconciliation is verified here, through the same generated API as an
36+
application, rather than through a lower-level raw SQL shortcut.
2237

2338
From the repository root, run `examples/verify-runtime-examples.sh`. The gate
2439
builds both retained examples against the current reactor sources, assigns each
25-
run an isolated temporary SQLite database, waits for its acceptance marker, and
26-
exits non-zero if either application fails or times out.
40+
example an isolated temporary SQLite database, runs each twice without cleanup
41+
between repetitions, and requires both the lifecycle and request-intent markers.
42+
It exits non-zero if either application fails or times out.

‎examples/school-management/src/main/java/com/example/schoolmanagementservice/App.java‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,7 @@ public CommandLineRunner teaQLConsoleStartup(
8787
if (!(dataServiceExecutor instanceof SchemaExecutor schema)) {
8888
throw new IllegalStateException("default data service has no schema capability");
8989
}
90+
BootstrapTraceVerifier.verify(runtime);
9091
context.ensureSchema();
9192
context.ensureSchema();
9293
SmartList<Platform> platforms = Q.platforms()
@@ -104,7 +105,8 @@ public CommandLineRunner teaQLConsoleStartup(
104105
&& constants.get(0).getId() == 1001L
105106
&& constants.get(1).getId() == 1002L,
106107
"SchoolType constants were not seeded");
107-
require(constants.get(0).getVersion() == 1L && constants.get(1).getVersion() == 1L,
108+
// The bootstrap verifier made one audited edit and one audited repair to PRIMARY.
109+
require(constants.get(0).getVersion() >= 3L && constants.get(1).getVersion() == 1L,
108110
"Repeated ensureSchema was not idempotent");
109111
require(new IdSpaceIdGenerator(database).nextId("SchoolType") > 1002L,
110112
"SchoolType ID floor did not advance beyond model constants");

0 commit comments

Comments
 (0)