Skip to content

sgnts.base.base

TSResourceSource dataclass

Bases: ParallelizeBase, TSSource


              flowchart TD
              sgnts.base.base.TSResourceSource[TSResourceSource]
              sgnts.base.base.TSSource[TSSource]
              sgnts.base.base._TSSource[_TSSource]

                              sgnts.base.base.TSSource --> sgnts.base.base.TSResourceSource
                                sgnts.base.base._TSSource --> sgnts.base.base.TSSource
                



              click sgnts.base.base.TSResourceSource href "" "sgnts.base.base.TSResourceSource"
              click sgnts.base.base.TSSource href "" "sgnts.base.base.TSSource"
              click sgnts.base.base._TSSource href "" "sgnts.base.base._TSSource"
            

Source class that is entirely data driven by an external resource.

This class uses ParallelizeBase to run data generation in a separate worker thread. Subclasses either implement the resource hook API (resource_open/resource_read, and optionally resource_gap_lag) to get reconnect handling, stream-continuity bookkeeping, and outage gap synthesis from the built-in worker loop -- or override the worker_process method entirely to define data generation themselves.

The worker communicates with the main thread via queues provided by ParallelizeBase. Data should be sent as (pad, buffer) tuples to the output queue using context.output_queue.put((pad, buf)).

Important: The worker runs on a bare instance in a separate process/thread, so hooks and worker_process cannot read instance attributes directly. Configuration reaches the worker through parameter extraction: keyword-only parameters on the hooks (or same-named worker_process parameters) are automatically supplied from the matching instance attributes at construction time.

Subclasses using the resource hook API should: 1. Implement resource_open(start, end) to open the resource and return a stream handle 2. Optionally override resource_read(stream) if one delivery is not simply next(stream); return {pad_name: [SeriesBuffer, ...]} 3. Optionally implement resource_setup() to create any worker-side bookkeeping attributes the hooks rely on 4. Optionally implement resource_gap_lag(pad_name) to bound outage gap synthesis using resource-specific latency knowledge 5. Declare any extra configuration the hooks need as keyword-only parameters on the hook signatures 6. Optionally deliver a zero-length data buffer on a pad ahead of its first real data to declare the pad's backend/dtype -- needed only when the first deliveries may be all gaps (e.g. a fully masked block), so a gap-first pad can still finalize its spec correctly (see output_prototype)

Subclasses overriding worker_process instead should: 1. Send data as (pad, buffer) tuples via context.output_queue.put((pad, buf)) 2. Check context.should_stop() to know when to exit

Exception handling follows SGN's improved Parallelize pattern: exceptions in the worker are caught by the framework, printed to stdout, and cause the worker to terminate. The main thread detects abnormal termination via the internal() method.

Thread safety

This base class is deliberately NOT marked thread_safe, and must not be: the flag is a plain inherited class attribute, so setting it here would silently declare every subclass -- current and future, in any downstream package -- thread safe with no audit gate.

The built-in graph-thread machinery IS per-pad safe under Pipeline.run(threaded=...):

  • internal() runs alone (all source pads depend on it). It is the only consumer of the worker output queue and the only writer of element-wide bookkeeping (latest_buffer_properties, first_buffer_properties, start/end, _pad_prototypes, _last_worker_delivery).
  • new(pad) calls CAN run concurrently across source pads but touch only per-pad-keyed state: _next_frame_dict[pad] via prepare_frame and buffer_queue[pad] in set_data. The at_eos write in set_data is a monotonic True-only latch, so a racy read at worst delays EOS propagation by one graph iteration.
  • The resource hooks and worker_process run on a bare worker-side instance (see above), never on graph threads, so hook-side state cannot race with pad callbacks no matter what the hooks do.

Subclasses whose element-side additions stay within the resource hook API may therefore declare thread_safe = True on themselves. Doing so is worthwhile: internal() can block up to the heartbeat deadline waiting on the worker, and an unmarked element blocks the pipeline's whole graph wave on the event-loop thread while a marked one blocks only a pool thread. Subclasses that override the graph-thread machinery (new, internal, set_data, output_prototype) or add element-side state read from those paths must re-audit against the rules above before declaring.

Parameters:

Name Type Description Default
start float | None

Optional[float] = None Start time in GPS seconds. Used by subclasses to determine when data generation should begin.

None
end float | None

Optional[float] = None End time in GPS seconds. Alternative to duration parameter. Cannot be given if duration is given.

None
duration float | None

Optional[float] = None Duration in seconds. Alternative to end parameter. If neither end nor duration is specified, defaults to maximum int64 value.

None
in_queue_timeout int

int = 60 Timeout in seconds when waiting for data from the worker. Used by get_data_from_queue() in the main thread. Time spent blocked in resource_open is waited out rather than counted.

60
heartbeat_interval float | None

Optional[float] = None Longest time in seconds that internal() may stall the pipeline's graph loop while accumulating a full stride of data. When the wait exceeds this, the source emits a zero-length heartbeat frame instead, so the rest of the pipeline keeps ticking and elements that have fallen behind can catch up (at roughly stride / heartbeat_interval times real time). Defaults to a quarter of the stride. Set to float("inf") to always wait for a full stride, which pins the throughput of every element in the pipeline to real time whenever this source is caught up.

None
reconnect bool

bool = True Reconnect after resource errors instead of ending the stream. With reconnect disabled a resource error ends the stream at EOS, recorded as the element's eos_error. Only applies to the resource hook API; subclasses overriding worker_process handle errors themselves.

True
reconnect_backoff float

float = 1.0 Initial backoff between reconnect attempts, in seconds. Doubles per consecutive failure up to reconnect_backoff_max.

1.0
reconnect_backoff_max float

float = 30.0 Upper bound on the reconnect backoff, in seconds.

30.0
max_reconnects int | None

int | None = 10 Consecutive failed reconnect attempts after which the worker gives up and ends the stream at EOS -- roughly 3 minutes of retries at the default backoff settings. The failure is logged and recorded as the element's eos_error, and Pipeline.run() raises PipelineEOSError after the graph drains so the run still exits abnormally. None retries forever; the counter resets whenever a read succeeds.

10
reconnect_gap_lag float | None

float | None = None How far behind wall clock to emit outage gaps on live streams while disconnected, in seconds. None defers to resource_gap_lag() per pad, falling back to DEFAULT_OUTAGE_GAP_LAG. Clamped to half of in_queue_timeout so outage gaps always flow before the pipeline's read timeout.

None
Source code in src/sgnts/base/base.py
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
@dataclass
class TSResourceSource(ParallelizeBase, TSSource):
    """Source class that is entirely data driven by an external resource.

    This class uses ParallelizeBase to run data generation in a separate
    worker thread. Subclasses either implement the resource hook API
    (resource_open/resource_read, and optionally resource_gap_lag) to
    get reconnect handling, stream-continuity bookkeeping, and outage
    gap synthesis from the built-in worker loop -- or override the
    worker_process method entirely to define data generation
    themselves.

    The worker communicates with the main thread via queues provided by
    ParallelizeBase. Data should be sent as (pad, buffer) tuples to
    the output queue using context.output_queue.put((pad, buf)).

    Important: The worker runs on a bare instance in a separate
    process/thread, so hooks and worker_process cannot read instance
    attributes directly. Configuration reaches the worker through
    parameter extraction: keyword-only parameters on the hooks (or
    same-named worker_process parameters) are automatically supplied
    from the matching instance attributes at construction time.

    Subclasses using the resource hook API should:
    1. Implement resource_open(start, end) to open the resource and
       return a stream handle
    2. Optionally override resource_read(stream) if one delivery is not
       simply next(stream); return {pad_name: [SeriesBuffer, ...]}
    3. Optionally implement resource_setup() to create any worker-side
       bookkeeping attributes the hooks rely on
    4. Optionally implement resource_gap_lag(pad_name) to bound outage
       gap synthesis using resource-specific latency knowledge
    5. Declare any extra configuration the hooks need as keyword-only
       parameters on the hook signatures
    6. Optionally deliver a zero-length data buffer on a pad ahead of
       its first real data to declare the pad's backend/dtype -- needed
       only when the first deliveries may be all gaps (e.g. a fully
       masked block), so a gap-first pad can still finalize its spec
       correctly (see output_prototype)

    Subclasses overriding worker_process instead should:
    1. Send data as (pad, buffer) tuples via
       context.output_queue.put((pad, buf))
    2. Check context.should_stop() to know when to exit

    Exception handling follows SGN's improved Parallelize pattern: exceptions in the
    worker are caught by the framework, printed to stdout, and cause the
    worker to terminate. The main thread detects abnormal termination via
    the internal() method.

    Thread safety:
        This base class is deliberately NOT marked ``thread_safe``, and
        must not be: the flag is a plain inherited class attribute, so
        setting it here would silently declare every subclass -- current
        and future, in any downstream package -- thread safe with no
        audit gate.

        The built-in graph-thread machinery IS per-pad safe under
        ``Pipeline.run(threaded=...)``:

        - ``internal()`` runs alone (all source pads depend on it). It
          is the only consumer of the worker output queue and the only
          writer of element-wide bookkeeping
          (``latest_buffer_properties``, ``first_buffer_properties``,
          ``start``/``end``, ``_pad_prototypes``,
          ``_last_worker_delivery``).
        - ``new(pad)`` calls CAN run concurrently across source pads
          but touch only per-pad-keyed state: ``_next_frame_dict[pad]``
          via ``prepare_frame`` and ``buffer_queue[pad]`` in
          ``set_data``. The ``at_eos`` write in ``set_data`` is a
          monotonic True-only latch, so a racy read at worst delays EOS
          propagation by one graph iteration.
        - The resource hooks and ``worker_process`` run on a bare
          worker-side instance (see above), never on graph threads, so
          hook-side state cannot race with pad callbacks no matter what
          the hooks do.

        Subclasses whose element-side additions stay within the
        resource hook API may therefore declare ``thread_safe = True``
        on themselves. Doing so is worthwhile: ``internal()`` can block
        up to the heartbeat deadline waiting on the worker, and an
        unmarked element blocks the pipeline's whole graph wave on the
        event-loop thread while a marked one blocks only a pool thread.
        Subclasses that override the graph-thread machinery (``new``,
        ``internal``, ``set_data``, ``output_prototype``) or add
        element-side state read from those paths must re-audit against
        the rules above before declaring.

    Args:
        start: Optional[float] = None
            Start time in GPS seconds. Used by subclasses to determine
            when data generation should begin.
        end: Optional[float] = None
            End time in GPS seconds. Alternative to duration parameter.
            Cannot be given if duration is given.
        duration: Optional[float] = None
            Duration in seconds. Alternative to end parameter.
            If neither end nor duration is specified, defaults to maximum int64 value.
        in_queue_timeout: int = 60
            Timeout in seconds when waiting for data from the worker.
            Used by get_data_from_queue() in the main thread. Time spent
            blocked in resource_open is waited out rather than counted.
        heartbeat_interval: Optional[float] = None
            Longest time in seconds that internal() may stall the pipeline's
            graph loop while accumulating a full stride of data. When the
            wait exceeds this, the source emits a zero-length heartbeat
            frame instead, so the rest of the pipeline keeps ticking and
            elements that have fallen behind can catch up (at roughly
            stride / heartbeat_interval times real time). Defaults to a
            quarter of the stride. Set to float("inf") to always wait for
            a full stride, which pins the throughput of every element in
            the pipeline to real time whenever this source is caught up.
        reconnect: bool = True
            Reconnect after resource errors instead of ending the
            stream. With reconnect disabled a resource error ends the
            stream at EOS, recorded as the element's eos_error. Only
            applies to the resource hook API; subclasses overriding
            worker_process handle errors themselves.
        reconnect_backoff: float = 1.0
            Initial backoff between reconnect attempts, in seconds.
            Doubles per consecutive failure up to reconnect_backoff_max.
        reconnect_backoff_max: float = 30.0
            Upper bound on the reconnect backoff, in seconds.
        max_reconnects: int | None = 10
            Consecutive failed reconnect attempts after which the worker
            gives up and ends the stream at EOS -- roughly 3 minutes of
            retries at the default backoff settings. The failure is
            logged and recorded as the element's eos_error, and
            ``Pipeline.run()`` raises ``PipelineEOSError`` after the
            graph drains so the run still exits abnormally. None
            retries forever; the counter resets whenever a read
            succeeds.
        reconnect_gap_lag: float | None = None
            How far behind wall clock to emit outage gaps on live
            streams while disconnected, in seconds. None defers to
            resource_gap_lag() per pad, falling back to
            DEFAULT_OUTAGE_GAP_LAG. Clamped to half of in_queue_timeout
            so outage gaps always flow before the pipeline's read
            timeout.

    """

    in_queue_timeout: int = 60
    heartbeat_interval: float | None = None
    reconnect: bool = True
    reconnect_backoff: float = 1.0
    reconnect_backoff_max: float = 30.0
    max_reconnects: int | None = 10
    reconnect_gap_lag: float | None = None
    _use_threading_override: bool = (
        True  # Always use threading for I/O bound data sources
    )
    at_eos: bool = False

    def __post_init__(self):
        self.queue_maxsize = 100

        self._is_setup = False

        # Which resource hook the worker is inside and since when, as
        # {"hook": (name, monotonic)}; written by the worker, read by the
        # dead-resource clock (see _worker_silence). Must exist before
        # ParallelizeBase extracts the worker parameters below.
        self._worker_activity: dict[str, tuple[str, float]] = {}

        # Initialize parent classes - IMPORTANT: Order matters!
        # TSSource validates end/duration and creates self.source_pads and self.srcs
        # ParallelizeBase extracts self.srcs for worker
        # super().__post_init__()
        TSSource.__post_init__(self)
        ParallelizeBase.__post_init__(self)

    def _resource_hook_params(self, hook_name: str) -> dict[str, inspect.Parameter]:
        """A hook's auto-extracted parameters, beyond the fixed contract.

        Hook parameters after the fixed positional contract must be
        keyword-only; each is supplied from the same-named instance
        attribute (or the parameter default) when the hook is called in
        the worker.
        """
        fixed = RESOURCE_HOOK_CONTRACTS[hook_name]
        extras: dict[str, inspect.Parameter] = {}
        for name, param in inspect.signature(
            getattr(self, hook_name)
        ).parameters.items():
            if name in fixed:
                continue
            if param.kind is inspect.Parameter.KEYWORD_ONLY:
                extras[name] = param
            elif param.kind in (
                inspect.Parameter.VAR_KEYWORD,
                inspect.Parameter.VAR_POSITIONAL,
            ):
                continue
            else:
                msg = (
                    f"{hook_name} parameter {name!r} must be keyword-only: "
                    "parameters beyond the fixed hook contract "
                    f"{fixed} are auto-extracted from instance attributes"
                )
                raise TypeError(msg)
        return extras

    def _extract_worker_parameters(self):
        params = super()._extract_worker_parameters()
        # the built-in hook-API worker loop declares resource_config in
        # its signature (so the base extraction seeded a default here);
        # subclasses overriding worker_process keep their own signatures
        if "resource_config" in params:
            hook_kwargs = {}
            for hook_name in RESOURCE_HOOK_CONTRACTS:
                for name, param in self._resource_hook_params(hook_name).items():
                    if hasattr(self, name):
                        hook_kwargs[name] = getattr(self, name)
                    elif param.default is not inspect.Parameter.empty:
                        hook_kwargs[name] = param.default
                    else:
                        msg = (
                            f"{hook_name} parameter {name!r} has no matching "
                            "instance attribute and no default"
                        )
                        raise ValueError(msg)
            # the element name rides along so worker-side code (and
            # resource hooks) can use the element-scoped self.logger; the
            # activity record so the worker can report which hook it is in
            params["resource_config"] = {
                "name": self.name,
                "hook_kwargs": hook_kwargs,
                "activity": self._worker_activity,
            }
        return params

    @property
    def is_setup(self):
        return self._is_setup

    def sample_shape(self, pad):
        """The channels per sample that a buffer should produce as a tuple
        (since it can be a tensor). For single channels just return ()"""
        props = self.first_buffer_properties[pad]
        assert props is not None
        return props["sample_shape"]

    def sample_rate(self, pad):
        """The integer sample rate that a buffer should carry"""
        props = self.first_buffer_properties[pad]
        assert props is not None
        return props["sample_rate"]

    @property
    def latest_offset(self):
        """The offset through which *every* pad has received data from the
        worker (the minimum of the per-pad latest end offsets). Pads that
        have not received any data yet count as int64 min. Using the
        minimum matters when pads receive data in different block sizes:
        the fastest pad's progress says nothing about whether the others
        can fill their frames."""
        return min(
            (
                numpy.iinfo(numpy.int64).min
                if properties is None
                else properties["end_offset"]
            )
            for properties in self.latest_buffer_properties.values()
        )

    @property
    def start_offset(self):
        offsets = [
            b["offset"] for b in self.first_buffer_properties.values() if b is not None
        ]
        return min(offsets)

    @property
    def end_offset(self):
        if self.end is None:
            return float("inf")
        return Offset.fromsec(self.end)

    def setup(self) -> None:
        """Initialize the TSResourceSource data structures."""
        if not self._is_setup:
            self.buffer_queue: dict[SourcePad, deque[SeriesBuffer]] = {
                p: deque() for p in self.rsrcs
            }
            self.latest_buffer_properties = {p: None for p in self.rsrcs}
            self.first_buffer_properties = {p: None for p in self.rsrcs}
            # Per-pad zero-length prototype recorded from worker deliveries,
            # consulted by output_prototype when a pad's first frame is a gap.
            self._pad_prototypes: dict[SourcePad, Array] = {}
            # Dead-resource clock: the last time the worker delivered
            # anything. Spans get_data_from_queue calls, so short
            # deadline-bounded reads still detect a resource that went
            # quiet mid-stream. Kept fresh by internal() while the source
            # is not waiting on the worker.
            self._last_worker_delivery = stime.time()
            # start time of the resource_open attempt already warned about
            self._opening_warned: float | None = None
            self._is_setup = True

    def _capture_pad_prototype(self, pad: SourcePad, buffers) -> None:
        """Record the pad's array prototype from newly delivered buffers.

        The first real buffer to arrive on a pad fixes its prototype: a
        zero-length slice preserving namespace, device, and dtype. This runs
        at arrival time -- before ``set_data`` intersects and repartitions the
        queue -- so the prototype survives however the buffers are later
        consumed or discarded. Later deliveries never change it (a pad's spec
        is fixed for the life of the stream).
        """
        if pad in self._pad_prototypes:
            return
        for buf in buffers:
            if not buf.is_gap and getattr(buf.data, "dtype", None) is not None:
                self._pad_prototypes[pad] = buf.data[:0]  # type: ignore[index]
                return

    def output_prototype(self, pad: SourcePad) -> Array:
        """Declare the pad's spec from the worker data already delivered.

        A resource source can emit a gap before a pad's first real data (e.g.
        a priming gap when the resource delivers data starting later than the
        frame origin), which would otherwise finalize the pad's spec to the
        numpy float64 default and reject the real data's dtype when it arrives.

        ``internal()`` pulls at least one buffer per pad from the worker
        before any frame is emitted, and every delivery is scanned on arrival
        (see ``_capture_pad_prototype``) -- so by the time a spec is finalized
        the true backend/dtype is known for any pad that has ever delivered
        real data. A worker whose first delivery carries no array at all
        (pure gaps, e.g. a fully masked block) can declare the pad's dtype
        explicitly by sending a zero-length data buffer ahead of them; it is
        recorded as the prototype and not queued as stream data. Falls back
        to the base numpy default when nothing real was ever delivered.
        """
        if not self._is_setup:
            return super().output_prototype(pad)
        proto = self._pad_prototypes.get(pad)
        if proto is not None:
            return proto
        return super().output_prototype(pad)

    @property
    def queued_duration(self):
        durations = [d[-1].end - d[0].start for d in self.buffer_queue.values() if d]
        if durations:
            return max(durations)
        else:
            return 0.0

    def check_worker_terminated(self):
        """A worker that set its shutdown event ended its stream -- it
        reached its end, could make no further progress, or gave up on a
        failing resource -- so promote the termination to EOS instead of
        treating it as abnormal. A give-up still fails the run after the
        drain: the stashed failure surfaces through eos_error and
        ``Pipeline.run()`` raises ``PipelineEOSError``."""
        if self.terminated.is_set() and self.worker_shutdown.is_set():
            self.at_eos = True
        super().check_worker_terminated()

    def _get_data_from_worker(
        self, timeout: int = 60, deadline: float | None = None
    ) -> dict[SourcePad, list[SeriesBuffer]]:
        """Get data from the worker via ParallelizeSourceElement's queue.

        Blocks until at least one buffer has arrived for every pad, or
        ``deadline`` (a ``time.time()`` timestamp) passes, whichever comes
        first. On deadline whatever arrived so far is returned, possibly
        nothing. A worker that delivers nothing for ``timeout`` seconds
        while the source is waiting on it is considered dead and raises
        ValueError; the silence clock spans calls (see setup), so
        deadline-bounded reads shorter than ``timeout`` still detect a
        resource that went quiet mid-stream. A worker blocked inside
        resource_open is waited out instead (see _worker_opening).
        """
        data_by_pad: dict[SourcePad, list[SeriesBuffer]] = {p: [] for p in self.rsrcs}

        # Collect data from worker until we have data for all pads
        while True:
            # Check if worker has terminated abnormally before trying to get data
            self.check_worker_terminated()
            if self.at_eos:
                # the worker finished cleanly; nothing more is coming
                return data_by_pad
            # SignalEOS installs a SIGINT handler that only records the signal —
            # it does not raise KeyboardInterrupt. Poll it here so Ctrl-C
            # interrupts this loop instead of waiting for the timeout.
            if self.signaled_eos():
                self.worker_stop.set()
                return data_by_pad
            now = stime.time()
            if deadline is not None and now >= deadline:
                return data_by_pad
            try:
                # Get data from worker queue (provided by ParallelizeSourceElement)
                wait = 0.1 if deadline is None else max(0.0, min(0.1, deadline - now))
                item = self.out_queue.get(timeout=wait)
            except queue.Empty:
                # Nothing ready. Only now consult the silence clock: a get
                # must be tried first so a healthy worker whose deliveries
                # simply sat undrained is never declared dead.
                if self._worker_silence() > timeout and not self._worker_opening(
                    timeout
                ):
                    raise ValueError(
                        f"Could not read from resource after {timeout} seconds"
                    )
                continue

            pad, buf = item
            data_by_pad[pad].append(buf)
            self._last_worker_delivery = stime.time()

            # Check if we have at least one stream buffer for each pad.
            # A zero-length data buffer is a spec declaration (see
            # output_prototype), not stream content: a pad that has only
            # declared its dtype has not delivered yet, and stopping on
            # its declaration would starve its queue for the first frame.
            if all(
                any(b.is_gap or len(b) > 0 for b in data_by_pad[p]) for p in self.rsrcs
            ):
                return data_by_pad

    def _worker_silence(self) -> float:
        """Seconds since the worker last delivered or entered a resource hook.

        Entering a hook counts as activity (see _mark_hook), so a read
        that starts after a long open gets the full timeout instead of
        inheriting the open's silence. Workers overriding worker_process
        never mark; for them only deliveries count, as before.
        """
        silence = stime.time() - self._last_worker_delivery
        hook = self._worker_activity.get("hook")
        if hook is not None:
            silence = min(silence, stime.monotonic() - hook[1])
        return silence

    def _worker_opening(self, timeout: int) -> bool:
        """Whether the worker is blocked inside resource_open.

        A blocking open is a (re)connect in progress, not a dead
        resource: its duration is the resource's business, and no outage
        gaps can flow while the worker is inside it. Raising there would
        cut down the very reconnect under way, so the attempt is waited
        out and logged instead, one warning per attempt once it has run
        past ``timeout``.
        """
        hook = self._worker_activity.get("hook")
        if hook is None or hook[0] != "resource_open":
            return False
        since = hook[1]
        if self._opening_warned != since:
            self._opening_warned = since
            self.logger.warning(
                "resource_open has been running for %.0fs with nothing delivered "
                "for %ds; waiting for the attempt to finish",
                stime.monotonic() - since,
                timeout,
            )
        return True

    def get_data_from_queue(self, deadline: float | None = None):
        """Retrieve data from the worker with a timeout.

        Args:
            deadline:
                float | None, ``time.time()`` timestamp past which to stop
                waiting and return with whatever data has arrived so far.
        """
        # Get data from worker
        data_by_pad = self._get_data_from_worker(
            timeout=self.in_queue_timeout, deadline=deadline
        )

        # Add data to output queues
        for pad, buffers in data_by_pad.items():
            if not buffers:
                continue
            self._capture_pad_prototype(pad, buffers)
            # A zero-length data buffer is a worker's explicit spec
            # declaration (see output_prototype): recorded above, it carries
            # no samples and is not queued as stream data.
            self.buffer_queue[pad].extend(
                buf for buf in buffers if buf.is_gap or len(buf) > 0
            )
            # Bookkeeping still counts every delivery: a declaration's offset
            # marks the stream start even when nothing was queued.
            self.latest_buffer_properties[pad] = buffers[-1].properties
            if self.first_buffer_properties[pad] is None:
                self.first_buffer_properties[pad] = buffers[0].properties

        # Update start from actual data if it wasn't explicitly set
        if self.start is None:
            self.start = Offset.tosec(self.start_offset)

        # If end wasn't explicitly set, calculate it from actual start + duration
        if self.end is None and self.duration is not None:
            self.end = self.start + self.duration

    def set_data(self, out_frame, pad):
        """This method will set data on out_frame based on the contents of the
        internal queue"""

        # Check if we are at EOS, if so, set the flag
        if out_frame.EOS:
            self.at_eos = True

        # If we have been given a zero length frame, just return it. That means
        # we didn't have data at the time the frame was prepared and we should
        # just go with it.
        if out_frame.offset == out_frame.end_offset:
            return out_frame

        # Otherwise create a TSFrame from all the buffers that we have queued up
        in_frame = TSFrame(buffers=list(self.buffer_queue[pad]))

        # make sure nothing is fishy
        assert out_frame.end_offset <= in_frame.end_offset, (
            f"Output frame end_offset {out_frame.end_offset} extends beyond "
            f"input frame end_offset {in_frame.end_offset}"
        )

        # intersect the TSSource provided output frame with the in_frame
        before, intersection, after = out_frame.intersect(in_frame)

        # Clear the queue
        self.buffer_queue[pad].clear()

        # and repopulate it with only stuff that is newer than what we just sent.
        if after is not None:
            self.buffer_queue[pad].extend(after.buffers)

        # It is possible that the out_frame is before the data we have in the
        # queue, if so the intersection will be None. Thats okay, we can just
        # pass along that gap buffer.
        if intersection is None:
            return out_frame

        # make sure to update EOS
        intersection.EOS = out_frame.EOS
        return intersection

    def __set_pad_buffer_params(
        self,
        pad: SourcePad,
    ) -> None:
        # Make sure this has only been called once per pad
        assert (
            pad not in self._new_buffer_dict
        ), f"Pad {pad.name} already exists in _new_buffer_dict - duplicate pad entry"

        self._new_buffer_dict[pad] = {
            "sample_rate": self.sample_rate(pad),
            "shape": self.sample_shape(pad)
            + (self.num_samples(self.sample_rate(pad)),),
        }
        self._next_frame_dict[pad] = TSFrame.from_buffer_kwargs(
            offset=self.start_offset, data=None, **self._new_buffer_dict[pad]
        )

    def resource_setup(self, *args: Any, **kwargs: Any) -> None:
        """One-time worker-side initialization before the first resource_open.

        Runs in the worker, exactly once per worker. The worker operates
        on a bare instance that never saw __init__/__post_init__, so any
        worker-side bookkeeping attributes the other hooks rely on must
        be created here rather than at construction time. Exceptions
        raised here are configuration errors and fail the pipeline
        rather than triggering reconnect handling. All parameters must
        be keyword-only and are auto-extracted from same-named instance
        attributes.
        """

    def resource_open(
        self, start: float | None, end: float | None, *args: Any, **kwargs: Any
    ) -> Any:
        """Open the external resource, returning a stream handle.

        Runs in the worker. Override together with resource_read to use
        the built-in resilient worker loop instead of overriding
        worker_process.

        Args:
            start:
                float | None, resume-adjusted GPS start time in seconds:
                the requested start on first open, the last delivered
                timestamp on reconnect, or None for a live stream.
            end:
                float | None, the requested GPS end time in seconds, or
                None if unbounded.

        Returns:
            Any, a stream handle passed to resource_read. If it has a
            close() method it is called on teardown and reconnect.

        Hook parameters beyond the fixed (start, end) contract must be
        keyword-only; each is auto-extracted from the same-named
        instance attribute (or the parameter default) and passed on
        every call, e.g.::

            def resource_open(self, start, end, *, channels):
                ...
        """
        raise NotImplementedError("resource hook API not implemented")

    def resource_read(
        self, stream: Any, *args: Any, **kwargs: Any
    ) -> dict[str, list[SeriesBuffer]]:
        """Read one block from the stream as pad-name -> buffers.

        Runs in the worker. The default treats the stream as an
        iterator of such dicts. Raise StopIteration when the stream
        ends; any other exception triggers reconnect handling. A
        zero-length data buffer ahead of a pad's first data declares
        its dtype (see output_prototype) and bypasses continuity
        bookkeeping. Parameters beyond the fixed (stream,) contract
        must be keyword-only and are auto-extracted from same-named
        instance attributes.
        """
        return next(stream)

    def resource_gap_lag(
        self, pad_name: str, *args: Any, **kwargs: Any
    ) -> float | None:
        """Optional per-pad outage-gap lag, in seconds.

        Runs in the worker. How far behind wall clock outage gaps may
        be emitted for this pad while the resource is disconnected --
        i.e. the span after which absent data is declared gap rather
        than late. Return None (the default) to use the
        reconnect_gap_lag setting or DEFAULT_OUTAGE_GAP_LAG. Elements
        whose resource carries a latency contract should derive the
        lag from it. Parameters beyond the fixed (pad_name,) contract
        must be keyword-only and are auto-extracted from same-named
        instance attributes.
        """
        return None

    def worker_process(
        self,
        context: WorkerContext,
        *,
        srcs: dict[str, SourcePad],
        start: float | None,
        end: float | None,
        in_queue_timeout: int,
        reconnect: bool,
        reconnect_backoff: float,
        reconnect_backoff_max: float,
        max_reconnects: int | None,
        reconnect_gap_lag: float | None,
        resource_config: dict[str, Any] | None = None,
    ) -> None:
        """Resilient worker loop driving the resource hook API.

        Called repeatedly by the framework; each call performs one read
        (or one step of reconnect handling). On resource errors the
        stream is reopened with capped exponential backoff; live
        streams bridge the outage with gap buffers so the pipeline
        keeps flowing, and bounded streams resume from the last
        delivered timestamp. Reconnect discontinuities are bridged with
        explicit gaps and re-delivered spans are trimmed, keeping every
        pad's stream contiguous and non-overlapping.

        Subclasses may instead override this method entirely to define
        data generation themselves; they should then send (pad, buffer)
        tuples via context.output_queue.put((pad, buf)) and check
        context.should_stop() to know when to exit.
        """
        state = context.state
        if "cfg" not in state:
            # First call: the worker runs on a bare instance, so
            # materialize the element name (for the element-scoped
            # self.logger), bind each hook's auto-extracted keyword
            # arguments (see _resource_hook_params), and freeze the
            # reconnect configuration alongside the stream bookkeeping.
            if resource_config:
                self.name = resource_config["name"]
            merged = (resource_config or {}).get("hook_kwargs", {})
            state["hook_kwargs"] = {
                hook_name: {
                    name: merged[name]
                    for name in self._resource_hook_params(hook_name)
                    if name in merged
                }
                for hook_name in RESOURCE_HOOK_CONTRACTS
            }
            state["cfg"] = {
                "live": start is None,
                "reconnect_backoff": reconnect_backoff,
                "reconnect_backoff_max": reconnect_backoff_max,
                "max_reconnects": max_reconnects,
                "reconnect_gap_lag": reconnect_gap_lag,
                "in_queue_timeout": in_queue_timeout,
            }
            # the element-side activity record the hook marks write to
            state["activity"] = (resource_config or {}).get("activity", {})
            state.setdefault("stream", None)
            state.setdefault("last_end", {})  # pad name -> end offset
            state.setdefault("pad_rate", {})  # pad name -> sample rate
            state.setdefault("failures", 0)
            state.setdefault("backoff_until", 0.0)
            self.resource_setup(**state["hook_kwargs"]["resource_setup"])
        cfg = state["cfg"]

        if context.should_stop():
            self._worker_close_stream(state)
            return

        live = cfg["live"]

        # wait out reconnect backoff, bridging the outage with gaps on
        # live streams so the pipeline keeps flowing
        if state["stream"] is None and state["failures"]:
            remaining = state["backoff_until"] - stime.monotonic()
            if remaining > 0:
                if live:
                    self._worker_emit_outage_gaps(context, srcs, state)
                stime.sleep(min(RECONNECT_BACKOFF_SLICE, remaining))
                return

        try:
            if state["stream"] is None:
                self._mark_hook(state, "resource_open")
                state["stream"] = self.resource_open(
                    self._worker_resume_start(state, start),
                    end,
                    **state["hook_kwargs"]["resource_open"],
                )
            self._mark_hook(state, "resource_read")
            deliveries = self.resource_read(
                state["stream"], **state["hook_kwargs"]["resource_read"]
            )
        except StopIteration:
            self._worker_close_stream(state)
            if end is not None and self._worker_reached_end(state, end):
                context.shutdown_event.set()
                return
            if not reconnect:
                context.shutdown_event.set()
                return
            # a bounded stream that ends twice at the same position has
            # no more data to give (e.g. its tail is absent from the
            # resource): treat as end-of-stream rather than retry forever
            position = dict(state["last_end"])
            if not live and state.get("eos_position") == position:
                context.shutdown_event.set()
                return
            state["eos_position"] = position
            self._worker_handle_disconnect(context, srcs, state, None)
            return
        except (NotImplementedError, AssertionError):
            # missing hook implementations and assertion failures are
            # configuration/invariant errors, not transient resource
            # failures: reconnecting cannot fix them and would mask
            # them behind gap synthesis
            raise
        except Exception as exc:
            self._worker_close_stream(state)
            if not reconnect:
                # same end-at-EOS treatment as an exhausted reconnect
                # budget (see _worker_handle_disconnect): the failure is
                # logged and stashed for eos_error, the stream ends
                context.shutdown_event.set()
                raise
            self._worker_handle_disconnect(context, srcs, state, exc)
            return

        if state["failures"]:
            self.logger.info(
                "resource stream resumed after %d reconnect attempt(s)",
                state["failures"],
            )
        state["failures"] = 0

        for pad_name, buffers in deliveries.items():
            delivered = self._worker_emit_buffers(
                context, srcs[pad_name], pad_name, buffers, state
            )
            if not delivered or context.should_stop():
                self._worker_close_stream(state)
                return

    @staticmethod
    def _mark_hook(state: dict, hook: str) -> None:
        """Record the resource hook the worker is entering, for the
        element's dead-resource clock (see _worker_silence)."""
        state["activity"]["hook"] = (hook, stime.monotonic())

    @staticmethod
    def _worker_put(context: WorkerContext, item) -> bool:
        """Put an item on the worker's output queue, staying stoppable.

        A plain blocking ``put()`` on the bounded output queue cannot
        observe a stop request: once the main thread stops draining
        (e.g. the pipeline is tearing down after an error elsewhere)
        the worker would block forever -- and worker threads cannot be
        killed, so a wedged worker outlives the pipeline. Poll
        instead, returning False when a stop was requested before the
        item could be delivered; the caller must then stop emitting.
        """
        while True:
            if context.should_stop():
                return False
            try:
                context.output_queue.put(item, timeout=WORKER_PUT_POLL_SLICE)
            except queue.Full:
                continue
            return True

    def _worker_emit_buffers(
        self,
        context: WorkerContext,
        pad: SourcePad,
        pad_name: str,
        buffers: list[SeriesBuffer],
        state: dict,
    ) -> bool:
        """Emit delivered buffers, keeping the pad stream contiguous.

        A buffer starting after the last delivered end (e.g. across a
        reconnect) is preceded by a bridging gap buffer; re-delivered
        spans are trimmed so buffers never overlap. Zero-length data
        buffers (dtype declarations) pass through untouched.

        Returns False when a stop request interrupted delivery; the
        worker should then stop instead of emitting further buffers.
        """
        last_end = state["last_end"].get(pad_name)
        for buf in buffers:
            if not buf.is_gap and len(buf) == 0:
                # dtype declaration, not stream content
                if not self._worker_put(context, (pad, buf)):
                    return False
                continue
            rate = buf.sample_rate
            state["pad_rate"][pad_name] = rate
            if last_end is not None:
                if buf.end_offset <= last_end:
                    continue
                if buf.offset > last_end:
                    # bridge the discontinuity so the pad queue stays
                    # contiguous
                    n = Offset.tosamples(buf.offset - last_end, rate)
                    gap = self._gap_buffer(last_end, rate, n)
                    if not self._worker_put(context, (pad, gap)):
                        return False
                elif buf.offset < last_end:
                    # trim the re-delivered leading span
                    n_trim = Offset.tosamples(last_end - buf.offset, rate)
                    if buf.is_gap:
                        buf = self._gap_buffer(last_end, rate, buf.shape[-1] - n_trim)
                    else:
                        data = cast("Array", buf.data)
                        buf = SeriesBuffer(
                            offset=last_end,
                            sample_rate=rate,
                            data=data[n_trim:],
                        )
            if not self._worker_put(context, (pad, buf)):
                return False
            last_end = buf.end_offset
            state["last_end"][pad_name] = last_end
        return True

    @staticmethod
    def _gap_buffer(offset: int, rate: int, samples: int) -> SeriesBuffer:
        """A gap buffer of the given sample length at the given offset."""
        return SeriesBuffer(
            offset=offset, sample_rate=rate, data=None, shape=(samples,)
        )

    def _worker_handle_disconnect(
        self,
        context: WorkerContext,
        srcs: dict[str, SourcePad],
        state: dict,
        exc: Exception | None,
    ) -> None:
        """Schedule a reconnect attempt, or give up if the budget is spent.

        Giving up ends the stream at EOS rather than crashing the
        pipeline: the shutdown event is set before raising, which
        promotes the worker's termination to a clean end of stream (see
        check_worker_terminated) so downstream elements drain and the
        run returns normally. The raise still records the failure -- the
        worker wrapper logs its traceback and stashes it where eos_error
        can report it after the run.
        """
        cfg = state["cfg"]
        max_reconnects = cfg["max_reconnects"]
        state["failures"] += 1
        failures = state["failures"]
        if max_reconnects is not None and failures > max_reconnects:
            self.logger.error(
                "resource failed after %d reconnect attempts; giving up "
                "and ending the stream",
                max_reconnects,
            )
            context.shutdown_event.set()
            if exc is not None:
                raise exc
            msg = (
                "resource stream ended and could not be resumed after "
                f"{max_reconnects} reconnect attempts"
            )
            raise RuntimeError(msg)
        backoff = min(
            cfg["reconnect_backoff"] * 2 ** (failures - 1),
            cfg["reconnect_backoff_max"],
        )
        self.logger.warning(
            "resource stream interrupted (%s); reconnecting in %.1fs (attempt %d)",
            exc if exc is not None else "stream ended",
            backoff,
            failures,
        )
        state["backoff_until"] = stime.monotonic() + backoff
        if cfg["live"]:
            self._worker_emit_outage_gaps(context, srcs, state)

    def _worker_emit_outage_gaps(
        self,
        context: WorkerContext,
        srcs: dict[str, SourcePad],
        state: dict,
    ) -> None:
        """Bridge a live-stream outage with gap buffers.

        While disconnected, each pad's stream is advanced with gaps up
        to (now - lag), keeping the pipeline flowing through outages of
        any length. The lag keeps a safety margin against gapping over
        data the reconnected stream will still deliver; see
        _worker_gap_lag. Pads that never delivered data are skipped
        (their rate is unknown), so outages before first data are
        bounded by in_queue_timeout instead.
        """
        now_ns = int(gpsnow() * Time.SECONDS)
        for pad_name, rate in state["pad_rate"].items():
            last_end = state["last_end"].get(pad_name)
            if last_end is None:
                continue
            lag = self._worker_gap_lag(pad_name, state)
            horizon = Offset.fromns(now_ns - int(lag * Time.SECONDS))
            n = (horizon - last_end) // (Offset.MAX_RATE // rate)
            if n <= 0:
                continue
            buf = self._gap_buffer(last_end, rate, n)
            if not self._worker_put(context, (srcs[pad_name], buf)):
                return
            state["last_end"][pad_name] = buf.end_offset

    def _worker_gap_lag(self, pad_name: str, state: dict) -> float:
        """Outage-gap horizon lag for a pad, in seconds.

        An explicit reconnect_gap_lag setting wins; otherwise the
        element's resource_gap_lag() hook is consulted, falling back to
        DEFAULT_OUTAGE_GAP_LAG. Clamped to half of in_queue_timeout so
        outage gaps always flow before the pipeline's read timeout.
        """
        cfg = state["cfg"]
        if cfg["reconnect_gap_lag"] is not None:
            lag = float(cfg["reconnect_gap_lag"])
        else:
            hook_lag = self.resource_gap_lag(
                pad_name, **state["hook_kwargs"]["resource_gap_lag"]
            )
            lag = float(hook_lag) if hook_lag is not None else DEFAULT_OUTAGE_GAP_LAG
        in_queue_timeout = cfg["in_queue_timeout"]
        cap = in_queue_timeout / 2
        if lag > cap:
            warned = state.setdefault("gap_lag_warned", set())
            if pad_name not in warned:
                self.logger.warning(
                    "outage gap lag %.1fs for %s exceeds half of "
                    "in_queue_timeout (%ds); clamping to %.1fs -- data "
                    "arriving later than the clamped lag after a reconnect "
                    "will be recorded as gaps (raise in_queue_timeout to "
                    "avoid)",
                    lag,
                    pad_name,
                    in_queue_timeout,
                    cap,
                )
                warned.add(pad_name)
            lag = cap
        return lag

    @staticmethod
    def _worker_resume_start(state: dict, start: float | None) -> float | None:
        """Start time for a (re)opened stream, in GPS seconds.

        Live streams always resume at "now". Bounded streams resume at
        the last delivered timestamp so no data is re-fetched or
        skipped; any small re-delivered overlap is trimmed on emission.
        """
        if start is None or not state["last_end"]:
            return start
        return Offset.tosec(min(state["last_end"].values()))

    @staticmethod
    def _worker_reached_end(state: dict, end: float) -> bool:
        """Whether every pad has been delivered through the end time."""
        if not state["last_end"]:
            return False
        end_offset = Offset.fromsec(end)
        return min(state["last_end"].values()) >= end_offset

    def _worker_close_stream(self, state: dict) -> None:
        """Close the stream handle to clean up resource-side threads."""
        stream = state.get("stream")
        if stream is not None and hasattr(stream, "close"):
            try:
                stream.close()
            except Exception:
                self.logger.warning("failed to close resource stream", exc_info=True)
        state["stream"] = None

    def internal(self):
        """Since internal() is guaranteed to be called prior to producing any
        data on a source pad, all setup is done here. First the resource itself is
        setup and the first data is pulled from the resource. Subsequent calls to
        internal only gets data from the resource if there is not enough data queued up
        to produce a result"""

        # Check if worker has terminated abnormally
        super().internal()

        # First setup the resource and pull the first data
        if not self.is_setup:
            self.setup()
            self.get_data_from_queue()
            # setup pads if they are not setup.
            # This must happen after the first get data
            for pad in self.rsrcs:
                if pad not in self._new_buffer_dict:
                    self.__set_pad_buffer_params(pad)

        # The dead-resource clock only measures time spent actually waiting
        # on the worker: when this iteration is not starved (enough data is
        # queued, or all requested data has been delivered), keep it fresh
        # so a later starved stretch is measured from when it began.
        if self.latest_offset >= min(self.current_end_offset, self.end_offset):
            self._last_worker_delivery = stime.time()

        # Accumulate data until every pad has enough for a full stride, so
        # that workers producing sub-stride blocks (e.g. 1/16 sec blocks
        # for a 1 sec stride) do not cause one heartbeat frame per block. But
        # never stall past the heartbeat deadline: a source pad blocking
        # here holds up *every* element in the pipeline's graph loop, so a
        # caught-up live source waiting out a full stride would pin the
        # whole pipeline at exactly real time and any element that fell
        # behind could never catch up. Past the deadline we return with a
        # partial stride and prepare_frame emits a single heartbeat,
        # letting the graph loop tick at 1/heartbeat_interval while this
        # source waits on the wall clock.
        deadline = stime.time() + resolve_heartbeat_interval(self.heartbeat_interval)
        while self.latest_offset < self.current_end_offset:
            if self.latest_offset >= self.end_offset:
                break
            # Bail on SIGINT/SIGTERM — prepare_frame will emit EOS.
            if self.signaled_eos():
                break
            if stime.time() >= deadline:
                break
            self.get_data_from_queue(deadline=deadline)

    def new(self, pad):
        # The heartbeat decision must be per-pad: another pad's data being
        # ahead says nothing about whether *this* pad can fill its frame,
        # and overstating latest_offset here would skip the heartbeat path
        # and send set_data a frame extending beyond this pad's data.
        properties = self.latest_buffer_properties[pad]
        assert properties is not None, f"pad {pad.name} has no data after setup"
        frame = self.prepare_frame(pad, latest_offset=properties["end_offset"])
        frame = self.set_data(frame, pad)
        # A cleanly finished worker delivers nothing further, so carry
        # EOS -- even when the requested end was not reached -- and let
        # the pipeline wind down instead of heartbeating forever.
        if self.at_eos:
            frame.EOS = True
        return frame

latest_offset property

The offset through which every pad has received data from the worker (the minimum of the per-pad latest end offsets). Pads that have not received any data yet count as int64 min. Using the minimum matters when pads receive data in different block sizes: the fastest pad's progress says nothing about whether the others can fill their frames.

check_worker_terminated()

A worker that set its shutdown event ended its stream -- it reached its end, could make no further progress, or gave up on a failing resource -- so promote the termination to EOS instead of treating it as abnormal. A give-up still fails the run after the drain: the stashed failure surfaces through eos_error and Pipeline.run() raises PipelineEOSError.

Source code in src/sgnts/base/base.py
def check_worker_terminated(self):
    """A worker that set its shutdown event ended its stream -- it
    reached its end, could make no further progress, or gave up on a
    failing resource -- so promote the termination to EOS instead of
    treating it as abnormal. A give-up still fails the run after the
    drain: the stashed failure surfaces through eos_error and
    ``Pipeline.run()`` raises ``PipelineEOSError``."""
    if self.terminated.is_set() and self.worker_shutdown.is_set():
        self.at_eos = True
    super().check_worker_terminated()

get_data_from_queue(deadline=None)

Retrieve data from the worker with a timeout.

Parameters:

Name Type Description Default
deadline float | None

float | None, time.time() timestamp past which to stop waiting and return with whatever data has arrived so far.

None
Source code in src/sgnts/base/base.py
def get_data_from_queue(self, deadline: float | None = None):
    """Retrieve data from the worker with a timeout.

    Args:
        deadline:
            float | None, ``time.time()`` timestamp past which to stop
            waiting and return with whatever data has arrived so far.
    """
    # Get data from worker
    data_by_pad = self._get_data_from_worker(
        timeout=self.in_queue_timeout, deadline=deadline
    )

    # Add data to output queues
    for pad, buffers in data_by_pad.items():
        if not buffers:
            continue
        self._capture_pad_prototype(pad, buffers)
        # A zero-length data buffer is a worker's explicit spec
        # declaration (see output_prototype): recorded above, it carries
        # no samples and is not queued as stream data.
        self.buffer_queue[pad].extend(
            buf for buf in buffers if buf.is_gap or len(buf) > 0
        )
        # Bookkeeping still counts every delivery: a declaration's offset
        # marks the stream start even when nothing was queued.
        self.latest_buffer_properties[pad] = buffers[-1].properties
        if self.first_buffer_properties[pad] is None:
            self.first_buffer_properties[pad] = buffers[0].properties

    # Update start from actual data if it wasn't explicitly set
    if self.start is None:
        self.start = Offset.tosec(self.start_offset)

    # If end wasn't explicitly set, calculate it from actual start + duration
    if self.end is None and self.duration is not None:
        self.end = self.start + self.duration

internal()

Since internal() is guaranteed to be called prior to producing any data on a source pad, all setup is done here. First the resource itself is setup and the first data is pulled from the resource. Subsequent calls to internal only gets data from the resource if there is not enough data queued up to produce a result

Source code in src/sgnts/base/base.py
def internal(self):
    """Since internal() is guaranteed to be called prior to producing any
    data on a source pad, all setup is done here. First the resource itself is
    setup and the first data is pulled from the resource. Subsequent calls to
    internal only gets data from the resource if there is not enough data queued up
    to produce a result"""

    # Check if worker has terminated abnormally
    super().internal()

    # First setup the resource and pull the first data
    if not self.is_setup:
        self.setup()
        self.get_data_from_queue()
        # setup pads if they are not setup.
        # This must happen after the first get data
        for pad in self.rsrcs:
            if pad not in self._new_buffer_dict:
                self.__set_pad_buffer_params(pad)

    # The dead-resource clock only measures time spent actually waiting
    # on the worker: when this iteration is not starved (enough data is
    # queued, or all requested data has been delivered), keep it fresh
    # so a later starved stretch is measured from when it began.
    if self.latest_offset >= min(self.current_end_offset, self.end_offset):
        self._last_worker_delivery = stime.time()

    # Accumulate data until every pad has enough for a full stride, so
    # that workers producing sub-stride blocks (e.g. 1/16 sec blocks
    # for a 1 sec stride) do not cause one heartbeat frame per block. But
    # never stall past the heartbeat deadline: a source pad blocking
    # here holds up *every* element in the pipeline's graph loop, so a
    # caught-up live source waiting out a full stride would pin the
    # whole pipeline at exactly real time and any element that fell
    # behind could never catch up. Past the deadline we return with a
    # partial stride and prepare_frame emits a single heartbeat,
    # letting the graph loop tick at 1/heartbeat_interval while this
    # source waits on the wall clock.
    deadline = stime.time() + resolve_heartbeat_interval(self.heartbeat_interval)
    while self.latest_offset < self.current_end_offset:
        if self.latest_offset >= self.end_offset:
            break
        # Bail on SIGINT/SIGTERM — prepare_frame will emit EOS.
        if self.signaled_eos():
            break
        if stime.time() >= deadline:
            break
        self.get_data_from_queue(deadline=deadline)

output_prototype(pad)

Declare the pad's spec from the worker data already delivered.

A resource source can emit a gap before a pad's first real data (e.g. a priming gap when the resource delivers data starting later than the frame origin), which would otherwise finalize the pad's spec to the numpy float64 default and reject the real data's dtype when it arrives.

internal() pulls at least one buffer per pad from the worker before any frame is emitted, and every delivery is scanned on arrival (see _capture_pad_prototype) -- so by the time a spec is finalized the true backend/dtype is known for any pad that has ever delivered real data. A worker whose first delivery carries no array at all (pure gaps, e.g. a fully masked block) can declare the pad's dtype explicitly by sending a zero-length data buffer ahead of them; it is recorded as the prototype and not queued as stream data. Falls back to the base numpy default when nothing real was ever delivered.

Source code in src/sgnts/base/base.py
def output_prototype(self, pad: SourcePad) -> Array:
    """Declare the pad's spec from the worker data already delivered.

    A resource source can emit a gap before a pad's first real data (e.g.
    a priming gap when the resource delivers data starting later than the
    frame origin), which would otherwise finalize the pad's spec to the
    numpy float64 default and reject the real data's dtype when it arrives.

    ``internal()`` pulls at least one buffer per pad from the worker
    before any frame is emitted, and every delivery is scanned on arrival
    (see ``_capture_pad_prototype``) -- so by the time a spec is finalized
    the true backend/dtype is known for any pad that has ever delivered
    real data. A worker whose first delivery carries no array at all
    (pure gaps, e.g. a fully masked block) can declare the pad's dtype
    explicitly by sending a zero-length data buffer ahead of them; it is
    recorded as the prototype and not queued as stream data. Falls back
    to the base numpy default when nothing real was ever delivered.
    """
    if not self._is_setup:
        return super().output_prototype(pad)
    proto = self._pad_prototypes.get(pad)
    if proto is not None:
        return proto
    return super().output_prototype(pad)

resource_gap_lag(pad_name, *args, **kwargs)

Optional per-pad outage-gap lag, in seconds.

Runs in the worker. How far behind wall clock outage gaps may be emitted for this pad while the resource is disconnected -- i.e. the span after which absent data is declared gap rather than late. Return None (the default) to use the reconnect_gap_lag setting or DEFAULT_OUTAGE_GAP_LAG. Elements whose resource carries a latency contract should derive the lag from it. Parameters beyond the fixed (pad_name,) contract must be keyword-only and are auto-extracted from same-named instance attributes.

Source code in src/sgnts/base/base.py
def resource_gap_lag(
    self, pad_name: str, *args: Any, **kwargs: Any
) -> float | None:
    """Optional per-pad outage-gap lag, in seconds.

    Runs in the worker. How far behind wall clock outage gaps may
    be emitted for this pad while the resource is disconnected --
    i.e. the span after which absent data is declared gap rather
    than late. Return None (the default) to use the
    reconnect_gap_lag setting or DEFAULT_OUTAGE_GAP_LAG. Elements
    whose resource carries a latency contract should derive the
    lag from it. Parameters beyond the fixed (pad_name,) contract
    must be keyword-only and are auto-extracted from same-named
    instance attributes.
    """
    return None

resource_open(start, end, *args, **kwargs)

Open the external resource, returning a stream handle.

Runs in the worker. Override together with resource_read to use the built-in resilient worker loop instead of overriding worker_process.

Parameters:

Name Type Description Default
start float | None

float | None, resume-adjusted GPS start time in seconds: the requested start on first open, the last delivered timestamp on reconnect, or None for a live stream.

required
end float | None

float | None, the requested GPS end time in seconds, or None if unbounded.

required

Returns:

Type Description
Any

Any, a stream handle passed to resource_read. If it has a

Any

close() method it is called on teardown and reconnect.

Hook parameters beyond the fixed (start, end) contract must be keyword-only; each is auto-extracted from the same-named instance attribute (or the parameter default) and passed on every call, e.g.::

def resource_open(self, start, end, *, channels):
    ...
Source code in src/sgnts/base/base.py
def resource_open(
    self, start: float | None, end: float | None, *args: Any, **kwargs: Any
) -> Any:
    """Open the external resource, returning a stream handle.

    Runs in the worker. Override together with resource_read to use
    the built-in resilient worker loop instead of overriding
    worker_process.

    Args:
        start:
            float | None, resume-adjusted GPS start time in seconds:
            the requested start on first open, the last delivered
            timestamp on reconnect, or None for a live stream.
        end:
            float | None, the requested GPS end time in seconds, or
            None if unbounded.

    Returns:
        Any, a stream handle passed to resource_read. If it has a
        close() method it is called on teardown and reconnect.

    Hook parameters beyond the fixed (start, end) contract must be
    keyword-only; each is auto-extracted from the same-named
    instance attribute (or the parameter default) and passed on
    every call, e.g.::

        def resource_open(self, start, end, *, channels):
            ...
    """
    raise NotImplementedError("resource hook API not implemented")

resource_read(stream, *args, **kwargs)

Read one block from the stream as pad-name -> buffers.

Runs in the worker. The default treats the stream as an iterator of such dicts. Raise StopIteration when the stream ends; any other exception triggers reconnect handling. A zero-length data buffer ahead of a pad's first data declares its dtype (see output_prototype) and bypasses continuity bookkeeping. Parameters beyond the fixed (stream,) contract must be keyword-only and are auto-extracted from same-named instance attributes.

Source code in src/sgnts/base/base.py
def resource_read(
    self, stream: Any, *args: Any, **kwargs: Any
) -> dict[str, list[SeriesBuffer]]:
    """Read one block from the stream as pad-name -> buffers.

    Runs in the worker. The default treats the stream as an
    iterator of such dicts. Raise StopIteration when the stream
    ends; any other exception triggers reconnect handling. A
    zero-length data buffer ahead of a pad's first data declares
    its dtype (see output_prototype) and bypasses continuity
    bookkeeping. Parameters beyond the fixed (stream,) contract
    must be keyword-only and are auto-extracted from same-named
    instance attributes.
    """
    return next(stream)

resource_setup(*args, **kwargs)

One-time worker-side initialization before the first resource_open.

Runs in the worker, exactly once per worker. The worker operates on a bare instance that never saw init/post_init, so any worker-side bookkeeping attributes the other hooks rely on must be created here rather than at construction time. Exceptions raised here are configuration errors and fail the pipeline rather than triggering reconnect handling. All parameters must be keyword-only and are auto-extracted from same-named instance attributes.

Source code in src/sgnts/base/base.py
def resource_setup(self, *args: Any, **kwargs: Any) -> None:
    """One-time worker-side initialization before the first resource_open.

    Runs in the worker, exactly once per worker. The worker operates
    on a bare instance that never saw __init__/__post_init__, so any
    worker-side bookkeeping attributes the other hooks rely on must
    be created here rather than at construction time. Exceptions
    raised here are configuration errors and fail the pipeline
    rather than triggering reconnect handling. All parameters must
    be keyword-only and are auto-extracted from same-named instance
    attributes.
    """

sample_rate(pad)

The integer sample rate that a buffer should carry

Source code in src/sgnts/base/base.py
def sample_rate(self, pad):
    """The integer sample rate that a buffer should carry"""
    props = self.first_buffer_properties[pad]
    assert props is not None
    return props["sample_rate"]

sample_shape(pad)

The channels per sample that a buffer should produce as a tuple (since it can be a tensor). For single channels just return ()

Source code in src/sgnts/base/base.py
def sample_shape(self, pad):
    """The channels per sample that a buffer should produce as a tuple
    (since it can be a tensor). For single channels just return ()"""
    props = self.first_buffer_properties[pad]
    assert props is not None
    return props["sample_shape"]

set_data(out_frame, pad)

This method will set data on out_frame based on the contents of the internal queue

Source code in src/sgnts/base/base.py
def set_data(self, out_frame, pad):
    """This method will set data on out_frame based on the contents of the
    internal queue"""

    # Check if we are at EOS, if so, set the flag
    if out_frame.EOS:
        self.at_eos = True

    # If we have been given a zero length frame, just return it. That means
    # we didn't have data at the time the frame was prepared and we should
    # just go with it.
    if out_frame.offset == out_frame.end_offset:
        return out_frame

    # Otherwise create a TSFrame from all the buffers that we have queued up
    in_frame = TSFrame(buffers=list(self.buffer_queue[pad]))

    # make sure nothing is fishy
    assert out_frame.end_offset <= in_frame.end_offset, (
        f"Output frame end_offset {out_frame.end_offset} extends beyond "
        f"input frame end_offset {in_frame.end_offset}"
    )

    # intersect the TSSource provided output frame with the in_frame
    before, intersection, after = out_frame.intersect(in_frame)

    # Clear the queue
    self.buffer_queue[pad].clear()

    # and repopulate it with only stuff that is newer than what we just sent.
    if after is not None:
        self.buffer_queue[pad].extend(after.buffers)

    # It is possible that the out_frame is before the data we have in the
    # queue, if so the intersection will be None. Thats okay, we can just
    # pass along that gap buffer.
    if intersection is None:
        return out_frame

    # make sure to update EOS
    intersection.EOS = out_frame.EOS
    return intersection

setup()

Initialize the TSResourceSource data structures.

Source code in src/sgnts/base/base.py
def setup(self) -> None:
    """Initialize the TSResourceSource data structures."""
    if not self._is_setup:
        self.buffer_queue: dict[SourcePad, deque[SeriesBuffer]] = {
            p: deque() for p in self.rsrcs
        }
        self.latest_buffer_properties = {p: None for p in self.rsrcs}
        self.first_buffer_properties = {p: None for p in self.rsrcs}
        # Per-pad zero-length prototype recorded from worker deliveries,
        # consulted by output_prototype when a pad's first frame is a gap.
        self._pad_prototypes: dict[SourcePad, Array] = {}
        # Dead-resource clock: the last time the worker delivered
        # anything. Spans get_data_from_queue calls, so short
        # deadline-bounded reads still detect a resource that went
        # quiet mid-stream. Kept fresh by internal() while the source
        # is not waiting on the worker.
        self._last_worker_delivery = stime.time()
        # start time of the resource_open attempt already warned about
        self._opening_warned: float | None = None
        self._is_setup = True

worker_process(context, *, srcs, start, end, in_queue_timeout, reconnect, reconnect_backoff, reconnect_backoff_max, max_reconnects, reconnect_gap_lag, resource_config=None)

Resilient worker loop driving the resource hook API.

Called repeatedly by the framework; each call performs one read (or one step of reconnect handling). On resource errors the stream is reopened with capped exponential backoff; live streams bridge the outage with gap buffers so the pipeline keeps flowing, and bounded streams resume from the last delivered timestamp. Reconnect discontinuities are bridged with explicit gaps and re-delivered spans are trimmed, keeping every pad's stream contiguous and non-overlapping.

Subclasses may instead override this method entirely to define data generation themselves; they should then send (pad, buffer) tuples via context.output_queue.put((pad, buf)) and check context.should_stop() to know when to exit.

Source code in src/sgnts/base/base.py
def worker_process(
    self,
    context: WorkerContext,
    *,
    srcs: dict[str, SourcePad],
    start: float | None,
    end: float | None,
    in_queue_timeout: int,
    reconnect: bool,
    reconnect_backoff: float,
    reconnect_backoff_max: float,
    max_reconnects: int | None,
    reconnect_gap_lag: float | None,
    resource_config: dict[str, Any] | None = None,
) -> None:
    """Resilient worker loop driving the resource hook API.

    Called repeatedly by the framework; each call performs one read
    (or one step of reconnect handling). On resource errors the
    stream is reopened with capped exponential backoff; live
    streams bridge the outage with gap buffers so the pipeline
    keeps flowing, and bounded streams resume from the last
    delivered timestamp. Reconnect discontinuities are bridged with
    explicit gaps and re-delivered spans are trimmed, keeping every
    pad's stream contiguous and non-overlapping.

    Subclasses may instead override this method entirely to define
    data generation themselves; they should then send (pad, buffer)
    tuples via context.output_queue.put((pad, buf)) and check
    context.should_stop() to know when to exit.
    """
    state = context.state
    if "cfg" not in state:
        # First call: the worker runs on a bare instance, so
        # materialize the element name (for the element-scoped
        # self.logger), bind each hook's auto-extracted keyword
        # arguments (see _resource_hook_params), and freeze the
        # reconnect configuration alongside the stream bookkeeping.
        if resource_config:
            self.name = resource_config["name"]
        merged = (resource_config or {}).get("hook_kwargs", {})
        state["hook_kwargs"] = {
            hook_name: {
                name: merged[name]
                for name in self._resource_hook_params(hook_name)
                if name in merged
            }
            for hook_name in RESOURCE_HOOK_CONTRACTS
        }
        state["cfg"] = {
            "live": start is None,
            "reconnect_backoff": reconnect_backoff,
            "reconnect_backoff_max": reconnect_backoff_max,
            "max_reconnects": max_reconnects,
            "reconnect_gap_lag": reconnect_gap_lag,
            "in_queue_timeout": in_queue_timeout,
        }
        # the element-side activity record the hook marks write to
        state["activity"] = (resource_config or {}).get("activity", {})
        state.setdefault("stream", None)
        state.setdefault("last_end", {})  # pad name -> end offset
        state.setdefault("pad_rate", {})  # pad name -> sample rate
        state.setdefault("failures", 0)
        state.setdefault("backoff_until", 0.0)
        self.resource_setup(**state["hook_kwargs"]["resource_setup"])
    cfg = state["cfg"]

    if context.should_stop():
        self._worker_close_stream(state)
        return

    live = cfg["live"]

    # wait out reconnect backoff, bridging the outage with gaps on
    # live streams so the pipeline keeps flowing
    if state["stream"] is None and state["failures"]:
        remaining = state["backoff_until"] - stime.monotonic()
        if remaining > 0:
            if live:
                self._worker_emit_outage_gaps(context, srcs, state)
            stime.sleep(min(RECONNECT_BACKOFF_SLICE, remaining))
            return

    try:
        if state["stream"] is None:
            self._mark_hook(state, "resource_open")
            state["stream"] = self.resource_open(
                self._worker_resume_start(state, start),
                end,
                **state["hook_kwargs"]["resource_open"],
            )
        self._mark_hook(state, "resource_read")
        deliveries = self.resource_read(
            state["stream"], **state["hook_kwargs"]["resource_read"]
        )
    except StopIteration:
        self._worker_close_stream(state)
        if end is not None and self._worker_reached_end(state, end):
            context.shutdown_event.set()
            return
        if not reconnect:
            context.shutdown_event.set()
            return
        # a bounded stream that ends twice at the same position has
        # no more data to give (e.g. its tail is absent from the
        # resource): treat as end-of-stream rather than retry forever
        position = dict(state["last_end"])
        if not live and state.get("eos_position") == position:
            context.shutdown_event.set()
            return
        state["eos_position"] = position
        self._worker_handle_disconnect(context, srcs, state, None)
        return
    except (NotImplementedError, AssertionError):
        # missing hook implementations and assertion failures are
        # configuration/invariant errors, not transient resource
        # failures: reconnecting cannot fix them and would mask
        # them behind gap synthesis
        raise
    except Exception as exc:
        self._worker_close_stream(state)
        if not reconnect:
            # same end-at-EOS treatment as an exhausted reconnect
            # budget (see _worker_handle_disconnect): the failure is
            # logged and stashed for eos_error, the stream ends
            context.shutdown_event.set()
            raise
        self._worker_handle_disconnect(context, srcs, state, exc)
        return

    if state["failures"]:
        self.logger.info(
            "resource stream resumed after %d reconnect attempt(s)",
            state["failures"],
        )
    state["failures"] = 0

    for pad_name, buffers in deliveries.items():
        delivered = self._worker_emit_buffers(
            context, srcs[pad_name], pad_name, buffers, state
        )
        if not delivered or context.should_stop():
            self._worker_close_stream(state)
            return

TSSink dataclass

Bases: TimeSeriesMixin[TSFrame], SinkElement[TimeSpanFrame]


              flowchart TD
              sgnts.base.base.TSSink[TSSink]
              sgnts.base.base.TimeSeriesMixin[TimeSeriesMixin]

                              sgnts.base.base.TimeSeriesMixin --> sgnts.base.base.TSSink
                


              click sgnts.base.base.TSSink href "" "sgnts.base.base.TSSink"
              click sgnts.base.base.TimeSeriesMixin href "" "sgnts.base.base.TimeSeriesMixin"
            

A time-series sink element.

Source code in src/sgnts/base/base.py
@dataclass
class TSSink(TimeSeriesMixin[TSFrame], SinkElement[TimeSpanFrame]):
    """A time-series sink element."""

    def internal(self) -> None:
        """Process frames by calling child class implementation.

        If the child class defines a process() method, it will be called with
        input frame dictionaries. Otherwise, child classes should override
        internal() directly.
        """
        super().internal()

        # Check if the element defines a process() method
        if hasattr(self, "process"):
            # Collect all input frames (both TSFrame and EventFrame)
            inframes: dict[SinkPad, TimeSpanFrame] = {}
            inframes.update(self.next_ts_inputs())
            inframes.update(self.next_event_inputs())

            # Call the process method
            self.process(inframes)  # type: ignore[attr-defined]

internal()

Process frames by calling child class implementation.

If the child class defines a process() method, it will be called with input frame dictionaries. Otherwise, child classes should override internal() directly.

Source code in src/sgnts/base/base.py
def internal(self) -> None:
    """Process frames by calling child class implementation.

    If the child class defines a process() method, it will be called with
    input frame dictionaries. Otherwise, child classes should override
    internal() directly.
    """
    super().internal()

    # Check if the element defines a process() method
    if hasattr(self, "process"):
        # Collect all input frames (both TSFrame and EventFrame)
        inframes: dict[SinkPad, TimeSpanFrame] = {}
        inframes.update(self.next_ts_inputs())
        inframes.update(self.next_event_inputs())

        # Call the process method
        self.process(inframes)  # type: ignore[attr-defined]

TSSource dataclass

Bases: _TSSource


              flowchart TD
              sgnts.base.base.TSSource[TSSource]
              sgnts.base.base._TSSource[_TSSource]

                              sgnts.base.base._TSSource --> sgnts.base.base.TSSource
                


              click sgnts.base.base.TSSource href "" "sgnts.base.base.TSSource"
              click sgnts.base.base._TSSource href "" "sgnts.base.base._TSSource"
            

A time-series source that generates data in fixed-size buffers where the user can specify the start time and end time. If you want a data driven source consider using TSResourceSource.

Parameters:

Name Type Description Default
start float | None

float, start time of first buffer, in seconds

None
end float | None

float, end time of the last buffer, in seconds

None
duration float | None

float, alternative to end option, specify the duration of time to be covered in seconds. Cannot be given if end is given.

None
Source code in src/sgnts/base/base.py
@dataclass
class TSSource(_TSSource):
    """A time-series source that generates data in fixed-size buffers where the
       user can specify the start time and end time. If you want a data driven
       source consider using TSResourceSource.

    Args:
        start:
            float, start time of first buffer, in seconds
        end:
            float, end time of the last buffer, in seconds
        duration:
            float, alternative to end option, specify the duration of
            time to be covered in seconds. Cannot be given if end is given.
    """

    start: float | None = None
    end: float | None = None
    duration: float | None = None

    def __post_init__(self):
        super().__post_init__()

        # Validate mutual exclusivity of end and duration
        if self.end is not None and self.duration is not None:
            raise ValueError("may specify either end or duration, not both")

        # Default to infinite duration if neither end nor duration specified
        if self.end is None and self.duration is None:
            self.duration = numpy.iinfo(numpy.int64).max

        # Calculate end from start + duration when both are available
        if self.start is not None and self.duration is not None:
            self.end = self.start + self.duration

        # Validate end > start when both are available
        if self.start is not None and self.end is not None:
            assert self.end > self.start, "end is before start"

    @property
    def end_offset(self):
        if self.end is None:
            return float("inf")
        return Offset.fromsec(self.end)

    @property
    def start_offset(self):
        if self.start is None:
            return None
        return Offset.fromsec(self.start)

    def set_pad_buffer_params(
        self,
        pad: SourcePad,
        sample_shape: tuple[int, ...],
        rate: int,
    ) -> None:
        """Set variables on the pad that are needed to construct SeriesBuffers.

        These should remain constant throughout the duration of the
        pipeline so this method may only be called once.

        Args:
            pad:
                SourcePad, the pad to setup buffers on
            sample_shape:
                tuple[int, ...], the shape of a single sample of the
                data, or put another way, the shape of the data except
                for the last (time) dimension,
                i.e. sample_shape=data.shape[:-1]
            rate:
                int, the sample rate of the data the pad will produce

        Raises:
            ValueError: If start or end times don't align to sample boundaries
                at the given rate

        """
        # Make sure this has only been called once per pad
        assert (
            pad not in self._new_buffer_dict
        ), f"Pad {pad.name} already exists in _new_buffer_dict - duplicate pad entry"

        # Validate that start and end times align to sample boundaries at this rate
        # This prevents obscure runtime errors during offset-to-sample conversions
        if self.start is not None:
            Offset.validate_time_alignment(self.start, rate, param_name="start")
        if self.end is not None and self.end != numpy.iinfo(numpy.int64).max:
            Offset.validate_time_alignment(self.end, rate, param_name="end")

        self._new_buffer_dict[pad] = {
            "sample_rate": rate,
            "shape": sample_shape + (self.num_samples(rate),),
        }
        self._next_frame_dict[pad] = TSFrame.from_buffer_kwargs(
            offset=self.start_offset, data=None, **self._new_buffer_dict[pad]
        )

set_pad_buffer_params(pad, sample_shape, rate)

Set variables on the pad that are needed to construct SeriesBuffers.

These should remain constant throughout the duration of the pipeline so this method may only be called once.

Parameters:

Name Type Description Default
pad SourcePad

SourcePad, the pad to setup buffers on

required
sample_shape tuple[int, ...]

tuple[int, ...], the shape of a single sample of the data, or put another way, the shape of the data except for the last (time) dimension, i.e. sample_shape=data.shape[:-1]

required
rate int

int, the sample rate of the data the pad will produce

required

Raises:

Type Description
ValueError

If start or end times don't align to sample boundaries at the given rate

Source code in src/sgnts/base/base.py
def set_pad_buffer_params(
    self,
    pad: SourcePad,
    sample_shape: tuple[int, ...],
    rate: int,
) -> None:
    """Set variables on the pad that are needed to construct SeriesBuffers.

    These should remain constant throughout the duration of the
    pipeline so this method may only be called once.

    Args:
        pad:
            SourcePad, the pad to setup buffers on
        sample_shape:
            tuple[int, ...], the shape of a single sample of the
            data, or put another way, the shape of the data except
            for the last (time) dimension,
            i.e. sample_shape=data.shape[:-1]
        rate:
            int, the sample rate of the data the pad will produce

    Raises:
        ValueError: If start or end times don't align to sample boundaries
            at the given rate

    """
    # Make sure this has only been called once per pad
    assert (
        pad not in self._new_buffer_dict
    ), f"Pad {pad.name} already exists in _new_buffer_dict - duplicate pad entry"

    # Validate that start and end times align to sample boundaries at this rate
    # This prevents obscure runtime errors during offset-to-sample conversions
    if self.start is not None:
        Offset.validate_time_alignment(self.start, rate, param_name="start")
    if self.end is not None and self.end != numpy.iinfo(numpy.int64).max:
        Offset.validate_time_alignment(self.end, rate, param_name="end")

    self._new_buffer_dict[pad] = {
        "sample_rate": rate,
        "shape": sample_shape + (self.num_samples(rate),),
    }
    self._next_frame_dict[pad] = TSFrame.from_buffer_kwargs(
        offset=self.start_offset, data=None, **self._new_buffer_dict[pad]
    )

TSTransform dataclass

Bases: TimeSeriesMixin[TSFrame], TransformElement[TimeSpanFrame]


              flowchart TD
              sgnts.base.base.TSTransform[TSTransform]
              sgnts.base.base.TimeSeriesMixin[TimeSeriesMixin]

                              sgnts.base.base.TimeSeriesMixin --> sgnts.base.base.TSTransform
                


              click sgnts.base.base.TSTransform href "" "sgnts.base.base.TSTransform"
              click sgnts.base.base.TimeSeriesMixin href "" "sgnts.base.base.TimeSeriesMixin"
            

A time-series transform element.

Source code in src/sgnts/base/base.py
@dataclass
class TSTransform(TimeSeriesMixin[TSFrame], TransformElement[TimeSpanFrame]):
    """A time-series transform element."""

    def internal(self) -> None:
        """Process frames by calling child class implementation.

        If the child class defines a process() method, it will be called with
        input and output frame dictionaries. Otherwise, child classes should
        override internal() directly.
        """
        super().internal()

        # Check if the element defines a process() method
        if hasattr(self, "process"):
            # Collect all input frames (both TSFrame and EventFrame)
            inframes: dict[SinkPad, TimeSpanFrame] = {}
            inframes.update(self.next_ts_inputs())
            inframes.update(self.next_event_inputs())

            # Collect all output collectors/frames (TSCollectFrame or EventFrame)
            ts_collectors = self.next_ts_outputs()
            outframes: dict[SourcePad, TimeSpanFrame | TSCollectFrame] = {}
            outframes.update(ts_collectors)
            outframes.update(self.next_event_outputs())

            # Call the process method
            self.process(inframes, outframes)  # type: ignore[attr-defined]

            # Close all TS collectors to commit buffers to parent frames
            for collector in ts_collectors.values():
                collector.close()

    def new(self, pad: SourcePad) -> TimeSpanFrame:
        """Return the output frame for the given pad.

        It should take the source pad as an argument and return a new
        TSFrame or EventFrame.

        Args:
            pad:
                SourcePad, The source pad that is producing the transformed frame

        Returns:
            TSFrame or EventFrame, The transformed frame

        """
        frame = self.outframes.get(pad)
        assert frame is not None
        return frame

internal()

Process frames by calling child class implementation.

If the child class defines a process() method, it will be called with input and output frame dictionaries. Otherwise, child classes should override internal() directly.

Source code in src/sgnts/base/base.py
def internal(self) -> None:
    """Process frames by calling child class implementation.

    If the child class defines a process() method, it will be called with
    input and output frame dictionaries. Otherwise, child classes should
    override internal() directly.
    """
    super().internal()

    # Check if the element defines a process() method
    if hasattr(self, "process"):
        # Collect all input frames (both TSFrame and EventFrame)
        inframes: dict[SinkPad, TimeSpanFrame] = {}
        inframes.update(self.next_ts_inputs())
        inframes.update(self.next_event_inputs())

        # Collect all output collectors/frames (TSCollectFrame or EventFrame)
        ts_collectors = self.next_ts_outputs()
        outframes: dict[SourcePad, TimeSpanFrame | TSCollectFrame] = {}
        outframes.update(ts_collectors)
        outframes.update(self.next_event_outputs())

        # Call the process method
        self.process(inframes, outframes)  # type: ignore[attr-defined]

        # Close all TS collectors to commit buffers to parent frames
        for collector in ts_collectors.values():
            collector.close()

new(pad)

Return the output frame for the given pad.

It should take the source pad as an argument and return a new TSFrame or EventFrame.

Parameters:

Name Type Description Default
pad SourcePad

SourcePad, The source pad that is producing the transformed frame

required

Returns:

Type Description
TimeSpanFrame

TSFrame or EventFrame, The transformed frame

Source code in src/sgnts/base/base.py
def new(self, pad: SourcePad) -> TimeSpanFrame:
    """Return the output frame for the given pad.

    It should take the source pad as an argument and return a new
    TSFrame or EventFrame.

    Args:
        pad:
            SourcePad, The source pad that is producing the transformed frame

    Returns:
        TSFrame or EventFrame, The transformed frame

    """
    frame = self.outframes.get(pad)
    assert frame is not None
    return frame

TimeSeriesMixin dataclass

Bases: ElementLike, Generic[TSFrameLike]


              flowchart TD
              sgnts.base.base.TimeSeriesMixin[TimeSeriesMixin]

              

              click sgnts.base.base.TimeSeriesMixin href "" "sgnts.base.base.TimeSeriesMixin"
            

Mixin that adds time-series capabilities to any SGN element.

This will produce aligned frames in preparedframes. If the adapter is not explicitly disabled, will trigger the audioadapter to queue data, and make padded or strided frames in preparedframes.

This mixin provides: - Frame alignment across multiple input pads - Optional adapter processing (overlap/stride/gap handling) - Timeout detection and EOS handling

Note

Subclasses can customize alignment behavior by setting class-level attributes: - static_unaligned_sink_pads: Declare which sink pads should not be aligned (e.g., EventFrame pads or auxiliary inputs).

Parameters:

Name Type Description Default
max_age float

float, the max age before timeout, in seconds

100.0
adapter_config AdapterConfig

AdapterConfig, holds parameters used for audioadapter behavior

AdapterConfig()
unaligned Sequence[str]

list[str], the list of unaligned sink pads.

list()
Source code in src/sgnts/base/base.py
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
@dataclass
class TimeSeriesMixin(ElementLike, Generic[TSFrameLike]):
    """Mixin that adds time-series capabilities to any SGN element.

    This will produce aligned frames in preparedframes. If the adapter
    is not explicitly disabled, will trigger the audioadapter to queue
    data, and make padded or strided frames in preparedframes.

    This mixin provides:
    - Frame alignment across multiple input pads
    - Optional adapter processing (overlap/stride/gap handling)
    - Timeout detection and EOS handling

    Note:
        Subclasses can customize alignment behavior by setting class-level
        attributes:
          - static_unaligned_sink_pads: Declare which sink pads should not be
            aligned (e.g., EventFrame pads or auxiliary inputs).

    Args:
        max_age:
            float, the max age before timeout, in seconds
        adapter_config:
            AdapterConfig, holds parameters used for audioadapter behavior
        unaligned:
            list[str], the list of unaligned sink pads.

    """

    # Class-level attributes for alignment configuration
    static_unaligned_sink_pads: ClassVar[list[str]] = []

    # Declared backend capability ("the array is the backend"): the set of
    # backend names this element can operate in, or ANY_BACKEND for pure
    # standard-`xp` elements. Validated against the actual data at runtime in
    # ``pull`` (see ``_check_backend``). The default is numpy; an element that
    # supports more must opt in, e.g. ``backends = frozenset({"numpy", "torch"})``
    # or ``backends = ANY_BACKEND``.
    backends: ClassVar[Union[frozenset[str], _AnyBackend]] = frozenset({"numpy"})

    # Whether this element may change the stream's *backend* (namespace/device),
    # not just dtype. Only edge elements (a ``Converter``) set this True; for every
    # other element the framework requires an ``output_prototype`` to keep the
    # input's namespace and device, so "the device changes only at a Converter"
    # holds by construction. See ``output_prototype``.
    changes_backend: ClassVar[bool] = False

    max_age: float = 100.0
    adapter_config: AdapterConfig = field(default_factory=AdapterConfig)
    unaligned: Sequence[str] = field(default_factory=list)

    def __post_init__(self) -> None:
        """Initialize timeseries state."""
        super().__post_init__()

        # Determine which user-provided input pads require alignment
        unaligned_names = list(self.unaligned) + self.static_unaligned_sink_pads

        # Convert pad names to SinkPad objects and store in instance variable
        self.unaligned_sink_pads = [
            self.snks[name] for name in unaligned_names  # type: ignore[attr-defined]
        ]
        self.aligned_sink_pads = [
            p for p in self.sink_pads if p not in self.unaligned_sink_pads
        ]

        # Initialize metadata for exempt sink pads
        self.unaligned_data: dict[SinkPad, TimeSpanFrame | None] = {
            p: None for p in self.unaligned_sink_pads
        }

        # Initialize the alignment metadata for all sink pads that need to be aligned
        self._is_aligned = False
        self.inbufs = {p: Audioadapter() for p in self.aligned_sink_pads}
        self.preparedframes: dict[SinkPad, TSFrame | None] = {
            p: None for p in self.aligned_sink_pads
        }
        self.aligned_slices: dict[SinkPad, TSSlices | None] = {
            p: None for p in self.aligned_sink_pads
        }
        self.outframes: dict[SourcePad, TimeSpanFrame | None] = {
            p: None for p in self.source_pads
        }
        self.preparedoutoffsets = {"offset": 0, "noffset": 0}
        self.at_EOS = False
        # Last complete spec per sink pad, keyed by pad name. Used to stamp
        # self-generated gap/heartbeat frames so an all-gap stretch keeps its own
        # pad's backend and dtype (pads may differ), and read by
        # ``input_prototype`` so an element can build a per-output prototype from
        # the specific inputs that determine it (many-to-many, different dtypes).
        self._input_specs: dict[str, Any] = {}
        # The one backend this element combines across its aligned pads. Set from
        # the first non-gap input and enforced thereafter (see _check_backend).
        self._stream_backend: Optional[str] = None
        self._last_ts: dict[SinkPad, float | None] = {
            p: None for p in self.aligned_sink_pads
        }
        self._last_offset: dict[SinkPad, int | None] = {
            p: None for p in self.aligned_sink_pads
        }
        self.metadata: dict[SinkPad, dict[Any, Any]] = {
            p: {} for p in self.aligned_sink_pads
        }

        # Initialize default frame types for inputs and outputs
        # These can be overridden by derived classes in configure()
        self.input_frame_types: dict[str, type[TimeSpanFrame]] = {
            name: TSFrame for name in self.sink_pad_names  # type: ignore[attr-defined]
        }
        # Initialize default output frame types (only for elements with source pads)
        # All pads default to TSFrame, elements can override in configure()
        self.output_frame_types: dict[str, type[TimeSpanFrame]] = {
            name: TSFrame for name in getattr(self, "source_pad_names", [])
        }

        # Configure adapter and element-specific attributes
        self.configure()

        self.is_adapter_enabled = self.adapter_config.is_enabled

        # Initialize adapter-specific state only if adapter is enabled
        self.audioadapters = None
        if self.is_adapter_enabled:
            # we need audioadapters
            self.audioadapters = {p: Audioadapter() for p in self.aligned_sink_pads}
            self.pad_zeros_offset: dict[SinkPad, int] = {}
            for p in self.aligned_sink_pads:
                if self.adapter_config.pad_zeros_startup is True:
                    # at startup, pad zeros in front of the first buffer to
                    # serve as history
                    self.pad_zeros_offset[p] = self.adapter_config.overlap[0]
                else:
                    self.pad_zeros_offset[p] = 0

        # Call validation hooks
        self.validate()

    def configure(self) -> None:
        """Configure element-specific settings."""
        pass

    def validate(self) -> None:
        """Validate element configuration."""
        pass

    def next_input(self) -> tuple[SinkPad, TSFrame]:
        """Convenience method - get single TSFrame input.

        Equivalent to next_ts_input(). For transforms that only work with TSFrames.

        Returns:
            TSFrame, single input frame
        """
        return self.next_ts_input()

    def next_output(self) -> tuple[SourcePad, TSCollectFrame]:
        """Convenience method - get single TSCollectFrame output.

        Equivalent to next_ts_output(). For transforms that only work with TSFrames.

        Note: Elements using this method must call `.close()` on the collector
        when done populating buffers.

        Returns:
            tuple[SourcePad, TSCollectFrame], pad and collector for output frame
        """
        return self.next_ts_output()

    def next_inputs(self) -> dict[SinkPad, TSFrame]:
        """Convenience method - get all TSFrame inputs.

        Equivalent to next_ts_inputs(). For transforms that only work with TSFrames.

        Returns:
            dict[SinkPad, TSFrame], dictionary of input frames
        """
        return self.next_ts_inputs()

    def next_outputs(self) -> dict[SourcePad, TSCollectFrame]:
        """Convenience method - get all TSCollectFrame outputs.

        Equivalent to next_ts_outputs(). For transforms that only work with TSFrames.

        Note: Elements using this method must call `.close()` on each collector
        when done populating buffers.

        Returns:
            dict[SourcePad, TSCollectFrame], dictionary of collectors for output frames
        """
        return self.next_ts_outputs()

    def next_ts_input(self) -> tuple[SinkPad, TSFrame]:
        """Get single TSFrame input.

        Returns:
            TSFrame, the single TSFrame from inputs

        Raises:
            AssertionError: If there is not exactly one TSFrame input.
        """
        all_ts = self.next_ts_inputs()
        assert (
            len(all_ts) == 1
        ), f"next_ts_input() requires exactly one TSFrame input, got {len(all_ts)}"
        return next(iter(all_ts.items()))

    def next_ts_inputs(self) -> dict[SinkPad, TSFrame]:
        """Get all TSFrame inputs based on input_frame_types configuration.

        Returns:
            dict[SinkPad, TSFrame], mapping of sink pads to TSFrame inputs
        """
        result: dict[SinkPad, TSFrame] = {}
        for pad in self.sink_pads:
            pad_name = self.rsnks[pad]  # type: ignore[attr-defined]
            if self.input_frame_types.get(pad_name, TSFrame) == TSFrame:
                if pad in self.aligned_sink_pads:
                    frame = self.preparedframes[pad]
                    assert frame is not None
                    result[pad] = frame
                else:
                    unaligned_frame = self.unaligned_data[pad]
                    assert isinstance(unaligned_frame, TSFrame), (
                        f"Expected TSFrame on unaligned pad {pad_name}, "
                        f"got {type(unaligned_frame).__name__}"
                    )
                    result[pad] = unaligned_frame
        return result

    def next_event_input(self) -> tuple[SinkPad, EventFrame]:
        """Get single EventFrame input.

        Returns:
            EventFrame, the single EventFrame from inputs

        Raises:
            AssertionError: If there is not exactly one EventFrame input.
        """
        all_events = self.next_event_inputs()
        assert len(all_events) == 1, (
            f"next_event_input() requires exactly one EventFrame input, "
            f"got {len(all_events)}"
        )
        return next(iter(all_events.items()))

    def next_event_inputs(self) -> dict[SinkPad, EventFrame]:
        """Get all EventFrame inputs based on input_frame_types configuration.

        Returns:
            dict[SinkPad, EventFrame], mapping of sink pads to EventFrame inputs
        """
        result: dict[SinkPad, EventFrame] = {}
        for pad in self.sink_pads:
            pad_name = self.rsnks[pad]  # type: ignore[attr-defined]
            if self.input_frame_types.get(pad_name) == EventFrame:
                if pad in self.unaligned_sink_pads:
                    frame = self.unaligned_data[pad]
                else:
                    frame = self.preparedframes[pad]
                assert isinstance(frame, EventFrame), (
                    f"Expected EventFrame on pad {pad_name}, "
                    f"got {type(frame).__name__}"
                )
                result[pad] = frame
        return result

    def next_ts_output(self) -> tuple[SourcePad, TSCollectFrame]:
        """Get single TSCollectFrame for output with offsets from preparedoutoffsets.

        Note: The caller must call `.close()` on the collector when done
        populating buffers.

        Returns:
            tuple[SourcePad, TSCollectFrame], pad and collector for the output
            frame

        Raises:
            AssertionError: If there is not exactly one TS output pad.
        """
        all_ts = self.next_ts_outputs()
        assert (
            len(all_ts) == 1
        ), f"next_ts_output() requires exactly one TS output pad, got {len(all_ts)}"
        return next(iter(all_ts.items()))

    def next_ts_outputs(self) -> dict[SourcePad, TSCollectFrame]:
        """Get all TSCollectFrames for output pads configured as TS outputs.

        Creates TSFrame instances with offset/noffset from preparedoutoffsets,
        then creates TSCollectFrame collectors for atomic buffer population.
        The parent TSFrames are automatically registered in self.outframes.

        Returns:
            dict[SourcePad, TSCollectFrame], mapping of source pads to collectors
        """
        offset = self.preparedoutoffsets["offset"]
        noffset = self.preparedoutoffsets["noffset"]
        at_EOS = any(
            frame.EOS for frame in self.preparedframes.values() if frame is not None
        )

        result: dict[SourcePad, TSCollectFrame] = {}
        for pad in self.source_pads:
            pad_name = self.rsrcs[pad]  # type: ignore[attr-defined]
            if self.output_frame_types.get(pad_name, TSFrame) == TSFrame:
                # An all-gap output frame has no array to read its backend from, so
                # stamp it from the per-pad output prototype (default: inherit the
                # input spec). Real frames read their backend from their own data.
                frame = TSFrame(
                    offset=offset,
                    noffset=noffset,
                    EOS=at_EOS,
                    spec_hint=self._output_hint(pad),
                )
                collector = frame.fill()
                result[pad] = collector
                # Automatically register the parent frame in outframes
                self.outframes[pad] = frame
        return result

    def _output_hint(self, pad: SourcePad) -> "SeriesDataSpec | None":
        """The backend spec stamped on ``pad``'s all-gap output frames.

        From ``output_prototype(pad)``: ``None`` inherits the input spec unchanged
        -- only meaningful when every input seen so far agrees on backend identity
        (namespace/dtype/device); inputs that differ make the inheritance ambiguous
        and raise, directing the element to declare an ``output_prototype``.
        Otherwise the prototype's namespace/dtype/device are read off the example
        array. A non-``Converter`` element may change only dtype, so its prototype
        must keep its inputs' namespace and device.
        """
        proto = self.output_prototype(pad)
        specs = list(self._input_specs.values())
        if proto is None:
            if not specs:
                return None
            first = specs[0]
            for other in specs[1:]:
                if (
                    other.namespace != first.namespace
                    or other.data_type != first.data_type
                    or other.device != first.device
                ):
                    raise BackendError(
                        f"element {self.name!r} has input pads with differing "
                        f"specs (namespace/dtype/device), so the spec of its "
                        f"all-gap output frames cannot be inherited from 'the' "
                        f"input; define output_prototype() to declare what "
                        f"{pad.name!r} emits."
                    )
            return first
        # An override implies inputs have been seen (a transform derives its output
        # from them), so input specs are established by the time we get here.
        assert specs
        spec = SeriesDataSpec.from_data(proto, specs[0].sample_rate)
        if not self.changes_backend and not any(
            spec.namespace == inp.namespace and spec.device == inp.device
            for inp in specs
        ):
            raise BackendError(
                f"element {self.name!r} produced an output_prototype with a "
                f"different backend (namespace/device) than its inputs; a transform "
                f"may change only dtype. Use a Converter to change namespace or "
                f"device, or set changes_backend = True."
            )
        return spec

    def output_prototype(self, pad: SourcePad) -> "Array | None":
        """A zero-length *example* of what ``pad`` emits -- the one hook for telling
        the framework an output's backend and dtype.

        Real data describes itself ("the array is the backend"), so this is used
        only to stamp this element's **all-gap** output frames. The framework reads
        ``namespace``, ``device`` and ``dtype`` off the returned array. Build it
        from the inputs with :meth:`input_prototype` so the backend rides through
        automatically and dtype/promotion follow the actual operation::

            def output_prototype(self, pad):
                # output dtype = result_type(input, factor); use your pad's name
                return self.input_prototype(self.sink_pad_names[0]) * self.factor

        Contract by role:

        - **Transform** -- may change only **dtype**. The framework asserts the
          returned prototype keeps the input's namespace+device; to change those
          you must be a Converter (set ``changes_backend = True``).
        - **Source** -- has no inputs, so it returns a literal, e.g.
          ``numpy.zeros(0)`` or ``torch.zeros(0, dtype=torch.float16, device="cuda")``.
        - **Default** (``None``) -- "same backend and dtype as my input": the
          pass-through case, which is most transforms. Write nothing. Only
          well-defined while all inputs share one backend identity: an element
          combining different dtypes must declare, or preparing its output
          frames raises ``BackendError`` once differing input specs are seen
          (see ``_output_hint``).

        Caveat -- an op that changes **both shape and dtype** (e.g. an FFT,
        real->complex) cannot be run on a length-0 array; *declare* the dtype
        instead of running the op::

            return self.input_prototype(self.sink_pad_names[0], dtype=complex)

        Returns:
            A zero-length array carrying the output's namespace/device/dtype, or
            ``None`` to inherit the input's spec unchanged.
        """
        return None

    def input_prototype(
        self, sink_pad_name: str, dtype: Any = None, device: Any = None
    ) -> "Array":
        """A zero-length array in a sink pad's backend, for building output prototypes.

        Returns ``namespace.zeros((0,), dtype=…, device=…)`` from the last complete
        spec seen on sink pad ``sink_pad_name``. ``dtype``/``device`` default to that
        input's own; pass them to override (``device`` only inside a Converter). Use
        this inside :meth:`output_prototype` so namespace and device are *inherited
        from the data* rather than hard-coded -- the reason a prototype is preferred
        over constructing a ``SeriesDataSpec`` by hand.

        Raises:
            KeyError: if no complete spec has been seen yet on ``sink_pad_name``.
                In a running pipeline this cannot fire by the time output frames
                are built: every sink pad records its spec on its first pull
                (frames carry a complete spec even when all-gap), and
                ``internal()`` runs only after the pulls.
        """
        spec = self._input_specs[sink_pad_name]
        namespace = spec.namespace
        return namespace.zeros(
            (0,),
            dtype=dtype if dtype is not None else spec.data_type,
            device=device if device is not None else spec.device,
        )

    def next_event_output(self) -> tuple[SourcePad, EventFrame]:
        """Get single EventFrame for output with offset/noffset from preparedoutoffsets.

        Returns:
            EventFrame, an empty event frame ready to be populated

        Raises:
            AssertionError: If there is not exactly one event output pad.
        """
        all_events = self.next_event_outputs()
        assert len(all_events) == 1, (
            f"next_event_output() requires exactly one event output pad, "
            f"got {len(all_events)}"
        )
        return next(iter(all_events.items()))

    def next_event_outputs(self) -> dict[SourcePad, EventFrame]:
        """Get all EventFrames for output pads configured as event outputs.

        Creates EventFrame instances with offset/noffset from preparedoutoffsets
        for all source pads configured to produce EventFrame. The frames are
        automatically registered in self.outframes for return.

        Returns:
            dict[SourcePad, EventFrame], mapping of source pads to empty EventFrames
        """
        offset = self.preparedoutoffsets["offset"]
        noffset = self.preparedoutoffsets["noffset"]
        at_EOS = any(
            frame.EOS for frame in self.preparedframes.values() if frame is not None
        )

        result: dict[SourcePad, EventFrame] = {}
        for pad in self.source_pads:
            pad_name = self.rsrcs[pad]  # type: ignore[attr-defined]
            if self.output_frame_types.get(pad_name) == EventFrame:
                frame = EventFrame(offset=offset, noffset=noffset, EOS=at_EOS)
                result[pad] = frame
                # Automatically register in outframes
                self.outframes[pad] = frame
        return result

    def pull(self, pad: SinkPad, frame: TimeSpanFrame) -> None:
        """Pull data and queue for alignment.

        Pull data from the input pads (source pads of upstream elements) and
        queue data to perform alignment once frames from all pads are pulled.

        Args:
            pad:
                SinkPad, The sink pad that is pulling the frame
            frame:
                TimeSpanFrame, The frame that is pulled to sink pad
        """
        self.at_EOS |= frame.EOS

        # Validate the incoming data's backend against this element's declared
        # capability. The array is the source of truth; a mismatch means a
        # Converter is missing on this link.
        self._check_backend(pad, frame)

        # Remember this pad's backend so heartbeats/gaps we emit keep it.
        spec = getattr(frame, "spec", None)
        if _is_complete_spec(spec):
            self._input_specs[pad.pad_name] = spec

        # Handle case of a pad that is exempt from alignment
        if pad in self.unaligned_sink_pads:
            # Store most recent data for exempt pads
            self.unaligned_data[pad] = frame
            # TODO maybe add bespoke timeout handling here
            return

        # Aligned pad: feed the alignment adapter with the whole frame, so it
        # adopts the frame's (gap-complete) spec before any buffer -- the adapter
        # knows its backend from the first frame, even an all-gap one, and across
        # any later all-gap / empty-then-refill window. The config adapters are
        # fed buffer-lists later in _adapter (no frame there), but the spec is
        # known by then, so seed them here too (adopt_spec ignores an
        # incomplete spec).
        if self.audioadapters is not None:
            self.audioadapters[pad].adopt_spec(spec)
        # Aligned TS pads always carry a TSFrame.
        self.inbufs[pad].push_frame(cast(TSFrame, frame))
        self.metadata[pad] = frame.metadata

        if self.timeout(pad):
            raise ValueError("pad %s has timed out" % pad.name)

    def _check_backend(self, pad: SinkPad, frame: TimeSpanFrame) -> None:
        """Validate the incoming data's backend, reading it from the actual array.

        Two checks (gaps, with no array, are skipped; a frame's buffers share one
        backend, so the first non-gap buffer settles the frame):

        1. **Capability** — unless the element declares ``ANY_BACKEND``, the data
           must be one of the declared ``backends``.
        2. **Agreement** — across the element's *aligned* sink pads (which are
           combined into one computation) and across time, every input must share
           one backend. The element commits to the first non-gap backend it sees
           and rejects a later mismatch, **even for ``ANY_BACKEND``**. This turns a
           combining element fed mixed backends (e.g. an Adder with numpy on one
           pad and torch on another) into a precise error here, instead of a
           cryptic numpy/torch failure deep inside ``process``.

        Args:
            pad:
                SinkPad, the pad the frame arrived on (named in the error)
            frame:
                TimeSpanFrame, the incoming frame to validate
        """
        for buf in frame:
            name = backend_name(getattr(buf, "data", None))
            if name is None:
                continue  # gap: no array, nothing to read
            if not isinstance(self.backends, _AnyBackend) and name not in self.backends:
                raise BackendError(
                    f"element {self.name!r} declares backends={set(self.backends)} "
                    f"but received {name!r} data on sink pad {pad.name!r}. Insert a "
                    f"Converter to a supported backend on this link."
                )
            if pad in self.aligned_sink_pads:
                if self._stream_backend is None:
                    self._stream_backend = name
                elif name != self._stream_backend:
                    raise BackendError(
                        f"element {self.name!r} established backend "
                        f"{self._stream_backend!r} but received {name!r} on sink "
                        f"pad {pad.name!r}. All inputs combined by an element must "
                        f"share one backend; insert a Converter on this link."
                    )
            return

    def _compute_aligned_offset(self, current_offset: int, align_to: int) -> int:
        """Compute aligned offset based on alignment boundary.

        Args:
            current_offset: Current offset in offsets
            align_to: Alignment boundary in offsets

        Returns:
            Aligned offset
        """
        return ((current_offset + align_to - 1) // align_to) * align_to

    def _adapter(self, pad: SinkPad, frame: list[SeriesBuffer]) -> list[SeriesBuffer]:
        """Use the audioadapter to handle streaming scenarios.

        This will pad with overlap before and after the target output
        data, and produce fixed-stride frames.

        The self.preparedframes are padded with the requested overlap padding. This
        method also produces a self.preparedoutoffsets, that infers the metadata
        information for the output buffer, with the data initialized as None.
        Downstream transforms can directly use the frames from self.preparedframes for
        computation, and then use the offset and noffset information in
        self.preparedoutoffsets to construct the output frame.

        If stride is not provided, the audioadapter will push out as many samples as it
        can. If stride is provided, the audioadapter will wait until there are enough
        samples to produce prepared frames.

        Args:
            pad:
                SinkPad, the sink pad on which to prepare adapted frames
            frame:
                TSFrame, the aligned frame

        Returns:
            list[SeriesBuffers], a list of SeriesBuffers that are adapted according to
            the adapter config

        Examples:
            upsampling:
                kernel length = 17
                need to pad 8 samples before and after
                overlap_samples = (8, 8)
                stride_samples = 16
                                                for output
                preparedframes:     ________................________
                                                stride
                                    pad         samples=16  pad
                                    samples=8               samples=8


            correlation:
                filter length = 16
                need to pad filter_length - 1 samples
                overlap_samples = (15, 0)
                stride_samples = 8
                                                    for output
                preparedframes:     ----------------........
                                                    stride_samples=8
                                    pad
                                    samples=15

        """
        assert self.audioadapters is not None
        a = self.audioadapters[pad]
        buf0 = frame[0]
        sample_rate = buf0.sample_rate
        overlap_samples = tuple(
            Offset.tosamples(o, sample_rate) for o in self.adapter_config.overlap
        )
        stride_samples = Offset.tosamples(self.adapter_config.stride, sample_rate)
        pad_zeros_samples = Offset.tosamples(self.pad_zeros_offset[pad], sample_rate)

        # push all buffers in the frame into the audioadapter
        for buf in frame:
            a.push(buf)

        # Check whether we have enough samples to produce a frame
        min_samples = sum(overlap_samples) + (stride_samples or 1) - pad_zeros_samples

        # figure out the offset for preparedframes and preparedoutoffsets
        offset = a.offset - self.pad_zeros_offset[pad]
        outoffset = offset + self.adapter_config.overlap[0]

        # Determine if we're using alignment mode
        use_alignment = (
            self.is_adapter_enabled and self.adapter_config.align_to is not None
        )

        # Apply alignment if configured
        if use_alignment:
            assert self.adapter_config.align_to is not None
            outoffset = self._compute_aligned_offset(
                outoffset,
                self.adapter_config.align_to,
            )

        preparedbufs = []

        # Check if we have enough data
        if use_alignment:
            # For aligned mode, check if we have data up to aligned_offset + stride
            aligned_end = outoffset + self.adapter_config.stride
            has_enough_data = a.end_offset >= aligned_end
        else:
            # Original check based on size
            has_enough_data = a.size >= min_samples

        if not has_enough_data:
            # not enough samples to produce output yet
            # make a heartbeat buffer
            shape = buf0.shape[:-1] + (0,)
            preparedbufs.append(
                SeriesBuffer(
                    offset=offset, sample_rate=sample_rate, data=None, shape=shape
                )
            )
            # prepare output frames, one buffer per frame
            self.preparedoutoffsets = {
                "offset": outoffset + self.adapter_config.offset_shift,
                "noffset": 0,
            }
        else:
            # We have enough samples, retrieve data
            if use_alignment:
                # Retrieve data at exact aligned offset
                aligned_end = outoffset + self.adapter_config.stride

                # Check for gaps in the aligned segment
                segment_has_gap, segment_has_nongap = a.segment_gaps_info(
                    (outoffset, aligned_end)
                )

                if not segment_has_nongap or (
                    self.adapter_config.skip_gaps and segment_has_gap
                ):
                    # Entire segment is gap — produce one gap buffer.
                    # The buffer retains stride_samples_actual shape (rather
                    # than 0 samples) so that all pads produce consistent
                    # durations; gaps are signalled by data=None.
                    stride_samples_actual = Offset.tosamples(
                        self.adapter_config.stride, sample_rate
                    )
                    shape = buf0.shape[:-1] + (stride_samples_actual,)
                    preparedbufs.append(
                        SeriesBuffer(
                            offset=outoffset,
                            sample_rate=sample_rate,
                            data=None,
                            shape=shape,
                        )
                    )
                elif segment_has_gap:
                    # Mixed gap/non-gap — preserve individual buffer
                    # boundaries so downstream can see transitions.
                    preparedbufs.extend(a.get_sliced_buffers((outoffset, aligned_end)))
                else:
                    # Pure non-gap — merge into one aligned buffer
                    data = a.copy_samples_by_offset_segment(
                        (outoffset, aligned_end), pad_start=False
                    )
                    stride_samples_actual = Offset.tosamples(
                        self.adapter_config.stride, sample_rate
                    )
                    shape = buf0.shape[:-1] + (stride_samples_actual,)
                    preparedbufs.append(
                        SeriesBuffer(
                            offset=outoffset,
                            sample_rate=sample_rate,
                            data=data,
                            shape=shape,
                        )
                    )

                # Flush data up to the END of the aligned segment (not the start)
                # This ensures next iteration starts after this segment
                a.flush_samples_by_end_offset(aligned_end)

                # Output offset metadata
                outnoffset = self.adapter_config.stride
                self.preparedoutoffsets = {
                    "offset": outoffset + self.adapter_config.offset_shift,
                    "noffset": outnoffset,
                }

                # No padding offset adjustment needed for aligned mode
                self.pad_zeros_offset[pad] = 0

            else:
                # copy all of the samples in the audioadapter
                if self.adapter_config.stride == 0:
                    # provide all the data
                    num_copy_samples = a.size
                else:
                    num_copy_samples = min_samples

                segment_has_gap, segment_has_nongap = a.segment_gaps_info(
                    (
                        a.offset,
                        a.offset + Offset.fromsamples(num_copy_samples, a.sample_rate),
                    )
                )

                # Check if we should preserve buffer boundaries (align_buffers mode)
                if self.adapter_config.align_buffers:
                    # Return sliced buffers without merging, preserving gaps
                    end_offset = a.offset + Offset.fromsamples(
                        num_copy_samples, a.sample_rate
                    )
                    preparedbufs = list(
                        a.get_sliced_buffers((a.offset, end_offset), pad_start=False)
                    )
                    outnoffset = end_offset - a.offset
                    self.preparedoutoffsets = {
                        "offset": a.offset + self.adapter_config.offset_shift,
                        "noffset": outnoffset,
                    }

                    # flush out samples from head of audioadapter
                    num_flush_samples = num_copy_samples - sum(overlap_samples)
                    if num_flush_samples > 0:
                        a.flush_samples(num_flush_samples)

                elif not segment_has_nongap or (
                    self.adapter_config.skip_gaps and segment_has_gap
                ):
                    # produce a gap buffer if
                    # 1. the whole segment is a gap or
                    # 2. there are gaps in the segment and we are skipping gaps
                    data = None

                    # flush out samples from head of audioadapter
                    num_flush_samples = num_copy_samples - sum(overlap_samples)
                    if num_flush_samples > 0:
                        a.flush_samples(num_flush_samples)

                    shape = buf0.shape[:-1] + (num_copy_samples + pad_zeros_samples,)

                    # update next zeros padding
                    self.pad_zeros_offset[pad] = -min(
                        0, Offset.fromsamples(num_flush_samples, sample_rate)
                    )
                    pbuf = SeriesBuffer(
                        offset=offset, sample_rate=sample_rate, data=data, shape=shape
                    )
                    preparedbufs.append(pbuf)
                    outnoffset = pbuf.noffset - sum(self.adapter_config.overlap)
                    self.preparedoutoffsets = {
                        "offset": outoffset + self.adapter_config.offset_shift,
                        "noffset": outnoffset,
                    }

                else:
                    # copy out samples from head of audioadapter
                    data = a.copy_samples(num_copy_samples)
                    if self.pad_zeros_offset[pad] > 0:
                        # pad zeros in front of the buffer; signal.pad dispatches
                        # on the data's backend (pad is not in the xp standard)
                        data = signal_pad(data, (pad_zeros_samples, 0))

                    # flush out samples from head of audioadapter
                    num_flush_samples = num_copy_samples - sum(overlap_samples)
                    if num_flush_samples > 0:
                        a.flush_samples(num_flush_samples)

                    shape = buf0.shape[:-1] + (num_copy_samples + pad_zeros_samples,)

                    # update next zeros padding
                    self.pad_zeros_offset[pad] = -min(
                        0, Offset.fromsamples(num_flush_samples, sample_rate)
                    )
                    pbuf = SeriesBuffer(
                        offset=offset, sample_rate=sample_rate, data=data, shape=shape
                    )
                    preparedbufs.append(pbuf)
                    outnoffset = pbuf.noffset - sum(self.adapter_config.overlap)
                    self.preparedoutoffsets = {
                        "offset": outoffset + self.adapter_config.offset_shift,
                        "noffset": outnoffset,
                    }

        return preparedbufs

    def _prepared_frame(
        self, sink_pad: SinkPad, buffers: list[SeriesBuffer]
    ) -> TSFrame:
        """A prepared input frame for ``sink_pad``, stamped with the pad's own
        spec so an all-gap frame keeps its backend and dtype. Never another
        pad's spec -- dtypes may differ; with no spec seen yet on this pad the
        frame keeps its computed default.
        """
        return TSFrame(
            EOS=self.at_EOS,
            buffers=buffers,
            metadata=self.metadata[sink_pad],
            spec_hint=self._input_specs.get(sink_pad.pad_name),
        )

    def internal(self) -> None:
        """Align buffers from all the sink pads.

        If AdapterConfig is provided, perform the requested
        overlap/stride streaming of frames.
        """
        # align if possible
        self._align()

        # put in heartbeat buffer if not aligned
        if not self._is_aligned:
            for sink_pad in self.aligned_sink_pads:
                self.preparedframes[sink_pad] = self._prepared_frame(
                    sink_pad,
                    [
                        SeriesBuffer(
                            offset=self.earliest,
                            sample_rate=self.inbufs[sink_pad].sample_rate,
                            data=None,
                            shape=self.inbufs[sink_pad].buffers[0].shape[:-1] + (0,),
                        ),
                    ],
                )
            # Set preparedoutoffsets for heartbeat (zero-length output)
            self.preparedoutoffsets = {
                "offset": self.earliest + self.adapter_config.offset_shift,
                "noffset": 0,
            }
        # Else pack all the buffers
        else:
            min_latest = self.min_latest
            earliest = self.earliest

            rates = set(
                self.inbufs[sink_pad].sample_rate for sink_pad in self.aligned_sink_pads
            )
            off = min_latest - earliest
            for rate in rates:
                factor = Offset.MAX_RATE // rate
                if off % factor:
                    off = off // factor * factor
                    min_latest = earliest + off

            for sink_pad in self.aligned_sink_pads:
                out = list(
                    self.inbufs[sink_pad].get_sliced_buffers(
                        (earliest, min_latest), pad_start=True
                    )
                )
                if min_latest > self.inbufs[sink_pad].offset:
                    self.inbufs[sink_pad].flush_samples_by_end_offset(min_latest)
                assert (
                    len(out) > 0
                ), "No buffers returned from get_sliced_buffers for aligned processing"

                # Apply adapter processing only if adapter is enabled
                if self.is_adapter_enabled:
                    out = self._adapter(sink_pad, out)

                self.preparedframes[sink_pad] = self._prepared_frame(sink_pad, out)

            # Apply buffer alignment if requested
            if self.adapter_config.align_buffers:
                computed_slices = self._compute_aligned_slices()
                for pad, slices in computed_slices.items():
                    self.aligned_slices[pad] = slices

                for pad in self.aligned_sink_pads:
                    aligned_slice = self.aligned_slices[pad]
                    assert aligned_slice is not None
                    frame = self.preparedframes[pad]
                    assert frame is not None
                    # Only align if there are slices (skip if all gaps)
                    if aligned_slice.slices:
                        self.preparedframes[pad] = frame.align(aligned_slice)

            # Set preparedoutoffsets for non-adapter case
            if not self.is_adapter_enabled:
                self.preparedoutoffsets = {
                    "offset": earliest + self.adapter_config.offset_shift,
                    "noffset": min_latest - earliest,
                }

    def _compute_aligned_slices(self) -> dict[SinkPad, TSSlices]:
        """Compute aligned slices for all pads based on minimum sampling rate.

        Extracts slices from prepared frames, finds the minimum
        sampling rate across all pads, and aligns all slices to that rate.
        """
        # Find minimum sampling rate across all aligned pads
        nongap_slices: dict[SinkPad, TSSlices] = {}
        sample_rates = []
        for pad in self.aligned_sink_pads:
            frame = self.preparedframes[pad]
            assert frame is not None
            sample_rates.append(frame.sample_rate)
        min_rate = min(sample_rates)

        # For each pad, extract slices corresponding to non-gaps and align to
        # minimum rate
        for pad in self.aligned_sink_pads:
            frame = self.preparedframes[pad]
            assert frame is not None
            # Extract non-gap buffer slices from the prepared frame
            buffer_slices = [buf.slice for buf in frame.buffers if not buf.is_gap]

            if not buffer_slices:
                # No non-gap buffers, no slices to align
                nongap_slices[pad] = TSSlices([])
                continue

            # align slices to minimum rate
            slices = TSSlices(buffer_slices)
            aligned = slices.align_to_rate(min_rate)
            nongap_slices[pad] = aligned

        start = self.preparedoutoffsets["offset"]
        end = start + self.preparedoutoffsets["noffset"]
        boundaries = sorted(
            set(
                [
                    start,
                    *list(
                        chain(
                            *[
                                [s.start, s.stop]
                                for slices in nongap_slices.values()
                                for s in slices
                            ]
                        )
                    ),
                    end,
                ]
            )
        )
        slice_boundaries = TSSlices(
            [
                TSSlice(b_start, b_stop)
                for b_start, b_stop in zip(boundaries[:-1], boundaries[1:])
            ]
        )

        return {pad: slice_boundaries for pad in self.aligned_sink_pads}

    def _align(self) -> None:
        """Align the buffers in self.inbufs."""

        def slice_from_pad(inbufs):
            if len(inbufs) > 0:
                return TSSlice(inbufs.offset, inbufs.end_offset)
            else:
                return TSSlice(-1, -1)

        def can_align():
            return TSSlices(
                [slice_from_pad(self.inbufs[p]) for p in self.inbufs]
            ).intersection()

        if not self._is_aligned and can_align():
            self._is_aligned = True

    def timeout(self, pad: SinkPad) -> bool:
        """Whether pad has timed-out due to oldest buffer exceeding max age.

        Args:
            pad:
                SinkPad, the sink pad to check for timeout

        Returns:
            True if the pad has timed out

        """
        return self.inbufs[pad].end_offset - self.inbufs[pad].offset > Offset.fromsec(
            self.max_age
        )

    def latest_by_pad(self, pad: SinkPad) -> int:
        """The latest offset among the queued up buffers in this pad.

        Args:
            pad:
                SinkPad, the requested sink pad

        Returns:
            int, the latest offset in the pad's buffer queue

        """
        return self.inbufs[pad].end_offset if self.inbufs[pad] else -1

    def earliest_by_pad(self, pad: SinkPad) -> int:
        """The earliest offset among the queued up buffers in this pad.

        Args:
            pad:
                SinkPad, the requested sink pad

        Returns:
            int, the earliest offset in the pad's buffer queue

        """
        return self.inbufs[pad].offset if self.inbufs[pad] else -1

    @property
    def latest(self) -> int:
        """The latest offset among all the buffers from all the pads."""
        return max(self.latest_by_pad(n) for n in self.inbufs)

    @property
    def earliest(self) -> int:
        """The earliest offset among all the buffers from all the pads."""
        return min(self.earliest_by_pad(n) for n in self.inbufs)

    @property
    def min_latest(self) -> int:
        """The earliest offset among each pad's latest offset."""
        return min(self.latest_by_pad(n) for n in self.inbufs)

    @property
    def is_aligned(self) -> bool:
        """Check if input frames are currently aligned across all pads.

        Returns:
            True if frames from all input pads have overlapping time ranges
            and can be processed together. False if waiting for more data.
        """
        return self._is_aligned

earliest property

The earliest offset among all the buffers from all the pads.

is_aligned property

Check if input frames are currently aligned across all pads.

Returns:

Type Description
bool

True if frames from all input pads have overlapping time ranges

bool

and can be processed together. False if waiting for more data.

latest property

The latest offset among all the buffers from all the pads.

min_latest property

The earliest offset among each pad's latest offset.

__post_init__()

Initialize timeseries state.

Source code in src/sgnts/base/base.py
def __post_init__(self) -> None:
    """Initialize timeseries state."""
    super().__post_init__()

    # Determine which user-provided input pads require alignment
    unaligned_names = list(self.unaligned) + self.static_unaligned_sink_pads

    # Convert pad names to SinkPad objects and store in instance variable
    self.unaligned_sink_pads = [
        self.snks[name] for name in unaligned_names  # type: ignore[attr-defined]
    ]
    self.aligned_sink_pads = [
        p for p in self.sink_pads if p not in self.unaligned_sink_pads
    ]

    # Initialize metadata for exempt sink pads
    self.unaligned_data: dict[SinkPad, TimeSpanFrame | None] = {
        p: None for p in self.unaligned_sink_pads
    }

    # Initialize the alignment metadata for all sink pads that need to be aligned
    self._is_aligned = False
    self.inbufs = {p: Audioadapter() for p in self.aligned_sink_pads}
    self.preparedframes: dict[SinkPad, TSFrame | None] = {
        p: None for p in self.aligned_sink_pads
    }
    self.aligned_slices: dict[SinkPad, TSSlices | None] = {
        p: None for p in self.aligned_sink_pads
    }
    self.outframes: dict[SourcePad, TimeSpanFrame | None] = {
        p: None for p in self.source_pads
    }
    self.preparedoutoffsets = {"offset": 0, "noffset": 0}
    self.at_EOS = False
    # Last complete spec per sink pad, keyed by pad name. Used to stamp
    # self-generated gap/heartbeat frames so an all-gap stretch keeps its own
    # pad's backend and dtype (pads may differ), and read by
    # ``input_prototype`` so an element can build a per-output prototype from
    # the specific inputs that determine it (many-to-many, different dtypes).
    self._input_specs: dict[str, Any] = {}
    # The one backend this element combines across its aligned pads. Set from
    # the first non-gap input and enforced thereafter (see _check_backend).
    self._stream_backend: Optional[str] = None
    self._last_ts: dict[SinkPad, float | None] = {
        p: None for p in self.aligned_sink_pads
    }
    self._last_offset: dict[SinkPad, int | None] = {
        p: None for p in self.aligned_sink_pads
    }
    self.metadata: dict[SinkPad, dict[Any, Any]] = {
        p: {} for p in self.aligned_sink_pads
    }

    # Initialize default frame types for inputs and outputs
    # These can be overridden by derived classes in configure()
    self.input_frame_types: dict[str, type[TimeSpanFrame]] = {
        name: TSFrame for name in self.sink_pad_names  # type: ignore[attr-defined]
    }
    # Initialize default output frame types (only for elements with source pads)
    # All pads default to TSFrame, elements can override in configure()
    self.output_frame_types: dict[str, type[TimeSpanFrame]] = {
        name: TSFrame for name in getattr(self, "source_pad_names", [])
    }

    # Configure adapter and element-specific attributes
    self.configure()

    self.is_adapter_enabled = self.adapter_config.is_enabled

    # Initialize adapter-specific state only if adapter is enabled
    self.audioadapters = None
    if self.is_adapter_enabled:
        # we need audioadapters
        self.audioadapters = {p: Audioadapter() for p in self.aligned_sink_pads}
        self.pad_zeros_offset: dict[SinkPad, int] = {}
        for p in self.aligned_sink_pads:
            if self.adapter_config.pad_zeros_startup is True:
                # at startup, pad zeros in front of the first buffer to
                # serve as history
                self.pad_zeros_offset[p] = self.adapter_config.overlap[0]
            else:
                self.pad_zeros_offset[p] = 0

    # Call validation hooks
    self.validate()

configure()

Configure element-specific settings.

Source code in src/sgnts/base/base.py
def configure(self) -> None:
    """Configure element-specific settings."""
    pass

earliest_by_pad(pad)

The earliest offset among the queued up buffers in this pad.

Parameters:

Name Type Description Default
pad SinkPad

SinkPad, the requested sink pad

required

Returns:

Type Description
int

int, the earliest offset in the pad's buffer queue

Source code in src/sgnts/base/base.py
def earliest_by_pad(self, pad: SinkPad) -> int:
    """The earliest offset among the queued up buffers in this pad.

    Args:
        pad:
            SinkPad, the requested sink pad

    Returns:
        int, the earliest offset in the pad's buffer queue

    """
    return self.inbufs[pad].offset if self.inbufs[pad] else -1

input_prototype(sink_pad_name, dtype=None, device=None)

A zero-length array in a sink pad's backend, for building output prototypes.

Returns namespace.zeros((0,), dtype=…, device=…) from the last complete spec seen on sink pad sink_pad_name. dtype/device default to that input's own; pass them to override (device only inside a Converter). Use this inside :meth:output_prototype so namespace and device are inherited from the data rather than hard-coded -- the reason a prototype is preferred over constructing a SeriesDataSpec by hand.

Raises:

Type Description
KeyError

if no complete spec has been seen yet on sink_pad_name. In a running pipeline this cannot fire by the time output frames are built: every sink pad records its spec on its first pull (frames carry a complete spec even when all-gap), and internal() runs only after the pulls.

Source code in src/sgnts/base/base.py
def input_prototype(
    self, sink_pad_name: str, dtype: Any = None, device: Any = None
) -> "Array":
    """A zero-length array in a sink pad's backend, for building output prototypes.

    Returns ``namespace.zeros((0,), dtype=…, device=…)`` from the last complete
    spec seen on sink pad ``sink_pad_name``. ``dtype``/``device`` default to that
    input's own; pass them to override (``device`` only inside a Converter). Use
    this inside :meth:`output_prototype` so namespace and device are *inherited
    from the data* rather than hard-coded -- the reason a prototype is preferred
    over constructing a ``SeriesDataSpec`` by hand.

    Raises:
        KeyError: if no complete spec has been seen yet on ``sink_pad_name``.
            In a running pipeline this cannot fire by the time output frames
            are built: every sink pad records its spec on its first pull
            (frames carry a complete spec even when all-gap), and
            ``internal()`` runs only after the pulls.
    """
    spec = self._input_specs[sink_pad_name]
    namespace = spec.namespace
    return namespace.zeros(
        (0,),
        dtype=dtype if dtype is not None else spec.data_type,
        device=device if device is not None else spec.device,
    )

internal()

Align buffers from all the sink pads.

If AdapterConfig is provided, perform the requested overlap/stride streaming of frames.

Source code in src/sgnts/base/base.py
def internal(self) -> None:
    """Align buffers from all the sink pads.

    If AdapterConfig is provided, perform the requested
    overlap/stride streaming of frames.
    """
    # align if possible
    self._align()

    # put in heartbeat buffer if not aligned
    if not self._is_aligned:
        for sink_pad in self.aligned_sink_pads:
            self.preparedframes[sink_pad] = self._prepared_frame(
                sink_pad,
                [
                    SeriesBuffer(
                        offset=self.earliest,
                        sample_rate=self.inbufs[sink_pad].sample_rate,
                        data=None,
                        shape=self.inbufs[sink_pad].buffers[0].shape[:-1] + (0,),
                    ),
                ],
            )
        # Set preparedoutoffsets for heartbeat (zero-length output)
        self.preparedoutoffsets = {
            "offset": self.earliest + self.adapter_config.offset_shift,
            "noffset": 0,
        }
    # Else pack all the buffers
    else:
        min_latest = self.min_latest
        earliest = self.earliest

        rates = set(
            self.inbufs[sink_pad].sample_rate for sink_pad in self.aligned_sink_pads
        )
        off = min_latest - earliest
        for rate in rates:
            factor = Offset.MAX_RATE // rate
            if off % factor:
                off = off // factor * factor
                min_latest = earliest + off

        for sink_pad in self.aligned_sink_pads:
            out = list(
                self.inbufs[sink_pad].get_sliced_buffers(
                    (earliest, min_latest), pad_start=True
                )
            )
            if min_latest > self.inbufs[sink_pad].offset:
                self.inbufs[sink_pad].flush_samples_by_end_offset(min_latest)
            assert (
                len(out) > 0
            ), "No buffers returned from get_sliced_buffers for aligned processing"

            # Apply adapter processing only if adapter is enabled
            if self.is_adapter_enabled:
                out = self._adapter(sink_pad, out)

            self.preparedframes[sink_pad] = self._prepared_frame(sink_pad, out)

        # Apply buffer alignment if requested
        if self.adapter_config.align_buffers:
            computed_slices = self._compute_aligned_slices()
            for pad, slices in computed_slices.items():
                self.aligned_slices[pad] = slices

            for pad in self.aligned_sink_pads:
                aligned_slice = self.aligned_slices[pad]
                assert aligned_slice is not None
                frame = self.preparedframes[pad]
                assert frame is not None
                # Only align if there are slices (skip if all gaps)
                if aligned_slice.slices:
                    self.preparedframes[pad] = frame.align(aligned_slice)

        # Set preparedoutoffsets for non-adapter case
        if not self.is_adapter_enabled:
            self.preparedoutoffsets = {
                "offset": earliest + self.adapter_config.offset_shift,
                "noffset": min_latest - earliest,
            }

latest_by_pad(pad)

The latest offset among the queued up buffers in this pad.

Parameters:

Name Type Description Default
pad SinkPad

SinkPad, the requested sink pad

required

Returns:

Type Description
int

int, the latest offset in the pad's buffer queue

Source code in src/sgnts/base/base.py
def latest_by_pad(self, pad: SinkPad) -> int:
    """The latest offset among the queued up buffers in this pad.

    Args:
        pad:
            SinkPad, the requested sink pad

    Returns:
        int, the latest offset in the pad's buffer queue

    """
    return self.inbufs[pad].end_offset if self.inbufs[pad] else -1

next_event_input()

Get single EventFrame input.

Returns:

Type Description
tuple[SinkPad, EventFrame]

EventFrame, the single EventFrame from inputs

Raises:

Type Description
AssertionError

If there is not exactly one EventFrame input.

Source code in src/sgnts/base/base.py
def next_event_input(self) -> tuple[SinkPad, EventFrame]:
    """Get single EventFrame input.

    Returns:
        EventFrame, the single EventFrame from inputs

    Raises:
        AssertionError: If there is not exactly one EventFrame input.
    """
    all_events = self.next_event_inputs()
    assert len(all_events) == 1, (
        f"next_event_input() requires exactly one EventFrame input, "
        f"got {len(all_events)}"
    )
    return next(iter(all_events.items()))

next_event_inputs()

Get all EventFrame inputs based on input_frame_types configuration.

Returns:

Type Description
dict[SinkPad, EventFrame]

dict[SinkPad, EventFrame], mapping of sink pads to EventFrame inputs

Source code in src/sgnts/base/base.py
def next_event_inputs(self) -> dict[SinkPad, EventFrame]:
    """Get all EventFrame inputs based on input_frame_types configuration.

    Returns:
        dict[SinkPad, EventFrame], mapping of sink pads to EventFrame inputs
    """
    result: dict[SinkPad, EventFrame] = {}
    for pad in self.sink_pads:
        pad_name = self.rsnks[pad]  # type: ignore[attr-defined]
        if self.input_frame_types.get(pad_name) == EventFrame:
            if pad in self.unaligned_sink_pads:
                frame = self.unaligned_data[pad]
            else:
                frame = self.preparedframes[pad]
            assert isinstance(frame, EventFrame), (
                f"Expected EventFrame on pad {pad_name}, "
                f"got {type(frame).__name__}"
            )
            result[pad] = frame
    return result

next_event_output()

Get single EventFrame for output with offset/noffset from preparedoutoffsets.

Returns:

Type Description
tuple[SourcePad, EventFrame]

EventFrame, an empty event frame ready to be populated

Raises:

Type Description
AssertionError

If there is not exactly one event output pad.

Source code in src/sgnts/base/base.py
def next_event_output(self) -> tuple[SourcePad, EventFrame]:
    """Get single EventFrame for output with offset/noffset from preparedoutoffsets.

    Returns:
        EventFrame, an empty event frame ready to be populated

    Raises:
        AssertionError: If there is not exactly one event output pad.
    """
    all_events = self.next_event_outputs()
    assert len(all_events) == 1, (
        f"next_event_output() requires exactly one event output pad, "
        f"got {len(all_events)}"
    )
    return next(iter(all_events.items()))

next_event_outputs()

Get all EventFrames for output pads configured as event outputs.

Creates EventFrame instances with offset/noffset from preparedoutoffsets for all source pads configured to produce EventFrame. The frames are automatically registered in self.outframes for return.

Returns:

Type Description
dict[SourcePad, EventFrame]

dict[SourcePad, EventFrame], mapping of source pads to empty EventFrames

Source code in src/sgnts/base/base.py
def next_event_outputs(self) -> dict[SourcePad, EventFrame]:
    """Get all EventFrames for output pads configured as event outputs.

    Creates EventFrame instances with offset/noffset from preparedoutoffsets
    for all source pads configured to produce EventFrame. The frames are
    automatically registered in self.outframes for return.

    Returns:
        dict[SourcePad, EventFrame], mapping of source pads to empty EventFrames
    """
    offset = self.preparedoutoffsets["offset"]
    noffset = self.preparedoutoffsets["noffset"]
    at_EOS = any(
        frame.EOS for frame in self.preparedframes.values() if frame is not None
    )

    result: dict[SourcePad, EventFrame] = {}
    for pad in self.source_pads:
        pad_name = self.rsrcs[pad]  # type: ignore[attr-defined]
        if self.output_frame_types.get(pad_name) == EventFrame:
            frame = EventFrame(offset=offset, noffset=noffset, EOS=at_EOS)
            result[pad] = frame
            # Automatically register in outframes
            self.outframes[pad] = frame
    return result

next_input()

Convenience method - get single TSFrame input.

Equivalent to next_ts_input(). For transforms that only work with TSFrames.

Returns:

Type Description
tuple[SinkPad, TSFrame]

TSFrame, single input frame

Source code in src/sgnts/base/base.py
def next_input(self) -> tuple[SinkPad, TSFrame]:
    """Convenience method - get single TSFrame input.

    Equivalent to next_ts_input(). For transforms that only work with TSFrames.

    Returns:
        TSFrame, single input frame
    """
    return self.next_ts_input()

next_inputs()

Convenience method - get all TSFrame inputs.

Equivalent to next_ts_inputs(). For transforms that only work with TSFrames.

Returns:

Type Description
dict[SinkPad, TSFrame]

dict[SinkPad, TSFrame], dictionary of input frames

Source code in src/sgnts/base/base.py
def next_inputs(self) -> dict[SinkPad, TSFrame]:
    """Convenience method - get all TSFrame inputs.

    Equivalent to next_ts_inputs(). For transforms that only work with TSFrames.

    Returns:
        dict[SinkPad, TSFrame], dictionary of input frames
    """
    return self.next_ts_inputs()

next_output()

Convenience method - get single TSCollectFrame output.

Equivalent to next_ts_output(). For transforms that only work with TSFrames.

Note: Elements using this method must call .close() on the collector when done populating buffers.

Returns:

Type Description
tuple[SourcePad, TSCollectFrame]

tuple[SourcePad, TSCollectFrame], pad and collector for output frame

Source code in src/sgnts/base/base.py
def next_output(self) -> tuple[SourcePad, TSCollectFrame]:
    """Convenience method - get single TSCollectFrame output.

    Equivalent to next_ts_output(). For transforms that only work with TSFrames.

    Note: Elements using this method must call `.close()` on the collector
    when done populating buffers.

    Returns:
        tuple[SourcePad, TSCollectFrame], pad and collector for output frame
    """
    return self.next_ts_output()

next_outputs()

Convenience method - get all TSCollectFrame outputs.

Equivalent to next_ts_outputs(). For transforms that only work with TSFrames.

Note: Elements using this method must call .close() on each collector when done populating buffers.

Returns:

Type Description
dict[SourcePad, TSCollectFrame]

dict[SourcePad, TSCollectFrame], dictionary of collectors for output frames

Source code in src/sgnts/base/base.py
def next_outputs(self) -> dict[SourcePad, TSCollectFrame]:
    """Convenience method - get all TSCollectFrame outputs.

    Equivalent to next_ts_outputs(). For transforms that only work with TSFrames.

    Note: Elements using this method must call `.close()` on each collector
    when done populating buffers.

    Returns:
        dict[SourcePad, TSCollectFrame], dictionary of collectors for output frames
    """
    return self.next_ts_outputs()

next_ts_input()

Get single TSFrame input.

Returns:

Type Description
tuple[SinkPad, TSFrame]

TSFrame, the single TSFrame from inputs

Raises:

Type Description
AssertionError

If there is not exactly one TSFrame input.

Source code in src/sgnts/base/base.py
def next_ts_input(self) -> tuple[SinkPad, TSFrame]:
    """Get single TSFrame input.

    Returns:
        TSFrame, the single TSFrame from inputs

    Raises:
        AssertionError: If there is not exactly one TSFrame input.
    """
    all_ts = self.next_ts_inputs()
    assert (
        len(all_ts) == 1
    ), f"next_ts_input() requires exactly one TSFrame input, got {len(all_ts)}"
    return next(iter(all_ts.items()))

next_ts_inputs()

Get all TSFrame inputs based on input_frame_types configuration.

Returns:

Type Description
dict[SinkPad, TSFrame]

dict[SinkPad, TSFrame], mapping of sink pads to TSFrame inputs

Source code in src/sgnts/base/base.py
def next_ts_inputs(self) -> dict[SinkPad, TSFrame]:
    """Get all TSFrame inputs based on input_frame_types configuration.

    Returns:
        dict[SinkPad, TSFrame], mapping of sink pads to TSFrame inputs
    """
    result: dict[SinkPad, TSFrame] = {}
    for pad in self.sink_pads:
        pad_name = self.rsnks[pad]  # type: ignore[attr-defined]
        if self.input_frame_types.get(pad_name, TSFrame) == TSFrame:
            if pad in self.aligned_sink_pads:
                frame = self.preparedframes[pad]
                assert frame is not None
                result[pad] = frame
            else:
                unaligned_frame = self.unaligned_data[pad]
                assert isinstance(unaligned_frame, TSFrame), (
                    f"Expected TSFrame on unaligned pad {pad_name}, "
                    f"got {type(unaligned_frame).__name__}"
                )
                result[pad] = unaligned_frame
    return result

next_ts_output()

Get single TSCollectFrame for output with offsets from preparedoutoffsets.

Note: The caller must call .close() on the collector when done populating buffers.

Returns:

Type Description
SourcePad

tuple[SourcePad, TSCollectFrame], pad and collector for the output

TSCollectFrame

frame

Raises:

Type Description
AssertionError

If there is not exactly one TS output pad.

Source code in src/sgnts/base/base.py
def next_ts_output(self) -> tuple[SourcePad, TSCollectFrame]:
    """Get single TSCollectFrame for output with offsets from preparedoutoffsets.

    Note: The caller must call `.close()` on the collector when done
    populating buffers.

    Returns:
        tuple[SourcePad, TSCollectFrame], pad and collector for the output
        frame

    Raises:
        AssertionError: If there is not exactly one TS output pad.
    """
    all_ts = self.next_ts_outputs()
    assert (
        len(all_ts) == 1
    ), f"next_ts_output() requires exactly one TS output pad, got {len(all_ts)}"
    return next(iter(all_ts.items()))

next_ts_outputs()

Get all TSCollectFrames for output pads configured as TS outputs.

Creates TSFrame instances with offset/noffset from preparedoutoffsets, then creates TSCollectFrame collectors for atomic buffer population. The parent TSFrames are automatically registered in self.outframes.

Returns:

Type Description
dict[SourcePad, TSCollectFrame]

dict[SourcePad, TSCollectFrame], mapping of source pads to collectors

Source code in src/sgnts/base/base.py
def next_ts_outputs(self) -> dict[SourcePad, TSCollectFrame]:
    """Get all TSCollectFrames for output pads configured as TS outputs.

    Creates TSFrame instances with offset/noffset from preparedoutoffsets,
    then creates TSCollectFrame collectors for atomic buffer population.
    The parent TSFrames are automatically registered in self.outframes.

    Returns:
        dict[SourcePad, TSCollectFrame], mapping of source pads to collectors
    """
    offset = self.preparedoutoffsets["offset"]
    noffset = self.preparedoutoffsets["noffset"]
    at_EOS = any(
        frame.EOS for frame in self.preparedframes.values() if frame is not None
    )

    result: dict[SourcePad, TSCollectFrame] = {}
    for pad in self.source_pads:
        pad_name = self.rsrcs[pad]  # type: ignore[attr-defined]
        if self.output_frame_types.get(pad_name, TSFrame) == TSFrame:
            # An all-gap output frame has no array to read its backend from, so
            # stamp it from the per-pad output prototype (default: inherit the
            # input spec). Real frames read their backend from their own data.
            frame = TSFrame(
                offset=offset,
                noffset=noffset,
                EOS=at_EOS,
                spec_hint=self._output_hint(pad),
            )
            collector = frame.fill()
            result[pad] = collector
            # Automatically register the parent frame in outframes
            self.outframes[pad] = frame
    return result

output_prototype(pad)

A zero-length example of what pad emits -- the one hook for telling the framework an output's backend and dtype.

Real data describes itself ("the array is the backend"), so this is used only to stamp this element's all-gap output frames. The framework reads namespace, device and dtype off the returned array. Build it from the inputs with :meth:input_prototype so the backend rides through automatically and dtype/promotion follow the actual operation::

def output_prototype(self, pad):
    # output dtype = result_type(input, factor); use your pad's name
    return self.input_prototype(self.sink_pad_names[0]) * self.factor

Contract by role:

  • Transform -- may change only dtype. The framework asserts the returned prototype keeps the input's namespace+device; to change those you must be a Converter (set changes_backend = True).
  • Source -- has no inputs, so it returns a literal, e.g. numpy.zeros(0) or torch.zeros(0, dtype=torch.float16, device="cuda").
  • Default (None) -- "same backend and dtype as my input": the pass-through case, which is most transforms. Write nothing. Only well-defined while all inputs share one backend identity: an element combining different dtypes must declare, or preparing its output frames raises BackendError once differing input specs are seen (see _output_hint).

Caveat -- an op that changes both shape and dtype (e.g. an FFT, real->complex) cannot be run on a length-0 array; declare the dtype instead of running the op::

return self.input_prototype(self.sink_pad_names[0], dtype=complex)

Returns:

Type Description
'Array | None'

A zero-length array carrying the output's namespace/device/dtype, or

'Array | None'

None to inherit the input's spec unchanged.

Source code in src/sgnts/base/base.py
def output_prototype(self, pad: SourcePad) -> "Array | None":
    """A zero-length *example* of what ``pad`` emits -- the one hook for telling
    the framework an output's backend and dtype.

    Real data describes itself ("the array is the backend"), so this is used
    only to stamp this element's **all-gap** output frames. The framework reads
    ``namespace``, ``device`` and ``dtype`` off the returned array. Build it
    from the inputs with :meth:`input_prototype` so the backend rides through
    automatically and dtype/promotion follow the actual operation::

        def output_prototype(self, pad):
            # output dtype = result_type(input, factor); use your pad's name
            return self.input_prototype(self.sink_pad_names[0]) * self.factor

    Contract by role:

    - **Transform** -- may change only **dtype**. The framework asserts the
      returned prototype keeps the input's namespace+device; to change those
      you must be a Converter (set ``changes_backend = True``).
    - **Source** -- has no inputs, so it returns a literal, e.g.
      ``numpy.zeros(0)`` or ``torch.zeros(0, dtype=torch.float16, device="cuda")``.
    - **Default** (``None``) -- "same backend and dtype as my input": the
      pass-through case, which is most transforms. Write nothing. Only
      well-defined while all inputs share one backend identity: an element
      combining different dtypes must declare, or preparing its output
      frames raises ``BackendError`` once differing input specs are seen
      (see ``_output_hint``).

    Caveat -- an op that changes **both shape and dtype** (e.g. an FFT,
    real->complex) cannot be run on a length-0 array; *declare* the dtype
    instead of running the op::

        return self.input_prototype(self.sink_pad_names[0], dtype=complex)

    Returns:
        A zero-length array carrying the output's namespace/device/dtype, or
        ``None`` to inherit the input's spec unchanged.
    """
    return None

pull(pad, frame)

Pull data and queue for alignment.

Pull data from the input pads (source pads of upstream elements) and queue data to perform alignment once frames from all pads are pulled.

Parameters:

Name Type Description Default
pad SinkPad

SinkPad, The sink pad that is pulling the frame

required
frame TimeSpanFrame

TimeSpanFrame, The frame that is pulled to sink pad

required
Source code in src/sgnts/base/base.py
def pull(self, pad: SinkPad, frame: TimeSpanFrame) -> None:
    """Pull data and queue for alignment.

    Pull data from the input pads (source pads of upstream elements) and
    queue data to perform alignment once frames from all pads are pulled.

    Args:
        pad:
            SinkPad, The sink pad that is pulling the frame
        frame:
            TimeSpanFrame, The frame that is pulled to sink pad
    """
    self.at_EOS |= frame.EOS

    # Validate the incoming data's backend against this element's declared
    # capability. The array is the source of truth; a mismatch means a
    # Converter is missing on this link.
    self._check_backend(pad, frame)

    # Remember this pad's backend so heartbeats/gaps we emit keep it.
    spec = getattr(frame, "spec", None)
    if _is_complete_spec(spec):
        self._input_specs[pad.pad_name] = spec

    # Handle case of a pad that is exempt from alignment
    if pad in self.unaligned_sink_pads:
        # Store most recent data for exempt pads
        self.unaligned_data[pad] = frame
        # TODO maybe add bespoke timeout handling here
        return

    # Aligned pad: feed the alignment adapter with the whole frame, so it
    # adopts the frame's (gap-complete) spec before any buffer -- the adapter
    # knows its backend from the first frame, even an all-gap one, and across
    # any later all-gap / empty-then-refill window. The config adapters are
    # fed buffer-lists later in _adapter (no frame there), but the spec is
    # known by then, so seed them here too (adopt_spec ignores an
    # incomplete spec).
    if self.audioadapters is not None:
        self.audioadapters[pad].adopt_spec(spec)
    # Aligned TS pads always carry a TSFrame.
    self.inbufs[pad].push_frame(cast(TSFrame, frame))
    self.metadata[pad] = frame.metadata

    if self.timeout(pad):
        raise ValueError("pad %s has timed out" % pad.name)

timeout(pad)

Whether pad has timed-out due to oldest buffer exceeding max age.

Parameters:

Name Type Description Default
pad SinkPad

SinkPad, the sink pad to check for timeout

required

Returns:

Type Description
bool

True if the pad has timed out

Source code in src/sgnts/base/base.py
def timeout(self, pad: SinkPad) -> bool:
    """Whether pad has timed-out due to oldest buffer exceeding max age.

    Args:
        pad:
            SinkPad, the sink pad to check for timeout

    Returns:
        True if the pad has timed out

    """
    return self.inbufs[pad].end_offset - self.inbufs[pad].offset > Offset.fromsec(
        self.max_age
    )

validate()

Validate element configuration.

Source code in src/sgnts/base/base.py
def validate(self) -> None:
    """Validate element configuration."""
    pass

make_ts_element(sgn_element_class)

Factory to create TS-enabled versions of SGN elements.

This provides a simple way to add TS capabilities to existing SGN elements so they can connect to TS pipelines. Uses a basic AdapterConfig() that works for most general-purpose applications.

Parameters:

Name Type Description Default
sgn_element_class Type

SGN element class to enhance

required

Returns:

Type Description
Type

New class that combines SGN element with TS capabilities

Source code in src/sgnts/base/base.py
def make_ts_element(sgn_element_class: Type) -> Type:
    """Factory to create TS-enabled versions of SGN elements.

    This provides a simple way to add TS capabilities to existing SGN elements
    so they can connect to TS pipelines. Uses a basic AdapterConfig() that works
    for most general-purpose applications.

    Args:
        sgn_element_class: SGN element class to enhance

    Returns:
        New class that combines SGN element with TS capabilities
    """

    @dataclass
    class TSEnabledElement(TimeSeriesMixin, sgn_element_class):
        """Dynamically created TS-enabled element."""

        # Use basic adapter config that works for general TS connectivity
        adapter_config: AdapterConfig = field(default_factory=AdapterConfig)

        def pull(self, pad, frame):
            """Pull frame and queue for alignment."""
            # Only call TimeSeriesMixin.pull for alignment
            # SGN element's pull logic happens in internal() from preparedframes
            TimeSeriesMixin.pull(self, pad, frame)

        def internal(self):
            """Align frames and pass to SGN element's pull() logic."""
            # First, let TimeSeriesMixin align the frames
            TimeSeriesMixin.internal(self)

            # Now call the SGN element's pull() with aligned frames
            for pad in self.aligned_sink_pads:
                frame = self.preparedframes[pad]
                sgn_element_class.pull(self, pad, frame)

        def new(self, pad):
            """Default implementation of new() for factory-created elements."""
            return self.outframes.get(pad)

    # Set a meaningful name for the new class
    TSEnabledElement.__name__ = f"TS{sgn_element_class.__name__}"
    TSEnabledElement.__qualname__ = f"TS{sgn_element_class.__qualname__}"

    return TSEnabledElement

resolve_heartbeat_interval(heartbeat_interval)

The bounded wait before a starved real-time source emits a heartbeat.

None means a quarter of the stride. float("inf") disables heartbeats entirely: the source may stall the pipeline's graph loop indefinitely, pinning every element at real time while it waits.

Source code in src/sgnts/base/base.py
def resolve_heartbeat_interval(heartbeat_interval: float | None) -> float:
    """The bounded wait before a starved real-time source emits a heartbeat.

    ``None`` means a quarter of the stride. ``float("inf")`` disables
    heartbeats entirely: the source may stall the pipeline's graph loop
    indefinitely, pinning every element at real time while it waits.
    """
    if heartbeat_interval is not None:
        return heartbeat_interval
    return Offset.tosec(Offset.SAMPLE_STRIDE_AT_MAX_RATE) / 4