Skip to content

Session Module

The notebook front door. dvma.launch(settings) starts the whole logger — acquisition bridge, native compute engine, session journal and embedded web UI — on a background thread inside the calling kernel, and returns a Session handle for pulling data out, pushing data back, and changing the open app's acquisition settings (Session.apply_settings). It is the successor to the removed dvma.Logger.

The server process, not the browser tab, owns the session document, so closing the tab loses nothing: reopen the URL and the app offers the session back.

Launching a Session

launch

launch(settings=None, open_browser=True, port=0, ui_dir=None, session_dir=None, recover=True, *, window=_UNSET, tf_averaging=_UNSET, save_dir=None)

Start a pydvma session and return its Session handle.

Runs the same server as pydvma-serve — acquisition bridge, native /engine compute host, session journal, embedded UI — on a daemon thread with its own event loop inside the calling process, so this works unchanged from a plain script and from inside Jupyter (whose kernel already runs an asyncio loop of its own).

The default port=0 takes an ephemeral port, so several sessions can run side by side; read the one actually bound from Session.url. Printing that URL is how a session announces itself, matching pydvma-serve's startup line.

Parameters:

  • settings (MySettings or None, default: None ) –

    acquisition settings the app opens with. Prefills Setup via /config (see _settings_to_config_json) and supplies the default acquisition driver; None prefills nothing and leaves the driver at 'auto' — a capture that names no device then records from the OS default input soundcard when there is one, else the mock generator (see pydvma.serve.resolve_default_device).

  • open_browser (bool, default: True ) –

    open the app in a browser tab (default True). Pass False for a headless or scripted launch — the URL is still printed and on Session.url.

  • port (int, default: 0 ) –

    TCP port to bind, or 0 (default) for an ephemeral one.

  • ui_dir (str or Path or None, default: None ) –

    built UI directory to serve. None (default) resolves exactly as pydvma-serve does — the dev checkout's webui/dist if present, else the copy packaged in the wheel, else no UI at all (the bridge still serves, with a help page).

  • session_dir (Path or str or None, default: None ) –

    where the journal's spill file lives and previous-run sessions are recovered from. Passed through to pydvma.serve.BridgeServer; None means the system temp dir. Tests and advanced users point this at a directory they control.

  • recover (bool, default: True ) –

    offer a previous run's spill file for recovery in the app (default True). Passed through to pydvma.serve.BridgeServer; False skips the startup scan entirely.

  • window (str or None, default: _UNSET ) –

    analysis window the app gives new data sets on both the Frequency and TF cards, as in Session.apply_settings. Omit for the app's own default.

  • tf_averaging (str, default: _UNSET ) –

    TF averaging mode for new data sets, as in Session.apply_settings. Omit for the app's own default.

  • save_dir (str or Path or None, default: None ) –

    the app's starting working folder, where Save and Load open. None (default) is the current working directory, which in Jupyter is the notebook's own folder, so saved files sit beside the notebook. The app's folder pill changes it; read it back with Session.save_dir.

Returns:

  • session ( Session ) –

    The handle for the running server. Its url is the address actually bound. Change the settings later with Session.apply_settings.

Raises:

  • ValueError –

    An unknown window or tf_averaging, or a save_dir that is not an existing folder.

  • ImportError –

    The optional server dependencies are missing; the message names pip install pydvma[serve].

  • RuntimeError –

    The server did not bind within STARTUP_TIMEOUT_S. It is chained to the underlying error when there was one (an OSError when an explicit port is already taken).

The Session Handle

Session

Session(server, thread, loop, url)

Bases: object

A running pydvma session: the served app plus its data.

Returned by launch; not constructed directly. Usable as a context manager, which closes the server on exit.

Parameters:

  • server (BridgeServer) –

    the running server, whose pydvma.serve.BridgeServer.journal holds the authoritative session document.

  • thread (Thread) –

    the daemon thread running it.

  • loop (AbstractEventLoop) –

    that thread's event loop.

  • url (str) –

    where the app is served, with a trailing slash.

Attributes:

  • url (str) –

    where the app is served (e.g. 'http://127.0.0.1:8760/') — hand it to a browser on another window, or re-open it after closing the tab; the session document survives (that is what the journal is for).

Attributes

url instance-attribute
url = url
save_dir property writable
save_dir

The app's working folder, where Save and Load open.

Starts as launch's save_dir (by default the notebook's folder) and follows the folder pill in the app, so after a save dvma.load_data(session.save_dir / name) finds the file.

Returns:

  • save_dir ( Path ) –

    the absolute folder path.

data property
data

The session's data as a fresh DataSet (read-only view).

Materialised from the journal on EVERY access: the posted session document, with any captures logged since that post merged in by _merge_dataset. Nothing here is shared with the app or the engine — mutating what you pull changes nothing until you push it back, and the ids carried through the container round-trip are what make that push land in place.

Still readable after close: pulling your data out of a session you have finished with is the point of the explicit handoff, and the journal outlives the server thread that fed it.

Returns:

  • dataset ( DataSet ) –

    A new DataSet built from the journal on this access: the posted session document plus any captures logged since it was posted. Empty when the session has no document and no pending captures yet.

Methods:

push
push(data)

Hand data to the session; connected apps offer to reload.

Merges into the CURRENT session data (data) rather than replacing it, by _merge_dataset's id rule — so pushing back something you pulled and edited updates that item in place, while genuinely new items append.

The merge replaces a matched item WHOLE, so what you push is what is stored — including the app-side display state a pulled item carries invisibly (channel labels, per-set analysis settings: the manifest keys pydvma.container stashes as _container_extra rather than dropping). Pull → modify → push therefore preserves it; pushing a NEWLY built item in place of a stored one legitimately replaces that state with nothing, and the app re-seeds its defaults on reload.

The read-merge-write cycle is guarded by the journal's generation counter, so nothing is lost to a race: if a capture lands, or the app's autosave posts, between the read and the write, the post is REFUSED and this retries from a fresh read (up to PUSH_MAX_ATTEMPTS times). Two concurrent pushes therefore serialise — one wins, the other re-merges on top of the winner's document — instead of one silently overwriting the other.

Parameters:

  • data (pydvma.datastructure.DataSet or a single data item) –

    what to hand over. Anything that is not already a DataSet is wrapped in one, so a lone pydvma.datastructure.TimeData (or any other item DataSet.add_to_dataset accepts, or a homogeneous list of them) works directly.

Raises:

  • TypeError –

    data is neither a DataSet nor something DataSet.add_to_dataset recognises (which would otherwise post an unchanged document and look like success).

  • RuntimeError –

    The session is closed, or the journal kept changing under every one of the PUSH_MAX_ATTEMPTS attempts.

apply_settings
apply_settings(settings=None, *, window=_UNSET, tf_averaging=_UNSET)

Change the acquisition settings of the app that is already open.

Every connected app tab applies settings to Setup and to the Acquire trigger exactly as it applies the launch settings at start-up, and shows a toast saying they came from the notebook. The served /config is replaced too, so a tab opened or reloaded later starts from these settings; with no tab open the call says so and the settings apply when one opens. Prints a one-line confirmation::

logger settings: 3000 Hz, 2 ch, 6 s, trigger armed on ch 0 at 0.25 V (applied in 1 app tab)

The settings replace the previous ones whole: a setting that is None CLEARS that setting in the app rather than leaving it. pretrig_samples=None (the MySettings default) disarms the trigger, so moving from hammer settings back to a noise capture needs no extra step, and pretrig_threshold=None (also the default) is 5 % of the input's full scale, as in the app.

Nothing changes while a capture is in progress — logging, armed and waiting for its trigger, or a Nonlin run between its captures: the call raises and the app is left as it was. Let the capture finish, or press Stop, and run it again.

A change that needs the live stream reopened (sample rate, channels, device, NI range) takes effect the way a Setup edit does: at the next capture, or when the live monitor is next started.

Parameters:

  • settings (MySettings or None, default: None ) –

    the new acquisition settings. None keeps the current ones, for a change of window or tf_averaging alone.

  • window (str or None, default: _UNSET ) –

    analysis window for both the Frequency and TF cards: one of APP_WINDOWS, or None for no window (pydvma's usual spelling). Applies to the captures taken from now on, and to loaded data that records no analysis settings (a file written from Python). Data already in the app keeps its own, and so does a file saved from the app, which records its settings and reopens exactly as saved. Omit to leave the app's choice (it starts at 'hann').

  • tf_averaging (str, default: _UNSET ) –

    TF averaging, applied like window: 'within' (frames within each capture, for noise), 'across' (one average over the sets that are on 'across', for repeated hammer hits; a set on another mode is never pulled in) or 'none'. Omit to leave the app's choice (it starts at 'within').

Raises:

  • RuntimeError –

    The session is closed; a capture is in progress (nothing was changed); or a tab refused the change (the message gives its reason).

  • ValueError –

    An unknown window or tf_averaging.

close
close()

Stop the server and its thread. Idempotent and thread-safe.

A second call — from this thread or another — is a clean no-op rather than a second stop injected into a shutdown already in progress. Prints a WARNING if the thread has not finished within SHUTDOWN_TIMEOUT_S, in which case the port may still be bound; the thread is a daemon, so it cannot keep the interpreter alive either way.

data keeps working afterwards (the journal is plain memory); push does not, since there is no longer an app to notify.

The Session Journal

The server-side store behind Session.data and Session.push. Held by pydvma.serve.BridgeServer; the browser app reads and writes it over the /engine socket. Normally used through Session rather than directly.

SessionJournal

SessionJournal(spill_path=None)

Bases: object

In-memory session document + pending captures + listeners.

Parameters:

  • spill_path (Path or str or None, default: None ) –

    file to mirror the current document into on every update (best-effort; errors are swallowed). None disables spilling; it can be set later with set_spill_path (a server on an ephemeral port only knows its identity after binding).

Attributes

generation property
generation

How many writes this journal has accepted (read-only).

Starts at 0 and increments on every accepted set_doc and every add_capture — see the module docstring. A refused set_doc does not increment it. Read it through state when the value must match the data you read; this property is for tests and diagnostics, where a bare counter is enough.

Returns:

  • generation ( int ) –

    The number of accepted writes so far.

spill_path property
spill_path

Where the document is mirrored (read-only).

Returns:

  • spill_path ( Path or str or None ) –

    The spill file, as it was set, or None when spilling is disabled.

spill_failures property
spill_failures

How many spills failed end-to-end and were swallowed (read-only).

Counts every _spill that had a document and a path but could not land it on disk — temp-file creation, the write, or an os.replace still failing after _replace_with_retry's whole ladder. A non-zero count means the spill file may be STALE relative to state; the next successful spill overwrites it, but nothing rewinds this counter. Disabled spilling (no path) and empty journals do not count — those are no-ops, not failures.

Returns:

  • spill_failures ( int ) –

    The number of failed spills since construction.

Methods:

set_doc
set_doc(doc_bytes, notify=False, expect_generation=None)

Replace the session document (and clear pending captures).

Only the captures this document PROVABLY contains are cleared: the document's unique_id set is read from its manifest (pydvma.container.manifest_ids) and a pending capture is dropped only when its own ids are a subset of it, so a capture that landed after the poster serialised its document — or one belonging to a different tab — survives the post and is still offered on the next state. A capture with no readable ids is cleared by any post (see the module docstring's clears-pending contract).

A refused post (expect_generation supplied and no longer matching) does NOTHING: the document is untouched, pending captures are untouched, no spill is written and no listener fires. Callers that pass expect_generation must handle the False by re-reading state and re-merging (see pydvma.session.Session.push).

Parameters:

  • doc_bytes (bytes, bytearray, or memoryview) –

    the full session document (the same bytes written to a .dvma file).

  • notify (bool, default: False ) –

    also call every registered listener after the replace. Used by pydvma.session.Session.push so connected apps reload; the app's own autosave posts use the default False (silent — the app already has what it just posted).

  • expect_generation (int or None, default: None ) –

    the generation this document was built from. When given, the post is refused unless the journal is still at that generation, so a capture or another writer's post that landed in between can never be silently overwritten (see the module docstring). None (the default) posts unconditionally — right for a writer that owns the whole document already.

Returns:

  • written ( bool ) –

    True when the document was written; False only when expect_generation was given and no longer matches.

add_capture
add_capture(dvma_bytes)

Register one capture's .dvma bytes, pending until a document containing it is posted (module docstring's contract).

The capture's identity — its TimeData unique_ids, read from the manifest by pydvma.container.manifest_ids and stored beside the bytes — is what a later set_doc matches against to decide whether that document already holds this capture. Reading it here, once, keeps the cost off every subsequent post.

This does NOT touch the spill file — the spill mirrors only the posted document (see the module docstring), so a capture registered here is absent from the crash artifact until the app's next autosave lands.

If appending pushes the pending list's total size over PENDING_CAPTURES_MAX_BYTES, the OLDEST pending entries are evicted until the total is back under the cap or only the entry just appended is left: the newest capture is never evicted, so one that alone exceeds the whole budget stays pending (alone). Any eviction is logged at WARNING with the bytes evicted, the bytes still held and the budget. See the module docstring's "Pending-captures budget" paragraph — this only matters when nothing posts a clearing document.

Parameters:

  • dvma_bytes (bytes, bytearray, or memoryview) –

    one capture's full .dvma bytes.

state
state()

Return a consistent snapshot of the journal.

The capture list is a fresh list of the capture BYTES (the per-capture id sets kept alongside them are the journal's own bookkeeping and never leave it), so mutating it never touches the journal. The document is returned by reference, but bytes is immutable so that is equivalent to a copy for callers.

Returns:

  • doc ( bytes or None ) –

    The posted session document, or None if nothing has been posted yet.

  • captures ( list[bytes] ) –

    The .dvma bytes of each capture registered since the last post and not yet in a posted document, oldest first.

  • generation ( int ) –

    The generation this snapshot describes. Hand it back as set_doc's expect_generation to post an update that refuses to clobber anything that landed since.

stamped_state
stamped_state()

Return a consistent snapshot of the journal with write times.

Everything state returns, plus when each part was written, all read under one lock so the times describe exactly the data beside them. Times are wall-clock seconds since the epoch (time.time()) — on the serving machine, which for the served app is the browser's machine too, so the app can compare them with its own Date.now() autosave timestamp.

Returns:

  • snapshot ( dict ) –

    doc (bytes or None) and doc_saved_at (when it was posted, or None); captures (list of bytes, oldest first, as state returns them) and captures_saved_at (each one's registration time, in the same order); generation (int, as state); recovered (bytes or None, as recovered) and recovered_saved_at (the adopted spill file's modification time, or None).

add_listener
add_listener(cb)

Register a zero-arg callable invoked on notify updates.

Listener exceptions are swallowed (one broken listener must not silence the rest). An update already in flight when unsubscribe() returns may still call cb once more — set_doc snapshots the listener list before releasing the lock, so a race between an in-progress notify and a concurrent unsubscribe is possible; consumers must tolerate one extra call.

Parameters:

  • cb (callable) –

    zero-argument callable to invoke on every notify=True update, until unsubscribed.

Returns:

  • unsubscribe ( callable ) –

    A zero-argument function that removes cb; calling it more than once is harmless.

set_spill_path
set_spill_path(path)

Set (or move) the spill target after construction — BridgeServer only knows its real port after binding.

Parameters:

  • path (Path or str or None) –

    file to mirror the current document into on every update, or None to disable spilling.

adopt_recovered
adopt_recovered(path)

Read a PREVIOUS run's spill file into memory as a recovery offer. Reading now — not at offer time — makes a later overwrite of the same path harmless. A missing or unreadable file is a no-op, as is an empty one.

Parameters:

  • path (Path or str) –

    the previous run's spill file to read.

Returns:

  • adopted ( bool ) –

    True if path was actually adopted (readable and non-empty), False on the no-op paths above. Callers that try several candidates in order (see pydvma.serve._adopt_previous_session) use this to know whether to keep trying the next one, rather than checking recovered for a change.

recovered
recovered()

Return the recovery offer adopted by adopt_recovered.

Returns:

  • doc ( bytes or None ) –

    The previous run's document bytes, or None when nothing was adopted or the offer was discarded.

discard_recovered
discard_recovered()

Drop the recovery offer and delete its file (the app's Dismiss).

Skips the delete when the recovered file IS the current spill target — a same-port restart adopts what is now its own live spill file, and deleting it would remove the live mirror, not just the stale offer. The comparison is normalised through os.path.abspath on both sides so a str spill path and a pathlib.Path recovered path (or vice versa) still compare equal when they name the same file. Best-effort on the delete; idempotent.

The Working Folder

Where the served app saves and loads by default: the folder the server started in, which for dvma.launch is the notebook's own folder. Held by pydvma.serve.BridgeServer; the app reads, lists and writes it over the /engine socket, and Session.save_dir reads and sets it from the notebook.

SaveFolder

SaveFolder(path=None)

The folder the served web logger saves into, and its file operations.

Thread-safe: the folder can be read and changed from any /engine connection (one per open tab) and from the notebook, via pydvma.session.Session.save_dir.

Parameters:

  • path (str or Path or None, default: None ) –

    the starting folder; None uses the current working directory, which for pydvma.launch is the notebook's folder. It must exist.

Raises:

  • ValueError –

    path is not an existing folder.

Attributes

path property
path

The current folder, as an absolute pathlib.Path.

Methods:

info
info()

The current folder as a dict for the app.

Returns:

  • info ( dict ) –

    dir (absolute path), name (its last part, or the whole path at a drive or filesystem root) and sep (this system's path separator).

set_dir
set_dir(path)

Make path the folder saves go to.

Parameters:

  • path (str or Path) –

    an existing folder, absolute or relative to the current one; ~ is expanded.

Returns:

  • info ( dict ) –

    info for the new folder.

Raises:

  • ValueError –

    path is not an existing folder.

listing
listing(path=None)

What the folder chooser shows for path.

Parameters:

  • path (str or Path or None, default: None ) –

    the folder to list, absolute or relative to the current one; None lists the current folder. Listing does not change the save folder.

Returns:

  • listing ( dict ) –

    dir (absolute path listed), parent (its parent, or None at a root), folders (subfolder names, hidden ones left out) and files (names of the loadable data files there, LISTED_EXTENSIONS), both sorted case-insensitively.

Raises:

  • ValueError –

    path is not a folder, or cannot be read.

save
save(name, data, overwrite=False)

Write data as name in the folder.

The write is atomic (a temporary file in the same folder, then a replace), so a failed save never leaves a truncated file behind. An existing file is replaced only with overwrite=True; otherwise nothing is written and the result says the file exists, so the app can ask first.

Parameters:

  • name (str) –

    file name, or a path relative to the folder (its parent folders must exist), or an absolute path. Must end in one of SAVE_EXTENSIONS.

  • data (bytes) –

    the file's contents.

  • overwrite (bool, default: False ) –

    replace an existing file.

Returns:

  • result ( dict ) –

    path (absolute path), saved (whether it was written) and exists (whether a file was already there).

Raises:

  • ValueError –

    a bad name or type, a missing parent folder, or a write the system refused (the message says why).

read
read(path)

Read a data file for the app's Load Data.

Parameters:

  • path (str or Path) –

    the file, absolute or relative to the folder. Must be one of LISTED_EXTENSIONS, the files the app can load; nothing else is read.

Returns:

  • result ( dict ) –

    name (the file name), path (absolute path) and data (its bytes).

Raises:

  • ValueError –

    not a loadable file type, not a file, or unreadable.

is_local_app_request

is_local_app_request(origin, host)

Whether a websocket request comes from the served app itself.

True only when the browser's Origin header names the same scheme-less host and port the request was sent to (Host), and that host is a loopback name. A page from any other site carries its own origin and is refused; a DNS-rebinding page (another site's name resolving to 127.0.0.1) passes the same-origin test but not the loopback one. A request with no Origin (not a browser) is refused too.

Parameters:

  • origin (str or None) –

    the request's Origin header.

  • host (str or None) –

    the request's Host header.

Returns:

  • allowed ( bool ) –

    True when file ops may be answered.