gitoria
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
- 5803cf4f|||PR vendor: Hybriel set-day59 and GC budget 32 MiBmre
- 9eff6627Merge branch 'f2-api-bugs' into mainGitoria
- 26117255|||PR apps API: review comments on files with spaces in their namemre
- b8796cecMerge branch 'f1-broken-json' into mainGitoria
- 2f2959c5|||PR apps API: broken JSON body gives 400 invalid_json, not 500mre
- f7c6ca07Merge branch 'ident-chooser-selector' into mainGitoria
- 691abb8e|||PR tests: find ident identity choice without the removed .choose classmre
- 16a3530fMerge branch 'heap-revert' into mainGitoria
- 220a80e0|||PR Remove temporary /__heap route and heap helper; logmre
- 13f0c342Merge branch 'hl25-records' into mainGitoria
- a002ecb7|||PR records: HL25 report, heap helper, logmre
- 2492a55cTemporary keyed /__heap route for the live memory snapshotmre
- fefaedd2log: tracker PR-only, HL25 startedmre
- 21aa57calog: parkmre
- e9f950a8reports: G25c soakmre
- a7783686log: deploy 9f41ffcmre
- 9f41ffc1log: W30b mergedmre
- bef635c1Merge branch 'w30b'mre
- 15b996a5Org list: keyed rows by @id, newest first, concat instead of hand loopmre
- c4f6d9e3reports: G25c growth huntmre