Skip to content

Commit c99b208

Browse files
Eric Prud'hommeauxclaude
andcommitted
~ review pass: leak fixes, ShEx validator memoization, PCH, task list
Leak fixes (LSan-verified in ubuntu:24.04 docker; test_DAWG went from 204 reported leaks to zero, ShExMap CLI clean): - SPARQLParser.ypp restoreFilter: delete the FilterExpressions carrier once its expressions move into the Filter op (leaked once per FILTER clause). - SWObjects.cpp StarVarSet::project: replace the non-owning NoDelExpressionAlias with an owning ExpressionAlias; the TTermExpressions are purpose-built for the call and were leaked. ShEx validator performance: - Memoize SORBE forms per triple expression on the Validator (sorbeCache, freed in the new ~Validator) instead of rebuilding and deleting them on every shape evaluation. - Cache completed (node, shapeLabel) results; only when no semantic-action handler is registered and the result took no cyclic assumption (assumedCount bookkeeping keeps it sound). Build: - Precompile SWObjects.hpp (Boost.Log/Regex weight); library compile CPU ~111s -> ~81s. - Logging.hpp: replace the SWObjects_STAND_ALONE conditional block (invisible to a precompiled header) with an explicit w3c_sw_DEFINE_LOGGER_GLOBALS macro invoked from SWObjects.cpp. Tests: - test_ShEx manifests owned by a static vector<unique_ptr> so leak checkers see them reachable (was an intentional raw leak). docs/code-review.md: prioritized follow-up task list from the review (ChainingMapper double-delete, bison %destructor error-path leaks with LSan numbers, eager-filter semact over-fire, ProductionVector RAII migration, visitor conversion, neighborhood indexing, header-only verdict, etc.). All 18 blocking ctest suites pass; the known-failure bucket is unchanged (function_library + md5/sha* only). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
1 parent 2e25236 commit c99b208

8 files changed

Lines changed: 265 additions & 42 deletions

File tree

‎CMakeLists.txt‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,10 @@ endif()
221221
target_compile_options(SWObjects PRIVATE -Wall -Wextra
222222
-Wno-unused-parameter -Wno-deprecated-declarations)
223223

224+
# SWObjects.hpp drags in Boost.Log (via Logging.hpp) and Boost.Regex;
225+
# precompiling it roughly halves the library's compile time.
226+
target_precompile_headers(SWObjects PRIVATE lib/SWObjects.hpp)
227+
224228
# ------------------------------------------------------------- executables ---
225229

226230
# The tools land in the source-tree bin/ directory (gitignored), as with the

‎docs/code-review.md‎

Lines changed: 168 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,168 @@
1+
# Code review notes and task list
2+
3+
From a review pass on 2026-07-18 (leak hunting under Linux LeakSanitizer,
4+
UB probes under AddressSanitizer, plus a read-through of ownership and
5+
header structure). Items fixed during the pass are marked **[fixed]**;
6+
the rest are queued for follow-up work, roughly in priority order.
7+
Suggested workflow: pick an item, reproduce with the command given,
8+
fix, and run `ctest --test-dir build` plus the item's repro.
9+
10+
## P1 — crashes / correctness
11+
12+
1. **ChainingMapper double-delete (intermittent crash).**
13+
`lib/ChainingMapper.hpp` `map()`: `delete op` after `BGPSimplifier`
14+
walks it. The rewriter (`QueryWalker::mapQuery`) can produce trees
15+
sharing subexpressions, so the tree-delete double-frees. Crashes
16+
`test_QueryMap bsbm/pieces/transformQuery` on some heap layouts
17+
(deterministic under `lldb` because ASLR is off; hidden under ASan
18+
and MallocStackLogging).
19+
*Suggested approach*: make `QueryWalker`'s sharing explicit — either
20+
clone at the sharing points (SWObjectDuplicator) or count references
21+
in the rewrite products. Verify with repeated
22+
`lldb -b -o run -o quit build/test_QueryMap`.
23+
24+
2. **Eager-filter semantic-action over-fire on unused candidates.**
25+
`lib/ShExSchema.cpp` `satisfiesShape` step 6 validates every
26+
(triple, constraint) candidate; a candidate that validates but is
27+
not chosen by the accepted matching still ran nested shapes' step-10
28+
semantic actions. `SemActHandler::mark`/`rollback` scopes bindings
29+
to *successful* subtrees, but successful-unused candidates still
30+
leak bindings into e.g. ShExMap. Faithful fix: dispatch semantic
31+
actions from the accepted solution only (re-walk the winning
32+
matching, re-validating value expressions with the handler enabled
33+
and pre-filter dispatch disabled).
34+
35+
3. **SPARQL `md5`/`sha*` builtins unimplemented** (8 known
36+
`test_SPARQL11` failures). `TTerm::FUNC_md5` etc. exist but no
37+
evaluator binds them. A small digest implementation (or vendored
38+
single-file SHA/MD5) in `lib/SWObjects.cpp`'s BuiltIn section would
39+
turn the suite fully green.
40+
41+
4. **`function_library` CSV `<foo>`-as-IRI** (1 known `test_SPARQL`
42+
failure). `lib/ResultSet.cpp` csv regex has the IRI branch disabled
43+
(`// disabled`) since ~2013 while the 2012 test expects it. Decide:
44+
re-enable for `text/csv` *input* (keeping SPARQL 1.1 CSV *results*
45+
conformance in `test_SPARQL11` csv tests) or retire the test.
46+
47+
## P2 — leaks / ownership
48+
49+
5. **[fixed]** `restoreFilter` leaked the `FilterExpressions` carrier
50+
per FILTER clause (LSan: 104 × 24 B via `SPARQLParser.ypp` +
51+
hangers-on). Now deleted after its expressions move into the
52+
`Filter` op.
53+
54+
6. **[fixed]** `StarVarSet::project` leaked a fresh `TTermExpression`
55+
per projected variable (LSan: 100 × 64 B) because it wrapped them
56+
in a deliberately non-owning alias. Now uses owning
57+
`ExpressionAlias`.
58+
59+
7. **Bison error-path leaks.** None of the grammars declare
60+
`%destructor`, so semantic values on the stack leak when a parse
61+
fails. LSan-confirmed for ShExC: after the fixes above, `test_ShEx`
62+
under LSan reports exactly this — ~18.5 KB / 222 allocations, all
63+
through `ShExDriver::parse` from the negativeSyntax suites (AST
64+
fragments from actions around `ShExCParser.ypp:696/835/985/1009`
65+
plus scanner token strings from `ShExCScanner.lpp:155-165`); the
66+
success paths (`test_DAWG`, `bin/sparql` ShExMap run) are clean.
67+
Adding `%destructor` per union member is mechanical but touchy:
68+
*do not delete* AtomFactory-interned values (`p_URI`, `p_TTerm`,
69+
`p_Literal` — the factory owns them), guard `p_SE`/`p_SEs`
70+
elements against the `driver.emptyShape` sentinel, and remember
71+
`p_SEs`/`p_TEs`/vector types own their elements. Do
72+
ShExCParser.ypp first as the template, verify with the docker LSan
73+
run, then replicate to the other grammars.
74+
75+
8. **`YaccDriver` error-path state.** `SPARQLDriver::curFilter`,
76+
`curBGP` etc. leak if a throw unwinds mid-parse. Consider owning
77+
these as `std::unique_ptr` in the drivers (release() at the
78+
handoff points).
79+
80+
9. **`getRDFLiteral` numeric branches ignore `p_LANGTAG`.**
81+
`lib/SWObjects.cpp`: the integer/decimal/double/boolean early
82+
returns drop a passed langtag without deleting it (invalid input,
83+
but a leak if it happens). Delete or reject explicitly.
84+
85+
## P3 — RAII / API modernization
86+
87+
10. **`ProductionVector` vs `NoDelProductionVector`.** The owning /
88+
non-owning split is by class choice with manual delete loops in
89+
destructors. A cleaner shape: one
90+
`template <typename T, bool Owning>` (or move owning containers to
91+
`std::vector<std::unique_ptr<const T>>`) so ownership is visible in
92+
the type. Big mechanical change; start with new code only
93+
(`ShEx::*` vectors) and leave the SPARQL AST for a dedicated pass.
94+
Note the TTerm/"POS" objects themselves are fine: AtomFactory owns
95+
them (interning maps freed in `~AtomFactory`), and their private
96+
constructors/destructors enforce it.
97+
98+
11. **`NamespaceMap` ownership flag.** `ParserDriver::freeNamespaces`
99+
bool + raw pointer is a hand-rolled maybe-owner; a
100+
`std::unique_ptr<NamespaceMap>` plus a non-owning observer pointer
101+
expresses it directly.
102+
103+
12. **test harness caches** (`tests/test_ShEx.cpp` SchemaCache /
104+
DataCache) use raw `new`/manual dtor loops — safe today, but
105+
`std::map<std::string, std::unique_ptr<Entry>>` removes the
106+
footgun.
107+
108+
## P4 — templating / duplication
109+
110+
13. **`dynamic_cast` dispatch in the ShEx validator.**
111+
`lib/ShExSchema.cpp` re-implements type dispatch with
112+
`dynamic_cast` chains in ~8 places (RefWalk, SorbeExpr, predicate
113+
collection, materializer in ShExMap.cpp) although
114+
`ShapeExprVisitor`/`TripleExprVisitor` exist. Converting the
115+
walkers to visitors removes the chains and the risk of missing a
116+
case when the AST grows.
117+
118+
14. **Grammar action boilerplate.** The `_Q..._E_Star/Plus` vector
119+
accumulation actions repeat ~20 times per grammar. A tiny driver
120+
template (`appendTo(vector*, elt)` as in ShExJison's helpers)
121+
would halve the .ypp action volume. Cosmetic; do when touching a
122+
grammar anyway.
123+
124+
15. **Interval/cardinality arithmetic** in `ShExSchema.cpp` and the
125+
`REPEAT_RANGE` handling in the scanner both re-implement
126+
min/max-with-unbounded logic; unify on `ShEx::Cardinality`.
127+
128+
## P5 — build / header layout
129+
130+
16. **Header-only is fine here — with one exception.** With ~10
131+
library TUs, ~25 generated parser TUs, and one-TU test/binary
132+
targets, keeping SimpleServer/SQLizer/WEBserver as headers is
133+
reasonable (each has 1–2 consumers; splitting buys little).
134+
The exception is `SWObjects.hpp` → `Logging.hpp` → Boost.Log/
135+
Phoenix/Thread in *every* TU. **[fixed]** for build time via
136+
`target_precompile_headers` (compile CPU ~111s → ~81s for the
137+
library). The structural fix, if wanted later: put a minimal
138+
logging facade in SWObjects.hpp and move the Boost.Log machinery
139+
behind a .cpp; that also unblocks non-Boost.Log consumers.
140+
141+
17. **[fixed]** `SWObjects_STAND_ALONE` macro-conditional definitions
142+
in Logging.hpp broke under PCH (macro state isn't seen by a
143+
precompiled header). Replaced with an explicit
144+
`w3c_sw_DEFINE_LOGGER_GLOBALS` invoked from SWObjects.cpp.
145+
146+
## P6 — performance
147+
148+
18. **[fixed]** ShEx SORBE forms were rebuilt on every shape
149+
evaluation; now memoized per triple expression on the `Validator`.
150+
151+
19. **[fixed]** Added a sound `(node, label)` result memo to the
152+
validator (used only without semantic-action handlers, and only
153+
for results that took no cyclic assumption).
154+
155+
20. **ShEx neighborhood extraction scans all triples**
156+
(`satisfiesShape` step 2 iterates the whole graph per focus node).
157+
`BasicGraphPattern` has SP/PO/OS indexes; using them makes
158+
validation linear in the neighborhood instead of the graph.
159+
160+
21. **`Matchings` is an unpruned cartesian product.** Fine for
161+
shexTest-sized neighborhoods; pathological EXTRA/multi-candidate
162+
data can explode. jena's `FeasibleMatchingsIterator` prunes with
163+
per-constraint interval bounds — port it if real workloads hit
164+
this.
165+
166+
22. **`GraphIndex::getObject`** in tests/test_ShEx.cpp is O(triples)
167+
per lookup over the manifest graph (~17k triples × ~1700 entries).
168+
Harness-only; index it if registration time ever matters.

‎lib/Logging.hpp‎

Lines changed: 24 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -446,28 +446,30 @@ BOOST_GLOBAL_FIXTURE( PrepareBoostTestLogger );
446446

447447
} /* namespace Logger */
448448

449-
#ifdef SWObjects_STAND_ALONE
450-
namespace Logger {
451-
int depth;
452-
453-
severity_level DefaultLog_level;
454-
severity_level RewriteLog_level;
455-
severity_level IOLog_level;
456-
severity_level ParsingLog_level;
457-
severity_level GraphMatchLog_level;
458-
severity_level SQLLog_level;
459-
severity_level ServiceLog_level;
460-
severity_level ProcessLog_level;
461-
462-
LabelToLevel_t LabelToLevel;
463-
std::vector<const char*> Labels;
464-
namespace {
465-
LabelInitializer TheLabelInitializer;
466-
}
467-
468-
} /* namespace Logger */
469-
470-
#endif /* SWObjects_STAND_ALONE */
449+
/* The definitions of the Logger globals live in SWObjects.cpp (see
450+
* w3c_sw_DEFINE_LOGGER_GLOBALS); a macro-conditional block here would be
451+
* skipped when this header is precompiled. */
452+
#define w3c_sw_DEFINE_LOGGER_GLOBALS \
453+
namespace w3c_sw { \
454+
namespace Logger { \
455+
int depth; \
456+
\
457+
severity_level DefaultLog_level; \
458+
severity_level RewriteLog_level; \
459+
severity_level IOLog_level; \
460+
severity_level ParsingLog_level; \
461+
severity_level GraphMatchLog_level; \
462+
severity_level SQLLog_level; \
463+
severity_level ServiceLog_level; \
464+
severity_level ProcessLog_level; \
465+
\
466+
LabelToLevel_t LabelToLevel; \
467+
std::vector<const char*> Labels; \
468+
namespace { \
469+
LabelInitializer TheLabelInitializer; \
470+
} \
471+
} /* namespace Logger */ \
472+
} /* namespace w3c_sw */
471473

472474
} // namespace w3c_sw
473475

‎lib/SPARQLParser.ypp‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,9 @@ protected:
175175
if (curOp == NULL)
176176
ensureBasicGraphPattern();
177177
curOp = new Filter(curOp, curFilter->m_Expressions.begin(), curFilter->m_Expressions.end());
178+
// the Filter now owns the expressions; free the carrier
179+
curFilter->m_Expressions.clear();
180+
delete curFilter;
178181
}
179182
curFilter = was;
180183
}

‎lib/SWObjects.cpp‎

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,8 @@
55
* $Id: SWObjects.cpp,v 1.17 2008-12-02 04:57:12 eric Exp $
66
*/
77

8-
#define SWObjects_STAND_ALONE
98
#include "SWObjects.hpp"
10-
#undef SWObjects_STAND_ALONE
9+
w3c_sw_DEFINE_LOGGER_GLOBALS // this translation unit owns the Logger globals
1110
#include "ResultSet.hpp"
1211
#include <string.h>
1312
#include <iomanip>
@@ -3288,14 +3287,11 @@ void RecursiveExpressor::valuesClause (const ValuesClause* const, const ResultSe
32883287
if (groupBy || having || orderConditions) {
32893288
// Ideally we wouldn't bother creating this list to sort column but
32903289
// <having> extends this list so detaching them would be challenging.
3291-
struct NoDelExpressionAlias : public ExpressionAlias {
3292-
NoDelExpressionAlias (const Expression* expr) : ExpressionAlias(expr) { }
3293-
~NoDelExpressionAlias () { expr = NULL; } // we don't want to duplicate expressions for no good reason.
3294-
};
32953290
ProductionVector<const ExpressionAlias*> expressions; // auto-deletes its payload
32963291
const VariableList* vars = rs->getKnownVars();
32973292
for (VariableListConstIterator it = vars->begin(); it != vars->end(); ++it)
3298-
expressions.push_back(new NoDelExpressionAlias(new TTermExpression(*it)));
3293+
// the alias owns (and frees) the TTermExpression made for it
3294+
expressions.push_back(new ExpressionAlias(new TTermExpression(*it)));
32993295
rs->project(&expressions, groupBy, having, orderConditions, db);
33003296
}
33013297
}

‎lib/ShExSchema.cpp‎

Lines changed: 43 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -461,7 +461,9 @@ namespace ShEx {
461461
}
462462

463463
typedef std::map<const TripleConstraint*, long> Bag;
464+
} // namespace
464465

466+
namespace detail {
465467
/** SORBE form of a triple expression plus origin bookkeeping (see
466468
* jena-shex TripleExprForValidation). */
467469
struct SorbeExpr {
@@ -697,7 +699,10 @@ namespace ShEx {
697699
return interval(relevant(), bag).contains1();
698700
}
699701
};
702+
} // namespace detail
703+
using detail::SorbeExpr;
700704

705+
namespace {
701706
/** Cartesian iteration over triple -> candidate-TC choices. */
702707
struct Matchings {
703708
std::vector<DataTriple> triples;
@@ -818,6 +823,22 @@ namespace ShEx {
818823
}
819824
};
820825

826+
Validator::~Validator () {
827+
for (std::map<const TripleExpr*, detail::SorbeExpr*>::iterator it = sorbeCache.begin();
828+
it != sorbeCache.end(); ++it)
829+
delete it->second;
830+
}
831+
832+
detail::SorbeExpr* Validator::getSorbe (const TripleExpr* expr) {
833+
std::map<const TripleExpr*, detail::SorbeExpr*>::const_iterator hit
834+
= sorbeCache.find(expr);
835+
if (hit != sorbeCache.end())
836+
return hit->second;
837+
detail::SorbeExpr* made = new detail::SorbeExpr(schema, expr);
838+
sorbeCache[expr] = made;
839+
return made;
840+
}
841+
821842
bool Validator::satisfies (const TTerm* node, const ShapeExpr* expr,
822843
const std::vector<DataTriple>* neigh) {
823844
size_t mark = semActHandler != NULL ? semActHandler->mark() : 0;
@@ -996,16 +1017,29 @@ namespace ShEx {
9961017

9971018
bool Validator::satisfiesLabel (const TTerm* node, const TTerm* label) {
9981019
std::pair<const TTerm*, const TTerm*> key(node, label);
999-
if (inProgress.find(key) != inProgress.end())
1020+
if (inProgress.find(key) != inProgress.end()) {
1021+
++assumedCount;
10001022
return true; // cyclic: assume conformant
1023+
}
1024+
// Completed results can be reused when no handler is watching. Only
1025+
// results computed without any assumption on the stack are cached.
1026+
bool cacheable = semActHandler == NULL;
1027+
if (cacheable) {
1028+
std::map<std::pair<const TTerm*, const TTerm*>, bool>::const_iterator hit
1029+
= memo.find(key);
1030+
if (hit != memo.end())
1031+
return hit->second;
1032+
}
10011033
std::map<const TTerm*, ShapeDecl*>::const_iterator decl = schema.declIndex.find(label);
10021034
if (decl == schema.declIndex.end()) {
10031035
lastError = "undefined shape " + label->toString();
10041036
return false;
10051037
}
1038+
size_t assumedBefore = assumedCount;
10061039
std::vector<const TTerm*> descendants = nonAbstractDescendants(label);
1040+
bool ret = false;
10071041
for (std::vector<const TTerm*>::const_iterator it = descendants.begin();
1008-
it != descendants.end(); ++it) {
1042+
!ret && it != descendants.end(); ++it) {
10091043
const ShapeExpr* expr = schema.getShapeExpr(*it);
10101044
if (expr == NULL)
10111045
continue;
@@ -1014,14 +1048,14 @@ namespace ShEx {
10141048
inProgress.insert(dkey);
10151049
const TTerm* outerDeclLabel = currentDeclLabel;
10161050
currentDeclLabel = *it;
1017-
bool ok = satisfies(node, expr, NULL);
1051+
ret = satisfies(node, expr, NULL);
10181052
currentDeclLabel = outerDeclLabel;
10191053
inProgress.erase(dkey);
10201054
inProgress.erase(key);
1021-
if (ok)
1022-
return true;
10231055
}
1024-
return false;
1056+
if (cacheable && assumedCount == assumedBefore)
1057+
memo[key] = ret; // independent of any cyclic assumption
1058+
return ret;
10251059
}
10261060

10271061
bool Validator::validate (const TTerm* node, const TTerm* label) {
@@ -1135,11 +1169,11 @@ namespace ShEx {
11351169
if (shape->closed && !nonMatchables.empty())
11361170
return false;
11371171

1138-
// 4. SORBE forms.
1172+
// 4. SORBE forms (memoized per triple expression).
11391173
std::vector<SorbeExpr*> sorbes;
11401174
for (std::vector<const TripleExpr*>::const_iterator it = exprs.begin();
11411175
it != exprs.end(); ++it)
1142-
sorbes.push_back(*it == NULL ? NULL : new SorbeExpr(schema, *it));
1176+
sorbes.push_back(*it == NULL ? NULL : getSorbe(*it));
11431177

11441178
bool ret = false;
11451179
{
@@ -1306,10 +1340,7 @@ namespace ShEx {
13061340
}
13071341
}
13081342

1309-
for (std::vector<SorbeExpr*>::const_iterator se = sorbes.begin();
1310-
se != sorbes.end(); ++se)
1311-
delete *se;
1312-
return ret;
1343+
return ret; // the SORBE forms stay cached on the validator
13131344
}
13141345

13151346
/* -------------------------------------------------- node constraint eval */

0 commit comments

Comments
 (0)