Lifecycle, cancellation and concurrency
A Safran instance holds real resources once it is used: an open SQLite index, the links store, sometimes a child process. This page explains how to release them (await using, close()), what closing does to calls that are still running, how to cancel a single call, and what runs in parallel and what does not.
Closing an instance
Safran is an AsyncDisposable. Declare it with await using and it is closed when the scope ends, also when the scope ends with an exception:
import { createSafran } from "@safran/core";
async function titleOf(ref: string): Promise<string> {
await using safran = await createSafran();
const ticket = await safran.tickets.get(ref);
return ticket.title;
} // safran.close() has run here, whether get() returned or threw
console.log(await titleOf("PAY-1423"));A long-running program (a server, a watcher) keeps one instance and calls close() on shutdown:
import { createSafran } from "@safran/core";
const safran = await createSafran();
async function shutdown(): Promise<void> {
await safran.close();
process.exit(0);
}
process.once("SIGINT", () => void shutdown());
process.once("SIGTERM", () => void shutdown());
// … serve requests with `safran` …Create one instance and reuse it. Creation validates the whole profile and the first code call opens the index; doing that per request wastes both.
What close() does
In this order:
- Nothing new starts. From this moment every call on the instance fails.
- Running calls are cancelled. The instance has one internal signal that every call runs under;
close()aborts it. Calls that were running end withABORTED; a runningrepos.syncorlinks.refreshreturns its report withaborted: true. - It waits for them to settle, for at most 30 seconds (
DEFAULT_CLOSE_GRACE_MS). The bound exists so that a connector that ignores its signal cannot keep the process from exiting. - Handles are released. The index Safran opened itself is closed, then the links store. Nothing can open a handle afterwards: a call that was already past its start refuses to open the index or the store once closing has begun.
close() is idempotent: calling it again returns the same promise. It does not reject because a running call failed.
import { createSafran, defineProfile, isSafranError } from "@safran/core";
import { FakeCodeIndex } from "@safran/kit/testing";
// An index whose searches never finish on their own, standing in for a slow embedding server.
const index = new FakeCodeIndex();
index.hang = true;
const safran = await createSafran({ profile: defineProfile({ version: 1, company: "acme" }), index });
const pending = safran.code.search("refund policy").catch((error: unknown) => error);
await safran.close(); // cancels the search and waits for it to settle
const outcome = await pending;
console.log(isSafranError(outcome, "ABORTED") ? `search ended with ${outcome.code}: ${outcome.message}` : outcome);
console.log(`index closed by Safran: ${index.closed > 0}`);$ bun close-cancels.ts
search ended with ABORTED: The operation was cancelled
index closed by Safran: falseThe last line is the ownership rule at work: this index was passed in, so it is not Safran's to close (see sharing one index).
Calls after close
A closed instance cannot be reopened. Every call fails with INVALID_INPUT:
import { createSafran, defineProfile, isSafranError } from "@safran/core";
const safran = await createSafran({ profile: defineProfile({ version: 1, company: "acme" }), index: false });
await safran.close();
await safran.close(); // a second close is a no-op
try {
await safran.company.whoOwns({ repo: "payments-api" });
} catch (error) {
if (!isSafranError(error)) throw error;
console.log(error.code);
console.log(error.format());
}$ bun after-close.ts
INVALID_INPUT
This Safran instance is closed
→ A closed instance cannot be used again; create a new one.Asynchronous methods reject with this error; the synchronous ones (tickets.resolve, docs.canFetch, repos.warnings, company.teams, company.glossary, company.conventions, company.expand) throw it. The read-only properties (profile, dataDir, the connector maps) stay readable.
So there are two different errors around closing, and they mean different things:
| Code | Situation | What to do |
|---|---|---|
ABORTED | The call was running when close() came. | Nothing: the program is shutting down. |
INVALID_INPUT "This Safran instance is closed" | The call was made after close(). | A bug in the caller: something kept a reference past shutdown. |
Cancellation
Every asynchronous call accepts a signal. It is the last argument's signal field everywhere: CallOptions is { signal?: AbortSignal }, and every other options type (PageOptions, search options, SyncOptions, LinkRefreshOptions) extends it.
import { createSafran, defineProfile, isSafranError } from "@safran/core";
import { FakeCodeIndex } from "@safran/kit/testing";
const index = new FakeCodeIndex();
index.hang = true;
await using safran = await createSafran({ profile: defineProfile({ version: 1, company: "acme" }), index });
try {
await safran.code.search("refund policy", { signal: AbortSignal.timeout(200) });
} catch (error) {
if (!isSafranError(error, "ABORTED")) throw error;
console.log(`${error.code}: ${error.message}`);
}
// A signal that has already fired: the call does not start.
try {
await safran.code.grep("refund", { signal: AbortSignal.abort() });
} catch (error) {
if (!isSafranError(error, "ABORTED")) throw error;
console.log(`${error.code}: ${error.message}`);
}
// Batches report cancellation instead of throwing.
const report = await safran.repos.sync({ signal: AbortSignal.abort() });
console.log(report);$ bun timeout.ts
ABORTED: The operation was cancelled
ABORTED: The operation was cancelled
{
results: [],
durationMs: 0,
aborted: true,
}The rules:
- A cancelled call throws
ABORTED. That holds whether you aborted anAbortController, anAbortSignal.timeout()fired, or the instance closed. There is no separate timeout code; if you need to tell a timeout from a user's cancel, look at your own signal'sreason. - A signal that already fired stops the call before it reaches a connector. No request is made.
- The two batch calls return instead of throwing.
repos.syncandlinks.refreshalways give you a report once they are past their argument checks; a cancelled run hasaborted: trueand marks the repos it did not finish asskipped, so work that completed is not lost. See sync and refresh. - Cancellation reaches the work, not just the promise. The signal is passed to connectors (HTTP requests are aborted, a retry wait ends), to
git(the process is terminated), to the indexer (it stops at the next batch) and to a regular-expressiongrep(its process is killed). - Combine signals with
AbortSignal.any([userSignal, AbortSignal.timeout(30_000)])for "until the user cancels, but no longer than thirty seconds".
Per-request timeouts inside connectors are separate from your signal. The HTTP client gives every attempt 30 seconds by default and reports an expired one as UPSTREAM ("timed out"), because that is the service being slow, not you cancelling.
/** Options accepted by every async call that may hit the network or the disk. */
export interface CallOptions {
signal?: AbortSignal;
}defined in packages/kit/src/types.ts
Sharing one index
Opening the code index loads it; two instances over the same data directory would each open it. When you run several instances in one process (one per tenant profile, or one per request context with different credentials), open the index once and pass it to each:
import { createSafran, defineProfile } from "@safran/core";
import { FakeCodeIndex } from "@safran/kit/testing";
const index = new FakeCodeIndex({
files: { "payments-api": { "src/refund/policy.ts": "export class RefundPolicy {}\n" } },
});
const profile = defineProfile({ version: 1, company: "acme" });
{
await using first = await createSafran({ profile, index });
await using second = await createSafran({ profile, index });
console.log((await first.code.search("RefundPolicy")).hits.length, (await second.code.grep("RefundPolicy")).total);
}
// Both instances are closed; the index is still open and still yours.
console.log(index.closed, (await index.status()).repos.map((repo) => repo.name));
await index.close();$ bun shared-index.ts
1 1
0 [ "payments-api" ]The example uses the in-memory FakeCodeIndex so that it runs anywhere; the real one comes from createCodeIndex({ dir, embedder }) in @safran/codeindex. The ownership rule is the same for both:
- An index you pass in is yours.
close()on the instance leaves it open. Close it yourself, after the instances that use it. - The index Safran opens is Safran's. It is opened on the first code call and closed by
close(). - A full
repos.sync()removes repositories that no host lists any more only from an index Safran opened itself. An index you passed in may serve other instances with other repositories, so it is never pruned.
Ticket-only use
Nothing about tickets needs the code index or an embedding model. Ticket, docs, repo listing, links and company calls never open the index or build the embedder, so an instance that is only asked about tickets works with the default options, on a machine without an embedding server.
Two options make that explicit:
import { builtinPlugins, createSafran, isSafranError } from "@safran/core";
// 1. Keep every connector, turn code search off.
await using safran = await createSafran({ index: false });
console.log((await safran.tickets.get("PAY-1423")).title);
try {
await safran.code.search("refund");
} catch (error) {
if (!isSafranError(error, "UNSUPPORTED")) throw error;
console.log(error.message); // Code search is disabled for this Safran instance
}
// 2. Register tracker plugins only. The profile must then have no `code.hosts` and no `docs` entries.
const trackers = builtinPlugins.filter((plugin) => plugin.kind === "tracker");
await using minimal = await createSafran({ profile: "tickets.yaml", builtinPlugins: false, plugins: trackers });
console.log([...minimal.trackers.keys()]);index: false | builtinPlugins: false + tracker plugins | |
|---|---|---|
| Code calls | UNSUPPORTED, at once | Fail on first use: no embedder plugin is registered |
embeddings entry of the profile | Not validated | Not validated |
repos.sync() | Needs fetchOnly: true | The profile has no code hosts, so there is nothing to sync |
| Profile entries for code hosts and docs | Built as usual | Fail creation with PLUGIN_NOT_FOUND |
Use the first when the same profile also serves code search elsewhere. Use the second to ship a small tool whose profile only lists trackers.
Concurrency
Calls on one instance can be made concurrently; Promise.all over ticket reads or searches is fine. Three things are serialised on purpose:
| What | Rule |
|---|---|
repos.sync | One at a time per instance. A second call waits for the first. |
links.refresh and links.relink | One at a time per instance, in the order they were called. |
| Index writes | One repository is indexed at a time. Searches, greps and file reads keep working while an index run is in progress and see each batch as it is committed. |
A call that waits in one of these queues can still be cancelled: its signal takes it out of the queue without running it. A sync and a links refresh do not block each other.
Across processes, each cloned repository is guarded by a lock file, and the index and the links store are SQLite databases in WAL mode, so a CLI command and a running MCP server can read the same data directory at the same time. Two processes syncing the same repository do not wait for each other: the second reports it as skipped.
Common mistakes
| Symptom | Cause |
|---|---|
| The process does not exit after the work is done | An instance was never closed. Use await using, or call close() in a finally. |
INVALID_INPUT: This Safran instance is closed | A call after close(), often from a callback or timer that outlived the scope of an await using. |
ABORTED from calls during shutdown | Expected: close() cancels what is running. Do not log it as an error. |
Catching an exception to detect a cancelled sync | A cancelled sync returns. Check report.aborted. |
| A shared index is closed while another instance uses it | The caller that created the index closes it, after every instance. Its calls fail with INDEX_NOT_READY otherwise. |