Skip to content

Commit 698b8c1

Browse files
author
Philip Z
committed
fix: classify private aggregate predicates before root SQL diagnostics
1 parent 38dab2d commit 698b8c1

7 files changed

Lines changed: 269 additions & 14 deletions

File tree

‎examples/trace-chain/README.md‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,17 @@ typed branch lineage and the originating root's query/request path. Prepared
1212
batches keep a separate statement list per member; concurrent saves do not share
1313
a collection. This checks returned evidence independently of the log sink.
1414
Native SQLite tests exercise all four query/mutation logging combinations.
15+
`GeneratedAggregateTraceExampleTest` adds root/nested × logging-off/on dynamic
16+
counts and numeric ID partitions, plus eight visible/filtered forward-detail
17+
membership cases. Every physical raw path is asserted, and safe projections
18+
redact private equal/set operands before the first root statement. Numeric
19+
partitions add no invented relation. Two-child membership and scoped count remain
20+
intact; a filtered parent keeps its actual ID while generated E rejects unfetched
21+
description. Loading a separate full view cannot fill in that first view.
22+
The aggregate helpers use the public inherited `BaseRequest` operations
23+
`setPartitionProperty`, `count`, and `addSingleAggregateDynamicProperty`, as
24+
exercised by `DerivedQueryTraceSqliteTest`; generated selectors and E access use
25+
retained field Assist. No application SQL, injected trace frames or library edits.
1526
Disabling diagnostic text does not remove the returned physical facts or change
1627
the number of committed audits. These raw facts are trusted internal diagnostics;
1728
apply `LogPrivacy.sql` before exporting one to a diagnostic sink, never serialize
@@ -42,7 +53,7 @@ Use Java 21 or newer, Maven, Bash and the normal repository dependencies:
4253
bash examples/trace-chain/verify.sh
4354
```
4455

45-
The script installs local source dependencies, runs all seventeen scenarios twice
56+
The script installs local source dependencies, runs all twenty-four test methods twice
4657
against one database without intermediate cleanup, and compares every generated
4758
library file's SHA256 before and after execution. It prints the retained
4859
directory containing the database, Maven logs and checksum manifests. Set
@@ -140,8 +151,8 @@ not invisible compiler work: its physical statement retains that root and the
140151
verified relation edge. Matching Facet targets are restricted by the counted
141152
FK identities, never by applying source-table predicates to the target table.
142153
Facet materialization preserves nested collection metadata without sharing its
143-
mutable map. The all-examples gate includes all three generated test classes
144-
(22 JUnit methods), twice against the same retained SQLite database.
154+
mutable map. The all-examples gate includes all four generated test classes
155+
(24 JUnit methods), twice against the same retained SQLite database.
145156
Facets loaded with a forward entity live in a runtime-owned `getQueryFacets()`
146157
sidecar, not a KSML field, dynamic field, JSON property or mutation-ledger key.
147158
`getQueryFacet(name) == null` means that Facet was not requested; a non-null
Lines changed: 182 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,182 @@
1+
package io.teaql.examples.tracechain;
2+
3+
import com.fasterxml.jackson.databind.ObjectMapper;
4+
import com.teaql.tracechainservice.E;
5+
import com.teaql.tracechainservice.Q;
6+
import com.teaql.tracechainservice.customerorder.CustomerOrder;
7+
import io.teaql.core.ExecutionMetadata;
8+
import io.teaql.core.TraceKind;
9+
import io.teaql.core.TraceNode;
10+
import io.teaql.runtime.LogPrivacy;
11+
import java.util.ArrayList;
12+
import java.util.LinkedHashMap;
13+
import java.util.List;
14+
import java.util.Map;
15+
import org.junit.Test;
16+
import static org.junit.Assert.*;
17+
18+
/** Application-owned TC-SQL-10: generated Q/E plus inherited runtime aggregate APIs. */
19+
public class GeneratedAggregateTraceExampleTest {
20+
private static final String PRIVATE = "JAVA-PRIVATE-AGGREGATE";
21+
private static final String COMMENT = "inspect " + PRIVATE;
22+
private static final String PURPOSE = "verify original aggregate ancestry";
23+
24+
@Test public void generatedAggregateRetainsRawPathsPrivacyAndNumericPartition() throws Exception {
25+
for (boolean nested : List.of(false, true)) for (boolean logging : List.of(false, true)) {
26+
var fixture = new GeneratedTraceChainExampleTest.Fixture(logging);
27+
var graph = fixture.saveNormativeGraph();
28+
graph.kept().updateName(PRIVATE);
29+
graph.order().auditAs("seed private aggregate operand").save(fixture.context);
30+
fixture.clear(); fixture.queryResults.clear();
31+
32+
var count = Q.orderItems().withNameIs(PRIVATE).limit(10);
33+
// Public BaseRequest contract, exercised by DerivedQueryTraceSqliteTest.
34+
// Partition by the real forward model edge; runtime resolves the reverse edge.
35+
count.setPartitionProperty("customerOrder"); count.count("count");
36+
var owner = Q.customerOrders().withIdIs(graph.order().getId()).limit(1);
37+
owner.addSingleAggregateDynamicProperty("selectedItemCount", count);
38+
CustomerOrder result = nested
39+
? E.payment(Q.payments().withIdIs(graph.payment().getId()).limit(1)
40+
.selectCustomerOrderWith(owner).comment(COMMENT).purpose(PURPOSE)
41+
.executeForOne(fixture.context)).getCustomerOrder().eval()
42+
: owner.comment(COMMENT).purpose(PURPOSE).executeForOne(fixture.context);
43+
assertEquals(graph.order().getId(), E.customerOrder(result).getId().eval());
44+
assertEquals("related aggregate must retain its actual scoped count", 1,
45+
((Number) result.getDynamicProperty("selectedItemCount")).intValue());
46+
var routes = nested ? List.of(List.<String>of(), List.of("customerOrder"),
47+
List.of("customerOrder", "orderItemList"))
48+
: List.of(List.<String>of(), List.of("orderItemList"));
49+
var raw = assertFacts(fixture, nested ? "Payment" : "CustomerOrder", routes, COMMENT,
50+
PURPOSE, "inspect [REDACTED]", logging);
51+
assertEquals(1, raw.stream().filter(f -> f.getParameterizedQuery().toUpperCase(java.util.Locale.ROOT).contains("COUNT(")).count());
52+
emit("JAVA_AGGREGATE_OBSERVED", Map.of("nested", nested, "logging", logging,
53+
"count", 1, "raw", observations(raw), "safe", observations(fixture.sql),
54+
"mutationCommands", fixture.commands.size(), "committedAudits", fixture.audit.size()));
55+
56+
fixture.clear(); fixture.queryResults.clear();
57+
// Identity is a numeric partition, not a model relation. It cannot add a relation frame.
58+
var selfCount = Q.customerOrders().withIdIs(graph.order().getId()).limit(1);
59+
selfCount.setPartitionProperty("id"); selfCount.count("count");
60+
var numericOwner = Q.customerOrders().withIdIs(graph.order().getId()).limit(1);
61+
numericOwner.addSingleAggregateDynamicProperty("selfCount", selfCount);
62+
var numeric = nested
63+
? E.payment(Q.payments().withIdIs(graph.payment().getId()).limit(1)
64+
.selectCustomerOrderWith(numericOwner).comment(COMMENT).purpose("numeric partition has no edge")
65+
.executeForOne(fixture.context)).getCustomerOrder().eval()
66+
: numericOwner.comment(COMMENT).purpose("numeric partition has no edge").executeForOne(fixture.context);
67+
assertEquals(1, ((Number) numeric.getDynamicProperty("selfCount")).intValue());
68+
var numericRoutes = nested ? List.of(List.<String>of(), List.of("customerOrder"), List.of("customerOrder"))
69+
: List.of(List.<String>of(), List.<String>of());
70+
var numericRaw = assertFacts(fixture, nested ? "Payment" : "CustomerOrder", numericRoutes,
71+
COMMENT, "numeric partition has no edge", COMMENT, logging);
72+
assertEquals(1, numericRaw.stream().filter(f -> f.getParameterizedQuery().toUpperCase(java.util.Locale.ROOT).contains("COUNT(")).count());
73+
emit("JAVA_AGGREGATE_NUMERIC", Map.of("nested", nested, "logging", logging,
74+
"count", 1, "raw", observations(numericRaw), "safe", observations(fixture.sql)));
75+
}
76+
}
77+
78+
@Test public void generatedCountAndMembershipSurviveFilteredForwardDetail() throws Exception {
79+
for (boolean nested : List.of(false, true)) for (boolean logging : List.of(false, true))
80+
for (boolean filtered : List.of(false, true)) {
81+
var fixture = new GeneratedTraceChainExampleTest.Fixture(logging);
82+
var graph = fixture.saveNormativeGraph();
83+
graph.kept().updateName(PRIVATE);
84+
var extra = Q.orderItems().comment("prepare second visible member")
85+
.purpose("verify full aggregate membership").newEntity(fixture.context);
86+
extra.updateName("Public aggregate member"); graph.order().addOrderItem(extra);
87+
graph.order().auditAs("seed independently scoped aggregate members").save(fixture.context);
88+
fixture.clear(); fixture.queryResults.clear();
89+
var count = Q.orderItems().withNameIs(PRIVATE).limit(10);
90+
count.setPartitionProperty("customerOrder"); count.count("count");
91+
var detail = Q.customerOrders().withIdIs(filtered ? -1L : graph.order().getId()).limit(1);
92+
var owner = Q.customerOrders().withIdIs(graph.order().getId()).limit(1)
93+
.selectOrderItemListWith(Q.orderItems().orderByIdAscending().limit(10)
94+
.selectCustomerOrderWith(detail));
95+
owner.addSingleAggregateDynamicProperty("selectedItemCount", count);
96+
var result = nested
97+
? E.payment(Q.payments().withIdIs(graph.payment().getId()).limit(1)
98+
.selectCustomerOrderWith(owner).comment(COMMENT).purpose(PURPOSE)
99+
.executeForOne(fixture.context)).getCustomerOrder().eval()
100+
: owner.comment(COMMENT).purpose(PURPOSE).executeForOne(fixture.context);
101+
var items = E.customerOrder(result).getOrderItemList().eval();
102+
assertEquals("unfetched forward detail cannot erase list membership", 2, items.size());
103+
assertEquals(1, ((Number) result.getDynamicProperty("selectedItemCount")).intValue());
104+
for (var item : items) {
105+
var identity = E.orderItem(item).getCustomerOrder().eval();
106+
assertNotNull(identity);
107+
assertEquals(graph.order().getId(), E.customerOrder(identity).getId().eval());
108+
if (filtered) assertThrows(io.teaql.core.value.TeaQLNotLoadedException.class,
109+
() -> E.customerOrder(identity).getDescription().eval());
110+
else assertEquals(graph.order().getDescription(), E.customerOrder(identity).getDescription().eval());
111+
}
112+
var routes = nested ? List.of(List.<String>of(), List.of("customerOrder"),
113+
List.of("customerOrder", "orderItemList"), List.of("customerOrder", "orderItemList", "customerOrder"),
114+
List.of("customerOrder", "orderItemList"))
115+
: List.of(List.<String>of(), List.of("orderItemList"), List.of("orderItemList", "customerOrder"), List.of("orderItemList"));
116+
var raw = assertFacts(fixture, nested ? "Payment" : "CustomerOrder", routes, COMMENT,
117+
PURPOSE, "inspect [REDACTED]", logging);
118+
emit("JAVA_AGGREGATE_MEMBERSHIP", Map.of("nested", nested, "logging", logging,
119+
"filtered", filtered, "count", 1, "members", 2, "rootID", graph.order().getId(),
120+
"foreignIDs", items.stream().map(i -> E.customerOrder(E.orderItem(i).getCustomerOrder().eval()).getId().eval()).toList(),
121+
"detail", filtered ? "NotLoaded" : "Loaded", "raw", observations(raw), "safe", observations(fixture.sql)));
122+
if (filtered) {
123+
fixture.clear(); fixture.queryResults.clear();
124+
var full = Q.orderItems().withIdIs(graph.kept().getId()).limit(1)
125+
.selectCustomerOrderWith(Q.customerOrders().limit(1))
126+
.comment("independent full detail").purpose("verify edge-owned view").executeForOne(fixture.context);
127+
assertEquals(graph.order().getDescription(), E.customerOrder(E.orderItem(full).getCustomerOrder().eval()).getDescription().eval());
128+
for (var item : items) assertThrows(io.teaql.core.value.TeaQLNotLoadedException.class,
129+
() -> E.customerOrder(E.orderItem(item).getCustomerOrder().eval()).getDescription().eval());
130+
var visibleRaw = assertFacts(fixture, "OrderItem", List.of(List.<String>of(), List.of("customerOrder")),
131+
"independent full detail", "verify edge-owned view", "independent full detail", logging);
132+
emit("JAVA_AGGREGATE_FORWARD", Map.of("nested", nested, "logging", logging,
133+
"originalDetailsStillNotLoaded", true, "fullDetailIndependent", true, "raw", observations(visibleRaw)));
134+
}
135+
}
136+
}
137+
138+
private static List<ExecutionMetadata> assertFacts(GeneratedTraceChainExampleTest.Fixture fixture,
139+
String root, List<List<String>> routes, String comment, String purpose, String safeComment, boolean logging) {
140+
var raw = fixture.queryResults.get(fixture.queryResults.size() - 1).statements();
141+
assertEquals(routes.size(), raw.size()); assertEquals(logging ? raw.size() : 0, fixture.sql.size());
142+
for (int i = 0; i < raw.size(); i++) {
143+
var expected = new ArrayList<>(List.of(new TraceNode(TraceKind.OPERATION, root, null, "query"),
144+
new TraceNode(TraceKind.REQUEST, root, null, "")));
145+
String parent = root;
146+
for (String relation : routes.get(i)) {
147+
expected.add(new TraceNode(TraceKind.RELATION, relation, null, parent + "." + relation));
148+
parent = relation.equals("orderItemList") ? "OrderItem" : "CustomerOrder";
149+
}
150+
expected.add(new TraceNode(TraceKind.PROVIDER, "sqlite", null, ""));
151+
expected.add(new TraceNode(TraceKind.SQL, "select", null, ""));
152+
assertFact(raw.get(i), expected, comment, purpose);
153+
assertFact(LogPrivacy.sql(raw.get(i), false), expected, safeComment, purpose);
154+
if (logging) assertFact(fixture.sql.get(i), expected, safeComment, purpose);
155+
}
156+
assertTrue(fixture.commands.isEmpty()); assertTrue(fixture.audit.isEmpty());
157+
assertTrue(fixture.context.getTraceChain().isEmpty()); return raw;
158+
}
159+
160+
private static void assertFact(ExecutionMetadata fact, List<TraceNode> expected, String comment, String purpose) {
161+
assertEquals(expected, fact.getTraceChain()); assertEquals(comment, fact.getComment());
162+
assertEquals(purpose, fact.getPurpose()); assertEquals("success", fact.getExecutionOutcome());
163+
assertTrue(fact.getParameterizedQuery().startsWith("SELECT"));
164+
}
165+
166+
private static List<Map<String, Object>> observations(List<ExecutionMetadata> facts) {
167+
return facts.stream().map(f -> {
168+
Map<String, Object> row = new LinkedHashMap<>();
169+
row.put("path", f.getTraceChain().stream().map(n -> {
170+
Map<String, Object> node = new LinkedHashMap<>();
171+
node.put("kind", n.getKind().name()); node.put("name", n.getName());
172+
node.put("entityId", n.getEntityId()); node.put("comment", n.getComment()); return node;
173+
}).toList());
174+
row.put("comment", f.getComment()); row.put("purpose", f.getPurpose());
175+
row.put("outcome", f.getExecutionOutcome()); row.put("sql", f.getParameterizedQuery()); return row;
176+
}).toList();
177+
}
178+
179+
private static void emit(String marker, Object value) throws Exception {
180+
System.out.println(marker + " " + new ObjectMapper().writeValueAsString(value));
181+
}
182+
}

‎examples/trace-chain/verify.sh‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ markers=(
4444
)
4545
for repetition in 1 2; do
4646
log="$run_dir/run-$repetition.log"
47-
if ! mvn -B -f "$example_dir/pom.xml" -Dtest=GeneratedTraceChainExampleTest,GeneratedFacetTraceExampleTest,GeneratedReverseFacetTraceExampleTest \
47+
if ! mvn -B -f "$example_dir/pom.xml" -Dtest=GeneratedTraceChainExampleTest,GeneratedFacetTraceExampleTest,GeneratedReverseFacetTraceExampleTest,GeneratedAggregateTraceExampleTest \
4848
"-Dteaql.trace.database=$database" test > "$log" 2>&1; then
4949
tail -n 100 "$log" >&2
5050
exit 1
@@ -55,7 +55,12 @@ for repetition in 1 2; do
5555
exit 1
5656
fi
5757
done
58-
grep -Fq 'Tests run: 22, Failures: 0, Errors: 0, Skipped: 0' "$log"
58+
grep -Fq 'Tests run: 24, Failures: 0, Errors: 0, Skipped: 0' "$log"
59+
for aggregate_marker in JAVA_AGGREGATE_OBSERVED JAVA_AGGREGATE_NUMERIC JAVA_AGGREGATE_MEMBERSHIP JAVA_AGGREGATE_FORWARD; do
60+
expected_count=4
61+
if [[ $aggregate_marker == JAVA_AGGREGATE_MEMBERSHIP ]]; then expected_count=8; fi
62+
[[ $(grep -c "^$aggregate_marker " "$log") == "$expected_count" ]]
63+
done
5964
grep -Fq 'JAVA_NESTED_FACET_CARRIER returned nested metadata and count verified' "$log"
6065
for logging in false true; do
6166
sink_count=0

‎teaql-core/src/main/java/io/teaql/core/SqlIntentRedactions.java‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,9 @@
88
@JsonIgnoreType
99
public final class SqlIntentRedactions {
1010
private record Secret(String value, boolean forced) {}
11-
private final List<Secret> secrets = new ArrayList<>();
11+
// Preclassification and physical binding capture may see the same operand.
12+
// Retain first-seen order without repeated work; forced provenance remains distinct.
13+
private final Set<Secret> secrets = new LinkedHashSet<>();
1214

1315
@FrameworkInternal("Independent nested-query provenance snapshot")
1416
public SqlIntentRedactions copy() {

‎teaql-core/src/test/java/io/teaql/core/SqlIntentRedactionsTest.java‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,19 @@
55
import static org.junit.Assert.*;
66

77
public class SqlIntentRedactionsTest {
8+
@Test public void repeatedTypedAndPhysicalCaptureIsIdempotentWithoutLosingForcedSecrets() {
9+
var source = new SqlIntentRedactions();
10+
for (int i = 0; i < 3; i++) source.capture(List.of(SqlParameterLogPolicy.MASKED), new Object[]{"SECRET"});
11+
var safe = new java.util.ArrayList<Object>(); source.appendTo(safe, false);
12+
assertEquals(List.of("SECRET"), safe);
13+
var child = source.copy(); child.include(source);
14+
child.capture(List.of(SqlParameterLogPolicy.CREDENTIAL), new Object[]{"SECRET"});
15+
child.capture(List.of(SqlParameterLogPolicy.MASKED), new Object[]{"NEXT"});
16+
var debug = new java.util.ArrayList<Object>(); child.appendTo(debug, true);
17+
assertEquals("forced classification must survive masked duplicates", List.of("SECRET"), debug);
18+
safe.clear(); source.appendTo(safe, false);
19+
assertEquals("descendant capture cannot mutate parent provenance", List.of("SECRET"), safe);
20+
}
821
@Test public void inheritedPolicyAndCredentialsMatchBindingPolicy() {
922
var parent = new io.teaql.core.meta.EntityDescriptor();
1023
var field = new io.teaql.core.meta.PropertyDescriptor();

0 commit comments

Comments
 (0)