jukebox
All repositories: gitoria
6.3 KB
#!/usr/bin/env python3"""Proc ABI ownership regression. Run after native/build.sh; Python stdlib only.The counting heap sees plugin allocations, independent of the host GC. consume()matches runtime/pluginval.hl: copy/consume children, then invoke owner cleanup.RSS is measured after warmup, without malloc_trim. Every batch must leave exactlythe same live allocations and fds and no child (running or zombie)."""import argparseimport ctypes as Cimport jsonimport osfrom pathlib import Pathimport selectimport timeclass String(C.Structure):_fields_ = [('ptr', C.c_void_p), ('len', C.c_size_t)]class Data(C.Union):_fields_ = [('number', C.c_double), ('string', String), ('object', C.c_void_p)]class Value(C.Structure):_fields_ = [('type', C.c_uint8), ('data', Data), ('deinit', C.c_void_p)]class Field(C.Structure):_fields_ = [('key', String), ('value', Value)]class Object(C.Structure):_fields_ = [('fields', C.POINTER(Field)), ('count', C.c_size_t), ('deinit', C.c_void_p)]class Iterator(C.Structure):_fields_ = [('context', C.c_void_p), ('next', C.c_void_p), ('deinit', C.c_void_p),('try_next', C.c_void_p), ('wake_fd', C.c_int),('head_stamp', C.c_void_p), ('close', C.c_void_p)]Alloc = C.CFUNCTYPE(C.c_size_t, C.c_size_t, C.c_size_t)Free = C.CFUNCTYPE(C.c_uint64, C.c_size_t)Usable = C.CFUNCTYPE(C.c_size_t, C.c_size_t)class Heap(C.Structure):_fields_ = [('alloc', Alloc), ('free', Free), ('usable', Usable)]libc = C.CDLL(None)libc.malloc.argtypes = [C.c_size_t]libc.malloc.restype = C.c_void_plibc.free.argtypes = [C.c_void_p]libc.malloc_usable_size.argtypes = [C.c_void_p]libc.malloc_usable_size.restype = C.c_size_tlive = {}@Allocdef alloc(alignment, size):assert alignment <= 16ptr = libc.malloc(size)live[ptr] = sizereturn ptr@Freedef free(ptr):live.pop(ptr)libc.free(ptr)return 0@Usabledef usable(ptr):return libc.malloc_usable_size(ptr)heap = Heap(alloc, free, usable)def text(raw):return Value(3, Data(string=String(C.cast(C.c_char_p(raw), C.c_void_p), len(raw))))def consume(value):if value.type == 3 or value.type == 7:result = C.string_at(value.data.string.ptr, value.data.string.len)elif value.type == 2:result = value.data.numberelif value.type == 5:# Transfer the iterator to the caller, as the runtime wrapper does.result = C.cast(value.data.object, C.POINTER(Iterator))elif value.type == 4:obj = C.cast(value.data.object, C.POINTER(Object))result = {}for i in range(obj.contents.count):field = obj.contents.fields[i]key = C.string_at(field.key.ptr, field.key.len).decode()result[key] = consume(field.value)if obj.contents.deinit:C.CFUNCTYPE(None, C.POINTER(Object))(obj.contents.deinit)(obj)else:result = Noneif value.deinit:C.CFUNCTYPE(None, C.POINTER(Value))(value.deinit)(C.byref(value))return resultdef rss():return int(Path('/proc/self/status').read_text().split('VmRSS:')[1].split()[0])def state():return len(live), sum(live.values()), len(os.listdir('/proc/self/fd'))def one(plugin, command, asynchronous, expected):arg = text(command)value = (plugin.hl_proc_spawn if asynchronous else plugin.hl_proc_run)(1, C.byref(arg))result = consume(value)if not asynchronous:assert result['exit'] == expectedassert len(result['out']) == (65536 if command.startswith(b'head') else 5 if command.startswith(b'printf') else 0)assert result['err'] == (b'bad' if expected == 7 else b'')returniterator = result['events']it = iterator.contentspoll = select.poll()poll.register(it.wake_fd, select.POLLIN)next_event = C.CFUNCTYPE(Value, C.c_void_p)(it.try_next)deadline = time.monotonic() + 10while True:assert time.monotonic() < deadline, 'child completion timeout'assert poll.poll(1000), 'child event timeout'event = next_event(it.context)data = consume(event)if data and 'exit' in data:assert data['exit'] == expectedbreakC.CFUNCTYPE(None, C.c_void_p)(it.deinit)(it.context)# Iterator storage belongs to the plugin, like runtime/plugwrap.hl's wrapper.def main():parser = argparse.ArgumentParser(description=__doc__)parser.add_argument('plugin', nargs='?', default=str(Path(__file__).resolve().parents[1] / 'libproc.so'))parser.add_argument('--calls', type=int, default=5000)parser.add_argument('--allow-leaks', action='store_true', help='collect baseline evidence without assertions')args = parser.parse_args()plugin = C.CDLL(str(Path(args.plugin).resolve()))plugin.hl_plugin_set_heap(C.byref(heap))for name in ['hl_proc_run', 'hl_proc_spawn']:fn = getattr(plugin, name)fn.argtypes = [C.c_uint32, C.POINTER(Value)]fn.restype = Valuefor asynchronous in [False, True]:for command, expected in [(b'true', 0), (b'printf hello', 0),(b'head -c 65536 /dev/zero', 0),(b"sh -c 'printf bad >&2; exit 7'", 7)]:for _ in range(100):one(plugin, command, asynchronous, expected)# The worker posts exit just before dropping its reference. Allow that# final release to finish before sampling, rather than racing its thread.time.sleep(.05)before, start_rss = state(), rss()for _ in range(args.calls):one(plugin, command, asynchronous, expected)time.sleep(.05)after, end_rss = state(), rss()children = Path(f'/proc/self/task/{os.getpid()}/children').read_text().strip()row = dict(form='spawn' if asynchronous else 'run', command=command.decode(),calls=args.calls, blocks=after[0]-before[0], bytes=after[1]-before[1],fd_before=before[2], fd_after=after[2], children=children,rss_growth_kib=end_rss-start_rss)print(json.dumps(row), flush=True)if not args.allow_leaks:assert after == before, rowassert not children, rowassert end_rss-start_rss <= 1024, rowif __name__ == '__main__':main()
Branches
Latest commits
- 502eeed5jukebox#20: vendor virtual-list initial resetKey baseline fixmre
- 3b76651cjukebox#20: update virtual-list README pin and resetKey optionsmre
- bc09e1e8|||PR jukebox#20: reset virtual lists through resetKey (partial validation)mre
- 10f8a8c8Merge branch 'code-order' into mainJukebox
- 204fc828Merge branch 'day72' into mainJukebox
- 95f5faae|||PR jukebox#7 Drop needless let declarationsmre
- 33072bb5|||PR Record day72 gates and Chrome proofmre
- 95f2cd73|||PR Use typed parent methods for screen playback and local server facesmre
- 6422a020Sync media-player at 51c3818mre
- b582ba1cVendor complete Hybriel day72 plugin setmre
- 02dccbc9Merge branch 'records-1119' into mainJukebox
- a39e1c23|||PR Records: missions 013-015, reconnect fix livemre
- fc7db075Merge branch 'reconnect-retry' into mainJukebox
- ac6f4c6fL2: plain declaration for a in pickedNextmre
- 2f335086Review round 2: only an explicit queue pick drops pend (not the automatic advance); jb23 records every source changemre
- 3eb6695fReview fixes: action generation, queue pick clears pend, Previous/Next retry the decided request, typed handlersmre
- 7a53c0c2|||PR A tap lost to a dead socket plays after reconnect (mission 015)mre
- 1f0cd77bMerge branch 'records-day41' into mainJukebox
- 67be229f|||PR Records: day41 live (PR #4), mission 012, statusmre
- 0bb027daconductor: caramboleyo is the user, not owner/creatorApollo