---
title: "Runtime lifecycle"
canonical: https://docs.qvac.tether.io/sdk/v0.23/runtime/lifecycle/
collection: "SDK"
package: "@qvac/sdk"
line: v0.23
current_line: false
---

# Runtime lifecycle (/sdk/v0.23/runtime/lifecycle)



## Overview

While running, the SDK keeps live resources in the host process — Hyperswarm sockets, Corestore handles, RAG corestore, registered download streams, and a request gate above handler dispatch. When the host app moves to background (mobile suspend, desktop minimize, daemon hibernation), holding those resources open wastes battery and can break sockets that are torn down by the OS.

`suspend()` pauses those resources and engages a lifecycle gate so non-lifecycle operations fail fast instead of hanging. `resume()` restores them when the app returns to foreground. `state()` is the source of truth for the current runtime state — useful for branching app logic without shadow-tracking suspend/resume locally.

`suspend()`, `resume()`, and `state()` are themselves never blocked by the gate, and all three are idempotent.

## Functions

1. `suspend()` — call from the background handler
2. `state()` — read `"active" | "suspending" | "suspended" | "resuming"`
3. `resume()` — call from the foreground handler

For how to use each function, see [SDK — API reference](/sdk/v0.23/reference/api/).

## Lifecycle states

`state()` returns one of:

* `"active"` — all SDK operations are accepted normally
* `"suspending"` — `suspend()` is in progress; non-lifecycle operations are already blocked
* `"suspended"` — runtime is paused; only `suspend()`, `resume()`, `state()` are accepted
* `"resuming"` — `resume()` is in progress; non-lifecycle operations are still blocked

A partial `resume()` failure leaves the runtime in `"suspended"` (not `"active"`), so callers can retry `resume()` without leaking the failed state.

## Behavior while suspended

<Callout type="info">
  While runtime state is not `"active"`, only `suspend()`, `resume()`, and `state()` are accepted. Any other request fails fast with `LIFECYCLE_OPERATION_BLOCKED` instead of hanging.
</Callout>

In-flight operations started **before** `suspend()` follow the matrix below:

| Operation                                          | During suspend                       | After resume            |
| -------------------------------------------------- | ------------------------------------ | ----------------------- |
| P2P / Hyperdrive download                          | Stalls cleanly                       | Continues automatically |
| HTTP download                                      | Bypass — bytes keep flowing          | (Already flowing)       |
| Local native inference (e.g. `completion()`)       | Runs to completion                   | n/a                     |
| New operation (e.g. `completion()`, `loadModel()`) | Throws `LIFECYCLE_OPERATION_BLOCKED` | Accepted                |

## Example

The following script loads a model, runs a completion, suspends the runtime, demonstrates that a new `completion()` is blocked while suspended, then resumes and runs another completion. `state()` is sampled at each step:

<Tabs>
  <Tab value="js" label="JavaScript" default>
    <WrapCode>
      ```js file=<rootDir>/packages/sdk/dist/examples/suspend-resume.js title="runtime-lifecycle.js" lineNumbers
      import { loadModel, LLAMA_3_2_1B_INST_Q4_0, completion, unloadModel, suspend, resume, state } from '@qvac/sdk';
      try {
          // Load a model
          const modelId = await loadModel({
              modelSrc: LLAMA_3_2_1B_INST_Q4_0,
              onProgress: (p) => {
                  const mb = (n) => (n / 1e6).toFixed(1);
                  const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`;
                  process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`);
                  if (p.percentage >= 100)
                      process.stderr.write('\n');
              }
          });
          console.log('▸ Model loaded\n');
          console.log(`▸ Lifecycle state: ${await state()}\n`);
          // Run a completion before suspending
          console.log('▸ Completion before suspend');
          const result1 = completion({
              modelId,
              history: [{ role: 'user', content: 'Say hello in one word' }],
              stream: true
          });
          for await (const token of result1.tokenStream) {
              process.stdout.write(token);
          }
          console.log('');
          // Suspend all networking and storage (e.g. app going to background)
          console.log('▸ Suspending...');
          await suspend();
          console.log(`▸ Lifecycle state: ${await state()}\n`);
          try {
              await completion({
                  modelId,
                  history: [{ role: 'user', content: 'This should fail' }],
                  stream: false
              }).text;
          }
          catch (error) {
              const name = error.name;
              if (name === 'LIFECYCLE_OPERATION_BLOCKED') {
                  console.log(`▸ Operation blocked while suspended (${name})`);
              }
              else {
                  throw error;
              }
          }
          // Simulate time in background
          console.log('\n▸ Simulating 3 seconds in background...');
          await new Promise((resolve) => setTimeout(resolve, 3000));
          // Resume when returning to foreground
          console.log('▸ Resuming...');
          await resume();
          console.log(`▸ Lifecycle state: ${await state()}\n`);
          // Run another completion after resuming
          console.log('▸ Completion after resume');
          const result2 = completion({
              modelId,
              history: [{ role: 'user', content: 'Say goodbye in one word' }],
              stream: true
          });
          for await (const token of result2.tokenStream) {
              process.stdout.write(token);
          }
          console.log('');
          await unloadModel({ modelId });
          console.log('▸ Model unloaded');
          process.exit(0);
      }
      catch (error) {
          console.error('✖', error);
          process.exit(1);
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="ts" label="TypeScript">
    <WrapCode>
      ```ts file=<rootDir>/packages/sdk/examples/suspend-resume.ts title="runtime-lifecycle.ts" lineNumbers
      import {
        loadModel,
        LLAMA_3_2_1B_INST_Q4_0,
        completion,
        unloadModel,
        suspend,
        resume,
        state
      } from '@qvac/sdk'

      try {
        // Load a model
        const modelId = await loadModel({
          modelSrc: LLAMA_3_2_1B_INST_Q4_0,
          onProgress: (p) => {
            const mb = (n: number) => (n / 1e6).toFixed(1)
            const line = `▸ Downloading ${p.percentage.toFixed(0)}% (${mb(p.downloaded)}/${mb(p.total)} MB)`
            process.stderr.write(process.stderr.isTTY ? `\r${line}` : `${line}\n`)
            if (p.percentage >= 100) process.stderr.write('\n')
          }
        })

        console.log('▸ Model loaded\n')

        console.log(`▸ Lifecycle state: ${await state()}\n`)

        // Run a completion before suspending
        console.log('▸ Completion before suspend')
        const result1 = completion({
          modelId,
          history: [{ role: 'user', content: 'Say hello in one word' }],
          stream: true
        })
        for await (const token of result1.tokenStream) {
          process.stdout.write(token)
        }
        console.log('')

        // Suspend all networking and storage (e.g. app going to background)
        console.log('▸ Suspending...')
        await suspend()
        console.log(`▸ Lifecycle state: ${await state()}\n`)

        try {
          await completion({
            modelId,
            history: [{ role: 'user', content: 'This should fail' }],
            stream: false
          }).text
        } catch (error: unknown) {
          const name = (error as { name?: string }).name
          if (name === 'LIFECYCLE_OPERATION_BLOCKED') {
            console.log(`▸ Operation blocked while suspended (${name})`)
          } else {
            throw error
          }
        }

        // Simulate time in background
        console.log('\n▸ Simulating 3 seconds in background...')
        await new Promise((resolve) => setTimeout(resolve, 3000))

        // Resume when returning to foreground
        console.log('▸ Resuming...')
        await resume()
        console.log(`▸ Lifecycle state: ${await state()}\n`)

        // Run another completion after resuming
        console.log('▸ Completion after resume')
        const result2 = completion({
          modelId,
          history: [{ role: 'user', content: 'Say goodbye in one word' }],
          stream: true
        })
        for await (const token of result2.tokenStream) {
          process.stdout.write(token)
        }
        console.log('')

        await unloadModel({ modelId })
        console.log('▸ Model unloaded')
        process.exit(0)
      } catch (error) {
        console.error('✖', error)
        process.exit(1)
      }
      ```
    </WrapCode>
  </Tab>

  <Tab value="python" label="Python">
    <WrapCode>
      ```python file=<rootDir>/packages/sdk-python/examples/suspend_resume.py title="runtime_lifecycle.py" lineNumbers
      """Python port of packages/sdk/examples/suspend-resume.ts.

      Loads a model, runs a completion, suspends the runtime, shows that a new
      `completion()` is blocked while suspended, then resumes and runs another
      completion. `state()` is sampled at each step.

      Python calls the generated `suspend`, `resume` and `state` stubs, so each one
      takes its request model. `Client` closes the SDK on exit.

      RUN: python examples/suspend_resume.py
      """

      from __future__ import annotations

      import asyncio
      import sys

      from tetherto.qvac_sdk import (
          Client,
          ResumeRequest,
          StateRequest,
          SuspendRequest,
          completion,
          load_model,
          resume,
          state,
          suspend,
          unload_model,
      )
      from tetherto.qvac_sdk.models import LLAMA_3_2_1B_INST_Q4_0


      def print_progress(p) -> None:
          """Print model download progress; pass as `on_progress=` to `load_model`."""
          line = (
              f"▸ Downloading {p.percentage:.0f}% "
              f"({p.downloaded / 1e6:.1f}/{p.total / 1e6:.1f} MB)"
          )
          print(line, end="\r" if sys.stderr.isatty() else "\n", file=sys.stderr)
          if p.percentage >= 100:
              print(file=sys.stderr)


      async def lifecycle_state(t) -> str:
          return (await state(t, StateRequest())).state.value


      async def stream_completion(t, model_id: str, content: str) -> None:
          run = completion(
              t, model_id=model_id, history=[{"role": "user", "content": content}]
          )
          async for event in run.events:
              if event.type == "contentDelta":
                  sys.stdout.write(event.text)
                  sys.stdout.flush()
          print()


      async def main() -> int:
          async with Client() as client:
              t = client.transport
              try:
                  # Load a model
                  model_id = await load_model(
                      t, model_src=LLAMA_3_2_1B_INST_Q4_0, on_progress=print_progress
                  )

                  print("▸ Model loaded\n")

                  print(f"▸ Lifecycle state: {await lifecycle_state(t)}\n")

                  # Run a completion before suspending
                  print("▸ Completion before suspend")
                  await stream_completion(t, model_id, "Say hello in one word")

                  # Suspend all networking and storage (e.g. app going to background)
                  print("▸ Suspending...")
                  await suspend(t, SuspendRequest())
                  print(f"▸ Lifecycle state: {await lifecycle_state(t)}\n")

                  try:
                      await completion(
                          t,
                          model_id=model_id,
                          history=[{"role": "user", "content": "This should fail"}],
                          stream=False,
                      ).text()
                  except Exception as error:
                      name = getattr(error, "name", None)
                      if name == "LIFECYCLE_OPERATION_BLOCKED":
                          print(f"▸ Operation blocked while suspended ({name})")
                      else:
                          raise

                  # Simulate time in background
                  print("\n▸ Simulating 3 seconds in background...")
                  await asyncio.sleep(3)

                  # Resume when returning to foreground
                  print("▸ Resuming...")
                  await resume(t, ResumeRequest())
                  print(f"▸ Lifecycle state: {await lifecycle_state(t)}\n")

                  # Run another completion after resuming
                  print("▸ Completion after resume")
                  await stream_completion(t, model_id, "Say goodbye in one word")

                  await unload_model(t, model_id)
                  print("▸ Model unloaded")
              except Exception as error:
                  print(f"✖ {error}", file=sys.stderr)
                  return 1
          return 0


      if __name__ == "__main__":
          sys.exit(asyncio.run(main()))
      ```
    </WrapCode>
  </Tab>

  <Tab value="kotlin" label="Kotlin">
    <WrapCode>
      ```kotlin file=<rootDir>/packages/sdk-kotlin/examples/src/SuspendResume.kt title="SuspendResume.kt" lineNumbers
      // Kotlin port of packages/sdk/examples/suspend-resume.ts.
      //
      // Loads a model, runs a completion, suspends the runtime, shows that a new
      // completion is blocked while suspended, then resumes and runs another
      // completion. `client.system.state()` is sampled at each step.
      //
      // `client.system` wraps the lifecycle operations: `pause()` sends `suspend`
      // (`suspend` is a Kotlin keyword), `resume()` and `state()`. The lifecycle
      // state is the generated `StateResponseState` enum. Worker errors map onto the
      // typed `QvacKnownException` hierarchy, so the blocked call is caught by its
      // own class, `ServerLifecycleOperationBlocked`, instead of comparing names.
      //
      // RUN: ./gradlew -p examples run -Pexample=SuspendResume

      import io.tether.qvac.sdk.QvacClient
      import io.tether.qvac.sdk.QvacCompletionOptions
      import io.tether.qvac.sdk.QvacMessage
      import io.tether.qvac.sdk.QvacProgressEvent
      import io.tether.qvac.sdk.completion
      import io.tether.qvac.sdk.generated.ModelConstant
      import io.tether.qvac.sdk.generated.Models
      import io.tether.qvac.sdk.generated.QvacKnownException
      import io.tether.qvac.sdk.generated.schema.LoadModelResponse
      import io.tether.qvac.sdk.generated.schema.ModelProgressResponse
      import io.tether.qvac.sdk.jvm.JvmBareKitTransport
      import io.tether.qvac.sdk.models
      import io.tether.qvac.sdk.run
      import io.tether.qvac.sdk.system
      import kotlinx.coroutines.delay
      import kotlinx.coroutines.runBlocking

      fun main(): Unit = runBlocking {
          val client = QvacClient(JvmBareKitTransport.connect())
          try {
              // Load a model
              val modelId = client.loadWithProgress(Models.LLAMA_3_2_1B_INST_Q4_0)

              println("▸ Model loaded\n")

              println("▸ Lifecycle state: ${client.lifecycleState()}\n")

              // Run a completion before suspending
              println("▸ Completion before suspend")
              client.streamCompletion(modelId, "Say hello in one word")

              // Suspend all networking and storage (e.g. app going to background)
              println("▸ Suspending...")
              client.system.pause()
              println("▸ Lifecycle state: ${client.lifecycleState()}\n")

              try {
                  client.completion.run(
                      modelId = modelId,
                      history = listOf(QvacMessage.user("This should fail")),
                      options = QvacCompletionOptions(stream = false),
                  ).text()
              } catch (error: QvacKnownException.ServerLifecycleOperationBlocked) {
                  println("▸ Operation blocked while suspended (${error.errorName})")
              }

              // Simulate time in background
              println("\n▸ Simulating 3 seconds in background...")
              delay(3_000)

              // Resume when returning to foreground
              println("▸ Resuming...")
              client.system.resume()
              println("▸ Lifecycle state: ${client.lifecycleState()}\n")

              // Run another completion after resuming
              println("▸ Completion after resume")
              client.streamCompletion(modelId, "Say goodbye in one word")

              client.models.unload(modelId)
              println("▸ Model unloaded")
          } finally {
              client.close()
          }
      }

      /** The lifecycle state by its wire name: `active`, `suspending`, `suspended` or `resuming`. */
      private suspend fun QvacClient.lifecycleState(): String = system.state().state.name.lowercase()

      private suspend fun QvacClient.streamCompletion(modelId: String, content: String) {
          completion.run(modelId = modelId, history = listOf(QvacMessage.user(content))).tokens.collect { print(it) }
          println()
      }

      /** Load [model], printing download progress, and return its model id. */
      private suspend fun QvacClient.loadWithProgress(model: ModelConstant): String {
          var result: LoadModelResponse? = null
          models.loadWithProgress(model.src, model.engine, model.name).collect { event ->
              when (event) {
                  is QvacProgressEvent.Progress -> printProgress(event.value)
                  is QvacProgressEvent.Result -> result = event.value
              }
          }
          val loaded = checkNotNull(result) { "loadModel ended without a result" }
          return loaded.modelId ?: error(loaded.error ?: "loadModel failed")
      }

      private fun printProgress(p: ModelProgressResponse) {
          val line = "▸ Downloading %.0f%% (%.1f/%.1f MB)".format(p.percentage, p.downloaded / 1e6, p.total / 1e6)
          if (System.console() != null) System.err.print("\r$line") else System.err.println(line)
          if (p.percentage >= 100) System.err.println()
      }
      ```
    </WrapCode>
  </Tab>
</Tabs>

<Callout type="success">
  **Tip:** all examples throughout this documentation are self-contained and runnable. For instructions on how to run them, see the [JS/TS quickstart](/sdk/v0.23/js-ts-sdk#quickstart), the [Python quickstart](/sdk/v0.23/python-sdk#quickstart), or the [Kotlin quickstart](/sdk/v0.23/kotlin-sdk#quickstart).
</Callout>
