Repository navigation
Closed
Description
Based on the OCaml rewatch reimplementation from #8653, we can prototype integrating the compiler directly into the rewatch executable to avoid having to spawn a bsc binary for each compilation step.
@cristianoc fed the prompt below into Fable, and I fed the same one into Astra.
I'll post the responses we got as separate comments. These can serve as a basis for further discussion.
We are porting Rewatch to OCaml as a drop-in for the Rust version. Next I want to see whether in-process bsc is worth it: stop spawning a bsc process per module, and ideally stop writing cmj/cmt (and maybe cmi) to disk at all.
Do not implement yet. Think this through with me.
Context:
- A lot of build time is process creation and artifact I/O, not typechecking.
- Integration might be >2x. I want a dirty prototype that measures that, even if it is incorrect and single-threaded.
- The compiler has lots of global/shared mutable state (Clflags, Config.load_path, Env cache, Ident, Js_config, typechecker mutation, etc.). There are essentially no tests that reuse one compiler process across modules.
- Getting rid of global state is probably much easier than the Rewatch port, but only if we know what to reset/isolate.
- No multicore required for the prototype. Sequential in-process with no cm* writes may already be faster.
- A real compiler service / parallel-from-one-process comes later.
Please:
- Survey how bsc is invoked today (parse vs compile), what it reads/writes (ast, cmi, cmj, cmt, js), and which globals would leak across compilations.
- Propose the smallest prototype that can give a real speedup signal on stdlib + tests (or a real project). What can stay on disk? What must be in memory? What must be reset between modules?
- Argue whether that prototype is the right next step, or whether something else is better (reset-and-reuse API, keep writing cmi only, compiler service still spawning-free but still on disk, etc.).
- Explicitly list what is likely to go well, what is likely to go wrong, and how we would get fooled by a misleading benchmark.
- Recommend a concrete goal we could later implement with /goal.
Reacted by Cristiano Calcagno and woonki
Metadata
Metadata
Assignees
Labels
No labels
Activity
cknitt commentedon Sep 15, 2026
Fable: In-process bsc: survey, measurements, and prototype proposal
Date: 2026-09-09. Machine: Apple M2 Max, 12 cores, macOS. Compiler:
_build/default/compiler/bsc/rescript_compiler_main.exeat commit d90b96a. Build system: rewatch (Rust) viacli/rescript.js.Summary
Stop spawning a bsc process per module is worth prototyping. The premise needs one correction: process spawn dominates, artifact I/O does not. A bsc process costs about 7 ms before it does any work, roughly half of that in bsc's own static initialization. For the tests corpus, spawns account for ~9 s of a 10.7 s sequential build; the actual parse/typecheck/codegen work is ~2.4 s of CPU; artifact I/O is under 1 s.
Consequences:
1. Measurements
Every build was preceded by
rescript clean. Threads controlled withRAYON_NUM_THREADS. Spawn counts: two per source file (parse to.ast, then compile), interfaces included.Per-process cost (averages over 20-50 runs):
/usr/bin/truebsc -version(exits during arg parsing, after all static init)bsc -bs-ast, 414-line Stdlib_Array.res-bs-cmi-onlyfrom .ast, Stdlib_Arraybsc -bs-ast, 2650-line mario_game.res-bs-cmi-onlyfrom .ast, mario_gameDerived, tests corpus, 1 thread: 1318 spawns x 6.8 ms = ~9.0 s of 10.7 s wall. CPU: 10.0 s total minus 1318 x 5.8 ms = ~2.4 s of real compiler work. Remaining sys after spawns ~0.9 s: that is the upper bound on artifact I/O.
Artifact volume, tests build: ast 3.4 MB, cmi 2.0 MB, cmj 0.1 MB, cmt 11.9 MB, mjs 0.9 MB.
Parallel spawning is expensive on macOS: 12 threads burn 15.8 CPU-s for 10.0 CPU-s of sequential work (sys doubles under contention). Spawn cost also limits parallel scaling, not only sequential time.
2. How bsc is invoked today
Rewatch spawns bsc directly (
Command::new(bsc_path).current_dir(<package>/lib/bs).args(...)), cwd is the package build dir, arguments mostly relative.sh -cis used only forjs-post-build, not on the hot path.Example (tests/tests,
rescript compiler-args src/mario_game.res):Per module: parse step writes the binary
.ast(with a dependency header that rewatchdeps.rsreads as lines); compile step reads the.ast. Interfaces get their own parse and compile, run just before the implementation (compile.rscompile_one). Rewatch blake3-hashes the module's cmi before and after the compile; if unchanged, dependents are skipped (is_clean).Compile-step reads:
Env.Persistent_signature.loadhook, set toBs_cmi_load.load_cmi, which usesConfig_util.find_opt=Misc.find_in_path_uncapoverConfig.load_path: twoSys.file_existsprobes per directory per lookup, no cache..resiexists (-bs-read-cmi):Typemod.type_implementation_morecallsfind_in_path_uncapandEnv.read_signaturedirectly by filename, bypassing the hook.Js_cmj_load.load_unitref hook,Js_cmj_format.from_file.Compile-step writes:
Env.save_signature/Cmi_format.create_cmi ?check_exists: compares with the existing file and skips the write if unchanged.Cmt_format_persistence.save_cmt(native impl; the playground impl is a no-op). EmbedsSys.argv, cwd, load path, imports.Js_cmj_format.to_file ~check_exists: digest compare, skip if unchanged..mjs/.js(+.map) viaLam_compile_main.lambda_as_module; thenBuild_artifact.mark_staleon the.astif warnings fired (so rewatch re-shows them).Prior art for one-process reuse:
compiler/jsoo/jsoo_playground_main.ml. Itsreset_compileris: warning buffer,Experimental_features.reset,Warnings.reset_fatal,Env.reset_cache_toplevel(keeps loaded cmi structures), thenLam_compile_env.resetandRes_compmisc.initial_envper compile.3. Global state that would leak across compilations
Top-level mutable cells (
ref,Hashtbl.create, etc.): compiler/ml 124, common (Js_config) 27, ext 9, core 7, frontend 2, syntax 0, gentype 21.A. Command-line configuration, set by arg parsing, never reset
Clflags: include_dirs, open_modules, all_ppx, output_name, assume_no_mli, dont_record_crc_unit, binary_annotations, bs_gentype, color, dump_* flags, transparent_modules, no_assert_false.Js_config: all 27 refs (jsx_, source_map, no_export, cmi_only, cmj_only, force_cmi/cmj, syntax_only, binary_ast, as_pp, debug, directives, all_module_aliases, cross_module_inline, ...).Warnings.currentoptions (parse_optionsis cumulative),Config.load_path,Runtime_package.path,Ext_path.project_root,Js_packages_state.packages_info/make_runtime,Location.input_name,absname.Ast_config.process_strsetsJs_config.no_exportanddirectivesfrom@@config;implementation_map(namespace mlmap) setsJs_config.cmj_only := truepermanently.Lam_compile_env.resetalready resetsno_exportbecause the playground hit this.B. Per-unit caches that already reset on the existing path
Res_compmisc.init_path:Config.load_pathandEnv.reset_cache(clears persistent_structures, crc_units, imported_units, current_unit, decl tables).Res_compmisc.initial_env:Ident.reinit(stamp counter back to the post-predef level).Lam_compile_env.reset: cached cmj tables.Typemod.type_implementation_more:Cmt_format.clear,Delayed_checks.reset_delayed_checks;Ctype.init_defper definition.Warnings.reset/reset_fatal/has_warningsandLocation.input_name: reset only in the-bs-syntax-onlymulti-file loop inrescript_compiler_main.ml, not on the compile path.Translmod.export_identifiers/js_hoisted,Lambda_exitscounters,Js_source_map.current,Typedtree.idents,Printtypname tables,Builtin_attributesdeprecated tracking.If the Env persistent cache is kept across modules (playground style),
imported_unitsmust still be cleared per unit (it feeds the cmi crc list and cmt imports) whilecrc_unitsmust be kept, otherwise later cmi files carry missing crcs.Env.clear_importsis not exported today.C. Typechecker scratch state
Ctype (levels, univar_pairs, trace flags, ...), Typecore, Typetexp, Printtyp, Btype snapshot counters. Reset by their own happy paths; left dirty when an error exception escapes mid-phrase. Monotone counters (
Btype.new_id,Subst.new_id) are fine.D. Process-level state
cwd (rewatch runs each bsc in the package's
lib/bs), stdout/stderr,at_exitflush of the error formatter,exitcalls in error paths (Bsc_args.bad_arg, reprint paths).Ident stamps: today each process restarts stamps at the same level, so cmi files from different modules already share stamp ranges; this works because
Subst.signaturerenames bound idents oninclude/openand persistent module idents have stamp 0. In-process is the same. Serving signatures from memory instead of marshalled copies is different: type nodes are mutable (desc, levels, abbreviation memo) and would be physically shared across consumers. The playground does this, but for one unit at a time.4. Proposed prototype: batch replay mode
Smallest prototype with a real signal, no rewatch changes:
RESCRIPT_BSC_EXEat a shim that appendscwd \t argvto a log and execs the real bsc. Run rewatch withRAYON_NUM_THREADS=1so the log is a valid topological order.-bs-batch <file>inrescript_compiler_main.ml: for each line:Sys.chdir, reset all group-A refs to defaults (addJs_config.reset,Clflagsreset,Warnings.reset+reset_fatal+has_warnings := false,Experimental_features.reset, packages state, project root, runtime path), parse args with the existingBsc_argsparser, runprocess_file, catch exceptions, report, continue. All artifacts still on disk.Then, inside the same prototype, three flag-gated experiments of ~20 lines each:
-bs-no-bin-annotto measure the cmt share.reset_cache_toplevel+ evict the unit just written + clear imports) to measure cmi reload cost.What stays on disk in step 2: everything. What must be in memory: nothing yet. What must be reset: group A before each arg parse, group B is already handled, group C only matters after errors, group D via chdir and exception-instead-of-exit.
5. Alternatives considered
is_cleanmechanism.6. What will go well, what will go wrong, how a benchmark fools us
Likely to go well:
Persistent_signature.load,Js_cmj_load.load_unit) and compare-and-skip writers already exist.Likely to go wrong:
@@config, namespace mapcmj_only).exitcalls ending the batch.Warnings.parse_options; per-package differing-wlists.How a benchmark would fool us:
check_existsskips); only the artifact diff catches that.make libis stamp-driven andrescript buildis incremental; every timed run must follow a clean.7. Recommended /goal
Add a
-bs-batchreplay mode to bsc plus a bsc-logging shim. Deliver a clean-build table for runtime, belt, tests and one real project comparing batch replay, spawn replay, and rewatch at 1 and 12 threads, on macOS and Linux. Deliver a byte-level artifact diff against a normal build with every leaked global listed and reset. Then run the three flag experiments: no cmt, cached Env, in-memory cmi/cmj.Non-goals: no parallelism, no rewatch changes, no removal of artifact writes in the product path.
Assumption: the OCaml rewatch port is not in this repository; the prototype does not depend on it.
Appendix: housekeeping done during the study
make testinitially failed on stale untracked artifacts from an older compiler: two.rescopies undertests/tests/lib/and 725 gitignored.cm*/.astfiles undertests/build_tests/super_errors*/. Only those ignored files were deleted;make testthen passed (744 mocha tests).packages/@rescript/darwin-arm64/bin/bsc.exeandpackages/@rescript/runtime/lib/ocamlwere out of sync untilmake lib; onlymakerefreshes those copies.cknitt commentedon Sep 15, 2026
Astra
Yes—this is worth prototyping. I would start with sequential compiler reuse, then remove CMT output and move CMJ into memory. Keep CMI and AST files on disk initially.
That can answer the performance question without first solving mutable type-graph ownership. I would push back on two assumptions:
This is based on source inspection of both Rewatch implementations and the compiler. No code changed or benchmarks run.
1. What happens today
Compiler invocations
Both Rust Rewatch and the OCaml port still launch external
bscprocesses.For an ordinary module without an interface, a clean build generally has two compiler launches:
.resinto.ast..astinto compiler artifacts and JavaScript.With
.resi, there are generally four: parse and compile each source. Namespace.mlmapcompilation adds another job. PPX commands can launch additional processes during parsing.Parsing performs the external PPX and built-in frontend transformations before writing the AST. Compilation reads that transformed AST; it should not run those transformations again. Rewatch reads the AST dependency header to construct its graph.
The relevant paths are Rust parsing, OCaml compiler jobs, and compiler dispatch.
Artifact roles
.ast/.iast.cmi.cmj.cmt/.cmtiCMJ matters even with cross-module inlining disabled. It carries information used for arity, dependency effects/purity, package/import resolution, and hoisted exports, as well as optional inlineable code. See CMJ consumers.
There is also driver-side I/O: artifact publication into
lib/ocaml, source copies, and sometimes JS copies. Removing compiler writes alone does not remove all artifact traffic.Existing reuse support—and its limits
There is already some deliberate reuse machinery:
Res_compmisc.init_pathrebuilds the load path and callsEnv.reset_cache.initial_envcallsIdent.reinit.Lam_compile_env.resetclears backend dependency state.Translmod.transl_implementationclears exports and hoisted-function accumulation.See compiler initialization.
The playground also repeatedly compiles in one process. That is useful precedent, not evidence of arbitrary multi-package build safety: its reset retains persistent environments and it bypasses parts of native compilation. Its
reset_compilercomment promises more than the short reset establishes for this use case. See playground reset.2. State that needs isolation
The useful distinction is per-request configuration, disposable compilation state, and intentionally retained dependency data.
Clflags,Js_config, experimental features, warning optionsClflags.Envpersistent and lookup caches, imports/CRC bookkeepingEnvobjects just to obtain a faster number.has_warnings, delayed checks, CMT accumulation, diagnostic filename/source stateThere are concrete failure cases already visible:
syntax_onlyandbinary_astenabled.cmj_only, which could suppress the next module’s JS.-bs-read-cmican leak into a module without an interface.Warnings.resetdoes not itself clear every warning-related accumulator.For the first prototype, abort the entire build on the first compiler error. That avoids pretending to support recovery while still testing successful sequential reuse.
3. The smallest useful experiment
I would implement one experimental clean-build runner with staged modes, using the existing OCaml build plan and argument generation.
It should run parse jobs in-process, retain the current dependency graph construction, then execute namespace/interface/implementation jobs sequentially in dependency order. Extract a thin callable driver from the executable’s argument handling and dispatch; do not design a comprehensive compiler-service API yet.
Modes
Also measure the existing normally parallel Rust and OCaml builds. A–D explain the mechanism; those normal builds establish practical value.
Why D is the useful target
What stays on disk: sources/configuration, ASTs, CMIs, JS/maps, and prebuilt external dependencies.
What must be retained in memory: CMJ data for modules compiled during this build, including their package identity/path.
What does not need retaining: CMTs, typed trees, completed modules’ typing environments.
CMJ already has a replaceable loader,
Js_cmj_load.load_unit. Its producer has a concentrated write point inLam_compile_main.compile. These are promising seams.The store must honor load-path resolution and package identity. A global
module_name → CMJtable is insufficient when different packages expose the same name. For modules rebuilt in the experiment, forbid fallback to stale disk CMJs; allow disk reads only for explicitly external dependencies.CMT output already has
-bs-no-bin-annot. But the experimental driver must accommodate missing annotations: normal publication and freshness logic expect them in places. GenType workloads need a separate configuration retaining annotations, or explicit exclusion.Why keep CMI?
Removing CMI involves more than replacing the ordinary dependency loader:
Subst.for_savingand maintains import digests.Ident.reinitcomplicates retention of objects with local identifiers.The relevant boundaries are signature saving and implementation/interface checking.
If CMI later looks expensive, the next experiment should be serialized CMI bytes in memory, decoded into fresh objects, preserving existing persistence semantics. Direct live-signature sharing can come afterward.
4. Is something else a better next step?
A narrow reset-and-reuse boundary is part of this prototype. A comprehensive global-state refactor is not a prerequisite.
My preference:
A persistent worker process would also eliminate per-module launches, and could eventually provide crash isolation. But for an OCaml caller it adds a protocol and lifecycle management without being necessary to answer the first question. Keep it as an architectural option.
Batching parse invocations is a cheaper alternative—the CLI already permits multiple syntax-only inputs—but varying output arguments and file-level state still need care. It measures only part of the opportunity.
I would reject the prototype only if it starts growing into a general service, watch-mode redesign, or mutable-signature cache before producing B–D timings.
5. What should go well, what may go wrong
Likely to go well
Likely to go wrong
I would allow rough architecture and a restricted workload. I would not allow silently missing modules or wrong JS to count as a speedup.
How the benchmark could fool us
The main traps:
make testas one block, obscuring build changes with unrelated test execution.Reuse the existing benchmark methodology, but replace equal-process-count checks with equal logical-job checks.
Measure interleaved release builds in isolated trees, including startup and shutdown. Report:
Use stdlib + the compiled test project, and preferably the previously measured large real project. Distinguish rebuilding stdlib from consuming it prebuilt.
6. Recommended later
/goalSuccess is a trustworthy decision, not necessarily 2×. A large B improvement validates reuse; a large C/D improvement validates artifact work. A disappointing D result tells us whether CMI/AST costs justify another experiment.
The relationships inspected were parse-to-dependency extraction, interface-to-implementation checking, CMJ-to-backend behavior, and annotations-to-tooling/build bookkeeping. They support this staged approach; a complete reset inventory and safe retention of live compiler graphs remain unverified.
cknitt commentedon Oct 26, 2026
Implemented by #8864 (request-scoped compiler state, safe to run repeatedly and in parallel) and #8781 (OCaml rewatch compiles in-process on OCaml domains), both merged 2026-10-15. Not writing cmj/cmt to disk was rated second-order here and can get its own issue if still wanted.