@colbymchenry/codegraph-win32-arm64 1.4.1 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (314) hide show
  1. package/bin/codegraph.cmd +1 -1
  2. package/lib/dist/bin/codegraph.js +206 -44
  3. package/lib/dist/bin/codegraph.js.map +1 -1
  4. package/lib/dist/context/formatter.d.ts +7 -1
  5. package/lib/dist/context/formatter.d.ts.map +1 -1
  6. package/lib/dist/context/formatter.js +12 -6
  7. package/lib/dist/context/formatter.js.map +1 -1
  8. package/lib/dist/context/index.d.ts +12 -0
  9. package/lib/dist/context/index.d.ts.map +1 -1
  10. package/lib/dist/context/index.js +101 -25
  11. package/lib/dist/context/index.js.map +1 -1
  12. package/lib/dist/db/index.d.ts +179 -0
  13. package/lib/dist/db/index.d.ts.map +1 -1
  14. package/lib/dist/db/index.js +368 -7
  15. package/lib/dist/db/index.js.map +1 -1
  16. package/lib/dist/db/migrations.d.ts +1 -1
  17. package/lib/dist/db/migrations.d.ts.map +1 -1
  18. package/lib/dist/db/migrations.js +25 -1
  19. package/lib/dist/db/migrations.js.map +1 -1
  20. package/lib/dist/db/queries.d.ts +234 -5
  21. package/lib/dist/db/queries.d.ts.map +1 -1
  22. package/lib/dist/db/queries.js +687 -53
  23. package/lib/dist/db/queries.js.map +1 -1
  24. package/lib/dist/db/schema.sql +16 -3
  25. package/lib/dist/db/sqlite-adapter.d.ts +3 -1
  26. package/lib/dist/db/sqlite-adapter.d.ts.map +1 -1
  27. package/lib/dist/db/sqlite-adapter.js +22 -4
  28. package/lib/dist/db/sqlite-adapter.js.map +1 -1
  29. package/lib/dist/db/wal-valve.d.ts +15 -2
  30. package/lib/dist/db/wal-valve.d.ts.map +1 -1
  31. package/lib/dist/db/wal-valve.js +88 -6
  32. package/lib/dist/db/wal-valve.js.map +1 -1
  33. package/lib/dist/directory.d.ts +29 -0
  34. package/lib/dist/directory.d.ts.map +1 -1
  35. package/lib/dist/directory.js +52 -0
  36. package/lib/dist/directory.js.map +1 -1
  37. package/lib/dist/extraction/extraction-version.d.ts +1 -1
  38. package/lib/dist/extraction/extraction-version.js +1 -1
  39. package/lib/dist/extraction/function-ref.d.ts.map +1 -1
  40. package/lib/dist/extraction/function-ref.js +6 -0
  41. package/lib/dist/extraction/function-ref.js.map +1 -1
  42. package/lib/dist/extraction/generated-detection.d.ts +48 -12
  43. package/lib/dist/extraction/generated-detection.d.ts.map +1 -1
  44. package/lib/dist/extraction/generated-detection.js +176 -11
  45. package/lib/dist/extraction/generated-detection.js.map +1 -1
  46. package/lib/dist/extraction/grammars.d.ts.map +1 -1
  47. package/lib/dist/extraction/grammars.js +101 -2
  48. package/lib/dist/extraction/grammars.js.map +1 -1
  49. package/lib/dist/extraction/index.d.ts +138 -3
  50. package/lib/dist/extraction/index.d.ts.map +1 -1
  51. package/lib/dist/extraction/index.js +518 -94
  52. package/lib/dist/extraction/index.js.map +1 -1
  53. package/lib/dist/extraction/kernel/decode.d.ts +9 -0
  54. package/lib/dist/extraction/kernel/decode.d.ts.map +1 -0
  55. package/lib/dist/extraction/kernel/decode.js +162 -0
  56. package/lib/dist/extraction/kernel/decode.js.map +1 -0
  57. package/lib/dist/extraction/kernel/index.d.ts +64 -0
  58. package/lib/dist/extraction/kernel/index.d.ts.map +1 -0
  59. package/lib/dist/extraction/kernel/index.js +279 -0
  60. package/lib/dist/extraction/kernel/index.js.map +1 -0
  61. package/lib/dist/extraction/kernel/layout.d.ts +101 -0
  62. package/lib/dist/extraction/kernel/layout.d.ts.map +1 -0
  63. package/lib/dist/extraction/kernel/layout.js +104 -0
  64. package/lib/dist/extraction/kernel/layout.js.map +1 -0
  65. package/lib/dist/extraction/kernel/loader.d.ts +103 -0
  66. package/lib/dist/extraction/kernel/loader.d.ts.map +1 -0
  67. package/lib/dist/extraction/kernel/loader.js +146 -0
  68. package/lib/dist/extraction/kernel/loader.js.map +1 -0
  69. package/lib/dist/extraction/languages/c-cpp.d.ts +14 -0
  70. package/lib/dist/extraction/languages/c-cpp.d.ts.map +1 -1
  71. package/lib/dist/extraction/languages/c-cpp.js +868 -16
  72. package/lib/dist/extraction/languages/c-cpp.js.map +1 -1
  73. package/lib/dist/extraction/languages/erlang.d.ts.map +1 -1
  74. package/lib/dist/extraction/languages/erlang.js +58 -22
  75. package/lib/dist/extraction/languages/erlang.js.map +1 -1
  76. package/lib/dist/extraction/languages/objc.d.ts.map +1 -1
  77. package/lib/dist/extraction/languages/objc.js +4 -0
  78. package/lib/dist/extraction/languages/objc.js.map +1 -1
  79. package/lib/dist/extraction/languages/rust.d.ts +20 -0
  80. package/lib/dist/extraction/languages/rust.d.ts.map +1 -1
  81. package/lib/dist/extraction/languages/rust.js +47 -20
  82. package/lib/dist/extraction/languages/rust.js.map +1 -1
  83. package/lib/dist/extraction/parse-pool.d.ts +15 -0
  84. package/lib/dist/extraction/parse-pool.d.ts.map +1 -1
  85. package/lib/dist/extraction/parse-pool.js +35 -1
  86. package/lib/dist/extraction/parse-pool.js.map +1 -1
  87. package/lib/dist/extraction/parse-worker.js +35 -1
  88. package/lib/dist/extraction/parse-worker.js.map +1 -1
  89. package/lib/dist/extraction/store-worker.d.ts +24 -0
  90. package/lib/dist/extraction/store-worker.d.ts.map +1 -0
  91. package/lib/dist/extraction/store-worker.js +139 -0
  92. package/lib/dist/extraction/store-worker.js.map +1 -0
  93. package/lib/dist/extraction/store-writer.d.ts +63 -0
  94. package/lib/dist/extraction/store-writer.d.ts.map +1 -0
  95. package/lib/dist/extraction/store-writer.js +174 -0
  96. package/lib/dist/extraction/store-writer.js.map +1 -0
  97. package/lib/dist/extraction/tree-sitter-types.d.ts +2 -0
  98. package/lib/dist/extraction/tree-sitter-types.d.ts.map +1 -1
  99. package/lib/dist/extraction/tree-sitter.d.ts +27 -5
  100. package/lib/dist/extraction/tree-sitter.d.ts.map +1 -1
  101. package/lib/dist/extraction/tree-sitter.js +257 -56
  102. package/lib/dist/extraction/tree-sitter.js.map +1 -1
  103. package/lib/dist/extraction/wasm/tree-sitter-c.wasm +0 -0
  104. package/lib/dist/extraction/wasm/tree-sitter-cpp.wasm +0 -0
  105. package/lib/dist/extraction/wasm/tree-sitter-dart.wasm +0 -0
  106. package/lib/dist/extraction/wasm/tree-sitter-go.wasm +0 -0
  107. package/lib/dist/extraction/wasm/tree-sitter-java.wasm +0 -0
  108. package/lib/dist/extraction/wasm/tree-sitter-javascript.wasm +0 -0
  109. package/lib/dist/extraction/wasm/tree-sitter-kotlin.wasm +0 -0
  110. package/lib/dist/extraction/wasm/tree-sitter-php.wasm +0 -0
  111. package/lib/dist/extraction/wasm/tree-sitter-python.wasm +0 -0
  112. package/lib/dist/extraction/wasm/tree-sitter-ruby.wasm +0 -0
  113. package/lib/dist/extraction/wasm/tree-sitter-rust.wasm +0 -0
  114. package/lib/dist/extraction/wasm/tree-sitter-swift.wasm +0 -0
  115. package/lib/dist/extraction/wasm/tree-sitter-tsx.wasm +0 -0
  116. package/lib/dist/extraction/wasm/tree-sitter-typescript.wasm +0 -0
  117. package/lib/dist/extraction/wasm-runtime-flags.d.ts +15 -0
  118. package/lib/dist/extraction/wasm-runtime-flags.d.ts.map +1 -1
  119. package/lib/dist/extraction/wasm-runtime-flags.js +27 -3
  120. package/lib/dist/extraction/wasm-runtime-flags.js.map +1 -1
  121. package/lib/dist/graph/queries.d.ts.map +1 -1
  122. package/lib/dist/graph/queries.js +2 -0
  123. package/lib/dist/graph/queries.js.map +1 -1
  124. package/lib/dist/graph/traversal.js +1 -1
  125. package/lib/dist/graph/traversal.js.map +1 -1
  126. package/lib/dist/index.d.ts +36 -2
  127. package/lib/dist/index.d.ts.map +1 -1
  128. package/lib/dist/index.js +305 -11
  129. package/lib/dist/index.js.map +1 -1
  130. package/lib/dist/installer/beta-signup.d.ts +54 -0
  131. package/lib/dist/installer/beta-signup.d.ts.map +1 -0
  132. package/lib/dist/installer/beta-signup.js +178 -0
  133. package/lib/dist/installer/beta-signup.js.map +1 -0
  134. package/lib/dist/installer/index.d.ts +4 -3
  135. package/lib/dist/installer/index.d.ts.map +1 -1
  136. package/lib/dist/installer/index.js +19 -6
  137. package/lib/dist/installer/index.js.map +1 -1
  138. package/lib/dist/installer/targets/claude.d.ts.map +1 -1
  139. package/lib/dist/installer/targets/claude.js +37 -5
  140. package/lib/dist/installer/targets/claude.js.map +1 -1
  141. package/lib/dist/installer/targets/codex.d.ts +22 -8
  142. package/lib/dist/installer/targets/codex.d.ts.map +1 -1
  143. package/lib/dist/installer/targets/codex.js +65 -48
  144. package/lib/dist/installer/targets/codex.js.map +1 -1
  145. package/lib/dist/installer/targets/copilot-cli.d.ts +32 -0
  146. package/lib/dist/installer/targets/copilot-cli.d.ts.map +1 -0
  147. package/lib/dist/installer/targets/copilot-cli.js +209 -0
  148. package/lib/dist/installer/targets/copilot-cli.js.map +1 -0
  149. package/lib/dist/installer/targets/copilot-jetbrains.d.ts +42 -0
  150. package/lib/dist/installer/targets/copilot-jetbrains.d.ts.map +1 -0
  151. package/lib/dist/installer/targets/copilot-jetbrains.js +238 -0
  152. package/lib/dist/installer/targets/copilot-jetbrains.js.map +1 -0
  153. package/lib/dist/installer/targets/copilot-vscode.d.ts +47 -0
  154. package/lib/dist/installer/targets/copilot-vscode.d.ts.map +1 -0
  155. package/lib/dist/installer/targets/copilot-vscode.js +219 -0
  156. package/lib/dist/installer/targets/copilot-vscode.js.map +1 -0
  157. package/lib/dist/installer/targets/registry.d.ts.map +1 -1
  158. package/lib/dist/installer/targets/registry.js +6 -0
  159. package/lib/dist/installer/targets/registry.js.map +1 -1
  160. package/lib/dist/installer/targets/toml.d.ts +6 -5
  161. package/lib/dist/installer/targets/toml.d.ts.map +1 -1
  162. package/lib/dist/installer/targets/toml.js +99 -20
  163. package/lib/dist/installer/targets/toml.js.map +1 -1
  164. package/lib/dist/installer/targets/types.d.ts +5 -5
  165. package/lib/dist/installer/targets/types.d.ts.map +1 -1
  166. package/lib/dist/mcp/daemon-manager.d.ts +1 -1
  167. package/lib/dist/mcp/daemon-manager.d.ts.map +1 -1
  168. package/lib/dist/mcp/daemon-manager.js +1 -1
  169. package/lib/dist/mcp/daemon-manager.js.map +1 -1
  170. package/lib/dist/mcp/daemon-paths.d.ts +6 -0
  171. package/lib/dist/mcp/daemon-paths.d.ts.map +1 -1
  172. package/lib/dist/mcp/daemon-paths.js +54 -0
  173. package/lib/dist/mcp/daemon-paths.js.map +1 -1
  174. package/lib/dist/mcp/daemon-registry.d.ts +10 -0
  175. package/lib/dist/mcp/daemon-registry.d.ts.map +1 -1
  176. package/lib/dist/mcp/daemon-registry.js +51 -3
  177. package/lib/dist/mcp/daemon-registry.js.map +1 -1
  178. package/lib/dist/mcp/daemon.d.ts +9 -6
  179. package/lib/dist/mcp/daemon.d.ts.map +1 -1
  180. package/lib/dist/mcp/daemon.js +10 -8
  181. package/lib/dist/mcp/daemon.js.map +1 -1
  182. package/lib/dist/mcp/engine.d.ts +3 -0
  183. package/lib/dist/mcp/engine.d.ts.map +1 -1
  184. package/lib/dist/mcp/engine.js +45 -3
  185. package/lib/dist/mcp/engine.js.map +1 -1
  186. package/lib/dist/mcp/explore-dedup.d.ts +137 -0
  187. package/lib/dist/mcp/explore-dedup.d.ts.map +1 -0
  188. package/lib/dist/mcp/explore-dedup.js +236 -0
  189. package/lib/dist/mcp/explore-dedup.js.map +1 -0
  190. package/lib/dist/mcp/explore-diagnostics.d.ts +289 -0
  191. package/lib/dist/mcp/explore-diagnostics.d.ts.map +1 -0
  192. package/lib/dist/mcp/explore-diagnostics.js +558 -0
  193. package/lib/dist/mcp/explore-diagnostics.js.map +1 -0
  194. package/lib/dist/mcp/explore-session-state.d.ts +217 -0
  195. package/lib/dist/mcp/explore-session-state.d.ts.map +1 -0
  196. package/lib/dist/mcp/explore-session-state.js +322 -0
  197. package/lib/dist/mcp/explore-session-state.js.map +1 -0
  198. package/lib/dist/mcp/index.d.ts +24 -0
  199. package/lib/dist/mcp/index.d.ts.map +1 -1
  200. package/lib/dist/mcp/index.js +67 -6
  201. package/lib/dist/mcp/index.js.map +1 -1
  202. package/lib/dist/mcp/liveness-watchdog.d.ts.map +1 -1
  203. package/lib/dist/mcp/liveness-watchdog.js +3 -1
  204. package/lib/dist/mcp/liveness-watchdog.js.map +1 -1
  205. package/lib/dist/mcp/proxy.d.ts.map +1 -1
  206. package/lib/dist/mcp/proxy.js +6 -1
  207. package/lib/dist/mcp/proxy.js.map +1 -1
  208. package/lib/dist/mcp/server-instructions.d.ts +2 -2
  209. package/lib/dist/mcp/server-instructions.d.ts.map +1 -1
  210. package/lib/dist/mcp/server-instructions.js +8 -3
  211. package/lib/dist/mcp/server-instructions.js.map +1 -1
  212. package/lib/dist/mcp/session.d.ts +16 -0
  213. package/lib/dist/mcp/session.d.ts.map +1 -1
  214. package/lib/dist/mcp/session.js +36 -13
  215. package/lib/dist/mcp/session.js.map +1 -1
  216. package/lib/dist/mcp/tools.d.ts +276 -10
  217. package/lib/dist/mcp/tools.d.ts.map +1 -1
  218. package/lib/dist/mcp/tools.js +2425 -237
  219. package/lib/dist/mcp/tools.js.map +1 -1
  220. package/lib/dist/project-config.d.ts +23 -0
  221. package/lib/dist/project-config.d.ts.map +1 -1
  222. package/lib/dist/project-config.js +39 -2
  223. package/lib/dist/project-config.js.map +1 -1
  224. package/lib/dist/resolution/c-fnptr-synthesizer.d.ts +1 -1
  225. package/lib/dist/resolution/c-fnptr-synthesizer.d.ts.map +1 -1
  226. package/lib/dist/resolution/c-fnptr-synthesizer.js +582 -138
  227. package/lib/dist/resolution/c-fnptr-synthesizer.js.map +1 -1
  228. package/lib/dist/resolution/callback-synthesizer.d.ts +54 -10
  229. package/lib/dist/resolution/callback-synthesizer.d.ts.map +1 -1
  230. package/lib/dist/resolution/callback-synthesizer.js +287 -167
  231. package/lib/dist/resolution/callback-synthesizer.js.map +1 -1
  232. package/lib/dist/resolution/cooperative-yield.d.ts +10 -2
  233. package/lib/dist/resolution/cooperative-yield.d.ts.map +1 -1
  234. package/lib/dist/resolution/cooperative-yield.js +6 -4
  235. package/lib/dist/resolution/cooperative-yield.js.map +1 -1
  236. package/lib/dist/resolution/frameworks/go.d.ts.map +1 -1
  237. package/lib/dist/resolution/frameworks/go.js +29 -6
  238. package/lib/dist/resolution/frameworks/go.js.map +1 -1
  239. package/lib/dist/resolution/frameworks/swift.d.ts.map +1 -1
  240. package/lib/dist/resolution/frameworks/swift.js +11 -1
  241. package/lib/dist/resolution/frameworks/swift.js.map +1 -1
  242. package/lib/dist/resolution/import-resolver.d.ts +2 -3
  243. package/lib/dist/resolution/import-resolver.d.ts.map +1 -1
  244. package/lib/dist/resolution/import-resolver.js +184 -9
  245. package/lib/dist/resolution/import-resolver.js.map +1 -1
  246. package/lib/dist/resolution/index.d.ts +87 -2
  247. package/lib/dist/resolution/index.d.ts.map +1 -1
  248. package/lib/dist/resolution/index.js +731 -134
  249. package/lib/dist/resolution/index.js.map +1 -1
  250. package/lib/dist/resolution/memory-budget.d.ts +48 -0
  251. package/lib/dist/resolution/memory-budget.d.ts.map +1 -0
  252. package/lib/dist/resolution/memory-budget.js +162 -0
  253. package/lib/dist/resolution/memory-budget.js.map +1 -0
  254. package/lib/dist/resolution/name-matcher.d.ts +42 -1
  255. package/lib/dist/resolution/name-matcher.d.ts.map +1 -1
  256. package/lib/dist/resolution/name-matcher.js +681 -99
  257. package/lib/dist/resolution/name-matcher.js.map +1 -1
  258. package/lib/dist/resolution/path-aliases.d.ts +6 -4
  259. package/lib/dist/resolution/path-aliases.d.ts.map +1 -1
  260. package/lib/dist/resolution/path-aliases.js +125 -17
  261. package/lib/dist/resolution/path-aliases.js.map +1 -1
  262. package/lib/dist/resolution/resolver-pool.d.ts +106 -0
  263. package/lib/dist/resolution/resolver-pool.d.ts.map +1 -0
  264. package/lib/dist/resolution/resolver-pool.js +344 -0
  265. package/lib/dist/resolution/resolver-pool.js.map +1 -0
  266. package/lib/dist/resolution/resolver-worker.d.ts +17 -0
  267. package/lib/dist/resolution/resolver-worker.d.ts.map +1 -0
  268. package/lib/dist/resolution/resolver-worker.js +141 -0
  269. package/lib/dist/resolution/resolver-worker.js.map +1 -0
  270. package/lib/dist/resolution/types.d.ts +3 -0
  271. package/lib/dist/resolution/types.d.ts.map +1 -1
  272. package/lib/dist/search/identifier-segments.d.ts +10 -0
  273. package/lib/dist/search/identifier-segments.d.ts.map +1 -1
  274. package/lib/dist/search/identifier-segments.js +29 -0
  275. package/lib/dist/search/identifier-segments.js.map +1 -1
  276. package/lib/dist/search/query-paths.d.ts +57 -0
  277. package/lib/dist/search/query-paths.d.ts.map +1 -0
  278. package/lib/dist/search/query-paths.js +298 -0
  279. package/lib/dist/search/query-paths.js.map +1 -0
  280. package/lib/dist/search/query-utils.d.ts +1 -1
  281. package/lib/dist/search/query-utils.d.ts.map +1 -1
  282. package/lib/dist/search/query-utils.js +13 -3
  283. package/lib/dist/search/query-utils.js.map +1 -1
  284. package/lib/dist/sync/watcher.d.ts +47 -1
  285. package/lib/dist/sync/watcher.d.ts.map +1 -1
  286. package/lib/dist/sync/watcher.js +127 -8
  287. package/lib/dist/sync/watcher.js.map +1 -1
  288. package/lib/dist/types.d.ts +61 -3
  289. package/lib/dist/types.d.ts.map +1 -1
  290. package/lib/dist/types.js +27 -1
  291. package/lib/dist/types.js.map +1 -1
  292. package/lib/dist/ui/color.d.ts +21 -0
  293. package/lib/dist/ui/color.d.ts.map +1 -0
  294. package/lib/dist/ui/color.js +42 -0
  295. package/lib/dist/ui/color.js.map +1 -0
  296. package/lib/dist/ui/glyphs.d.ts +35 -10
  297. package/lib/dist/ui/glyphs.d.ts.map +1 -1
  298. package/lib/dist/ui/glyphs.js +59 -12
  299. package/lib/dist/ui/glyphs.js.map +1 -1
  300. package/lib/dist/ui/shimmer-progress.d.ts.map +1 -1
  301. package/lib/dist/ui/shimmer-progress.js +78 -4
  302. package/lib/dist/ui/shimmer-progress.js.map +1 -1
  303. package/lib/dist/ui/shimmer-worker.js +25 -17
  304. package/lib/dist/ui/shimmer-worker.js.map +1 -1
  305. package/lib/dist/ui/types.d.ts +0 -2
  306. package/lib/dist/ui/types.d.ts.map +1 -1
  307. package/lib/dist/upgrade/index.d.ts +7 -0
  308. package/lib/dist/upgrade/index.d.ts.map +1 -1
  309. package/lib/dist/upgrade/index.js +18 -5
  310. package/lib/dist/upgrade/index.js.map +1 -1
  311. package/lib/kernel/codegraph-kernel.node +0 -0
  312. package/lib/node_modules/.package-lock.json +1 -1
  313. package/lib/package.json +6 -1
  314. package/package.json +6 -2
@@ -47,6 +47,7 @@ const fs = __importStar(require("fs"));
47
47
  const path = __importStar(require("path"));
48
48
  const name_matcher_1 = require("./name-matcher");
49
49
  const import_resolver_1 = require("./import-resolver");
50
+ const resolver_pool_1 = require("./resolver-pool");
50
51
  const frameworks_1 = require("./frameworks");
51
52
  const callback_synthesizer_1 = require("./callback-synthesizer");
52
53
  const cooperative_yield_1 = require("./cooperative-yield");
@@ -244,6 +245,32 @@ class ReferenceResolver {
244
245
  qualifiedNameCache; // qualified_name → nodes cache
245
246
  fileLinesCache; // file → split lines cache
246
247
  methodMatchCache; // lang\0Type::method → matching method nodes
248
+ // Per-(language, methodName) owner index for getMethodMatches: buckets a
249
+ // method name's candidates by their qualifiedName's last two segments so a
250
+ // (type, method) query is a lookup instead of an O(candidates) filter per
251
+ // methodMatchCache miss. Derived purely from node rows (stable through the
252
+ // resolution loop, same window nameCache relies on); dropped in clearCaches.
253
+ methodOwnerIndexCache = new Map();
254
+ // Generation-tagged memo for getSupertypes. Supertype edges GROW during the
255
+ // resolution loop (batch k persists its implements/extends edges BEFORE
256
+ // batch k+1 fans out — the #1320 ordering), so a plain cache would freeze an
257
+ // early batch's emptier answer and change later batches' outcomes. Within
258
+ // one batch the edge state is fixed by that same ordering, so entries are
259
+ // tagged with a generation that advances at every batch entry point
260
+ // (resolveBatchYielding / resolveListForAdmission) — a stale-gen entry is
261
+ // recomputed, making the memo behavior-identical to no memo at every point
262
+ // in time. On the Swift compiler the unmemoized walk ran 971k times for
263
+ // 565s of combined worker time (~581µs each, recursion-multiplied).
264
+ supertypeGen = 0;
265
+ supertypeMemo = new Map();
266
+ /** Invalidate the getSupertypes memo — call when resolved edges may have advanced. */
267
+ advanceSupertypeGeneration() {
268
+ this.supertypeGen++;
269
+ // Lazy invalidation via the gen tag; bound the map so a long run over many
270
+ // batches doesn't accrete dead entries.
271
+ if (this.supertypeMemo.size > 50_000)
272
+ this.supertypeMemo.clear();
273
+ }
247
274
  // Node kinds are a small fixed set (~24), so this is a plain Map, not an LRU.
248
275
  // getNodesByKind returns the FULL node list for a kind; it was previously
249
276
  // uncached — a per-ref `SELECT * FROM nodes WHERE kind=?` + row-mapping. Called
@@ -372,10 +399,19 @@ class ReferenceResolver {
372
399
  this.qualifiedNameCache.clear();
373
400
  this.fileLinesCache.clear();
374
401
  this.methodMatchCache.clear();
402
+ this.methodOwnerIndexCache.clear();
403
+ this.supertypeMemo.clear();
404
+ this.supertypeGen++;
375
405
  this.nodesByKindCache.clear();
376
406
  this.knownNames = null;
377
407
  this.knownFiles = null;
378
408
  this.cachesWarmed = false;
409
+ // The import-resolver's and name-matcher's per-context memos assume the
410
+ // same stable window as the caches above — drop them together.
411
+ if (this.context) {
412
+ (0, import_resolver_1.clearImportResolverMemos)(this.context);
413
+ (0, name_matcher_1.clearNameMatcherMemos)(this.context);
414
+ }
379
415
  }
380
416
  /** `readFile` through the LRU content cache (null = read failed, also cached). */
381
417
  readFileCached(filePath) {
@@ -424,15 +460,61 @@ class ReferenceResolver {
424
460
  this.nameCache.set(methodName, candidates);
425
461
  }
426
462
  const want = `${typeName}::${methodName}`;
427
- const matches = [];
428
- for (const m of candidates) {
429
- if (m.kind !== 'method')
430
- continue;
431
- if (m.language !== language)
432
- continue;
433
- const qn = m.qualifiedName;
434
- if (qn === want || qn.endsWith(`::${want}`))
435
- matches.push(m);
463
+ let matches;
464
+ if (typeName.includes('::') || methodName.includes(':')) {
465
+ // Legacy linear filter for the shapes the owner index below can't
466
+ // key exactly: a multi-segment typeName (the endsWith test then
467
+ // spans more than two `::` segments) and ObjC selectors (whose
468
+ // single/empty-keyword colons defeat the segment split). Tiny
469
+ // populations; the per-key memo above still amortizes them.
470
+ matches = [];
471
+ for (const m of candidates) {
472
+ if (m.kind !== 'method')
473
+ continue;
474
+ if (m.language !== language)
475
+ continue;
476
+ const qn = m.qualifiedName;
477
+ if (qn === want || qn.endsWith(`::${want}`))
478
+ matches.push(m);
479
+ }
480
+ }
481
+ else {
482
+ // Owner index: the linear filter above is O(all same-named methods)
483
+ // per CACHE MISS, and on overload-heavy landscapes the distinct
484
+ // (type, method) key space is so large the per-key memo never
485
+ // amortizes — Swift's `init` has tens of thousands of candidates
486
+ // and the compiler repo measured 732µs per failing call, most of it
487
+ // this scan (re-entered once per supertype recursion level, too).
488
+ // Bucket each (language, methodName)'s candidates ONCE by the
489
+ // qualifiedName's last two `::` segments — exactly the span the
490
+ // `qn === want || qn.endsWith('::' + want)` predicate tests for a
491
+ // segment-clean typeName — then every query is a map lookup.
492
+ // Bucket insertion follows candidate order, so each bucket is
493
+ // byte-identical to what the linear filter produced.
494
+ const idxKey = `${language} ${methodName}`;
495
+ let ownerIndex = this.methodOwnerIndexCache.get(idxKey);
496
+ if (!ownerIndex) {
497
+ ownerIndex = new Map();
498
+ for (const m of candidates) {
499
+ if (m.kind !== 'method')
500
+ continue;
501
+ if (m.language !== language)
502
+ continue;
503
+ const qn = m.qualifiedName;
504
+ const i2 = qn.lastIndexOf('::');
505
+ if (i2 < 0)
506
+ continue; // single-segment qn can never match `T::m`
507
+ const i1 = qn.lastIndexOf('::', i2 - 1);
508
+ const bucketKey = i1 < 0 ? qn : qn.slice(i1 + 2);
509
+ const bucket = ownerIndex.get(bucketKey);
510
+ if (bucket)
511
+ bucket.push(m);
512
+ else
513
+ ownerIndex.set(bucketKey, [m]);
514
+ }
515
+ this.methodOwnerIndexCache.set(idxKey, ownerIndex);
516
+ }
517
+ matches = ownerIndex.get(want) ?? [];
436
518
  }
437
519
  this.methodMatchCache.set(key, matches);
438
520
  return matches;
@@ -524,20 +606,34 @@ class ReferenceResolver {
524
606
  // Matching by simple name (not id) reconciles a type declared in one node
525
607
  // (`KF::Builder`) with conformance declared in a separate extension node
526
608
  // (`KF.Builder: KFOptionSetter`) — both have name `Builder`.
609
+ // Memoized per batch generation (see supertypeMemo): within a batch the
610
+ // edge state is fixed, and the conformance walk re-queries the same
611
+ // popular supertypes (Swift stdlib protocols especially) thousands of
612
+ // times per batch.
613
+ const memoKey = `${language} ${typeName}`;
614
+ const hit = this.supertypeMemo.get(memoKey);
615
+ if (hit && hit.gen === this.supertypeGen)
616
+ return hit.supers;
527
617
  const typeNodes = this.context
528
618
  .getNodesByName(typeName)
529
619
  .filter((n) => SUPERTYPE_BEARING_KINDS.has(n.kind) && n.language === language);
530
- if (typeNodes.length === 0)
531
- return [];
532
- const supertypes = new Set();
533
- for (const tn of typeNodes) {
534
- for (const edge of this.queries.getOutgoingEdges(tn.id, ['implements', 'extends'])) {
535
- const target = this.queries.getNodeById(edge.target);
536
- if (target?.name && target.name !== typeName)
537
- supertypes.add(target.name);
620
+ let supers;
621
+ if (typeNodes.length === 0) {
622
+ supers = [];
623
+ }
624
+ else {
625
+ const supertypes = new Set();
626
+ for (const tn of typeNodes) {
627
+ for (const edge of this.queries.getOutgoingEdges(tn.id, ['implements', 'extends'])) {
628
+ const target = this.queries.getNodeById(edge.target);
629
+ if (target?.name && target.name !== typeName)
630
+ supertypes.add(target.name);
631
+ }
538
632
  }
633
+ supers = [...supertypes];
539
634
  }
540
- return [...supertypes];
635
+ this.supertypeMemo.set(memoKey, { gen: this.supertypeGen, supers });
636
+ return supers;
541
637
  },
542
638
  getImportMappings: (filePath, language) => {
543
639
  const cacheKey = filePath;
@@ -615,12 +711,13 @@ class ReferenceResolver {
615
711
  column: ref.column,
616
712
  filePath: ref.filePath || this.getFilePathFromNodeId(ref.fromNodeId),
617
713
  language: ref.language || this.getLanguageFromNodeId(ref.fromNodeId),
714
+ rowId: ref.rowId,
618
715
  }));
619
716
  const total = refs.length;
620
717
  let lastReportedPercent = -1;
621
718
  for (let i = 0; i < refs.length; i++) {
622
719
  const ref = refs[i]; // Array index is guaranteed to be in bounds
623
- const result = this.resolveOne(ref);
720
+ const result = this.resolveOneTimed(ref);
624
721
  if (result) {
625
722
  resolved.push(result);
626
723
  byMethod[result.resolvedBy] = (byMethod[result.resolvedBy] || 0) + 1;
@@ -779,13 +876,21 @@ class ReferenceResolver {
779
876
  // indexed under the bare name, so the existence check strips the dot.
780
877
  // Nix static path imports (`import ./x.nix`) name a FILE, not a symbol —
781
878
  // they bypass the symbol-existence check and resolve via resolveViaImport.
782
- const existenceName = ref.language === 'arkts' && ref.referenceName.startsWith('.')
879
+ let existenceName = ref.language === 'arkts' && ref.referenceName.startsWith('.')
783
880
  ? ref.referenceName.slice(1)
784
881
  : ref.referenceName;
785
- if (!(0, import_resolver_1.isNixPathImportRef)(ref) &&
786
- !this.hasAnyPossibleMatch(existenceName) &&
787
- !this.matchesAnyImport(ref) &&
788
- !this.frameworks.some((f) => f.claimsReference?.(ref.referenceName))) {
882
+ // Erlang refs carry the call-site arity (`f/1`, `mod::f/2` — #1610); the
883
+ // name index stores bare names, so existence is checked arity-less.
884
+ if (ref.language === 'erlang')
885
+ existenceName = existenceName.replace(/\/\d{1,3}$/, '');
886
+ const tPre = this.profileStages ? process.hrtime.bigint() : 0n;
887
+ const preFilterPass = (0, import_resolver_1.isNixPathImportRef)(ref) ||
888
+ this.hasAnyPossibleMatch(existenceName) ||
889
+ this.matchesAnyImport(ref) ||
890
+ this.frameworks.some((f) => f.claimsReference?.(ref.referenceName));
891
+ if (this.profileStages)
892
+ this.stageAdd('preFilter', ref, preFilterPass, tPre);
893
+ if (!preFilterPass) {
789
894
  return null;
790
895
  }
791
896
  // Function-as-value refs (#756) get a dedicated, strictly-gated path:
@@ -802,7 +907,13 @@ class ReferenceResolver {
802
907
  const viaImport = this.gateLanguage((0, import_resolver_1.resolveViaImport)(ref, this.context), ref);
803
908
  if (viaImport) {
804
909
  const target = this.queries.getNodeById(viaImport.targetNodeId);
805
- if (target && (target.kind === 'function' || target.kind === 'method')) {
910
+ if (target &&
911
+ (target.kind === 'function' ||
912
+ target.kind === 'method' ||
913
+ // Python (#1478): an imported class used as a value (`return
914
+ // OrgSerializerFull`) resolves through its import like any
915
+ // callback — mirrors matchFunctionRef's bareClassOk.
916
+ (ref.language === 'python' && target.kind === 'class'))) {
806
917
  return viaImport;
807
918
  }
808
919
  }
@@ -811,7 +922,10 @@ class ReferenceResolver {
811
922
  // JVM FQN imports skip framework/name-matcher: `import com.example.Bar`
812
923
  // resolves directly through the qualifiedName index, which is unambiguous
813
924
  // even when several `Bar` classes exist in different packages.
925
+ const tJvm = this.profileStages ? process.hrtime.bigint() : 0n;
814
926
  const jvmImport = (0, import_resolver_1.resolveJvmImport)(ref, this.context);
927
+ if (this.profileStages)
928
+ this.stageAdd('jvmImport', ref, !!jvmImport, tJvm);
815
929
  if (jvmImport)
816
930
  return jvmImport;
817
931
  // Razor/Blazor: a markup or `@code` type ref resolves through the file's
@@ -830,16 +944,27 @@ class ReferenceResolver {
830
944
  // JS → native `calls`) — `gateFrameworkLanguage` only drops a type/import
831
945
  // edge between two KNOWN families (see its doc), never a `calls` bridge or
832
946
  // a config↔code edge.
947
+ const tFw = this.profileStages ? process.hrtime.bigint() : 0n;
948
+ let fwEarly = null;
833
949
  for (const framework of this.frameworks) {
834
950
  const result = this.gateFrameworkLanguage(framework.resolve(ref, this.context), ref);
835
951
  if (result) {
836
- if (result.confidence >= 0.9)
837
- return result; // High confidence, return immediately
952
+ if (result.confidence >= 0.9) {
953
+ fwEarly = result; // High confidence, return immediately (below)
954
+ break;
955
+ }
838
956
  candidates.push(result);
839
957
  }
840
958
  }
959
+ if (this.profileStages)
960
+ this.stageAdd('frameworks', ref, fwEarly !== null, tFw);
961
+ if (fwEarly)
962
+ return fwEarly;
841
963
  // Strategy 2: Try import-based resolution
964
+ const tImp = this.profileStages ? process.hrtime.bigint() : 0n;
842
965
  const importResult = this.gateLanguage((0, import_resolver_1.resolveViaImport)(ref, this.context), ref);
966
+ if (this.profileStages)
967
+ this.stageAdd('viaImport', ref, !!importResult, tImp);
843
968
  if (importResult) {
844
969
  if (importResult.confidence >= 0.9)
845
970
  return importResult;
@@ -861,7 +986,10 @@ class ReferenceResolver {
861
986
  : null;
862
987
  }
863
988
  // Strategy 3: Try name matching
989
+ const tName = this.profileStages ? process.hrtime.bigint() : 0n;
864
990
  let nameResult = this.gateLanguage((0, name_matcher_1.matchReference)(ref, this.context), ref);
991
+ if (this.profileStages)
992
+ this.stageAdd('nameMatch', ref, !!nameResult, tName);
865
993
  // Nix has no ambient cross-file namespace — a callee binds lexically
866
994
  // (same file) or through explicit import/callPackage wiring (the import
867
995
  // path above). A cross-file name match is wrong by construction: every
@@ -931,13 +1059,14 @@ class ReferenceResolver {
931
1059
  }
932
1060
  }
933
1061
  // Promote "calls" to "instantiates" when the resolved target is a
934
- // class/struct. Languages without a `new` keyword (Python, Ruby)
1062
+ // class/struct/union. Languages without a `new` keyword (Python, Ruby)
935
1063
  // express instantiation as `Foo()` — extraction can't tell that
936
1064
  // apart from a function call without symbol info, but resolution
937
1065
  // can: if `Foo` resolves to a class, the call IS an instantiation.
938
1066
  if (kind === 'calls') {
939
1067
  const targetNode = this.queries.getNodeById(ref.targetNodeId);
940
- if (targetNode && (targetNode.kind === 'class' || targetNode.kind === 'struct')) {
1068
+ if (targetNode &&
1069
+ (targetNode.kind === 'class' || targetNode.kind === 'struct' || targetNode.kind === 'union')) {
941
1070
  kind = 'instantiates';
942
1071
  }
943
1072
  }
@@ -971,6 +1100,52 @@ class ReferenceResolver {
971
1100
  };
972
1101
  });
973
1102
  }
1103
+ /**
1104
+ * Split resolved refs into rows deletable by id and hand-built refs that
1105
+ * must fall back to the key-tuple delete. Rows loaded from the database
1106
+ * carry their row id and are deleted by exactly that id; the key tuple
1107
+ * omits line/col, so it also removes SIBLING rows — the same caller calling
1108
+ * the same callee at other lines — that a later batch hadn't attempted yet:
1109
+ * when a batch boundary split a caller's same-named call sites, the later
1110
+ * sites' edges were silently never created (#1269).
1111
+ */
1112
+ static partitionResolvedCleanup(resolved) {
1113
+ const rowIds = [];
1114
+ const legacyKeys = [];
1115
+ for (const r of resolved) {
1116
+ if (r.original.rowId != null)
1117
+ rowIds.push(r.original.rowId);
1118
+ else
1119
+ legacyKeys.push({
1120
+ fromNodeId: r.original.fromNodeId,
1121
+ referenceName: r.original.referenceName,
1122
+ referenceKind: r.original.referenceKind,
1123
+ });
1124
+ }
1125
+ return { rowIds, legacyKeys };
1126
+ }
1127
+ /**
1128
+ * Same row-id precision for parking unresolvable refs as status='failed'
1129
+ * (#1240): the key-tuple fallback would flip same-key sibling rows in later
1130
+ * batches to 'failed' before they were ever attempted, and resolution
1131
+ * outcome can differ per call site (receiver-type inference reads the
1132
+ * ref's line), so a sibling must not inherit this row's failure (#1269).
1133
+ */
1134
+ static partitionFailedCleanup(unresolved) {
1135
+ const byRowId = [];
1136
+ const legacyKeys = [];
1137
+ for (const r of unresolved) {
1138
+ if (r.rowId != null)
1139
+ byRowId.push({ rowId: r.rowId, referenceName: r.referenceName });
1140
+ else
1141
+ legacyKeys.push({
1142
+ fromNodeId: r.fromNodeId,
1143
+ referenceName: r.referenceName,
1144
+ referenceKind: r.referenceKind,
1145
+ });
1146
+ }
1147
+ return { byRowId, legacyKeys };
1148
+ }
974
1149
  /**
975
1150
  * Resolve and persist edges to database
976
1151
  */
@@ -984,11 +1159,9 @@ class ReferenceResolver {
984
1159
  }
985
1160
  // Clean up resolved refs from unresolved_refs table so metrics are accurate
986
1161
  if (result.resolved.length > 0) {
987
- this.queries.deleteSpecificResolvedReferences(result.resolved.map((r) => ({
988
- fromNodeId: r.original.fromNodeId,
989
- referenceName: r.original.referenceName,
990
- referenceKind: r.original.referenceKind,
991
- })));
1162
+ const { rowIds, legacyKeys } = ReferenceResolver.partitionResolvedCleanup(result.resolved);
1163
+ this.queries.deleteReferencesByRowIds(rowIds);
1164
+ this.queries.deleteSpecificResolvedReferences(legacyKeys);
992
1165
  }
993
1166
  // Park unresolvable refs as status='failed' — parity with
994
1167
  // resolveAndPersistBatched. Deleting them was wrong (#1240): a ref whose
@@ -1000,11 +1173,9 @@ class ReferenceResolver {
1000
1173
  // is still 'pending', so any pending row at rest belongs to an
1001
1174
  // interrupted run and the sweep can key off the pending count.
1002
1175
  if (result.unresolved.length > 0) {
1003
- this.queries.markReferencesFailed(result.unresolved.map((r) => ({
1004
- fromNodeId: r.fromNodeId,
1005
- referenceName: r.referenceName,
1006
- referenceKind: r.referenceKind,
1007
- })));
1176
+ const { byRowId, legacyKeys } = ReferenceResolver.partitionFailedCleanup(result.unresolved);
1177
+ this.queries.markReferencesFailedByRowIds(byRowId);
1178
+ this.queries.markReferencesFailed(legacyKeys);
1008
1179
  }
1009
1180
  return result;
1010
1181
  }
@@ -1026,22 +1197,22 @@ class ReferenceResolver {
1026
1197
  this.queries.insertEdges(edges.slice(i, i + PERSIST_CHUNK));
1027
1198
  await maybeYield();
1028
1199
  }
1029
- const resolvedKeys = result.resolved.map((r) => ({
1030
- fromNodeId: r.original.fromNodeId,
1031
- referenceName: r.original.referenceName,
1032
- referenceKind: r.original.referenceKind,
1033
- }));
1034
- for (let i = 0; i < resolvedKeys.length; i += PERSIST_CHUNK) {
1035
- this.queries.deleteSpecificResolvedReferences(resolvedKeys.slice(i, i + PERSIST_CHUNK));
1200
+ const resolvedCleanup = ReferenceResolver.partitionResolvedCleanup(result.resolved);
1201
+ for (let i = 0; i < resolvedCleanup.rowIds.length; i += PERSIST_CHUNK) {
1202
+ this.queries.deleteReferencesByRowIds(resolvedCleanup.rowIds.slice(i, i + PERSIST_CHUNK));
1036
1203
  await maybeYield();
1037
1204
  }
1038
- const unresolvedKeys = result.unresolved.map((r) => ({
1039
- fromNodeId: r.fromNodeId,
1040
- referenceName: r.referenceName,
1041
- referenceKind: r.referenceKind,
1042
- }));
1043
- for (let i = 0; i < unresolvedKeys.length; i += PERSIST_CHUNK) {
1044
- this.queries.markReferencesFailed(unresolvedKeys.slice(i, i + PERSIST_CHUNK));
1205
+ for (let i = 0; i < resolvedCleanup.legacyKeys.length; i += PERSIST_CHUNK) {
1206
+ this.queries.deleteSpecificResolvedReferences(resolvedCleanup.legacyKeys.slice(i, i + PERSIST_CHUNK));
1207
+ await maybeYield();
1208
+ }
1209
+ const failedCleanup = ReferenceResolver.partitionFailedCleanup(result.unresolved);
1210
+ for (let i = 0; i < failedCleanup.byRowId.length; i += PERSIST_CHUNK) {
1211
+ this.queries.markReferencesFailedByRowIds(failedCleanup.byRowId.slice(i, i + PERSIST_CHUNK));
1212
+ await maybeYield();
1213
+ }
1214
+ for (let i = 0; i < failedCleanup.legacyKeys.length; i += PERSIST_CHUNK) {
1215
+ this.queries.markReferencesFailed(failedCleanup.legacyKeys.slice(i, i + PERSIST_CHUNK));
1045
1216
  await maybeYield();
1046
1217
  }
1047
1218
  return result;
@@ -1112,6 +1283,7 @@ class ReferenceResolver {
1112
1283
  */
1113
1284
  async resolveBatchYielding(batch, maybeYield) {
1114
1285
  this.warmCaches();
1286
+ this.advanceSupertypeGeneration();
1115
1287
  const resolved = [];
1116
1288
  const unresolved = [];
1117
1289
  const byMethod = {};
@@ -1124,8 +1296,9 @@ class ReferenceResolver {
1124
1296
  column: raw.column,
1125
1297
  filePath: raw.filePath || this.getFilePathFromNodeId(raw.fromNodeId),
1126
1298
  language: raw.language || this.getLanguageFromNodeId(raw.fromNodeId),
1299
+ rowId: raw.rowId,
1127
1300
  };
1128
- const result = this.resolveOne(ref);
1301
+ const result = this.resolveOneTimed(ref);
1129
1302
  if (result) {
1130
1303
  resolved.push(result);
1131
1304
  byMethod[result.resolvedBy] = (byMethod[result.resolvedBy] || 0) + 1;
@@ -1133,7 +1306,11 @@ class ReferenceResolver {
1133
1306
  else {
1134
1307
  unresolved.push(ref);
1135
1308
  }
1136
- await maybeYield();
1309
+ // Fast-path the per-ref yield check: awaiting the async no-op costs a
1310
+ // microtask hop per ref, which dominates at ~10⁵ refs (see MaybeYield).
1311
+ const y = maybeYield();
1312
+ if (y)
1313
+ await y;
1137
1314
  }
1138
1315
  return {
1139
1316
  resolved,
@@ -1146,12 +1323,144 @@ class ReferenceResolver {
1146
1323
  },
1147
1324
  };
1148
1325
  }
1326
+ /**
1327
+ * Resolve a list of refs and return everything the ADMISSION side needs to
1328
+ * persist the outcome: resolutions, failures, the deferred post-pass refs
1329
+ * this run produced (drained, so the caller owns routing them), and stats.
1330
+ * This is the resolver-worker entry point — it runs the exact per-ref loop
1331
+ * of resolveBatchYielding, minus the main-thread yields (worker threads have
1332
+ * no watchdog heartbeat to starve). Results are in input order.
1333
+ */
1334
+ /**
1335
+ * CODEGRAPH_RESOLVE_PROFILE=1: per-outcome wall-clock histogram of
1336
+ * resolveOne, keyed by the winning strategy (`resolvedBy`) or
1337
+ * `fail:<referenceKind>` — the §7a.2 "profile the per-ref path" probe. The
1338
+ * kernel-scale batch loop is ~430s and CORE-INVARIANT (835.9s pooled-4-on-8
1339
+ * ≈ 812.5s sequential-on-2 for the whole superphase), so the next lever is
1340
+ * which CLASS of ref the time belongs to, not more parallelism. Off by
1341
+ * default: the hrtime pair costs ~100ns/ref only when the env is set.
1342
+ */
1343
+ resolveProfile = process.env.CODEGRAPH_RESOLVE_PROFILE ? new Map() : null;
1344
+ /**
1345
+ * CODEGRAPH_RESOLVE_PROFILE=2 additionally attributes time to the
1346
+ * STRATEGIES inside resolveOne (`stage:<name>|<refKind>|hit/miss` rows in
1347
+ * the same histogram) — i.e. WHICH machinery a failing class of refs pays
1348
+ * for, not just that it fails. =1 keeps the per-outcome rows only.
1349
+ */
1350
+ profileStages = process.env.CODEGRAPH_RESOLVE_PROFILE === '2';
1351
+ stageAdd(stage, ref, hit, t0) {
1352
+ if (!this.resolveProfile)
1353
+ return;
1354
+ const dt = process.hrtime.bigint() - t0;
1355
+ const key = `stage:${stage}|${ref.referenceKind}|${hit ? 'hit' : 'miss'}`;
1356
+ const slot = this.resolveProfile.get(key);
1357
+ if (slot) {
1358
+ slot.n++;
1359
+ slot.ns += dt;
1360
+ }
1361
+ else {
1362
+ this.resolveProfile.set(key, { n: 1, ns: dt });
1363
+ }
1364
+ }
1365
+ resolveOneTimed(ref) {
1366
+ if (!this.resolveProfile)
1367
+ return this.resolveOne(ref);
1368
+ const t0 = process.hrtime.bigint();
1369
+ const result = this.resolveOne(ref);
1370
+ const dt = process.hrtime.bigint() - t0;
1371
+ const key = result ? result.resolvedBy : `fail:${ref.referenceKind}`;
1372
+ const slot = this.resolveProfile.get(key);
1373
+ if (slot) {
1374
+ slot.n++;
1375
+ slot.ns += dt;
1376
+ }
1377
+ else {
1378
+ this.resolveProfile.set(key, { n: 1, ns: dt });
1379
+ }
1380
+ return result;
1381
+ }
1382
+ /** Dump the CODEGRAPH_RESOLVE_PROFILE histogram to stderr (no-op when off). */
1383
+ dumpResolveProfile(label) {
1384
+ if (!this.resolveProfile || this.resolveProfile.size === 0)
1385
+ return;
1386
+ const rows = [...this.resolveProfile.entries()]
1387
+ .map(([k, v]) => ({ k, n: v.n, ms: Number(v.ns / 1000000n) }))
1388
+ .sort((a, b) => b.ms - a.ms);
1389
+ for (const r of rows) {
1390
+ console.error(`[resolve-profile] ${label} ${r.k}: n=${r.n} total=${(r.ms / 1000).toFixed(1)}s avg=${((r.ms * 1000) / Math.max(1, r.n)).toFixed(0)}µs`);
1391
+ }
1392
+ // =2 only: this thread's matchReference sub-stage table rides along.
1393
+ (0, name_matcher_1.dumpNameMatcherProfile)(label);
1394
+ }
1395
+ resolveListForAdmission(refs) {
1396
+ this.warmCaches();
1397
+ this.advanceSupertypeGeneration();
1398
+ const resolved = [];
1399
+ const unresolved = [];
1400
+ const byMethod = {};
1401
+ for (const raw of refs) {
1402
+ const ref = {
1403
+ fromNodeId: raw.fromNodeId,
1404
+ referenceName: raw.referenceName,
1405
+ referenceKind: raw.referenceKind,
1406
+ line: raw.line,
1407
+ column: raw.column,
1408
+ filePath: raw.filePath || this.getFilePathFromNodeId(raw.fromNodeId),
1409
+ language: raw.language || this.getLanguageFromNodeId(raw.fromNodeId),
1410
+ rowId: raw.rowId,
1411
+ };
1412
+ const result = this.resolveOneTimed(ref);
1413
+ if (result) {
1414
+ resolved.push(result);
1415
+ byMethod[result.resolvedBy] = (byMethod[result.resolvedBy] || 0) + 1;
1416
+ }
1417
+ else {
1418
+ unresolved.push(ref);
1419
+ }
1420
+ }
1421
+ return {
1422
+ resolved,
1423
+ unresolved,
1424
+ deferredChain: this.deferredChainRefs.splice(0),
1425
+ deferredThisMember: this.deferredThisMemberRefs.splice(0),
1426
+ byMethod,
1427
+ };
1428
+ }
1429
+ /**
1430
+ * The resolver's live ResolutionContext — resolver-pool workers use it to
1431
+ * run synthesis passes against their own read-only connection.
1432
+ */
1433
+ getResolutionContext() {
1434
+ return this.context;
1435
+ }
1436
+ /**
1437
+ * Re-queue deferred post-pass refs produced by resolver workers, preserving
1438
+ * their admission order so resolveChainedCallsViaConformance /
1439
+ * resolveDeferredThisMemberRefs process them exactly as the sequential path
1440
+ * would have.
1441
+ */
1442
+ appendDeferredFromWorkers(deferredChain, deferredThisMember) {
1443
+ this.deferredChainRefs.push(...deferredChain);
1444
+ this.deferredThisMemberRefs.push(...deferredThisMember);
1445
+ }
1149
1446
  /**
1150
1447
  * Resolve and persist in batches to keep memory bounded.
1151
1448
  * Processes unresolved references in chunks, persisting edges and cleaning
1152
1449
  * up resolved refs after each batch to avoid accumulating large arrays.
1153
1450
  */
1154
- async resolveAndPersistBatched(onProgress, batchSize = 5000) {
1451
+ async resolveAndPersistBatched(onProgress, batchSize = 5000, onSynthesisProgress,
1452
+ // When provided, big batches fan out across a read-only resolver-worker
1453
+ // pool with results admitted in canonical order (see resolver-pool.ts).
1454
+ // Sequential fallback on any pool failure. CODEGRAPH_NO_PARALLEL_RESOLVE=1
1455
+ // disables entirely. bulkEdgeLoad hooks (when provided) bracket the batch
1456
+ // loop with drop/recreate of the non-unique edge indexes on big runs —
1457
+ // see DatabaseConnection.beginBulkEdgeLoad. backpressure (when provided)
1458
+ // is the WAL valve's writer-side backstop (WalCheckpointValve.backpressure):
1459
+ // called at pool-idle boundaries so a full backfill can actually complete —
1460
+ // the valve's timer-driven passive passes stay perpetually partial against
1461
+ // the pool's continuous reads, which is how a kernel-scale resolution grew
1462
+ // a 22GB WAL on a 4.6GB DB (migration plan §7a.1).
1463
+ parallel) {
1155
1464
  // Resolution runs on the indexer's MAIN thread, and the #850 liveness
1156
1465
  // watchdog SIGKILLs a process whose event loop stalls past its window (60s
1157
1466
  // by default). A single dense batch's resolveAll — or the synthesis pass
@@ -1159,6 +1468,19 @@ class ReferenceResolver {
1159
1468
  // (#1091). A shared yielder lets both give the watchdog heartbeat a regular
1160
1469
  // window to fire; see ./cooperative-yield.
1161
1470
  const maybeYield = (0, cooperative_yield_1.createYielder)();
1471
+ if (process.env.CODEGRAPH_SYNTH_TIMINGS) {
1472
+ console.error(`[pool-timing] backpressure hook: ${parallel?.backpressure ? 'present' : 'absent'}`);
1473
+ }
1474
+ // CODEGRAPH_RESOLVE_PROFILE loop-stage attribution: the §7a.2 kernel-scale
1475
+ // histogram showed resolveOne owns only ~93s of the ~436s batch loop —
1476
+ // these counters name where the other ~340s goes (reads, edge build+insert,
1477
+ // deletes/marks, the per-batch count guard).
1478
+ const loopProf = process.env.CODEGRAPH_RESOLVE_PROFILE
1479
+ ? { read: 0, settle: 0, backpressure: 0, recycle: 0, createEdges: 0, insertEdges: 0, deletes: 0, marks: 0, countGuard: 0 }
1480
+ : null;
1481
+ const lp = (k, t0) => { if (loopProf)
1482
+ loopProf[k] = (loopProf[k] ?? 0) + (Date.now() - t0); };
1483
+ let tLp = 0;
1162
1484
  await this.warmCachesYielding(maybeYield);
1163
1485
  const total = this.queries.getUnresolvedReferencesCount();
1164
1486
  let processed = 0;
@@ -1168,95 +1490,370 @@ class ReferenceResolver {
1168
1490
  unresolved: 0,
1169
1491
  byMethod: {},
1170
1492
  };
1171
- // Process in batches. We always read from offset 0 because every ref the
1172
- // batch processed leaves the pending set (resolved rows are deleted,
1493
+ // Parallel pool, started immediately but never awaited up front: early
1494
+ // batches run sequentially while the workers boot (module load + readonly
1495
+ // DB open + framework detect + cache warm ≈ hundreds of ms), and the loop
1496
+ // switches to fan-out the moment the pool reports ready — so pool boot
1497
+ // costs zero wall-clock. Any failure downgrades to sequential permanently.
1498
+ let pool = null;
1499
+ let poolReady = false;
1500
+ // True once pool creation has been attempted by EITHER engage site (the
1501
+ // up-front ref-count gate or the adaptive projection below) — a pool that
1502
+ // failed or was destroyed must stay down (downgrade is permanent), and
1503
+ // tryCreate's sizing probes shouldn't re-run every batch on hosts that
1504
+ // declined.
1505
+ let poolEngageTried = false;
1506
+ const createPool = (t0, why) => {
1507
+ poolEngageTried = true;
1508
+ if (!parallel)
1509
+ return null;
1510
+ const p = resolver_pool_1.ResolverPool.tryCreate(parallel.dbPath, this.projectRoot);
1511
+ p?.ready().then(() => {
1512
+ poolReady = true;
1513
+ if (process.env.CODEGRAPH_SYNTH_TIMINGS)
1514
+ console.error(`[pool-timing] pool ready after ${Date.now() - t0}ms (${why})`);
1515
+ }, () => {
1516
+ void p.destroy().catch(() => undefined);
1517
+ if (pool === p)
1518
+ pool = null;
1519
+ });
1520
+ return p;
1521
+ };
1522
+ if (parallel && total >= (0, resolver_pool_1.minRefsForPool)()) {
1523
+ pool = createPool(Date.now(), 'ref-count');
1524
+ }
1525
+ // Adaptive engagement bar (see the batch-loop hook): projected remaining
1526
+ // sequential settle above this boots the pool mid-loop. Boot is async and
1527
+ // fan-out waits for ready, so a marginal engage costs background boot
1528
+ // only; the bar just needs to clear the fan-out's own overhead class.
1529
+ const ADAPTIVE_ENGAGE_SETTLE_MS = 400;
1530
+ let adaptiveSeqMs = 0;
1531
+ let adaptiveSeqRefs = 0;
1532
+ // Process in PIPELINED batches (double-buffer). The enumeration is the
1533
+ // head of the pending set in rowid order; every ref a persisted batch
1534
+ // processed leaves the pending set (resolved rows are deleted,
1173
1535
  // unresolvable ones flip to status='failed'), shifting the remaining
1174
1536
  // pending rows forward.
1175
1537
  let prevRemaining = Number.POSITIVE_INFINITY;
1176
- while (true) {
1177
- const batch = this.queries.getUnresolvedReferencesBatch(0, batchSize);
1178
- if (batch.length === 0)
1179
- break;
1180
- const result = await this.resolveBatchYielding(batch, maybeYield);
1181
- // Persist in bounded sub-transactions with yields between: a whole
1182
- // batch's edge insert / keyed deletes are otherwise one solid
1183
- // synchronous span each on a multi-GB index, sitting BETWEEN the
1184
- // per-ref yields — the last unyielded stretch of the resolution loop.
1185
- // Crash semantics are unchanged (already several transactions): edges
1186
- // land before their refs are deleted, so a kill mid-way re-resolves
1187
- // the remainder idempotently on the next run/sweep (#1187).
1188
- const PERSIST_CHUNK = 1000;
1189
- // Persist edges immediately
1190
- const edges = this.createEdges(result.resolved);
1191
- for (let i = 0; i < edges.length; i += PERSIST_CHUNK) {
1192
- this.queries.insertEdges(edges.slice(i, i + PERSIST_CHUNK));
1193
- await maybeYield();
1538
+ // Cadence for the worker connection recycling below — ~8 batches
1539
+ // ≈ 40k refs between recycles keeps the WAL shallow at kernel scale
1540
+ // while a small sync never recycles at all. (25 recovered only half
1541
+ // the write tax — the WAL re-deepened between recycles; reopens are
1542
+ // sub-millisecond so the shorter cadence is ~free.)
1543
+ const RECYCLE_EVERY_BATCHES = 8;
1544
+ let batchesSinceRecycle = 0;
1545
+ // Begin one batch: fan out to the pool when it's ready and the batch is
1546
+ // big enough — workers then resolve batch k+1 WHILE the main thread
1547
+ // persists batch k (persist measured at ~58% of resolution wall on a
1548
+ // 255k-ref repo, all of it previously spent with the pool idle).
1549
+ // Sequential batches stay lazy: they run on the main thread at settle
1550
+ // time, where an early start would only contend with the persist.
1551
+ const beginBatch = (batch) => {
1552
+ if (pool && poolReady && resolver_pool_1.ResolverPool.worthParallel(batch.length)) {
1553
+ return {
1554
+ mode: 'pool',
1555
+ settled: pool.resolveBatch(batch).then((out) => ({ ok: true, out }), (err) => ({ ok: false, err })),
1556
+ };
1194
1557
  }
1195
- // Clean up resolved refs so they don't appear in the next batch
1196
- const resolvedKeys = result.resolved.map((r) => ({
1197
- fromNodeId: r.original.fromNodeId,
1198
- referenceName: r.original.referenceName,
1199
- referenceKind: r.original.referenceKind,
1200
- }));
1201
- for (let i = 0; i < resolvedKeys.length; i += PERSIST_CHUNK) {
1202
- this.queries.deleteSpecificResolvedReferences(resolvedKeys.slice(i, i + PERSIST_CHUNK));
1203
- await maybeYield();
1558
+ return { mode: 'seq' };
1559
+ };
1560
+ // Settle an in-flight batch to a ResolutionResult. Deferred post-pass refs
1561
+ // are appended HERE, in loop order — never inside the fan-out promise — so
1562
+ // admission order stays exactly the sequential order even while a later
1563
+ // batch resolves concurrently. A pool failure downgrades to sequential
1564
+ // permanently and re-resolves this batch on the main thread.
1565
+ const settleBatch = async (inFlight, batch) => {
1566
+ if (inFlight.mode === 'pool') {
1567
+ const settled = await inFlight.settled;
1568
+ if (settled.ok) {
1569
+ this.appendDeferredFromWorkers(settled.out.deferredChain, settled.out.deferredThisMember);
1570
+ return {
1571
+ resolved: settled.out.resolved,
1572
+ unresolved: settled.out.unresolved,
1573
+ stats: {
1574
+ total: batch.length,
1575
+ resolved: settled.out.resolved.length,
1576
+ unresolved: settled.out.unresolved.length,
1577
+ byMethod: settled.out.byMethod,
1578
+ },
1579
+ };
1580
+ }
1581
+ (0, errors_1.logDebug)('Parallel resolution failed; falling back to sequential', {
1582
+ error: settled.err instanceof Error ? settled.err.message : String(settled.err),
1583
+ });
1584
+ if (pool)
1585
+ await pool.destroy().catch(() => undefined);
1586
+ pool = null;
1204
1587
  }
1205
- // Park unresolvable refs from this batch as status='failed' so they
1206
- // leave the pending set (the batch reader and non-progress guard below
1207
- // only see pending rows) but stay retryable when a later sync adds a
1208
- // symbol that could satisfy them (#1240).
1209
- const unresolvedKeys = result.unresolved.map((r) => ({
1210
- fromNodeId: r.fromNodeId,
1211
- referenceName: r.referenceName,
1212
- referenceKind: r.referenceKind,
1213
- }));
1214
- for (let i = 0; i < unresolvedKeys.length; i += PERSIST_CHUNK) {
1215
- this.queries.markReferencesFailed(unresolvedKeys.slice(i, i + PERSIST_CHUNK));
1216
- await maybeYield();
1588
+ return this.resolveBatchYielding(batch, maybeYield);
1589
+ };
1590
+ // Bulk edge load: on big runs, drop the non-unique edge indexes for the
1591
+ // duration of the batch loop (the identity index stays — OR IGNORE dedup
1592
+ // and the source-keyed supertype-walk reads both live on it). Recreated in
1593
+ // the inner finally BEFORE synthesis, whose passes read kind-keyed.
1594
+ // Measured on a 224k-edge resolution set: insert 2.8s → 1.1s + 0.3s
1595
+ // recreate. Same ref-count gate as the pool so small syncs never pay the
1596
+ // recreate cost.
1597
+ let bulkEdgesActive = false;
1598
+ if (parallel?.bulkEdgeLoad && total >= (0, resolver_pool_1.minRefsForPool)()) {
1599
+ try {
1600
+ parallel.bulkEdgeLoad.begin();
1601
+ bulkEdgesActive = true;
1217
1602
  }
1218
- // Aggregate stats
1219
- aggregateStats.total += result.stats.total;
1220
- aggregateStats.resolved += result.stats.resolved;
1221
- aggregateStats.unresolved += result.stats.unresolved;
1222
- for (const [method, count] of Object.entries(result.stats.byMethod)) {
1223
- aggregateStats.byMethod[method] = (aggregateStats.byMethod[method] || 0) + count;
1603
+ catch { /* keep the indexes; inserts just pay the per-row maintenance */ }
1604
+ }
1605
+ // Same gate for the ref-index window: the loop's deletes stop maintaining
1606
+ // the five sync-path unresolved_refs indexes, and the end-of-loop rebuild
1607
+ // is near-free (only failed refs survive the loop).
1608
+ let bulkRefsActive = false;
1609
+ if (parallel?.refIndexLoad && total >= (0, resolver_pool_1.minRefsForPool)()) {
1610
+ try {
1611
+ parallel.refIndexLoad.begin();
1612
+ bulkRefsActive = true;
1224
1613
  }
1225
- processed += batch.length;
1226
- onProgress?.(processed, total);
1227
- // Yield so progress UI can render between batches
1228
- await new Promise(resolve => setImmediate(resolve));
1229
- // NOTE: there used to be an extra early break here when a batch resolved
1230
- // nothing (`result.unresolved.length === batch.length`). That was wrong:
1231
- // an all-unresolvable batch still DELETES its rows (progress), yet the
1232
- // break abandoned every batch after it in the same run — on a repo whose
1233
- // first 5000 refs are all external/stdlib calls, resolution stopped at
1234
- // batch one and left the rest of the table as permanent orphans (#1187).
1235
- // The count-based guard below catches the true no-progress case.
1236
- // Non-progress guard (defense-in-depth). Because we re-read from offset 0
1237
- // each pass, the PENDING population MUST shrink every iteration — resolved
1238
- // refs are deleted and unresolvable ones are marked failed above, and both
1239
- // leave the pending set the batch reader sees. If it didn't shrink, a
1240
- // resolver returned a match whose `original.referenceName` differs from the
1241
- // stored row, so the keyed delete/update no-ops, and we'd re-read +
1242
- // re-resolve + re-insert the same rows forever (the runaway that grew a
1243
- // 99-file repo to 5M edges / 1.4 GB before the Go-fallback fix). Stop
1244
- // rather than grow the graph without bound.
1245
- const remaining = this.queries.getUnresolvedReferencesCount();
1246
- if (remaining >= prevRemaining)
1247
- break;
1248
- prevRemaining = remaining;
1614
+ catch { /* keep the indexes; deletes just pay the per-row maintenance */ }
1249
1615
  }
1250
- // Dynamic-edge synthesis: now that all base `calls` edges are persisted,
1251
- // synthesize observer/callback dispatch edges (dispatcher → registered
1252
- // callbacks) that static parsing leaves out. Best-effort — never fail the
1253
- // index on it. See docs/design/callback-edge-synthesis.md.
1254
1616
  try {
1255
- aggregateStats.byMethod['callback-synthesis'] = await (0, callback_synthesizer_1.synthesizeCallbackEdges)(this.queries, this.context);
1617
+ try {
1618
+ tLp = Date.now();
1619
+ let batch = this.queries.getUnresolvedReferencesBatchAfter(0, batchSize);
1620
+ lp('read', tLp);
1621
+ let inFlight = batch.length > 0 ? beginBatch(batch) : null;
1622
+ while (batch.length > 0 && inFlight) {
1623
+ // Prefetch the NEXT batch before this one persists: this batch's rows
1624
+ // are still pending (nothing has mutated the table since they were
1625
+ // read), so seeking past this batch's last row id in the same rowid
1626
+ // enumeration yields the following batch (keyset — OFFSET re-walked the
1627
+ // accumulated failed prefix every read, 54.6s at kernel scale, §7a.2).
1628
+ tLp = Date.now();
1629
+ const nextBatch = this.queries.getUnresolvedReferencesBatchAfter(batch[batch.length - 1].rowId, batchSize);
1630
+ lp('read', tLp);
1631
+ const tBatch = Date.now();
1632
+ const result = await settleBatch(inFlight, batch);
1633
+ if (process.env.CODEGRAPH_SYNTH_TIMINGS)
1634
+ console.error(`[pool-timing] batch ${inFlight.mode}: ${batch.length} refs in ${Date.now() - tBatch}ms`);
1635
+ lp('settle', tBatch);
1636
+ // Adaptive pool engagement: the fixed ref-count gate can't see PER-REF
1637
+ // cost, and settle rates differ ~9× by language (56k Rust refs cost
1638
+ // more sequential settle than 154k Go refs — 36µs vs 4µs measured on
1639
+ // tokio/prometheus). After each sequential batch, project the remaining
1640
+ // settle from the observed rate and boot the pool mid-loop when it
1641
+ // clears the bar. The loop already switches to fan-out only when the
1642
+ // async boot reports ready, admission order is mode-independent, and
1643
+ // 2-core/low-memory hosts still decline inside tryCreate's sizing —
1644
+ // so the switch changes wall-clock, never the graph.
1645
+ if (inFlight.mode === 'seq' && parallel && pool === null && !poolEngageTried) {
1646
+ adaptiveSeqMs += Date.now() - tBatch;
1647
+ adaptiveSeqRefs += batch.length;
1648
+ const remaining = total - processed - batch.length;
1649
+ const projectedMs = (adaptiveSeqMs / Math.max(1, adaptiveSeqRefs)) * Math.max(0, remaining);
1650
+ if (projectedMs >= ADAPTIVE_ENGAGE_SETTLE_MS) {
1651
+ if (process.env.CODEGRAPH_SYNTH_TIMINGS) {
1652
+ console.error(`[pool-timing] adaptive engage: projected ${Math.round(projectedMs)}ms sequential settle over ${remaining} remaining refs`);
1653
+ }
1654
+ pool = createPool(Date.now(), 'adaptive');
1655
+ }
1656
+ }
1657
+ // WAL-valve backstop at the ONE pool-idle boundary of the double-buffer
1658
+ // (this batch settled, the next not yet fanned out): past the hard cap
1659
+ // the writer parks for a full backfill here, where the pool's readers
1660
+ // are all between statements — so the backfill completes, readers
1661
+ // re-enter at SQLite's backfilled mark, and the next persist commit
1662
+ // WRAPS the WAL instead of growing it. No-op (one fstat) under the cap.
1663
+ tLp = Date.now();
1664
+ const bp = parallel?.backpressure?.();
1665
+ if (bp)
1666
+ await bp;
1667
+ lp('backpressure', tLp);
1668
+ // Recycle the workers' read connections periodically at this same
1669
+ // worker-idle boundary (batch k settled, batch k+1 not yet fanned
1670
+ // out): a long-lived reader pins WAL checkpoint progress, and the
1671
+ // deep WAL that accumulates behind it taxes the writer's OWN page
1672
+ // operations — the §7a.6 writes-under-readers finding (deletes
1673
+ // 42.6s → 118.8s from 0 to 4 attached readers; an aggressive valve
1674
+ // recovered the writes but paid +129s in full-park folds). Releasing
1675
+ // the read marks every ~25 batches lets the existing checkpoints
1676
+ // advance instead, at ~milliseconds of reopen cost. A failed recycle
1677
+ // downgrades to sequential permanently, same as a failed fan-out.
1678
+ if (pool && poolReady && ++batchesSinceRecycle >= RECYCLE_EVERY_BATCHES) {
1679
+ batchesSinceRecycle = 0;
1680
+ tLp = Date.now();
1681
+ try {
1682
+ await pool.recycleWorkers();
1683
+ }
1684
+ catch (err) {
1685
+ (0, errors_1.logDebug)('Worker connection recycle failed; falling back to sequential', {
1686
+ error: err instanceof Error ? err.message : String(err),
1687
+ });
1688
+ await pool.destroy().catch(() => undefined);
1689
+ pool = null;
1690
+ }
1691
+ lp('recycle', tLp);
1692
+ }
1693
+ // Persist in bounded sub-transactions with yields between: a whole
1694
+ // batch's edge insert / keyed deletes are otherwise one solid
1695
+ // synchronous span each on a multi-GB index, sitting BETWEEN the
1696
+ // per-ref yields — the last unyielded stretch of the resolution loop.
1697
+ // Crash semantics are unchanged (already several transactions): edges
1698
+ // land before their refs are deleted, so a kill mid-way re-resolves
1699
+ // the remainder idempotently on the next run/sweep (#1187).
1700
+ const PERSIST_CHUNK = 1000;
1701
+ const tPersist = Date.now();
1702
+ // Persist edges BEFORE fanning out the next batch: later batches read
1703
+ // this batch's edges — resolveMethodOnType walks supertype chains over
1704
+ // `extends`/`implements` edges that earlier batches resolved, so a
1705
+ // receiver typed as a subclass only reaches a method declared on its
1706
+ // base class if those edges are visible. (Validated on dubbo: fanning
1707
+ // out first downgraded exactly those supertype-method resolutions from
1708
+ // the 0.9 typed-receiver path to the 0.65 word-overlap fallback.)
1709
+ tLp = Date.now();
1710
+ const edges = this.createEdges(result.resolved);
1711
+ lp('createEdges', tLp);
1712
+ tLp = Date.now();
1713
+ for (let i = 0; i < edges.length; i += PERSIST_CHUNK) {
1714
+ this.queries.insertEdges(edges.slice(i, i + PERSIST_CHUNK));
1715
+ await maybeYield();
1716
+ }
1717
+ lp('insertEdges', tLp);
1718
+ // NOW fan the next batch out — workers see exactly the edge state the
1719
+ // sequential baseline would (every batch ≤ this one committed), while
1720
+ // the main thread spends the REST of the persist (ref deletes + failed
1721
+ // parking below) overlapped with their resolution — the double-buffer.
1722
+ const nextInFlight = nextBatch.length > 0 ? beginBatch(nextBatch) : null;
1723
+ // Clean up resolved refs so they don't appear in the next batch —
1724
+ // by row id, so a same-key sibling ref in a LATER batch (same caller
1725
+ // calling the same callee at another line) is left pending for its own
1726
+ // attempt instead of being swept out with this batch's rows (#1269).
1727
+ tLp = Date.now();
1728
+ let removedThisBatch = 0;
1729
+ const resolvedCleanup = ReferenceResolver.partitionResolvedCleanup(result.resolved);
1730
+ for (let i = 0; i < resolvedCleanup.rowIds.length; i += PERSIST_CHUNK) {
1731
+ removedThisBatch += this.queries.deleteReferencesByRowIds(resolvedCleanup.rowIds.slice(i, i + PERSIST_CHUNK));
1732
+ await maybeYield();
1733
+ }
1734
+ for (let i = 0; i < resolvedCleanup.legacyKeys.length; i += PERSIST_CHUNK) {
1735
+ removedThisBatch += this.queries.deleteSpecificResolvedReferences(resolvedCleanup.legacyKeys.slice(i, i + PERSIST_CHUNK));
1736
+ await maybeYield();
1737
+ }
1738
+ lp('deletes', tLp);
1739
+ // Park unresolvable refs from this batch as status='failed' so they
1740
+ // leave the pending set (the batch reader and non-progress guard below
1741
+ // only see pending rows) but stay retryable when a later sync adds a
1742
+ // symbol that could satisfy them (#1240).
1743
+ tLp = Date.now();
1744
+ const failedCleanup = ReferenceResolver.partitionFailedCleanup(result.unresolved);
1745
+ for (let i = 0; i < failedCleanup.byRowId.length; i += PERSIST_CHUNK) {
1746
+ removedThisBatch += this.queries.markReferencesFailedByRowIds(failedCleanup.byRowId.slice(i, i + PERSIST_CHUNK));
1747
+ await maybeYield();
1748
+ }
1749
+ for (let i = 0; i < failedCleanup.legacyKeys.length; i += PERSIST_CHUNK) {
1750
+ removedThisBatch += this.queries.markReferencesFailed(failedCleanup.legacyKeys.slice(i, i + PERSIST_CHUNK));
1751
+ await maybeYield();
1752
+ }
1753
+ lp('marks', tLp);
1754
+ if (process.env.CODEGRAPH_SYNTH_TIMINGS)
1755
+ console.error(`[pool-timing] batch persist: ${Date.now() - tPersist}ms`);
1756
+ // Aggregate stats
1757
+ aggregateStats.total += result.stats.total;
1758
+ aggregateStats.resolved += result.stats.resolved;
1759
+ aggregateStats.unresolved += result.stats.unresolved;
1760
+ for (const [method, count] of Object.entries(result.stats.byMethod)) {
1761
+ aggregateStats.byMethod[method] = (aggregateStats.byMethod[method] || 0) + count;
1762
+ }
1763
+ processed += batch.length;
1764
+ onProgress?.(processed, total);
1765
+ // Yield so progress UI can render between batches
1766
+ await new Promise(resolve => setImmediate(resolve));
1767
+ // NOTE: there used to be an extra early break here when a batch resolved
1768
+ // nothing (`result.unresolved.length === batch.length`). That was wrong:
1769
+ // an all-unresolvable batch still DELETES its rows (progress), yet the
1770
+ // break abandoned every batch after it in the same run — on a repo whose
1771
+ // first 5000 refs are all external/stdlib calls, resolution stopped at
1772
+ // batch one and left the rest of the table as permanent orphans (#1187).
1773
+ // The count-based guard below catches the true no-progress case.
1774
+ // Non-progress guard (defense-in-depth). Each iteration enumerates from
1775
+ // the head of the pending set, so the PENDING population MUST shrink
1776
+ // every iteration — resolved refs are deleted and unresolvable ones are
1777
+ // marked failed above, and both leave the pending set the batch reader
1778
+ // sees. If it didn't shrink, a resolver returned a match whose
1779
+ // `original.referenceName` differs from the stored row, so the keyed
1780
+ // delete/update no-ops, and we'd re-read + re-resolve + re-insert the
1781
+ // same rows forever (the runaway that grew a 99-file repo to 5M edges /
1782
+ // 1.4 GB before the Go-fallback fix). Stop rather than grow the graph
1783
+ // without bound. (An in-flight prefetched batch is abandoned unsettled —
1784
+ // fan-out has no side effects until settleBatch appends its results.)
1785
+ // Non-progress signal, now O(1): `changes` summed across this batch's
1786
+ // deletes + failed-parks is the DIRECT evidence the guard's old count
1787
+ // diff inferred — a resolver returning a mismatched name makes the keyed
1788
+ // cleanup no-op, which shows up here as zero removals. The per-batch
1789
+ // COUNT(*) it replaces walked every remaining pending row — O(N²/batch)
1790
+ // over a run, 93.9s of the kernel-scale batch loop (§7a.2). A REAL count
1791
+ // runs only on the suspicious path (claimed-work batch removed nothing —
1792
+ // e.g. every row was a sibling a legacy-key sweep already consumed),
1793
+ // where it arbitrates stop-vs-continue exactly as before.
1794
+ if (removedThisBatch <= 0 && batch.length > 0) {
1795
+ tLp = Date.now();
1796
+ const remaining = this.queries.getUnresolvedReferencesCount();
1797
+ lp('countGuard', tLp);
1798
+ if (remaining >= prevRemaining)
1799
+ break;
1800
+ prevRemaining = remaining;
1801
+ }
1802
+ // Advance the pipeline: the prefetched batch (already fanned out when
1803
+ // the pool is on) becomes the current one.
1804
+ batch = nextBatch;
1805
+ inFlight = nextInFlight;
1806
+ }
1807
+ }
1808
+ finally {
1809
+ // Recreate the edge indexes BEFORE synthesis (kind-keyed reads) and on
1810
+ // any error path. A crash before this line is healed by the next
1811
+ // DatabaseConnection open (schema.sql re-applies IF NOT EXISTS).
1812
+ if (bulkRefsActive) {
1813
+ const tRef = Date.now();
1814
+ await parallel.refIndexLoad.end();
1815
+ if (process.env.CODEGRAPH_SYNTH_TIMINGS)
1816
+ console.error(`[phase-timing] ref-index-recreate: ${Date.now() - tRef}ms`);
1817
+ }
1818
+ if (bulkEdgesActive) {
1819
+ const tIdx = Date.now();
1820
+ await parallel.bulkEdgeLoad.end();
1821
+ if (process.env.CODEGRAPH_SYNTH_TIMINGS)
1822
+ console.error(`[phase-timing] edge-index-recreate: ${Date.now() - tIdx}ms`);
1823
+ // The recreate just wrote every non-unique edge index into the WAL
1824
+ // (multi-GB at kernel scale) with the pool idle — fold before the
1825
+ // synthesis passes pin readers against it for minutes.
1826
+ const bp = parallel?.backpressure?.();
1827
+ if (bp)
1828
+ await bp;
1829
+ }
1830
+ }
1831
+ // Dynamic-edge synthesis: now that all base `calls` edges are persisted,
1832
+ // synthesize observer/callback dispatch edges (dispatcher → registered
1833
+ // callbacks) that static parsing leaves out. Best-effort — never fail the
1834
+ // index on it. The pool (when it survived resolution) is REUSED to fan the
1835
+ // independent passes across its read-only workers — that's why its destroy
1836
+ // lives in the finally below, after synthesis, not at the end of the batch
1837
+ // loop. See docs/design/callback-edge-synthesis.md.
1838
+ const tSynth = Date.now();
1839
+ try {
1840
+ aggregateStats.byMethod['callback-synthesis'] = await (0, callback_synthesizer_1.synthesizeCallbackEdges)(this.queries, this.context, onSynthesisProgress, pool, parallel?.backpressure);
1841
+ }
1842
+ catch {
1843
+ // synthesis is additive and optional; ignore failures
1844
+ }
1845
+ if (process.env.CODEGRAPH_SYNTH_TIMINGS)
1846
+ console.error(`[phase-timing] callback-synthesis: ${Date.now() - tSynth}ms`);
1847
+ }
1848
+ finally {
1849
+ if (pool)
1850
+ await pool.destroy().catch(() => undefined);
1256
1851
  }
1257
- catch {
1258
- // synthesis is additive and optional; ignore failures
1852
+ if (loopProf) {
1853
+ const parts = Object.entries(loopProf).map(([k, v]) => `${k}=${(v / 1000).toFixed(1)}s`).join(' ');
1854
+ console.error(`[resolve-profile] loop-stages ${parts}`);
1259
1855
  }
1856
+ this.dumpResolveProfile('main');
1260
1857
  return {
1261
1858
  resolved: [],
1262
1859
  unresolved: [],