Skip to content
safran

Type to search. Enter opens the first result.

    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:

    scoped.ts
    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:

    server.ts
    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:

    1. Nothing new starts. From this moment every call on the instance fails.
    2. Running calls are cancelled. The instance has one internal signal that every call runs under; close() aborts it. Calls that were running end with ABORTED; a running repos.sync or links.refresh returns its report with aborted: true.
    3. 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.
    4. 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.

    close-cancels.ts
    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: false

    The 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:

    after-close.ts
    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:

    CodeSituationWhat to do
    ABORTEDThe 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.

    timeout.ts
    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 an AbortController, an AbortSignal.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's reason.
    • 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.sync and links.refresh always give you a report once they are past their argument checks; a cancelled run has aborted: true and marks the repos it did not finish as skipped, 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-expression grep (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:

    shared-index.ts
    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:

    tickets-only.ts
    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: falsebuiltinPlugins: false + tracker plugins
    Code callsUNSUPPORTED, at onceFail on first use: no embedder plugin is registered
    embeddings entry of the profileNot validatedNot validated
    repos.sync()Needs fetchOnly: trueThe profile has no code hosts, so there is nothing to sync
    Profile entries for code hosts and docsBuilt as usualFail 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:

    WhatRule
    repos.syncOne at a time per instance. A second call waits for the first.
    links.refresh and links.relinkOne at a time per instance, in the order they were called.
    Index writesOne 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

    SymptomCause
    The process does not exit after the work is doneAn instance was never closed. Use await using, or call close() in a finally.
    INVALID_INPUT: This Safran instance is closedA call after close(), often from a callback or timer that outlived the scope of an await using.
    ABORTED from calls during shutdownExpected: close() cancels what is running. Do not log it as an error.
    Catching an exception to detect a cancelled syncA cancelled sync returns. Check report.aborted.
    A shared index is closed while another instance uses itThe caller that created the index closes it, after every instance. Its calls fail with INDEX_NOT_READY otherwise.