hf2q 0.1.30

Pure Rust CLI for converting HuggingFace models to hardware-optimized formats and serving them over an OpenAI-compatible API on Apple Silicon
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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
"""Q5 sampler/first-stop/cleanup using proven Native9 lifetime ownership.

PIDs/PGIDs are diagnostics. Only gated root registration and kernel parent
lifetime edges establish ownership; all signals use fresh audited identities.
"""
import ctypes
import errno
import hashlib
import json
import math
import os
from pathlib import Path
import signal
import subprocess
import sys
import threading
import time

import q5_host

native_owned = q5_host.native_owned
OWNERSHIP_SCHEMA = native_owned.SCHEMA
FOOTPRINT_SOURCE = 'proc_pid_rusage:RUSAGE_INFO_V0:ri_phys_footprint'
_FOOTPRINT_LOCAL = threading.local()


class CommandDeadline:
    """One monotonic entrypoint budget; cleanup is mandatory even after expiry."""

    def __init__(self, seconds, started_ns=None):
        if seconds is not None and (type(seconds) not in (int, float) or
                                    not math.isfinite(seconds) or seconds <= 0):
            raise ValueError('deadline seconds must be finite and positive')
        self.seconds = seconds
        self.started_ns = time.monotonic_ns() if started_ns is None else started_ns
        self.expires_ns = None if seconds is None else self.started_ns + math.ceil(seconds * 1e9)

    def expired(self):
        return self.expires_ns is not None and time.monotonic_ns() >= self.expires_ns

    def stop(self):
        return {'reason': 'command_deadline', 'detail': str(self.seconds), 'sample_index': None,
                'sample_start_ns': time.monotonic_ns(), 'sample_end_ns': None}

    def trip(self, latch):
        if self.expired():
            latch.trip(self.stop())
            return True
        return False

    def record(self):
        now = time.monotonic_ns()
        return {'seconds': self.seconds, 'started_ns': self.started_ns, 'expires_ns': self.expires_ns,
                'origin': 'main entry, never reset', 'elapsed_seconds': (now - self.started_ns) / 1e9,
                'exceeded': self.expires_ns is not None and now >= self.expires_ns}


class _RusageInfoV0(ctypes.Structure):
    # Darwin SDK sys/resource.h:202-213. RUSAGE_INFO_V0 is a fixed 96-byte ABI.
    _fields_ = [('ri_uuid', ctypes.c_uint8 * 16)] + [
        (name, ctypes.c_uint64) for name in (
            'ri_user_time', 'ri_system_time', 'ri_pkg_idle_wkups', 'ri_interrupt_wkups',
            'ri_pageins', 'ri_wired_size', 'ri_resident_size', 'ri_phys_footprint',
            'ri_proc_start_abstime', 'ri_proc_exit_abstime')]


def _native_footprint(pid):
    """Actual current physical-footprint ledger; never RSS or a CLI fallback.

    The caller must bracket this numeric API with NativeTable expected lifetime
    and execution version. No unqualified result can commit to an aggregate.
    """
    if not hasattr(_FOOTPRINT_LOCAL, 'read'):
        libproc = ctypes.CDLL('/usr/lib/libproc.dylib', use_errno=True)
        read = libproc.proc_pid_rusage
        read.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_void_p]
        read.restype = ctypes.c_int
        native_owned.require(ctypes.sizeof(_RusageInfoV0) == 96, 'unexpected rusage_info_v0 ABI')
        _FOOTPRINT_LOCAL.read, _FOOTPRINT_LOCAL.info = read, _RusageInfoV0()
    info = _FOOTPRINT_LOCAL.info
    ctypes.set_errno(0)
    if _FOOTPRINT_LOCAL.read(pid, 0, ctypes.byref(info)) != 0:
        raise OSError(ctypes.get_errno() or errno.EIO, f'native footprint unavailable pid={pid}')
    if info.ri_proc_exit_abstime:
        raise OSError(errno.ESRCH, f'cannot measure exited task pid={pid}')
    return int(info.ri_phys_footprint)


def source_bindings():
    paths = q5_host.source_bindings()
    path = Path(__file__).resolve()
    paths[str(path)] = q5_host.digest(path)
    return paths


def compact(host):
    if host is None:
        return None
    vm = host['vm']
    return {'free_plus_cached_bytes': vm['free_plus_cached_bytes'], 'compressor_bytes': vm['compressor_bytes'],
            'wired_bytes': vm['wired_bytes'], 'anonymous_bytes': vm['anonymous_bytes'],
            'file_backed_bytes': vm['file_backed_bytes'], 'free_bytes': vm['free_bytes'],
            'speculative_bytes': vm['speculative_bytes'], 'swap_used_bytes': host['swap']['used_bytes'],
            'pressure_level': host['pressure_level'], 'pressure': host['pressure'],
            'memorystatus_level': host['memorystatus_level']}


class Ownership(dict):
    """PID -> first-observed native identity; never accepts a numeric root."""
    def __init__(self, lock):
        super().__init__()
        self.lock = lock
        self.native = native_owned.NativeTable(q5_host.KERNEL_IDENTITY_SOURCE)
        self.tree = native_owned.OwnedTree(self.native)
        self.tree.known = self
        self.popens, self.root_identities = [], {}
        self.term_sent, self.kill_sent = set(), set()
        self.closed = False

    def observe(self):
        rows, live = self.tree.observe()
        # Match the proven single-root primitive's conservative root-group
        # collision refusal for EVERY registered root. A PGID can deny safety,
        # but can never confer ownership or permission to signal a PID.
        roots = {row['pgid'] for row in self.root_identities.values()}
        for row in rows.values():
            if row['pgid'] in roots and row['pid'] not in live:
                self.tree.refused_pgids.add(row['pgid'])
        return rows, live

    def signal_live(self, sig):
        sent = self.term_sent if sig == signal.SIGTERM else self.kill_sent
        for _ in range(native_owned.MAX_COHERENT_OWNER_ATTEMPTS):
            try:
                rows, live = self.observe()
                for row in self.tree.descendant_first(live):
                    key = (row['pid'], row['lifetime_id'])
                    if key in sent:
                        continue
                    self.tree.signal_identity(row, sig)
                    sent.add(key)
                return rows, live
            except native_owned.RefreshRequired as error:
                self.tree.metadata_transitions.append({
                    'reason': str(error), 'before': error.before, 'after': error.after,
                    'observed_ns': time.monotonic_ns()})
        raise native_owned.OwnershipError('immediate signal metadata did not stabilize')

    def evidence(self):
        return {'schema': OWNERSHIP_SCHEMA,
                'identity_authority': 'Darwin uniqueid/parent_uniqueid; audited p_idversion signal',
                'root_identities': list(self.root_identities.values()),
                'known_identities': list(self.values()),
                'signal_events': list(self.tree.events),
                'metadata_transitions': list(self.tree.metadata_transitions),
                'native_observations': self.native.observations,
                'last_collection_proved_exits': list(self.native.exited_during_collection)}


def launch(argv, *, cwd=None, env=None, stdout=None, stderr=None, latch, stdin=subprocess.DEVNULL):
    """Popen-compatible result; gate stays closed until immutable registration.

    Popen.args remains the true gate launch. native_launch records both that
    actual argv and the requested eventual exec argv for native-aware consumers.
    """
    native_owned.require(isinstance(latch, StopLatch), 'native launch requires StopLatch')
    native_owned.require(isinstance(argv, (list, tuple)) and argv and all(isinstance(a, str) for a in argv),
                         'native launch requires an explicit argv')
    owner = latch.ownership
    with owner.lock:
        native_owned.require(not owner.closed and latch.armed and not latch.event.is_set(),
                             'refusing launch after stop/cleanup')
        reader, writer, proc = -1, -1, None
        try:
            reader, writer = os.pipe()
            gate_argv = [sys.executable, '-E', '-s', '-B', str(q5_host.NATIVE9_SOURCE),
                         '--exec-gate', str(reader), '--', *argv]
            proc = subprocess.Popen(gate_argv, cwd=cwd, env=env, stdin=stdin, stdout=stdout, stderr=stderr,
                                    start_new_session=True, pass_fds=(reader,))
            owner.popens.append(proc)
            os.close(reader)
            reader = -1
            row = owner.native.process(proc.pid)
            native_owned.require(row is not None and row['ppid'] == os.getpid() and row['pgid'] == proc.pid,
                                 'gated native root identity/parent/session unavailable')
            native_owned.require(proc.pid not in owner, 'root PID already registered')
            owner[proc.pid] = dict(row)
            owner.root_identities[proc.pid] = dict(row)
            latch.groups.append(row['pgid'])  # diagnostics only
            owner.observe()
            native_owned.require(not latch.event.is_set() and latch.armed, 'stop arrived before exec gate release')
            proc.native_launch = {'gate_argv': gate_argv, 'exec_argv': list(argv),
                                  'root_identity': dict(row), 'registered_ns': time.monotonic_ns()}
            native_owned.require(os.write(writer, b'x') == 1, 'owned exec gate release failed')
            return proc
        except BaseException as error:
            owner.tree.errors.append('root launch failed: ' + repr(error))
            # Closing the unreleased gate exits without executing the workload.
            # Registered children remain in owner.popens for ordinary cleanup.
            raise
        finally:
            if reader != -1:
                os.close(reader)
            if writer != -1:
                os.close(writer)




def _server_members(owner, live, pgid):
    root = owner.root_identities.get(pgid)
    native_owned.require(root is not None, 'unregistered footprint root refused')
    lifetimes = {root['lifetime_id']}
    changed = True
    while changed:
        changed = False
        for row in owner.values():
            if row['parent_lifetime_id'] in lifetimes and row['lifetime_id'] not in lifetimes:
                lifetimes.add(row['lifetime_id'])
                changed = True
    return [row for row in live.values() if row['lifetime_id'] in lifetimes]




def _footprint_stats(members, pgid, footprint, *, owner, footprint_source='footprint'):
    """Commit only a fully measured, freshly reobserved owned cohort.

    Exec may refresh metadata only within an already proved lifetime. An exit
    is an explicit kernel-proved departure, never an unmeasured zero. Any exec
    across a footprint bracket, new member, or changed final cohort discards
    the entire attempt. A failed footprint is a departure only after strong
    expected-lifetime absence; live/unknown targets and foreign lifetimes fail.
    The existing sample-age/reaction policy still bounds use of this result.
    """
    native_owned.require(isinstance(owner, Ownership), 'footprint requires native Ownership')
    native = q5_host.native_table()
    errors, transitions, departures, collections = [], [], [], []
    first_coherence_error, complete, total = None, False, None
    identity_keys = ('lifetime_id', 'pid_version', 'ppid', 'pgid', 'parent_lifetime_id')

    def transition(reason, before, after):
        event = {'reason': reason, 'before': before, 'after': after,
                 'observed_ns': time.monotonic_ns()}
        transitions.append(event)
        if after is None:
            departures.append(event)
        return event

    def observe():
        with owner.lock:
            _, live = owner.observe()
            native_owned.require(not owner.tree.refused_pgids, 'native ownership contains mixed groups')
            return _server_members(owner, live, pgid)

    for attempt in range(native_owned.MAX_COHERENT_OWNER_ATTEMPTS):
        collection = {'attempt': attempt + 1, 'start_ns': time.monotonic_ns(),
                      'initial_identities': members, 'measurements': [], 'complete': False}
        collections.append(collection)
        try:
            measured = {}
            for row in members:
                with owner.lock:
                    identity = owner.get(row['pid'])
                    native_owned.require(identity is not None and identity['lifetime_id'] == row['lifetime_id'],
                                         'unowned footprint lifetime refused')
                before = native.process(row['pid'], expected_lifetime=row['lifetime_id'])
                if before is None:
                    transition('proved exit before footprint', row, None)
                    continue
                if any(before[key] != row[key] for key in identity_keys):
                    transition('same-lifetime metadata refreshed before footprint', row, before)
                began = time.monotonic_ns()
                try:
                    value = footprint(row['pid'])
                except (q5_host.ObservationError, OSError) as error:
                    failure = {'before': before, 'error': repr(error),
                               'start_ns': began, 'end_ns': time.monotonic_ns()}
                    collection.setdefault('observer_failures', []).append(failure)
                    try:
                        after = native.process(row['pid'], expected_lifetime=before['lifetime_id'])
                    except (OSError, native_owned.OwnershipError) as identity_error:
                        # Keep the original observer failure as well as the
                        # reason absence could not be proved. Neither is zero.
                        raise q5_host.ObservationError(
                            f'{error!r}; target departure unproved: {identity_error!r}') from identity_error
                    failure['after'] = after
                    if after is not None:
                        raise
                    event = transition('footprint failed for proved departed target; aggregate discarded',
                                       before, None)
                    event['observation_error'] = repr(error)
                    # Refresh the complete cohort inside the original bound;
                    # no partial values from this failed attempt can survive.
                    raise native_owned.RefreshRequired(
                        f'footprint failed for proved departed target: {error!r}', before, None) from error
                native_owned.require(type(value) is int and value >= 0, 'invalid actual footprint')
                after = native.process(row['pid'], expected_lifetime=row['lifetime_id'])
                measurement = {'before': before, 'after': after, 'footprint_bytes': value,
                               'start_ns': began, 'end_ns': time.monotonic_ns()}
                collection['measurements'].append(measurement)
                if after is None:
                    transition('proved exit during footprint; value discarded', before, None)
                    continue
                if any(after[key] != before[key] for key in identity_keys):
                    transition('metadata changed during footprint; value discarded', before, after)
                    raise native_owned.RefreshRequired('footprint identity changed during observation',
                                                       before, after)
                measured[row['pid']] = measurement
            final = observe()
            collection['final_identities'] = final
            final_pids = {row['pid'] for row in final}
            for pid in measured.keys() - final_pids:
                before = measured[pid]['after']
                after = native.process(pid, expected_lifetime=before['lifetime_id'])
                transition('member left final cohort; aggregate discarded', before, after)
            # All live final members must have actual measurements in THIS
            # attempt. Reobserve new descendants, including escaped observers;
            # never recursively chase them without the fixed attempt bound.
            if final_pids != set(measured):
                transition('owned cohort changed; aggregate discarded', members, final)
                raise native_owned.RefreshRequired('footprint cohort changed during observation', members, final)
            for row in final:
                before = measured[row['pid']]['after']
                after = native.process(row['pid'], expected_lifetime=before['lifetime_id'])
                if after is None or any(after[key] != before[key] or row[key] != before[key]
                                        for key in identity_keys):
                    transition('final footprint identity changed; aggregate discarded', before, after)
                    raise native_owned.RefreshRequired('footprint identity changed after observation', before, after)
            # Preserve canonical post-cleanup semantics: a proved empty cohort
            # has no footprint reading, not zero and not an observation error.
            total = sum(item['footprint_bytes'] for item in measured.values()) if final else None
            members, complete = final, bool(final)
            collection['complete'] = complete
            collection['empty_cohort_proved'] = not final
            break
        except native_owned.RefreshRequired as error:
            collection['coherence_error'] = repr(error)
            if first_coherence_error is None:
                first_coherence_error = repr(error)
            # No stale or partially measured value survives a retry.
            if attempt + 1 == native_owned.MAX_COHERENT_OWNER_ATTEMPTS:
                errors.append(first_coherence_error)
                break
            try:
                members = observe()
            except (q5_host.ObservationError, OSError, native_owned.OwnershipError) as error:
                errors.extend([first_coherence_error, repr(error)])
                break
        except (q5_host.ObservationError, OSError, native_owned.OwnershipError) as error:
            if first_coherence_error is not None:
                errors.append(first_coherence_error)
            errors.append(repr(error))
            collection['error'] = repr(error)
            break
        finally:
            collection['end_ns'] = time.monotonic_ns()
    return {'pgid': pgid, 'members': [row['pid'] for row in members],
            'footprint_bytes': total if complete else None,
            'footprint_source': footprint_source if complete else None,
            'rss_bytes': None, 'errors': errors, 'native_identities': members,
            'cohort_complete': complete, 'metadata_transitions': transitions,
            'footprint_backend': footprint_source,
            'proved_departures': departures, 'collections': collections,
            'aggregation': 'registered server root and native-lifetime descendants, including escaped groups'}


def take_sample(index, pgid=None, roots=(), known=None):
    sample = {'index': index, 'start_ns': time.monotonic_ns(), 'host': None, 'group': None, 'errors': []}
    try:
        sample['host'] = q5_host.host_memory()
    except (q5_host.ObservationError, OSError, native_owned.OwnershipError) as error:
        sample['errors'].append(repr(error))
    if pgid is not None or roots:
        try:
            native_owned.require(isinstance(known, Ownership), 'sampling roots requires native Ownership')
            with known.lock:
                native_owned.require(set(roots) <= set(known.root_identities), 'unregistered sample root')
                _, live = known.observe()
                native_owned.require(not known.tree.refused_pgids, 'native ownership contains mixed groups')
                members = _server_members(known, live, pgid) if pgid is not None else []
            if pgid is not None:
                sample['group'] = _footprint_stats(members, pgid, _native_footprint, owner=known,
                                                   footprint_source=FOOTPRINT_SOURCE)
                sample['errors'].extend(sample['group']['errors'])
        except (q5_host.ObservationError, OSError, native_owned.OwnershipError) as error:
            sample['errors'].append(repr(error))
            # Canonical Monitor treats host=None as blind even if cap is absent.
            sample['host'] = None
            sample['group'] = {'pgid': pgid, 'members': list(roots), 'footprint_bytes': None,
                               'footprint_source': None, 'rss_bytes': None}
    sample['end_ns'] = time.monotonic_ns()
    return sample


class StopLatch:
    """First decision wins and immediately audits/signals owned identities."""
    def __init__(self):
        # RLock permits a Python operator-signal handler to interrupt launch on
        # this same thread. The gate's post-registration stop check stays closed.
        self.lock, self.event = threading.RLock(), threading.Event()
        self.stop, self.signal_ns, self.groups, self.armed = None, None, [], True
        self.ownership = Ownership(self.lock)
        self.observer_custody = q5_host.ObserverCustody()

    def trip(self, stop):
        with self.lock:
            if self.stop is not None or not self.armed:
                return False
            self.stop = dict(stop, decided_ns=time.monotonic_ns())
            try:
                if self.ownership.root_identities and not self.ownership.closed:
                    self.ownership.signal_live(signal.SIGTERM)
            except native_owned.RefreshRequired as error:
                self.ownership.tree.metadata_transitions.append({
                    'reason': str(error), 'before': error.before, 'after': error.after,
                    'observed_ns': time.monotonic_ns()})
            except BaseException as error:
                self.ownership.tree.errors.append('immediate stop: ' + repr(error))
            finally:
                events = self.ownership.tree.events
                self.signal_ns = time.monotonic_ns() if any(e['result'] == 'sent' for e in events) else None
                self.event.set()
            return True


class Sampler(threading.Thread):
    def __init__(self, monitor, interval, path, latch):
        super().__init__(name='q5-sampler', daemon=True)
        self.monitor, self.interval, self.latch = monitor, interval, latch
        self.path, self.halt = path, threading.Event()
        self.pgid, self.roots, self.known = None, set(), latch.ownership
        self.observer_custody = latch.observer_custody
        self.error = None
        self.deadline = None

    def run(self):
        with q5_host.observer_scope(self.observer_custody):
            self._run()

    def _run(self):
        index, target = 0, time.monotonic()
        try:
            with open(self.path, 'w', encoding='utf-8') as out:
                while not self.halt.is_set():
                    if self.deadline is not None:
                        self.deadline.trip(self.latch)
                    sample = take_sample(index, self.pgid, tuple(self.roots), self.known)
                    with self.latch.lock:
                        ready_ns = self.monitor.ready_ns
                        decision = self.monitor.feed(sample)
                        row = {**{key: sample[key] for key in ('index', 'start_ns', 'end_ns', 'group', 'errors')},
                               'host': compact(sample['host']), 'monitor_ready_ns': ready_ns}
                    out.write(json.dumps(row, separators=(',', ':')) + '\n')
                    out.flush()
                    if decision is not None:
                        self.latch.trip(decision)
                    index += 1
                    target += self.interval
                    delay = target - time.monotonic()
                    if delay < 0:
                        target = time.monotonic()
                    elif self.halt.wait(delay):
                        break
        except BaseException as error:
            self.error = repr(error)
            self.latch.trip({'reason': 'sampler_blind', 'detail': 'sampler thread failed: ' + self.error,
                             'sample_index': index, 'sample_start_ns': time.monotonic_ns(), 'sample_end_ns': None})


def terminate(pgids, known, popens, term_grace, kill_grace, already_signaled_ns=None):
    """Original grace windows, fresh native observation on every cleanup tick.

    Late children receive TERM then KILL inside the existing deadlines. Numeric
    PGIDs never confer authority; no new root can be adopted during cleanup.
    """
    native_owned.require(isinstance(known, Ownership), 'cleanup requires native Ownership')
    began = time.monotonic()
    term_deadline, end = began + term_grace, began + term_grace + kill_grace
    with known.lock:
        native_owned.require(set(pgids) <= set(known.root_identities), 'unregistered cleanup root')
        native_owned.require(all(any(proc is child for child in known.popens) for proc in popens),
                             'unregistered cleanup Popen')
        # Canonical cleanup independently repeats TERM after an immediate stop.
        # Track this cleanup phase separately, without extending either grace.
        known.term_sent.clear()
        known.kill_sent.clear()
        known.closed = True
    result = {'pgids': sorted(set(pgids)), 'term_ns': already_signaled_ns, 'kill_ns': None, 'empty_ns': None}
    remaining = None
    while True:
        with known.lock:
            for proc in known.popens:
                proc.poll()
            try:
                rows, live = known.observe()
                # Mixed-group detection is conservative refusal, not numeric
                # group ownership or permission to signal unrelated members.
                remaining = [row for row in rows.values()
                             if row['pid'] in live or row['pgid'] in known.tree.refused_pgids]
                if not remaining and all(proc.returncode is not None for proc in known.popens):
                    result['empty_ns'] = time.monotonic_ns()
                    break
                for row in known.tree.descendant_first(live):
                    key = (row['pid'], row['lifetime_id'])
                    if key not in known.term_sent:
                        if known.tree.signal_identity(row, signal.SIGTERM):
                            result['term_ns'] = result['term_ns'] or time.monotonic_ns()
                        known.term_sent.add(key)
                    elif time.monotonic() >= term_deadline and key not in known.kill_sent:
                        if known.tree.signal_identity(row, signal.SIGKILL):
                            result['kill_ns'] = result['kill_ns'] or time.monotonic_ns()
                        known.kill_sent.add(key)
            except native_owned.RefreshRequired as error:
                known.tree.metadata_transitions.append({'reason': str(error), 'before': error.before,
                                                       'after': error.after, 'observed_ns': time.monotonic_ns()})
                remaining = None
            except BaseException as error:
                known.tree.errors.append(repr(error))
                remaining = None
        if time.monotonic() >= end:
            break
        time.sleep(min(0.05, max(0, end - time.monotonic())))
    with known.lock:
        for proc in known.popens:
            proc.poll()
        # A failed final collection may never reuse an earlier empty observation.
        try:
            rows, live = known.observe()
            remaining = [row for row in rows.values()
                         if row['pid'] in live or row['pgid'] in known.tree.refused_pgids]
        except BaseException as error:
            known.tree.errors.append('final native observation: ' + repr(error))
            remaining = None
        reaped = all(proc.returncode is not None for proc in known.popens)
        result.update(known.evidence())
        result['pgids'] = sorted({row['pgid'] for row in known.values()} | set(pgids))
        result.update(remaining=remaining, refused_pgids=sorted(known.tree.refused_pgids),
                      errors=list(known.tree.errors), direct_child_reaped=reaped,
                      exit_codes=[proc.returncode for proc in popens],
                      proven=result['empty_ns'] is not None and remaining == [] and reaped
                      and not known.tree.errors and not known.tree.refused_pgids)
    return result