Skip to content

Commit b5b50b9

Browse files
author
Philip Z
committed
fix: preserve nested facet metadata and request-owned membership queries
1 parent 0d514a3 commit b5b50b9

8 files changed

Lines changed: 217 additions & 11 deletions

File tree

‎examples/trace-chain/README.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,8 @@ and the `runtime-examples` Maven profile.
6868
| Late-consumed stream | The real JDBC cursor opens without Context frames; consuming after an unrelated query retains the stream's original comment, purpose, root type and generated E result |
6969
| Nested Facets | PaymentAttempt facets load Payment and its CustomerOrder facet; all five physical queries keep PaymentAttempt as the root, preserve the logical relation route and return the selected payment with count 1 |
7070
| Facet inside a loaded relation | A PaymentAttempt loads Payment and its CustomerOrder facet; all four physical queries keep the original root, including the already-loaded `payment` ancestor |
71+
| Returned nested Facet metadata | `GeneratedFacetTraceExampleTest` checks that the returned payments Facet retains its orders Facet; executing nested SQL alone does not prove result carriage |
72+
| Full nested membership counts | A one-row page over three attempts / two payments returns both payment and order counts of 2; matching/all Facets and logging off/on execute seven real SELECTs, including materialized predicate lookups, on one originating collector |
7173

7274
The first run begins with CustomerOrder and Payment both numbered 100, items
7375
201/202, attempt 401 and shipment 501. IDs come from `IdSpaceIdGenerator`, not
@@ -129,6 +131,14 @@ its concurrency safety or complete advanced-query/cancellation coverage.
129131

130132
Derived Facet requests inherit both the root intent and the parent's complete
131133
immutable path, rather than rebuilding the origin from the facet entity.
134+
Membership COUNT compilation also carries the originating request, including
135+
its statement observer. A materialized relation predicate is an actual query,
136+
not invisible compiler work: its physical statement retains that root and the
137+
verified relation edge. Matching Facet targets are restricted by the counted
138+
FK identities, never by applying source-table predicates to the target table.
139+
Facet materialization preserves nested collection metadata without sharing its
140+
mutable map. The all-examples gate includes both generated test classes
141+
(19 JUnit methods), twice against the same retained SQLite database.
132142
Native `DerivedQueryTraceSqliteTest` separately exercises dynamic aggregates:
133143
filtered counts, an aggregate inside a loaded relation, safe parent-value
134144
redaction, logging disabled, and a numeric partition without a model relation.
Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
package io.teaql.examples.tracechain;
2+
3+
import com.teaql.tracechainservice.E;
4+
import com.teaql.tracechainservice.Q;
5+
import com.teaql.tracechainservice.customerorder.CustomerOrder;
6+
import com.teaql.tracechainservice.payment.Payment;
7+
import io.teaql.core.Entity;
8+
import io.teaql.core.ExecutionMetadata;
9+
import io.teaql.core.SmartList;
10+
import io.teaql.core.TraceKind;
11+
import io.teaql.core.TraceNode;
12+
import io.teaql.runtime.LogPrivacy;
13+
import java.util.List;
14+
import org.junit.Test;
15+
import static org.junit.Assert.*;
16+
17+
/** TC-SQL-09: check returned nested metadata, not just successful facet SQL. */
18+
public class GeneratedFacetTraceExampleTest {
19+
@Test public void nestedFacetMetadataRemainsAttachedToTheReturnedFacetCollection() throws Exception {
20+
var fixture = new GeneratedTraceChainExampleTest.Fixture();
21+
var graph = fixture.saveNormativeGraph();
22+
fixture.clear();
23+
var rows = Q.paymentAttempts().withIdIs(graph.attempt().getId()).limit(1)
24+
.facetByPaymentAs("payments", Q.payments().withIdIs(graph.payment().getId()).limit(1)
25+
.facetByCustomerOrderAs("orders", Q.customerOrders().withIdIs(graph.order().getId()).limit(1)))
26+
.comment("load nested facet metadata").purpose("verify the returned collection, not only SQL").executeForList(fixture.context);
27+
assertEquals(1, rows.size());
28+
var payments = rows.getFacet("payments");
29+
assertNotNull(payments); assertEquals(1, payments.size());
30+
var orders = payments.getFacet("orders");
31+
assertNotNull("nested Facet metadata must survive materialization", orders);
32+
assertEquals(1, orders.size());
33+
assertEquals(graph.order().getId(), E.customerOrder((CustomerOrder) orders.get(0)).getId().eval());
34+
assertEquals(1, count((CustomerOrder) orders.get(0)));
35+
System.out.println("JAVA_NESTED_FACET_CARRIER returned nested metadata and count verified");
36+
}
37+
38+
@Test public void nestedFacetCountsSurviveMaterializationBeyondTheVisiblePage() throws Exception {
39+
for (boolean logging : List.of(false, true)) {
40+
for (boolean includeAll : List.of(false, true)) {
41+
var fixture = new GeneratedTraceChainExampleTest.Fixture(logging);
42+
var graph = fixture.saveNormativeGraph();
43+
var payment = Q.payments().comment("prepare another facet member")
44+
.purpose("verify full membership beyond one visible row").newEntity(fixture.context);
45+
payment.updateReferenceCode("FACET-PAYMENT-" + fixture.base);
46+
for (int i = 0; i < 2; i++) {
47+
var attempt = Q.paymentAttempts().comment("prepare a counted attempt")
48+
.purpose("verify full facet membership").newEntity(fixture.context);
49+
attempt.updateReferenceCode("FACET-ATTEMPT-" + fixture.base + "-" + i);
50+
payment.addPaymentAttempt(attempt);
51+
}
52+
graph.order().addPayment(payment);
53+
graph.order().auditAs("seed nested facet membership").save(fixture.context);
54+
long orderId = E.customerOrder(graph.order()).getId().eval();
55+
long paymentId = E.payment(payment).getId().eval();
56+
fixture.clear(); fixture.queryResults.clear();
57+
String comment = "load bounded nested payment facets";
58+
String purpose = "verify returned full counts and original query ancestry";
59+
var rows = Q.paymentAttempts()
60+
.withPaymentMatching(Q.payments().filterByCustomerOrder(orderId))
61+
.orderByIdDescending().limit(1)
62+
.facetByPaymentAs("payments", Q.payments().filterByCustomerOrder(orderId)
63+
.orderByIdDescending().limit(1)
64+
.facetByCustomerOrderAs("orders", Q.customerOrders().withIdIs(orderId).limit(1), includeAll), includeAll)
65+
.comment(comment).purpose(purpose).executeForList(fixture.context);
66+
assertEquals("bounded visible attempt page", 1, rows.size());
67+
var payments = rows.getFacet("payments");
68+
assertNotNull("first-level facet metadata", payments);
69+
assertEquals(1, payments.size());
70+
var selected = (Payment) payments.get(0);
71+
assertEquals(paymentId, E.payment(selected).getId().eval().longValue());
72+
assertEquals("first-level count is not the one-row visible page", 2, count(selected));
73+
var orders = payments.getFacet("orders");
74+
assertNotNull("nested Facet metadata must survive materialization", orders);
75+
assertEquals(1, orders.size());
76+
var order = (CustomerOrder) orders.get(0);
77+
assertEquals(orderId, E.customerOrder(order).getId().eval().longValue());
78+
assertEquals("nested count uses both filtered payments, not the visible payment page", 2, count(order));
79+
var raw = fixture.queryResults.get(fixture.queryResults.size() - 1).statements();
80+
// The page and its COUNT each materialize the predicate. Both
81+
// real SELECTs must belong to the originating collector.
82+
var routes = List.of(List.of("payment"), List.<String>of(), List.of("payment"),
83+
List.<String>of(), List.of("payment"), List.of("payment"),
84+
List.of("payment", "customerOrder"));
85+
assertEquals(routes.size(), raw.size());
86+
for (int i = 0; i < raw.size(); i++) {
87+
assertPath(raw.get(i), routes.get(i), comment, purpose);
88+
assertEquals("real SELECT completed", "success", raw.get(i).getExecutionOutcome());
89+
var safe = LogPrivacy.sql(raw.get(i), false);
90+
assertPath(safe, routes.get(i), comment, purpose);
91+
if (i == 3 || i == 5) {
92+
assertTrue("physical membership COUNT", raw.get(i).getParameterizedQuery().toUpperCase().contains("COUNT("));
93+
assertFalse("membership count must not reuse the visible page limit",
94+
raw.get(i).getParameterizedQuery().toUpperCase().contains("LIMIT 1"));
95+
}
96+
}
97+
assertEquals(logging ? raw.size() : 0, fixture.sql.size());
98+
for (int i = 0; i < fixture.sql.size(); i++) assertPath(fixture.sql.get(i), routes.get(i), comment, purpose);
99+
assertTrue(fixture.context.getTraceChain().isEmpty());
100+
System.out.printf("JAVA_NESTED_FACET {\"logging\":%s,\"includeAll\":%s,\"visible\":1,\"paymentCount\":2,\"orderCount\":2,\"physicalStatements\":7,\"safeSinkStatements\":%d}%n",
101+
logging, includeAll, fixture.sql.size());
102+
}
103+
}
104+
}
105+
106+
private static int count(Entity entity) {
107+
return ((Number) entity.getDynamicProperty("count")).intValue();
108+
}
109+
110+
private static void assertPath(ExecutionMetadata fact, List<String> route, String comment, String purpose) {
111+
var expected = new java.util.ArrayList<>(List.of(
112+
new TraceNode(TraceKind.OPERATION, "PaymentAttempt", null, "query"),
113+
new TraceNode(TraceKind.REQUEST, "PaymentAttempt", null, "")));
114+
String owner = "PaymentAttempt";
115+
for (String edge : route) {
116+
expected.add(new TraceNode(TraceKind.RELATION, edge, null, owner + "." + edge));
117+
owner = edge.equals("payment") ? "Payment" : "CustomerOrder";
118+
}
119+
expected.add(new TraceNode(TraceKind.PROVIDER, "sqlite", null, ""));
120+
expected.add(new TraceNode(TraceKind.SQL, "select", null, ""));
121+
assertEquals("complete canonical physical path", expected, fact.getTraceChain());
122+
assertEquals(comment, fact.getComment());
123+
assertEquals(purpose, fact.getPurpose());
124+
}
125+
}

‎examples/trace-chain/verify.sh‎

Lines changed: 10 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 \
47+
if ! mvn -B -f "$example_dir/pom.xml" -Dtest=GeneratedTraceChainExampleTest,GeneratedFacetTraceExampleTest \
4848
"-Dteaql.trace.database=$database" test > "$log" 2>&1; then
4949
tail -n 100 "$log" >&2
5050
exit 1
@@ -55,7 +55,15 @@ for repetition in 1 2; do
5555
exit 1
5656
fi
5757
done
58-
grep -Fq 'Tests run: 17, Failures: 0, Errors: 0, Skipped: 0' "$log"
58+
grep -Fq 'Tests run: 19, Failures: 0, Errors: 0, Skipped: 0' "$log"
59+
grep -Fq 'JAVA_NESTED_FACET_CARRIER returned nested metadata and count verified' "$log"
60+
for logging in false true; do
61+
for all in false true; do
62+
sink_count=0
63+
if [[ $logging == true ]]; then sink_count=7; fi
64+
grep -Fq "JAVA_NESTED_FACET {\"logging\":$logging,\"includeAll\":$all,\"visible\":1,\"paymentCount\":2,\"orderCount\":2,\"physicalStatements\":7,\"safeSinkStatements\":$sink_count}" "$log"
65+
done
66+
done
5967
printf 'PASS Java generated Trace Chain run %s on the same database\n' "$repetition"
6068
done
6169
library_manifest > "$run_dir/library-after.sha256"

‎teaql-sql-portable/src/main/java/io/teaql/core/sql/SqlAstCompiler.java‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,12 @@ public String buildAggregationSQL(
8989
SearchRequest<?> request,
9090
Map<String, Object> parameters,
9191
List<String> tables) {
92-
92+
// A facet/count compilation can materialize a relation predicate just
93+
// like a data SELECT. Carry the captured intent in this compilation's
94+
// bindings, never in the shared Context.
95+
if (parameters instanceof SqlParameters tracked) {
96+
tracked.captureQueryContext(request);
97+
}
9398
String idTable = tables.get(0);
9499
String whereSql = prepareCondition(metadata, repository, userContext, idTable, request.getSearchCriteria(), parameters);
95100

‎teaql-sql-portable/src/main/java/io/teaql/core/sql/SqlParameters.java‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,25 @@ public final class SqlParameters extends HashMap<String, Object> {
1010
private SqlParameterLogPolicy currentPolicy = SqlParameterLogPolicy.UNKNOWN;
1111
private boolean generated = true;
1212
private io.teaql.core.QueryIntent queryIntent;
13+
private io.teaql.core.SearchRequest<?> originatingQuery;
1314

1415
/** Immutable originating intent for cross-provider relation predicates during this compilation. */
1516
public io.teaql.core.QueryIntent queryIntent() { return queryIntent; }
1617
public void captureQueryIntent(io.teaql.core.QueryIntent intent) {
1718
if (queryIntent == null) queryIntent = java.util.Objects.requireNonNull(intent, "intent");
1819
}
20+
/** Provider-owned scoped request, retained only for this compilation. */
21+
public io.teaql.core.SearchRequest<?> originatingQuery() { return originatingQuery; }
22+
public void captureQueryContext(io.teaql.core.SearchRequest<?> request) {
23+
var intent = request.inheritedQueryIntent();
24+
if (intent == null && request.comment() != null && request.purpose() != null) {
25+
intent = io.teaql.core.QueryIntent.of(request.comment(), request.purpose());
26+
}
27+
if (intent != null) {
28+
captureQueryIntent(intent);
29+
if (originatingQuery == null) originatingQuery = request;
30+
}
31+
}
1932

2033
public SqlParameterLogPolicy policy(String name) {
2134
return policies.getOrDefault(name, SqlParameterLogPolicy.UNKNOWN);

‎teaql-sql-portable/src/main/java/io/teaql/core/sql/expression/SubQueryParser.java‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,11 @@ public String toSql(
8989
throw new io.teaql.core.TeaQLRuntimeException(
9090
"[INTERNAL QUERY CONTEXT REQUIRED] Materialized relation predicate requires originating query intent.");
9191
}
92-
SmartList<Entity> referred = userContext.internalExecuteForList(new TempRequest(dependsOn, rootIntent));
92+
var origin = parameters instanceof io.teaql.core.sql.SqlParameters tracked
93+
? tracked.originatingQuery() : null;
94+
SmartList<Entity> referred = origin != null && sqlColumnResolver instanceof PortableSQLRepository<?> owner
95+
? owner.materializeRelationPredicate(userContext, dependsOn, origin, propertyName)
96+
: userContext.internalExecuteForList(new TempRequest(dependsOn, rootIntent));
9397
Set dependsOnValues = new HashSet<>();
9498
for (Entity entity : referred) {
9599
Object propertyValue = entity.getProperty(dependsOnPropertyName);

‎teaql-sql-portable/src/main/java/io/teaql/core/sql/portable/PortableSQLRepository.java‎

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -223,11 +223,7 @@ public Map<Class, SQLExpressionParser> getExpressionParsers() {
223223

224224
public String buildDataSQL(UserContext userContext, SearchRequest request, Map<String, Object> parameters) {
225225
if (parameters instanceof io.teaql.core.sql.SqlParameters tracked) {
226-
var origin = request.inheritedQueryIntent();
227-
if (origin == null && request.comment() != null && request.purpose() != null) {
228-
origin = io.teaql.core.QueryIntent.of(request.comment(), request.purpose());
229-
}
230-
if (origin != null) tracked.captureQueryIntent(origin);
226+
tracked.captureQueryContext(request);
231227
}
232228
String partitionProperty = request.getPartitionProperty();
233229
if (ObjectUtil.isNotEmpty(partitionProperty) && request.getSlice() != null) {
@@ -238,6 +234,17 @@ public String buildDataSQL(UserContext userContext, SearchRequest request, Map<S
238234
return compiler.buildDataSQL(sqlMetadata, this, userContext, request, parameters);
239235
}
240236

237+
/** Framework-owned predicate lookup; keep all physical work on its request's collector. */
238+
public SmartList<Entity> materializeRelationPredicate(UserContext context, SearchRequest<?> child,
239+
SearchRequest<?> origin, String propertyName) {
240+
var source = SqlDiagnosticRequest.source(context, origin);
241+
var property = findProperty(propertyName);
242+
var lookup = property instanceof Relation
243+
? SqlDiagnosticRequest.forRelation(child, source, origin, propertyName)
244+
: SqlDiagnosticRequest.forDerived(child, source, origin);
245+
return context.internalExecuteForList(lookup);
246+
}
247+
241248
// ==========================================
242249
// Named parameter → positional parameter conversion
243250
// ==========================================
@@ -798,7 +805,8 @@ private SmartList<T> loadWithIntent(UserContext userContext, SearchRequest<T> re
798805
if (facetRequests != null && !facetRequests.isEmpty()) {
799806
io.teaql.core.sql.SqlAstCompiler compiler = new io.teaql.core.sql.SqlAstCompiler();
800807
for (io.teaql.core.FacetRequest facetRequest : facetRequests) {
801-
io.teaql.core.internal.TempRequest tr = new io.teaql.core.internal.TempRequest(request);
808+
io.teaql.core.internal.TempRequest tr =
809+
SqlDiagnosticRequest.forDerived(request, intent, request);
802810
tr.setAggregations(new io.teaql.core.Aggregations());
803811
tr.groupBy(facetRequest.getRelationName());
804812
tr.count("count");
@@ -832,7 +840,12 @@ private SmartList<T> loadWithIntent(UserContext userContext, SearchRequest<T> re
832840
SqlDiagnosticRequest.forRelation(
833841
relationReq, facetIntent, request, facetRequest.getRelationName());
834842
if (facetRequest.isMergeCriteria()) {
835-
fetchRelReq.appendSearchCriteria(request.getSearchCriteria());
843+
// The count query already applied the source's
844+
// filters. Its FK membership is the only valid
845+
// restriction on the target: source predicates
846+
// belong to another table/type (even "id").
847+
fetchRelReq.appendSearchCriteria(fetchRelReq.createBasicSearchCriteria(
848+
BaseEntity.ID_PROPERTY, io.teaql.core.criteria.Operator.IN, relIds));
836849
}
837850
SmartList<?> loadedRels = relationRepo.loadInternal(userContext, fetchRelReq, facetIntent);
838851
java.util.List<String> countAliases = relationReq.getAggregations().getAggregates()
@@ -849,6 +862,10 @@ private SmartList<T> loadWithIntent(UserContext userContext, SearchRequest<T> re
849862
}
850863
facetEntities.add(rel);
851864
}
865+
// Materialization changes the row carrier, not the
866+
// nested facet result. Preserve its collection-owned
867+
// metadata without sharing the mutable map itself.
868+
loadedRels.getFacets().forEach(facetEntities::addFacet);
852869
}
853870
}
854871
smartList.addFacet(facetRequest.getFacetName(), facetEntities);

0 commit comments

Comments
 (0)