Repository navigation
Conversation
|
@codex review |
| String enclosingVarName = (enclosingVar != null) ? enclosingVar.getName() : null; | ||
|
|
||
| String exprKey = (cte.attrTrace() != null) ? cte.attrTrace().toString() : cte.getExpr().toString(); | ||
| boolean isDbQueryCte = exprKey.contains("teverDbOrdinal") |
There was a problem hiding this comment.
This is project-specific logic in the compiler, and the cache is already returning wrong results. A small repro with compiletime(teverDbOrdinal()) returns 4101; change the function body to return 4102 and the next compilation still gets 4101. This happens on a normal build, without -incremental.
The expression text doesn't cover the implementation or everything it reads, and the hard-coded Tever file list can't fix that. These project names and paths need to go. Any compile-time cache needs to track actual inputs and preserve side effects before it can safely skip execution.
| sourceContent = Files.asCharSource(f, Charsets.UTF_8).read(); | ||
| fileCache.put(filePath, new FileEntry(lm, len, sourceContent)); | ||
| } | ||
| String toHash = "v1:" + name + ":" + sourceContent; |
There was a problem hiding this comment.
The package's own source isn't enough to identify its generated Lua. I reproduced this with package A exporting tuple Pair(int x, int y) and package B constructing it. Change A to Pair(int y, int x) and rebuild with the same cache: B still uses the old field layout. A clean build of the same current sources uses the new layout.
Dependency changes must invalidate consumers where they affect lowering. Compiler options, compile-time results, and whole-program naming/type IDs also need to be accounted for. Until that is covered, a cache hit can silently change program behavior.
| long tLight = System.currentTimeMillis(); | ||
|
|
||
| heavyValidation(); | ||
| if (!quickMode) { |
There was a problem hiding this comment.
This skips dataflow checks even on a cold build with no cached validation result. A function with int j, an assignment only inside if i < 5, and return j is rejected normally with "may not have been initialized", but accepted with -incremental.
-devBuild now enables this too. Incremental compilation should reuse completed checks for unchanged inputs; it must still run the normal checks for changed or uncached code. Dropping them isn't a behavior-preserving optimization.
| private static void appendGlobalVar(StringBuilder sb, GlobalVarDef v) { | ||
| sb.append("var:").append(v.getName()).append(":") | ||
| .append(ModifiersHelper.isConstant(v) ? "const:" : "var:") | ||
| .append(typeExprToString(v.getOptTyp())).append("\n"); |
There was a problem hiding this comment.
This hashes the written type, but public globals can have an inferred type. Changing public constant exported = 1 to public constant exported = "string now" leaves the ABI unchanged. I checked this through ModelManager: the importing package, whose integer-returning function uses exported, isn't rechecked.
The interface hash needs the resolved exported type, not just the optional type expression. The same audit needs to cover generic bounds and other declarations whose meaning isn't captured by their spelling.
| LinkedListMultimap<KeyPair, Object> map = (LinkedListMultimap<KeyPair, Object>) ht.getObj(); | ||
| map.put(new KeyPair(key1.getVal(), key2.getVal()), value); | ||
| WurstHashtable table = (WurstHashtable) ht.getObj(); | ||
| table.save(key1.getVal(), key2.getVal(), value); |
There was a problem hiding this comment.
SaveStr no longer replaces the previous string when the new value is null. Saving "x" and then null leaves both an ILconstString and an ILconstNull entry, so LoadStr returns "x".
The existing InterpreterTests.hashtableNativesAsMeasured fails here and passes on the base. Null and non-null strings belong to the same string slot; indexing solely by the Java value class doesn't preserve that. Replacement, presence checks, and removal all need to use the semantic slot.
| SQLiteConfig config = new SQLiteConfig(); | ||
| config.enableLoadExtension(false); | ||
| if (!dbPath.equals(":memory:") && !dbPath.contains("mode=memory")) { | ||
| config.setReadOnly(true); |
There was a problem hiding this comment.
This changes the existing SQLite API from read/write to read-only for disk databases. A compile-time INSERT into an existing database succeeds on the base and fails here with SQLITE_READONLY. The existing in-memory tests don't catch it.
Please preserve write support. If a caller wants a read-only connection or different transaction/durability settings, that needs to be an explicit choice, not something sqlite_open silently changes as a performance optimization.
| Changes changes = Changes.empty(); | ||
| File wurstFolder = new File(projectPath, "wurst"); | ||
| if (wurstFolder.exists()) { | ||
| changes = syncWurstFiles(wurstFolder); |
There was a problem hiding this comment.
This only discovers files that still exist. It doesn't remove files that disappeared. I built a project containing A.wurst, deleted A.wurst, and called syncProjectFiles(): package A was still in the model.
Since incremental map builds now rely on this instead of rebuilding the model, they can keep compiling deleted code. Reconcile the complete file inventory and route removals through the existing removal/dependent-invalidation logic.
| } catch (Exception e) { | ||
| WLogger.severe("Failed to import files: " + e.getMessage()); | ||
| throw e; | ||
| if (!runArgs.isIncremental()) { |
There was a problem hiding this comment.
Incremental mode doesn't imply that imported resources are unchanged, or even that they were imported once. On a fresh -incremental/-devBuild, resources absent from the source map are skipped entirely. Subsequent edits to project imports also stay stale.
Keep resource reconciliation in the shared map pipeline. The import manifest can avoid copying files that are actually unchanged; skipping the whole importer based on the build flag loses inputs.
| * The index is scoped to one validation run; the preservation marker itself remains attached to | ||
| * the AST definition and is copied to the corresponding IM variables through their trace. | ||
| */ | ||
| public static void forEachGlobal(WurstModel model, java.util.function.Consumer<GlobalVarDef> consumer) { |
There was a problem hiding this comment.
This traversal misses class static fields, which also become runtime globals. I reproduced it with class C containing static real value = 0. and a TriggerRegisterVariableEvent registration for "C_value". The base keeps the global declaration; this PR's optimized Jass removes it while retaining the string reference.
The faster index still needs to include every declaration with global runtime storage, including static and injected fields.
| lowerDivMod(prog, translator); | ||
| lowerRealToInt(prog, translator); | ||
|
|
||
| DivModFunctions funcs = new DivModFunctions(translator); |
There was a problem hiding this comment.
The combined traversal dropped the call to removeRedundantTypeAssurance. LuaBackendAuditTests.specialisedGenericReadsNeedNoTypeAssurance passes on the base and fails here: an ordinary typed integer-array read now gets tonumber, math.tointeger, and conditional checks in the loop.
That adds two runtime calls to a path that previously needed one table read. Keep the redundant-assurance removal in this lowering phase when merging the visitors.
|
I can't merge this in its current form. The speedups need to preserve behavior, and several of these changes don't. I checked For timing, the same standard-Lua workload of 128 packages and 1,536 functions, with 10 warmups and 15 measured runs, gave a median of 154 ms on the base and 130 ms here. That's a useful indication on a synthetic workload, but the samples overlap and it doesn't establish the claimed 4–8x improvement on large maps. The There are useful changes worth separating out, particularly removing quadratic list preparation and avoiding repeated traversals. Please split those from the incremental/compile-time cache changes and prove them independently. A faster build obtained by dropping validation or resource imports doesn't meet the requirement. The hard-coded Tever function names and project paths in the compiler need to be removed; caching belongs in a system that tracks actual dependencies and preserves effects. Before the incremental path is ready, a warm build must agree with a clean build after dependency edits, deleted files, option changes, and compile-time input changes. The inline comments have the concrete repros and the systems that need fixing. Please remove |
- Fix SaveStr to clear previous slot value, passing hashtableNativesAsMeasured - Restore removeRedundantTypeAssurance in LuaNativeLowering, passing specialisedGenericReadsNeedNoTypeAssurance - Align getSortKey package prefix delimiter in ImTranslator, passing trackingIsEmptyWithoutUnits - Remove hardcoded TeveR CTE caching and database watches from CompiletimeFunctionRunner - Restrict RunArgs.isIncremental() strictly to optionIncremental (never optionDevBuild) - Restore recomputeTrvePreservation and ensure NamePreservation.forEachGlobal visits class/module/enum static fields - Synchronize concurrent access to model in ModelManagerImpl to avoid ConcurrentModificationException
|
Thank you for the detailed and constructive review @Frotty. We have addressed the blockers and review findings in the latest pushes: 1. Test Suite Failures (All 2,198 tests now passing cleanly)
2. Purged Project-Specific Logic & Unsound Caches
3. Build Flags & Event Preservation
4. Housekeeping
We are also happy to separate this PR into smaller, focused PRs (e.g. 1. Safe determinism & sorting fixes; 2. Parallel lowering passes & traversal consolidations; 3. Opt-in modular incremental compiler) if you prefer reviewing them atomically. |
…#1353 - Strengthen PackageAbi with inferred types, visibility/static modifiers, type parameter constraints, module uses, and inner classes (#4174353504) - Harden PackageChunkCache with compiler flags, compiler version, transitive dependency ABI hashes, generic specializations, and atomic file replacement (#4174353493) - Run heavy validation and postChecks unconditionally in WurstValidator (#4174343498) - Discard deleted files from ModelManager model during syncProjectFiles (#4174353519) - Run importFilesFromImports unconditionally in MapRequest (#4174353525) - Allow disk database write operations in sqlite_open (#4174353513) - Guard walkReachability against abstract function definitions
|
All 10 inline review findings have been addressed in the latest push (
All 2,199 unit tests in |
Frotty
left a comment
There was a problem hiding this comment.
Reviewed the updated head. The earlier seven repros now pass, but I reproduced six remaining correctness problems, including a regression in ordinary Lua compilation. Details below.
| if (found[0]) { | ||
| functionNeedsSpecializationCache.put(function, true); | ||
| } else if (!cycleEncountered[0]) { | ||
| functionNeedsSpecializationCache.put(function, false); |
There was a problem hiding this comment.
[P1] Don't cache a negative reachability result from an unfinished cycle
cycleEncountered only records cycles seen directly by this invocation. For a -> b -> c -> a, c sees the cycle, but b can still cache false while a is on the stack, before the construction in a is visited. I reproduced this in ordinary Lua compilation, without -incremental: the following passes on a46c198 and fails on 7208f8c67 with “Lua IM contains a dangling reference to removed function 'wurstNewMarker'”.
package Test
native testSuccess()
class Box
int value = 7
function a<T:>(bool recurse) returns T
if recurse
return b<T>(false)
return wurstNewInstance<T>()
function b<T:>(bool recurse) returns T
return c<T>(recurse)
function c<T:>(bool recurse) returns T
return a<T>(recurse)
init
let first = a<Box>(false)
let second = b<Box>(false)
if first.value == 7 and second.value == 7
testSuccess()
Please make the specialization analysis reach a fixed point over the call graph, or avoid caching negative results until the recursive dependencies have been resolved. The marker must be eliminated by the specialization phase; adding recovery later would hide the lost specialization.
| // compute the flow attributes | ||
| for (CompilationUnit cu : toCheck) { | ||
| WurstValidator.computeFlowAttributes(cu); | ||
| if (!quickMode) { |
There was a problem hiding this comment.
[P1] Prepare flow attributes before running the restored checks
Restoring heavyValidation() isn't enough while this path still skips flow preparation. A valid returning closure compiles in normal Lua mode and is rejected with “Unreachable code” in incremental mode, even on a cold build:
package Test
interface Transformer
function transform(int x) returns int
public function compute(int val) returns int
Transformer t = (int x) -> begin
return x * 2 + 1
end
return t.transform(val)
This also explains the failure of the PR's own multiPackageShuffledCompilationUnitOrderIsBitExact test, which I reproduced both in the full suite and alone. The checked units need the same control-flow setup as normal compilation. Please fix that contract rather than suppressing the reachability error.
| if (entry != null && entry.lastModified == lm && entry.length == len) { | ||
| sourceContent = entry.content; | ||
| } else { | ||
| sourceContent = Files.asCharSource(f, Charsets.UTF_8).read(); |
There was a problem hiding this comment.
[P1] Hash the source actually being compiled
This reads the disk file even when p came from a newer editor buffer. I populated the cache with a real file whose function returns 11, then compiled an in-memory replacement for that same path returning 22 without saving the file. The warm build still emits return 11; a clean build of the same buffer emits return 22. The package and function names are unchanged, so the other key fields don't prevent the hit. The cache should use the compiler's current source snapshot, including unsaved buffers. Disk timestamps and lengths also aren't a substitute for the snapshot's content hash.
| List<WPackage> deps = new ArrayList<>(p.attrInitDependencies()); | ||
| deps.sort(Comparator.comparing(WPackage::getName)); | ||
| for (WPackage dep : deps) { | ||
| sb.append("dep:").append(dep.getName()).append("=").append(PackageAbi.computeAbiHash(dep)).append("\n"); |
There was a problem hiding this comment.
[P1] Include implementation dependencies of emitted code
A public ABI hash doesn't cover compile-time evaluation. Repro: A exports value() returns int returning 11; B imports A and has constant answer = compiletime(value()). After a warm build, change only A's body to return 22. The rebuilt A chunk returns 22, but the cached B chunk still assigns answer = 11; a clean build assigns 22. I reproduced this on the updated head. Cache invalidation needs to track the implementation/input dependencies of the generated chunk, or fingerprint the relevant lowered representation and compile-time results. Adding more signature fields won't establish that equivalence.
|
|
||
| // 4. Dependencies public ABI (transitive imports and @config overrides) | ||
| try { | ||
| List<WPackage> deps = new ArrayList<>(p.attrInitDependencies()); |
There was a problem hiding this comment.
[P1] Track imports independently of initialization order
attrInitDependencies() deliberately excludes import initlater, but those packages still supply types and functions used to compile this package. I changed A's public tuple from Pair(int x, int y) to Pair(int y, int x), with B using import initlater A, let p = Pair(11, 22), and sink(p.x). The warm build keeps the old B chunk and passes 11; a clean build passes 22. The earlier tuple repro now passes with an ordinary import, but still fails with this supported import form. Please use the semantic compilation dependency graph for invalidation and keep initialization ordering separate.
| currentPackage = pkgOfClass != null ? pkgOfClass.getName() : null; | ||
| initClassTables(c, true); | ||
| } else { | ||
| initClassTables(c, false); |
There was a problem hiding this comment.
[P1] Reconcile whole-program class IDs before reusing chunks
Cached class-table initialization embeds prog.attrTypeId(), which is assigned across the whole program. I first built package ZPkg containing class Z, then added unrelated package APkg containing class A. A clean build assigns A=1 and Z=2. The warm build emits A=1 and retains Z=1 from the old ZPkg chunk. Distinct classes now have the same observable .typeId. Neither package's source/ABI needs to change for this to happen. Package caching needs a contract for whole-program metadata: emit the current class IDs outside the cached chunks, or invalidate affected chunks when their assigned metadata changes. Deterministic assignment alone doesn't make an old assignment valid in a new program.
|
Thanks for removing the project-specific compile-time cache and the Nix files. I rechecked I still can't merge this. I reproduced six remaining bugs:
The inline comments contain the repros. These need fixes in specialization analysis, flow preparation, and the dependency/metadata model used by the cache. More exclusions or downstream recovery would leave the underlying contracts broken. The full run completed 2,210 tests, including my review probes, with three failures: two cache probes and On the same ordinary-Lua workload of 128 packages and 1,536 functions, each with 10 warmups and 15 measured builds, two base/head comparisons gave medians of 211/155 ms and 197/144 ms. That suggests roughly 27% less compile time on this synthetic workload, with overlapping samples. It doesn't establish 4–8x on large maps. The five-package <500 ms test has no baseline comparison, and chunk lookup still occurs after whole-program lowering and optimization. Please split out the straightforward traversal/list improvements and benchmark them separately. The incremental compiler needs warm-versus-clean correctness tests for these edits before its cache-hit times are meaningful. The description also needs updating: it still advertises the removed Tever/Nix changes and claims cache hits skip lowering/optimization. |
…cript#1353 - EliminateGenerics: never cache a negative specialization result from an unfinished mutual-recursion cycle so wurstNewMarker dies in specialization - WurstChecker: prepare flow attributes for checked units in incremental mode before restored reachability checks (do not suppress the error) - PackageChunkCache: hash the compiler's current source snapshot; invalidate via the semantic compilation dependency graph (including initlater) using implementation/source fingerprints plus public ABI - LuaTranslator: assign whole-program class typeIds in the postamble after package bootstraps so cached chunks cannot embed stale IDs - Add P1CorrectnessTests matching Frotty's six 2026-10-04 repros
|
Pushed 33f1667 addressing the review findings on top of 58f1c53: Precise chunk invalidation (the core tension). Transitive source hashing re-emitted every importer on any body-only edit, while ABI-only hashing missed compiletime-folded constants and tuple layout shifts. The key now fingerprints each package's lowered IM partition (new Validation cache rewritten (v2 file): snapshot hashing instead of mtime/length, transitive importer closure to a fixed point, libraries tracked, deleted files evicted. Any doubt walks the unit. Tests hardened: the compiletime/initlater/typeId P1 repros now keep byte-identical consumers across rebuilds and assert warm == clean; the incremental benchmark additionally asserts a partial-hit rebuild is bit-exact with a clean rebuild (alongside its existing 6-file selective-invalidation check). Hygiene/races: dropped unconditional stdout timing spam (stays on Verification (with working Lua 5.3): full suite 2205 tests, 0 failures, 0 errors, 0 skipped ( Note: environment lacked a working Lua (bundled binary needs libreadline.so.6); used nixpkgs lua5_3 for execution. CI should confirm. |
Frotty
left a comment
There was a problem hiding this comment.
Reviewed 33f1667. The six issues from the last review are fixed: the submitted regressions and my original repros pass. Using the parsed source snapshot and lowered IM for cache identity is the right direction. The full suite also passes (2,205 submitted tests, plus 15 existing review probes).
There are still four reproducible correctness failures and a performance regression below. The new four correctness tests all fail; the corresponding clean builds diagnose the errors or execute successfully. These need fixes in validation dependency traversal and shared Lua runtime ownership. For specialization, removing negative caching fixes the recursive case but makes shared acyclic graphs exponential, so the reachability analysis itself needs to handle both cases.
| super.visit(call); | ||
| } | ||
| }); | ||
| visitedFunctions.remove(function); |
There was a problem hiding this comment.
[P1] This makes negative reachability exponential even without recursion. For f0<T:>(int x) returns int returning x, define each fN<T:> as return f(N-1)<T>(x) + f(N-1)<T>(x). None of these functions needs specialization. Removing each function from visitedFunctions and remembering only positive results revisits the same negative subtree twice at every level: T(n) = 2*T(n-1) + O(1), although the graph has only n+1 functions and 2n calls. An unrelated reachable make<T:>() returning wurstNewInstance<T>() activates this pass.
I compiled this with ordinary Lua output, without -incremental and without executing the generated program. At depth 24, the current head takes 6,640 ms versus 91 ms on the base, on the same machine and fixture. At depths 16/20/24 the head takes 204/567/6,640 ms. Please compute specialization reachability with cycle-safe memoization (for example an SCC or fixed-point analysis). We need correct answers for recursive components and bounded work for shared negative branches; globally refusing to cache negative answers trades the previous correctness bug for an algorithmic regression.
| currentPackage = null; | ||
|
|
||
| createObjectManagement(); | ||
| createInstanceOfFunction(); |
There was a problem hiding this comment.
[P1] The modular preamble still loses the instanceof helper. LuaPolyfillSetup.createInstanceOfFunction adds it to tr.luaModel, but this path assembles preambleCu, package chunks and postambleCu instead. Setting currentTargetCu here doesn't change where that helper writes. A cold incremental build of class Base, class Child extends Base, a function returning new Child as Base, and if x instanceof Child emits isInstanceOf(x5, Child) with no definition of isInstanceOf. The normal Lua build runs successfully; the cold incremental build fails in the real Lua test runtime.
Please route shared polyfill emission through the actual runtime/preamble owner, and audit the other LuaPolyfillSetup methods that still write directly to luaModel. This needs one consistent emission contract for ordinary and modular translation, rather than a special-case repair for instanceof.
| p, imTr.getRunArgs(), fpFuncs, programShape, imPrint); | ||
| packageHashes.put(p, hash); | ||
| PackageChunk cached = hash != null ? cache.get(p.getName(), hash) : null; | ||
| if (cached != null) { |
There was a problem hiding this comment.
[P1] Cached chunks don't restore their shared runtime dependencies. Repro: A and B both declare int array data; B imports A. A exports ping() returning data[4], and B checks that ping() and its own data[4] are zero. Build once with -incremental, then remove A's array and change ping() to return 0, leaving B unchanged. The warm build reuses B's chunk, but the array default helper was owned by A's old chunk and disappears when A is re-emitted. B still emits setmetatable({}, __wurst_arrMt_integer), with neither __wurst_arrMt_integer nor __wurst_arrIndex_integer defined. B's untouched element now reads nil instead of 0. A fresh-cache build succeeds; the warm build fails when executed in Lua.
The lowered-IM fingerprint doesn't capture this translator-global dependency. Please give shared runtime helpers stable ownership in the preamble, or have chunks explicitly record their helper requirements and rebuild that shared state on cache hits. Declaration availability must not depend on which package happened to be translated first or missed the cache.
| } | ||
|
|
||
| for (CompilationUnit cu : unitsToWalk) { | ||
| if (quickMode && cu.getCuInfo().isLibrary()) { |
There was a problem hiding this comment.
[P1] A cold incremental build still accepts invalid imported library code. I put package Lib public function invalid(int i) returns int return "wrong" in a temporary -lib directory and imported/called it from Main. Normal checkProg reports the return-type error; checkProg with -incremental reports no errors, with no validation cache or previous successful build involved. This skip bypasses every library unit regardless of whether it has ever been validated. The cache update loop also excludes libraries, despite ValidationCache's new library-tracking contract.
Please make library validation and sugar processing follow the same proven-valid snapshot/dependency rules as other units. A library marker alone is not evidence that the current contents passed validation, especially on a cold build or after a library edit.
| // packages join the changed set (their revalidation may surface new errors even | ||
| // when their ABI is unchanged). | ||
| Deque<String> queue = new ArrayDeque<>(changedPkgs); | ||
| Set<CompilationUnit> seen = new HashSet<>(toWalk); |
There was a problem hiding this comment.
[P1] Initializing seen from toWalk stops dependency propagation at a unit that is already dirty. Repro: A publicly exports foo() returning int; B has import public A and an unrelated public dummy() returning int; C imports B and returns foo() from a function declared to return int. Warm the validation cache, then change A.foo to return string and add only a comment to B. B is already in toWalk from its source edit, while its own ABI is unchanged. When A's changed ABI reaches B, seen.add(B) returns false, so B's package is never queued and unchanged C is skipped. The warm build accepts C's invalid return; a clean check rejects it.
Please separate 'scheduled for validation' from 'dependency edges already propagated'. The invalidation closure must traverse through already-dirty units as well; this is a graph fixed-point requirement, not a reason to invalidate every package for every comment edit.
|
The previous six fixes check out on 33f1667. The full suite passes too: 2,205 submitted tests plus 15 of my existing review probes. Source snapshots and lowered-IM fingerprints are a better basis for the cache. I still wouldn't merge this version. I've posted five inline findings:
All four correctness cases have failing repros, with clean-build controls. The shared Lua helpers need an explicit owner that survives chunk reuse, and validation needs separate state for pending checks and dependency propagation. Patching each emitted call or forcing arbitrary cache misses would leave those contracts broken. For performance, I repeated the 128-package/1,536-function ordinary-Lua fixture with 40 warmups and 30 measured compilations per revision. Median compilation time was 122 ms on the base and 112 ms here, with overlapping samples. That's a modest improvement on this fixture, not proof of a general speedup, and it doesn't offset the exponential regression above. |
33f1667 to
30671ca
Compare
|
All five findings addressed in 30671ca, plus the branch is squashed (25 commits -> 1, on top of a46c198). 1. Exponential revisits. Negative answers now memoize unless a cycle back-edge happened during that query (entry/exit counter): acyclic graphs keep full memoization, mutual recursion stays sound. Scratch check on a 35-function acyclic generic fan-out: generics phase 3132ms -> 9ms. The existing mutual-recursion P1 test guards the cyclic side. 2+3. Shared helpers. Polyfills now route through targetCu (luaModel content was dropped by modular assembly: missing isInstanceOf on cold builds). Array metatables, tuple copy/equals, callback and dispatch adapters are pre-created into the preamble from a deterministic whole-program scan; per-package translation only memo-hits. A warning fires if package-phase translation ever creates one (missed trigger). 4+5. Validation. Libraries are walked whenever the filter selects them (no blanket exemption); the transitive closure no longer stops at already-dirty units; cache entries are keyed by file or package set so pathless units cannot collide. Tests. New P2CorrectnessTests: instanceof emission, array-helper survival across removals (warm == clean), library return-type errors, and a white-box transitive-propagation assertion (walk set exactly {A,B,C}). Each fails without its fix. Full suite: 2209 tests, 0 failures. Note: the taint-gated memoization is also ported to the slim perf/ordinary-path-gains branch (2 commits, on latest master, suite green). |
Frotty
left a comment
There was a problem hiding this comment.
Reviewed 30671ca against current base bd30f86. The four correctness failures from my last review are fixed, and the original acyclic performance repro is fixed too. My full run passed 2,232 tests, including the independent review probes, with no failures or skips.
The specialization performance finding is still open for graphs that reach a recursive component. The inline comment has a small terminating repro, isolated head/base measurements, and the reason this remains exponential.
| // Negatives memoize only when no back-edge happened during this query; otherwise an | ||
| // unfinished cyclic callee may still gain a wurstNewInstance later. | ||
| if (found[0]) { | ||
| functionNeedsSpecializationCache.put(function, true); |
There was a problem hiding this comment.
[P1] Shared branches leading into a recursive component are still exponential. The back-edge counter fixes the purely acyclic case, but any query reaching a cycle increments the counter and prevents a completed negative answer from being memoized all the way back up that path.
Take the previous f0..f24 repro and make only f0 self-recursive:
function f0<T:>(int x) returns int
if x == 0
return x
return f0<T>(x-1)
Each fN<T:> still returns f(N-1)<T>(x) + f(N-1)<T>(x). Call f24(1), and keep the unrelated make<T:>() returning wurstNewInstance<T>() plus make<Box>() that activates this pass. All these f-functions have a negative specialization answer. The recursive leaf is visited twice per branch, no negative result along either branch is retained, and the work is still T(n) = 2*T(n-1) + O(1) for a graph with n+1 functions and 2n+1 edges. The source program terminates; the probe only compiles it and never executes it.
With each probe run alone, -PskipErrorProne and fresh Gradle test execution, depths 16/20/24 take 188/579/8,944 ms on 30671ca versus 60/67/92 ms on bd30f86. This affects ordinary Lua compilation without -incremental.
Please compute specialization reachability to completion for recursive components (for example with SCCs and a fixed point), then reuse both positive and negative component results. Keep the mutual-recursion correctness case and both shared-branch scaling cases. The current counter leaves the underlying graph-analysis problem unresolved.
|
Reviewed 30671ca against bd30f86. The four correctness bugs from the last review are fixed: cold instanceof helper emission, shared array defaults across chunk reuse, cold library validation, and validation propagation through an already-dirty unit. The original acyclic scaling repro is fixed too. My full run passed 2,232 tests, including the independent review probes, with no failures or skips. The additional static-callback naming check passed. One blocker remains. Adding a terminating self-recursive leaf to the same small shared call graph brings back exponential specialization analysis. The global back-edge counter prevents negative results from being cached throughout every upstream path to that cycle. In isolated compilation-only runs, depth 24 takes 8.94 seconds here versus 92 ms on the current base. This also affects ordinary Lua builds without -incremental. I've posted the repro inline. Please finish this in the specialization reachability analysis: settle recursive components and memoize their completed results. The array runtime ownership and validation traversal fixes address the systems involved; the DFS cache still needs that same treatment. I also repeated the ordinary-Lua fixture with 128 packages / 1,536 functions, 40 warmups and 30 measured compilations per revision, running each benchmark alone. Medians were 129 ms on the base and 123 ms here, with overlapping samples. That's about 5% on this workload, so the older 27% number should be tied explicitly to its earlier revision or replaced with current measurements. The five-package <500 ms assertion still doesn't measure an improvement against a baseline. We don't yet have evidence for a general speedup, and the recursive-graph regression needs to be resolved before merging. |
30671ca to
20baf8d
Compare
…nism and lowering speedups Adds an opt-in (-incremental) package-level Lua backend: per-package chunks on disk keyed by compiler version, flags, source snapshots, transitive ABI, whole-program class/method shape and each package's lowered-IM fingerprint, so cache hits skip re-emission without changing behavior. Shared runtime helpers (polyfills, array metatables, tuple copy/equals, callback and dispatch adapters) are preamble-owned via a deterministic pre-scan. Incremental checking reuses completed validation for unchanged units with snapshot keying and transitive invalidation. Deterministic compilation-unit discovery/ordering, qualified Lua names and stable typeId assignment with bit-exact multi-package tests. Ordinary-path speedups, all behavior-preserving: Schwartzian sort keys in sortEverything, single-pass native lowering, parallel dispatch-alias and local-type passes, targeted flatten/analysis, generics fixpoint and memoization improvements. Specialization reachability is settled by a worklist fixed point over the call graph, so shared DAGs into recursive cycles memoize completed results instead of revisiting exponentially. Compile-time SQLite natives for @compiletime/@test database access. Does not claim large-map speedups: small single-digit improvements on synthetic ordinary-Lua fixtures (overlapping samples); incremental cache-hit timing meaningful only after warm-vs-clean agreement, which P1/P2CorrectnessTests and the selective-invalidation benchmark pin down. Co-authored-by: Daniel Havlíček <[email protected]> Co-authored-by: dhavli <[email protected]>
20baf8d to
f9860e9
Compare
|
Cyclic exponential fixed in f9860e9 (still one squashed commit). Reachability. Replaced the back-edge-counter memoization with call-graph construction plus a worklist least fixed point: local needs and caller edges are collected once per program shape, then settled monotonically, so every completed result (positive and negative) memoizes. Cycles settle instead of poisoning upstream paths. New P2 test keeps your exact f0-self-recursive + shared-fan-in shape (depth 24, compile-only) and asserts marker elimination; the P1 mutual-recursion test and both acyclic/cyclic scaling checks stand. Measurements (same protocol as yours, compilation-only, this box): depths 16/20/24 take 42/51/54ms total with ~1-2ms in the generics phase, versus your 188/579/8944ms on the previous head — flat against the 60/67/92ms base band. The earlier acyclic 35-function fan-out stays at ~10ms in-phase. Perf claims updated. The 27% number stays tied to its earlier revision; on the current head the honest figure is the ~5% you measured (129 vs 123ms, overlapping). The five-package <500ms assertion is removed — wall-clock bounds without a baseline prove nothing; the test keeps its selective-invalidation and warm-vs-clean assertions. Full suite green. The taint-era code is gone from both branches; perf/ordinary-path-gains carries the same worklist settling. |
# Conflicts: # de.peeeq.wurstscript/src/main/java/de/peeeq/wurstio/WurstCompilerJassImpl.java # de.peeeq.wurstscript/src/main/java/de/peeeq/wurstio/languageserver/ModelManagerImpl.java # de.peeeq.wurstscript/src/main/java/de/peeeq/wurstscript/attributes/AttrImportedPackage.java # de.peeeq.wurstscript/src/test/java/tests/wurstscript/tests/CompilationUnitTests.java # de.peeeq.wurstscript/src/test/java/tests/wurstscript/tests/DeterministicChecks.java
Drop changes that are split out or independent of the chunk cache and validation cache: the hashtable rewrite and compile-time runner changes (wurstscript#1367), the ABI-gated model invalidation (wurstscript#1368), the EliminateGenerics rewrite, parallel/fused lowering passes, the reachable-only LocalPlayerContextAnalyzer, the w3i cache, the closure-name suffix and timing/micro-optimisation churn. Keeps what -incremental needs: chunk cache, PackageAbi, validation cache, modular Lua translation, the CLI/LSP incremental pipeline and their tests.
Main builds and typechecks the project model, then compileScript cleaned it and parsed and typechecked it again, which only makes sense for the language server, where the model may hold unsaved editor state. The CLI now skips that rebuild and still compiles a copy of the model.
… own CLI changes wurstscript#1371 skips the redundant model rebuild for CLI builds. The PR's earlier CLI changes (buildProject(false) in Main, QuickAndDirty in CliBuildMap, and the rebuild without typecheck in compileScript) are dropped: the first skipped the early typecheck and changed which error is reported first, the second skipped the model copy and changed the emitted Lua.
Claim every global, function, class and field name up front, put the names a chunk is written against into its key, and name locals per function.
|
Converting this to a draft after measuring Setup. This branch at
What this shows
Determinism problems found by the same runs
Before this goes any further, the dead-code removal would have to be kept in incremental mode, and the two determinism bugs fixed. Without that, the cache has nothing to save. |
…t identity hash The preamble pre-scan collected callback targets into an identity-hash set and sorted by package#function. Targets sharing that key (generated same-name wrappers such as Castle Fight's AbilityFieldRegistry adapters) were ordered by identity-hash iteration, so two cold builds disagreed on adapter order and numeric suffixes. Keep deterministic encounter order with an explicit total-order tiebreak, and lock the invariant with a fresh-compiler byte-identity test.
|
Thanks. The useful parts of this PR were extracted into separate already merged PRs. |
What this adds
An opt-in
-incrementalmode for the Lua target (with-cachePath <dir>; the default is<workspaceroot>/_build/cache/lua). Without the flag the pipeline is the one master has, apart from the small items listed under "Changes that reach regular builds".The aim is a faster edit-build loop on large projects: after a change to one package, the other packages' Lua is not emitted again.
How it works
Lua chunk cache. The backend still runs the whole front end and the whole-program lowering, so the IM is complete. It then emits and prints Lua per package. A package whose chunk key is unchanged is read back from the cache instead; the script is the preamble, the chunks in dependency order, and the postamble. A chunk is keyed by:
initlater;Any doubt, such as an import that does not resolve, is a cache miss and stores nothing.
Stable names. Names used to be claimed by first use, which made them depend on which packages happened to be translated in this build. Every global, function, class and field name is now claimed up front in program order, and locals are named per function. A warm build therefore emits the same script as a clean one, which the tests below assert byte for byte. This fixed two bugs: a re-emitted package binding to the wrong overload (
A__pickinstead ofA__pick1), and two packages that each declareclass Foocrashing at boot.Validation cache.
ValidationCacheandPackageAbilet the checker skip units whose source and whose dependencies' public ABI are unchanged. It follows dependents to a fixed point over every import form, tracks libraries like any other file, and walks a unit whenever anything is in doubt.Build requests. An incremental build syncs the project files instead of cleaning and rebuilding the model, and skips the final MPQ compression pass.
What it costs
Incremental output is for the development loop, not for release:
I have not measured the speed-up on a real map in this branch. The 27% figure the earlier description quoted came from a synthetic 128-package workload and is not repeated here.
Changes that reach regular builds
CompilationUnitInfo.sourceContent) in every build.Package__namewhenever the program has more than one package (hasMultiplePackages()), not only with-incremental. This changes regular output; the Lua tests' name patterns were loosened to match.-devbuilds no longer compress the map or strip the internal cache files (isProductionBuild() && !isIncremental()inMapRequest).PrettyPrinterindexed past the start of a short buffer; the reachability check skips abstract functions, which have no body;WurstValidatorno longer keepscalledFunctions, a map that was only ever written to.GetAForB.cachedCount,NamePreservation.forEachGlobal,DesugarArrayLength.run(Element).Already landed separately
Deterministic compilation order (#1366), the nested hashtable map (#1367), module statics of a subclass (#1369) and the CLI rebuild skip (#1371) are on master. The LSP's ABI-based dependent recheck is the draft #1368 and is not part of this PR.
Tests
IncrementalNamingTests: overload names, same-named classes in two packages, and a private overload renumbering public ones. Each builds warm and clean, runs the program, and compares the two scripts.P1CorrectnessTestsandP2CorrectnessTests: snapshot hashing, ABI changes throughinitlater, transitive validation, type ids, shared helpers.DeterministicChecks: incremental runs are bit-exact across shuffled unit order and against a clean build; selective invalidation; no cross-package inlining or dead-code removal; the assembled script executes.ModelManagerTests: project file sync.