Skip to content

Commit cd073e6

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 b9d633e commit cd073e6

13 files changed

Lines changed: 430 additions & 572 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
@@ -455,8 +455,7 @@ private ResidentWorker worker(final ScriptInfo info, final String script)
455455
throw scriptException(e.getMessage(), e);
456456
}
457457
if (env == null) throw noEnvironment();
458-
return workerService.worker(env.name, env.config(), env::builder,
459-
ApposePythonScriptEngine::launch);
458+
return env.worker(workerService);
460459
}
461460

462461
/** 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
@@ -174,6 +176,18 @@ public String config() {
174176
return scheme + "\n" + content;
175177
}
176178

179+
/**
180+
* Gets the resident worker of this environment (see
181+
* {@link ResidentWorkerService#worker}), as scripts run it: replacing the
182+
* environment's worker of an earlier configuration, if any. The
183+
* environment is built by the worker's first task, or when asked (see
184+
* {@link ResidentWorker#environment()}).
185+
*/
186+
public ResidentWorker worker(final ResidentWorkerService workers) {
187+
return workers.worker(name, config(), this::builder,
188+
ApposePythonScriptEngine::launch);
189+
}
190+
177191
/** Creates a builder for the environment. */
178192
Builder<?> builder() {
179193
final Builder<?> builder = Appose.content(content);

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

Lines changed: 47 additions & 0 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,8 +59,20 @@ 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;
75+
private final Future<?> before;
5876
private final List<BuildListener> listeners = new CopyOnWriteArrayList<>();
5977

6078
private volatile Environment env;
@@ -65,7 +83,21 @@ public class LazyEnvironment {
6583
* @param builder Builder for the environment; built on first use.
6684
*/
6785
public LazyEnvironment(final String name, final Builder<?> builder) {
86+
this(name, builder, CompletableFuture.completedFuture(null));
87+
}
88+
89+
/**
90+
* @param name Name of the environment, as reported to listeners, and as
91+
* given to the builder.
92+
* @param builder Builder for the environment; built on first use.
93+
* @param before What to wait for before building: e.g. the end of a worker
94+
* still using the environment's earlier configuration.
95+
*/
96+
public LazyEnvironment(final String name, final Builder<?> builder,
97+
final Future<?> before)
98+
{
6899
this.name = name;
100+
this.before = before;
69101
// Note: Subscribe once, here, and dispatch to the current listeners,
70102
// because builders accumulate subscribers with every call.
71103
this.builder = builder.name(name) //
@@ -96,14 +128,29 @@ public Environment get() throws BuildException {
96128
if (env != null) return env;
97129
synchronized (BUILD_LOCKS.computeIfAbsent(name, k -> new Object())) {
98130
if (env != null) return env;
131+
try {
132+
before.get();
133+
}
134+
catch (final InterruptedException exc) {
135+
Thread.currentThread().interrupt();
136+
throw new BuildException("Interrupted waiting to build " + name,
137+
exc);
138+
}
139+
catch (final ExecutionException exc) {
140+
// NB: Whatever it was could not be waited for: build anyway.
141+
}
99142
listeners.forEach(l -> l.buildStarted(name));
143+
BUILDING.add(name);
100144
try {
101145
env = builder.build();
102146
}
103147
catch (final BuildException | RuntimeException exc) {
104148
listeners.forEach(l -> l.buildFinished(name, exc));
105149
throw exc;
106150
}
151+
finally {
152+
BUILDING.remove(name);
153+
}
107154
listeners.forEach(l -> l.buildFinished(name, null));
108155
return env;
109156
}

‎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: 29 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, 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<>();
@@ -100,11 +105,18 @@ public ResidentWorker worker(final String name, final String config,
100105
{
101106
final ResidentWorker stale;
102107
final ResidentWorker worker;
108+
// NB: The environment is rebuilt in place: only once the stale worker,
109+
// still using it, has ended.
110+
final CompletableFuture<Void> staleEnded = new CompletableFuture<>();
103111
synchronized (entries) {
112+
if (disposed) {
113+
throw new IllegalStateException("The context was disposed");
114+
}
104115
final Entry entry = entries.get(name);
105116
if (entry != null && entry.config.equals(config)) return entry.worker;
106117
stale = entry == null ? null : entry.worker;
107-
final LazyEnvironment env = new LazyEnvironment(name, builder.get());
118+
final LazyEnvironment env = new LazyEnvironment(name, builder.get(),
119+
staleEnded);
108120
env.addBuildListener(SciJavaTasks.buildListener(taskService,
109121
statusService, log));
110122
env.addBuildListener(new BuildListener() {
@@ -119,7 +131,9 @@ public void buildFinished(final String envName, final Throwable error) {
119131
worker = new ResidentWorker(env, launcher);
120132
entries.put(name, new Entry(config, worker));
121133
}
122-
if (stale != null) stale.release();
134+
if (stale == null) staleEnded.complete(null);
135+
else stale.release().whenComplete((v, exc) -> staleEnded.complete(
136+
null));
123137
return worker;
124138
}
125139

@@ -148,6 +162,18 @@ public ResidentWorker find(final String name, final String config) {
148162
}
149163
}
150164

165+
/**
166+
* Gets the resident worker of the named environment, whatever its
167+
* configuration: e.g. to wait, via its {@link ResidentWorker#exclusive()}
168+
* lock, for a script it runs before replacing it.
169+
*/
170+
public Optional<ResidentWorker> current(final String name) {
171+
synchronized (entries) {
172+
final Entry entry = entries.get(name);
173+
return entry == null ? Optional.empty() : Optional.of(entry.worker);
174+
}
175+
}
176+
151177
/** Gets the current resident workers. */
152178
public List<ResidentWorker> workers() {
153179
final List<ResidentWorker> list = new ArrayList<>();
@@ -172,6 +198,7 @@ public void dispose() {
172198
releaseAll();
173199
synchronized (entries) {
174200
entries.clear();
201+
disposed = true;
175202
}
176203
}
177204

‎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)