Skip to content

Commit e81fd83

Browse files
gselzerclaude
andcommitted
Prebuild script environments for completion, not overlays
Completion now builds the environment a script declares, in the background, once its configuration has stayed the same for a while (ApposePythonEnvironments): waiting for a script running in it first, and replacing its worker, as the script's next run would. Completion then analyzes the script there, conda packages and environment files included; and the next run need not build it. So the dependency overlays are gone. Also, an environment is no longer rebuilt in place while a worker of its earlier configuration may still be running: ResidentWorker.release() says when its process has ended, which LazyEnvironment waits for; and files of an environment being built are not used. Workers are made in one place (ScriptEnvironment.worker). FIXME: unsaved scripts are named differently by completion and by runs from the script editor, so a run builds another environment. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 6b18ac0 commit e81fd83

13 files changed

Lines changed: 426 additions & 574 deletions

‎src/main/java/org/scijava/plugins/scripting/appose/python/ApposePythonScriptEngine.java‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -459,8 +459,7 @@ private ResidentWorker worker(final ScriptInfo info, final String script)
459459
throw scriptException(e.getMessage(), e);
460460
}
461461
if (env == null) throw noEnvironment();
462-
return workerService.worker(env.name, env.activate, env.config(),
463-
env::builder, ApposePythonScriptEngine::launch);
462+
return env.worker(workerService);
464463
}
465464

466465
/** Creates the service of a worker in the given (built) environment. */

‎src/main/java/org/scijava/plugins/scripting/appose/python/ScriptEnvironment.java‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,8 @@
4141
import org.apposed.appose.Appose;
4242
import org.apposed.appose.Builder;
4343
import org.scijava.plugins.scripting.appose.python._internal.InlineMetadata;
44+
import org.scijava.plugins.scripting.appose.python._internal.ResidentWorker;
45+
import org.scijava.plugins.scripting.appose.python._internal.ResidentWorkerService;
4446

4547
/**
4648
* The Appose environment a script declares: either inline, via a PEP 723
@@ -191,6 +193,18 @@ public String config() {
191193
return scheme + "\n" + content;
192194
}
193195

196+
/**
197+
* Gets the resident worker of this environment (see
198+
* {@link ResidentWorkerService#worker}), as scripts run it: replacing the
199+
* environment's worker of an earlier configuration, if any. The
200+
* environment is built by the worker's first task, or when asked (see
201+
* {@link ResidentWorker#environment()}).
202+
*/
203+
public ResidentWorker worker(final ResidentWorkerService workers) {
204+
return workers.worker(name, activate, config(), this::builder,
205+
ApposePythonScriptEngine::launch);
206+
}
207+
194208
/** Creates a builder for the environment. */
195209
Builder<?> builder() {
196210
final Builder<?> builder = Appose.content(content);

‎src/main/java/org/scijava/plugins/scripting/appose/python/_internal/LazyEnvironment.java‎

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,11 @@
3131

3232
import java.util.List;
3333
import java.util.Map;
34+
import java.util.Set;
35+
import java.util.concurrent.CompletableFuture;
3436
import java.util.concurrent.ConcurrentHashMap;
37+
import java.util.concurrent.ExecutionException;
38+
import java.util.concurrent.Future;
3539
import java.util.concurrent.CopyOnWriteArrayList;
3640

3741
import org.apposed.appose.BuildException;
@@ -45,6 +49,8 @@
4549
* Builds of environments with the same name are serialized, even across
4650
* instances, because they share a directory on disk: e.g. when the
4751
* environment's configuration changes while an older build is still running.
52+
* For the same reason, a build may wait for a worker of the environment's
53+
* earlier configuration to end, so as not to rebuild beneath it.
4854
* </p>
4955
*/
5056
public class LazyEnvironment {
@@ -53,9 +59,21 @@ public class LazyEnvironment {
5359
private static final Map<String, Object> BUILD_LOCKS =
5460
new ConcurrentHashMap<>();
5561

62+
/** The names of the environments being built now. */
63+
private static final Set<String> BUILDING = ConcurrentHashMap.newKeySet();
64+
65+
/**
66+
* Whether the named environment is being built now: if so, its files are
67+
* not to be used yet (e.g. its Python may exist before its packages do).
68+
*/
69+
public static boolean isBuilding(final String name) {
70+
return BUILDING.contains(name);
71+
}
72+
5673
private final String name;
5774
private final Builder<?> builder;
5875
private final String activate;
76+
private final Future<?> before;
5977
private final List<BuildListener> listeners = new CopyOnWriteArrayList<>();
6078

6179
private volatile Environment env;
@@ -66,7 +84,7 @@ public class LazyEnvironment {
6684
* @param builder Builder for the environment; built on first use.
6785
*/
6886
public LazyEnvironment(final String name, final Builder<?> builder) {
69-
this(name, builder, null);
87+
this(name, builder, null, CompletableFuture.completedFuture(null));
7088
}
7189

7290
/**
@@ -75,12 +93,15 @@ public LazyEnvironment(final String name, final Builder<?> builder) {
7593
* @param builder Builder for the environment; built on first use.
7694
* @param activate Name of the sub-environment to activate once built (e.g.
7795
* a pixi environment), or null to use the environment as built.
96+
* @param before What to wait for before building: e.g. the end of a worker
97+
* still using the environment's earlier configuration.
7898
*/
7999
public LazyEnvironment(final String name, final Builder<?> builder,
80-
final String activate)
100+
final String activate, final Future<?> before)
81101
{
82102
this.name = name;
83103
this.activate = activate;
104+
this.before = before;
84105
// Note: Subscribe once, here, and dispatch to the current listeners,
85106
// because builders accumulate subscribers with every call.
86107
this.builder = builder.name(name) //
@@ -111,7 +132,19 @@ public Environment get() throws BuildException {
111132
if (env != null) return env;
112133
synchronized (BUILD_LOCKS.computeIfAbsent(name, k -> new Object())) {
113134
if (env != null) return env;
135+
try {
136+
before.get();
137+
}
138+
catch (final InterruptedException exc) {
139+
Thread.currentThread().interrupt();
140+
throw new BuildException("Interrupted waiting to build " + name,
141+
exc);
142+
}
143+
catch (final ExecutionException exc) {
144+
// NB: Whatever it was could not be waited for: build anyway.
145+
}
114146
listeners.forEach(l -> l.buildStarted(name));
147+
BUILDING.add(name);
115148
try {
116149
final Environment built = builder.build();
117150
env = activate == null ? built : built.activate(activate);
@@ -120,6 +153,9 @@ public Environment get() throws BuildException {
120153
listeners.forEach(l -> l.buildFinished(name, exc));
121154
throw exc;
122155
}
156+
finally {
157+
BUILDING.remove(name);
158+
}
123159
listeners.forEach(l -> l.buildFinished(name, null));
124160
return env;
125161
}

‎src/main/java/org/scijava/plugins/scripting/appose/python/_internal/ResidentWorker.java‎

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,9 @@
3232
import java.io.IOException;
3333
import java.io.UncheckedIOException;
3434
import java.util.Map;
35+
import java.util.concurrent.CompletableFuture;
36+
import java.util.concurrent.ExecutorService;
37+
import java.util.concurrent.Executors;
3538
import java.util.concurrent.locks.Lock;
3639
import java.util.concurrent.locks.ReentrantLock;
3740
import java.util.function.Consumer;
@@ -61,6 +64,14 @@
6164
*/
6265
public class ResidentWorker implements AutoCloseable {
6366

67+
/** Where released workers are waited for, until their processes end. */
68+
private static final ExecutorService EXITS = Executors.newCachedThreadPool(
69+
r -> {
70+
final Thread t = new Thread(r, "appose-worker-exit");
71+
t.setDaemon(true);
72+
return t;
73+
});
74+
6475
private final LazyEnvironment environment;
6576
private final Function<Environment, Service> launcher;
6677
private final Lock exclusive = new ReentrantLock();
@@ -141,11 +152,23 @@ public synchronized boolean isAlive() {
141152
/**
142153
* Ends the worker process gently, letting pending tasks finish, and
143154
* releasing everything it holds. The environment stays built.
155+
*
156+
* @return When the process has ended (at once, if none was running): e.g.
157+
* so that its environment is not rebuilt while it still uses it.
144158
*/
145-
public synchronized void release() {
146-
if (service == null) return;
147-
service.close();
159+
public synchronized CompletableFuture<Void> release() {
160+
if (service == null) return CompletableFuture.completedFuture(null);
161+
final Service s = service;
162+
s.close();
148163
service = null;
164+
return CompletableFuture.runAsync(() -> {
165+
try {
166+
s.waitFor();
167+
}
168+
catch (final InterruptedException exc) {
169+
Thread.currentThread().interrupt();
170+
}
171+
}, EXITS);
149172
}
150173

151174
/** Ends the worker process immediately, interrupting any pending tasks. */

‎src/main/java/org/scijava/plugins/scripting/appose/python/_internal/ResidentWorkerService.java‎

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,8 @@
3333
import java.util.HashMap;
3434
import java.util.List;
3535
import java.util.Map;
36+
import java.util.Optional;
37+
import java.util.concurrent.CompletableFuture;
3638
import java.util.concurrent.CopyOnWriteArrayList;
3739
import java.util.function.Function;
3840
import java.util.function.Supplier;
@@ -76,6 +78,9 @@ public class ResidentWorkerService extends AbstractService implements
7678
/** Environments by name and activation, each with its configuration and worker. */
7779
private final Map<String, Entry> entries = new HashMap<>();
7880

81+
/** Whether the context was disposed: no more workers are made. */
82+
private boolean disposed;
83+
7984
/** Told about every environment's builds. */
8085
private final List<BuildListener> buildListeners =
8186
new CopyOnWriteArrayList<>();
@@ -104,12 +109,18 @@ public ResidentWorker worker(final String name, final String activate,
104109
final ResidentWorker stale;
105110
final ResidentWorker worker;
106111
final String key = key(name, activate);
112+
// NB: The environment is rebuilt in place: only once the stale worker,
113+
// still using it, has ended.
114+
final CompletableFuture<Void> staleEnded = new CompletableFuture<>();
107115
synchronized (entries) {
116+
if (disposed) {
117+
throw new IllegalStateException("The context was disposed");
118+
}
108119
final Entry entry = entries.get(key);
109120
if (entry != null && entry.config.equals(config)) return entry.worker;
110121
stale = entry == null ? null : entry.worker;
111122
final LazyEnvironment env = new LazyEnvironment(name, builder.get(),
112-
activate);
123+
activate, staleEnded);
113124
env.addBuildListener(SciJavaTasks.buildListener(taskService,
114125
statusService, log));
115126
env.addBuildListener(new BuildListener() {
@@ -124,7 +135,9 @@ public void buildFinished(final String envName, final Throwable error) {
124135
worker = new ResidentWorker(env, launcher);
125136
entries.put(key, new Entry(config, worker));
126137
}
127-
if (stale != null) stale.release();
138+
if (stale == null) staleEnded.complete(null);
139+
else stale.release().whenComplete((v, exc) -> staleEnded.complete(
140+
null));
128141
return worker;
129142
}
130143

@@ -158,6 +171,24 @@ public ResidentWorker find(final String name, final String activate,
158171
}
159172
}
160173

174+
/**
175+
* Gets the resident worker of the named environment with the given
176+
* activation, whatever its configuration: e.g. to wait, via its
177+
* {@link ResidentWorker#exclusive()} lock, for a script it runs before
178+
* replacing it.
179+
*
180+
* @param name Name of the environment.
181+
* @param activate Name of the activated sub-environment, or null for none.
182+
*/
183+
public Optional<ResidentWorker> current(final String name,
184+
final String activate)
185+
{
186+
synchronized (entries) {
187+
final Entry entry = entries.get(key(name, activate));
188+
return entry == null ? Optional.empty() : Optional.of(entry.worker);
189+
}
190+
}
191+
161192
/** The key of the named environment's worker with the given activation. */
162193
private static String key(final String name, final String activate) {
163194
return activate == null ? name : name + "\0" + activate;
@@ -187,6 +218,7 @@ public void dispose() {
187218
releaseAll();
188219
synchronized (entries) {
189220
entries.clear();
221+
disposed = true;
190222
}
191223
}
192224

‎src/main/java/org/scijava/plugins/scripting/appose/python/completion/ApposePythonDialect.java‎

Lines changed: 5 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,6 @@
4141
import net.imglib2.RandomAccessibleInterval;
4242

4343
import org.apposed.appose.NDArray;
44-
import org.apposed.appose.util.Environments;
4544
import org.scijava.code.lsp.Environment;
4645
import org.scijava.code.lsp.ScriptDialect;
4746
import org.scijava.plugin.Parameter;
@@ -51,9 +50,8 @@
5150
import org.scijava.script.ScriptLanguage;
5251

5352
/**
54-
* Describes how to turn Appose python scripts into plain python code, and
55-
* where they run (see {@link ApposePythonEnvironments}), searching the
56-
* packages they declare but that lacks, too (see {@link DependencyOverlays}).
53+
* Describes how to parse Appose python scripts into plain python code and
54+
* report the environment where they run
5755
*
5856
* @author Gabriel Selzer
5957
*/
@@ -71,14 +69,6 @@ public class ApposePythonDialect implements ScriptDialect {
7169

7270
private ApposePythonEnvironments environments;
7371

74-
/**
75-
* How long a script's dependencies must stay unchanged before packages
76-
* missing from its environment are installed for completion, in ms.
77-
*/
78-
private static final long OVERLAY_SETTLE = 1500;
79-
80-
private static DependencyOverlays overlays;
81-
8272
@Override
8373
public boolean supports(final ScriptLanguage language) {
8474
return language instanceof ApposePythonScriptLanguage;
@@ -93,12 +83,9 @@ public String languageId() {
9383
public Environment environment(final String text,
9484
final Optional<File> file)
9585
{
96-
// NB: As its #@script line, or its inline metadata, says; plus the
97-
// packages it declares but that environment lacks (installed for
98-
// completion only, see DependencyOverlays).
99-
final String path = file.map(File::getPath).orElse(null);
100-
return overlays().environment(text, path, environments().environment(
101-
text, path));
86+
// NB: As its #@script line, or its inline metadata, says.
87+
return environments().environment(text, file.map(File::getPath).orElse(
88+
null));
10289
}
10390

10491
@Override
@@ -158,19 +145,6 @@ static String parameterType(final Class<?> type) {
158145
return null;
159146
}
160147

161-
/**
162-
* Gets the overlays of packages scripts declare, but their environments
163-
* lack: one set, for all dialect instances (sessions).
164-
*/
165-
private static synchronized DependencyOverlays overlays() {
166-
if (overlays == null) {
167-
overlays = new DependencyOverlays(DependencyOverlays::install, new File(
168-
Environments.apposeEnvsDir(), "appose-python-completion-overlays"),
169-
OVERLAY_SETTLE, System::currentTimeMillis);
170-
}
171-
return overlays;
172-
}
173-
174148
/** Gets where scripts run, creating it on first use. */
175149
private synchronized ApposePythonEnvironments environments() {
176150
if (environments == null) {

0 commit comments

Comments
 (0)