[Bug] chaos-serve 在清空缓存后仍随编译批次保留更多内存(9.4.3)
SafeLine 9.4.3 的 chaos-serve 在处理不同页面内容后,即使清空缓存,分配器统计的在用量仍随编译批次增长。希望协助判断这是预期保留还是缺陷,并确认有无支持的缓解方式。
此报告只包含新建隔离容器和合成 HTML;没有生产地址、账号、请求、配置或堆转储。没有将此现象定性为已定位的源代码泄漏。
版本与环境
- 9.4.3 镜像固定为
chaitin/safeline-chaos-g@sha256:201fee21803b52cef58942a85fa13bebcac16c5813d67b81e0e507d6708875aa。 /app/chaos-serveSHA256:affb2f1eb2e11032213d245901498f74be41e6e58236d765dff4d50f78b7eb8e。- 在 Linux ARM64 的独立 Docker 环境中运行官方 linux/amd64 镜像,使用 x86 仿真。整个测试作业受 2 GiB / 2 CPU 限制;容器之间没有共享业务数据。尚未在原生 x86_64 环境复测,RSS 包含仿真开销,不用它作生产容量估算。
- 较新 9.4.4 镜像 digest 为
sha256:a4eab2e7335f536420524a73a8599094fec7f0539bf710b645abb32607148fdc。逐文件核对后,chaos-serve、libc 的 SHA256、默认 core 参数、镜像分配器环境变量及入口脚本中的分配器设置均与上述 9.4.3 相同,因此没有把同一程序的重复运行写作 9.4.4 的独立升级验收。其他组件及完整升级未测。
最小输入及观测方法
- 仅运行镜像内的
/app/chaos-serve,从自带默认配置复制临时文件,改 STPP 为容器 TCP 端口并仅向宿主回环地址发布。 max_cache_size=128, item_count=1, item_ttl=3600,启动日志确认生效;临时站点通过PUT /config/1设置{"water_mark":""}。- 每批 100 个不同的
<p>synthetic-N</p>,每个发送两次,完整读取 STPP 响应。共 400 个页面、800 次请求,编译 parse/print 各 400 次。 - 每批调用
DELETE /cache/all(均返回 200),短暂空闲后取所有 arena 的malloc_info,再调用一次malloc_trim(0)后复取。另做不发送 STPP 请求、只执行清空和观测的对照。 - 通过一个仅用于隔离测试的预加载观察线程调用 GNU libc 的原生接口;不替换 malloc/free、不更改产品二进制、不读取对象内容或保存堆。观察线程的源码完整附后。
这里的“估算在用量”是 XML 顶层 system.current - total.rest - total.fast + total.mmap,包含分配器开销、未显示为 free 的线程缓存等,不等同于可达对象大小,也不能单凭该数值确定源码泄漏点。
最小复现结果
无输入对照:4 次清空、快照和 trim,编译数始终 0;估算在用量仅从 6,027,091 增至 6,034,396 字节。
| 累计不同页面 | parse / print 次数 | 清空并 trim 后估算在用量(bytes) | 同时 RSS(KiB,含仿真开销) |
|---|---|---|---|
| 100 | 100 / 100 | 8,707,873 | 49,028 |
| 200 | 200 / 200 | 10,710,088 | 51,664 |
| 300 | 300 / 300 | 13,024,649 | 57,820 |
| 400 | 400 / 400 | 14,722,219 | 61,168 |
各批第二次无输入快照与 trim 后在用量几乎一致,未看到与请求阶段同量级的观察开销增长。
较大输入的补充结果
同镜像 item_count=10,每批 250 个不同的合成 HTML(每页 15 请求),每批清空并 trim 后,估算在用量约为 56、105、146、204 MiB(累计 1,000 页面)。清空后的 RSS 约 455、513、545、623 MiB,trim 后约 100、149、190、271 MiB。这同时存在大量已释放但驻留的空闲页,以及清空后仍保留的分配器在用量。单看 RSS 不足以区分两者。
另外,不清空的连续输入测试中,仅把容量 3000 改为 128、保留单项 10 份结果,累计 200→1,000 个不同页面时 RSS 仍从 475,852 增至 659,660 KiB,未能据此确认稳定上限。小容量用响应哈希复用及重新编译核实了逐出;没有把该参数当作已验证修复。
希望确认
- 清空页面结果缓存后,还有哪些按编译内容保留的对象或缓存?是否预期存在累计增长?
- 有无无需关闭页面防护、能够限制该部分保留的官方设置或已修复版本?
- 若需要进一步证据,建议使用哪个受支持的对象/分配统计入口?
下面是已运行的最小复现源文件。需要 Python 3、Docker 和适配 linux/amd64 的 gcc/glibc 头文件。测试环境用 Ubuntu 24.04 ARM64 的交叉 GCC 编译观察库;原生 x86_64 的运行结果尚未取得。请只在一次性隔离环境执行,端口 19000/19001 需空闲。
x86_64-linux-gnu-gcc -shared -fPIC -O2 -Wl,--no-as-needed heapdiag.c -l:libpthread.so.0 -o libheapdiag.so
sudo docker pull --platform linux/amd64 chaitin/safeline-chaos-g@sha256:201fee21803b52cef58942a85fa13bebcac16c5813d67b81e0e507d6708875aa
python3 allocator_min_probe.py
heapdiag.c
#define _GNU_SOURCE
#include <stdio.h>
#include <malloc.h>
#include <unistd.h>
#include <pthread.h>
extern int legacy_create(pthread_t *,const pthread_attr_t *,void *(*)(void *),void *);
__asm__(".symver legacy_create,pthread_create@GLIBC_2.2.5");
static void snapshot(unsigned n,const char *part){
char path[128];snprintf(path,sizeof(path),"/tmp/heapdiag-%u-%s.xml",n,part);
FILE *out=fopen(path,"w");if(out){malloc_info(0,out);fclose(out);}
}
static void *observe(void *unused){
unsigned seq=0;
for(;;){
usleep(50000);
if(access("/tmp/heapdiag.request",F_OK))continue;
FILE *in=fopen("/tmp/heapdiag.request","r");if(!in)continue;
int action=fgetc(in);fclose(in);unlink("/tmp/heapdiag.request");seq++;
snapshot(seq,"before");int trimmed=-1;
if(action=='T'){trimmed=malloc_trim(0);snapshot(seq,"after");}
FILE *done=fopen("/tmp/heapdiag.done","w");if(done){fprintf(done,"%u %d\n",seq,trimmed);fclose(done);}
}
return NULL;
}
__attribute__((constructor)) static void init(void){
pthread_t thread;int rc=legacy_create(&thread,NULL,observe,NULL);
if(rc)fprintf(stderr,"heapdiag thread failed: %d\n",rc);
}
cache_common.py
import subprocess,json,re,urllib.request,urllib.error,time,socket,struct,hashlib,tempfile,pathlib
IMAGE='chaitin/safeline-chaos-g@sha256:201fee21803b52cef58942a85fa13bebcac16c5813d67b81e0e507d6708875aa'
SHA='affb2f1eb2e11032213d245901498f74be41e6e58236d765dff4d50f78b7eb8e'
D=['sudo','docker'];owned=[]
def emit(tag,data):print(json.dumps({'tag':tag,'data':data}),flush=True)
def run(args,timeout=20,check=True):
r=subprocess.run(D+args,text=True,capture_output=True,timeout=timeout)
if check and r.returncode:raise RuntimeError(json.dumps({'command':args[:4],'rc':r.returncode,'error':r.stderr[-800:]}))
return r
def frame(body):
site=b'1';host=b'diagnostic.invalid';args=struct.pack('>I',12+len(site)+len(host))+struct.pack('>I',len(site))+site+struct.pack('>I',len(host))+host
payload=args+body;return struct.pack('>HI',2,len(payload))+bytes(16)+payload
def read_exact(conn,n):
data=bytearray()
while len(data)<n:
part=conn.recv(n-len(data))
if not part:raise RuntimeError('incomplete synthetic STPP response')
data.extend(part)
return bytes(data)
def request(body):
with socket.create_connection(('127.0.0.1',19001),timeout=4) as conn:
conn.sendall(frame(body));header=read_exact(conn,22);kind,size=struct.unpack('>HI',header[:6]);assert kind==2 and 0<size<4194304
data=read_exact(conn,size)
return {'size':size,'sha256':hashlib.sha256(data).hexdigest()}
def counters(name):
r=run(['logs',name]);logs=re.sub(r'\x1b\[[0-9;]*m','',r.stdout+'\n'+r.stderr)
return {'parse':len(re.findall(r'Compiler\.parse',logs)),'print':len(re.findall(r'Compiler::print',logs))}
allocator_common.py
from cache_common import *
import xml.etree.ElementTree as ET
def rss(name):
rows=run(['top',name,'-eo','pid,comm,rss']).stdout.splitlines()[1:]
return int(next(x.split()[2] for x in rows if 'chaos-serve' in x))
def snap(name,trim=False):
r=run(['exec',name,'cat','/tmp/heapdiag.done'],check=False);old=int(r.stdout.split()[0]) if r.returncode==0 else 0
run(['exec',name,'sh','-c',"printf '"+('T' if trim else 'S')+"' > /tmp/heapdiag.request"])
for _ in range(50):
r=run(['exec',name,'cat','/tmp/heapdiag.done'],check=False)
if r.returncode==0 and int(r.stdout.split()[0])>old:break
time.sleep(.1)
else:raise RuntimeError('allocator snapshot was not produced')
seq,trimmed=map(int,r.stdout.split());out={'seq':seq,'trim_return':trimmed,'emulated_rss_kib':rss(name)}
for part in ['before','after'] if trim else ['before']:
raw=run(['exec',name,'cat','/tmp/heapdiag-'+str(seq)+'-'+part+'.xml']).stdout
root=ET.fromstring(raw)
def size(tag,kind):
x=root.find("./"+tag+"[@type='"+kind+"']");return int(x.attrib['size']) if x is not None else 0
system=size('system','current');free=size('total','rest')+size('total','fast');mmap=size('total','mmap')
out[part]={'arena_count':len(root.findall('./heap')),'arena_system_bytes':system,'arena_free_bytes':free,'mmap_bytes':mmap,'approx_in_use_with_overhead_bytes':system-free+mmap}
return out
allocator_min_probe.py
from cache_common import *
from allocator_common import rss,snap
try:
name='safeline3716-min-allocator';owned.append(name)
command="mkdir -p /tmp/diag /app/chaos && cp /app/workdir/config.toml /tmp/diag/config.toml && sed -i 's@listen = \"unix:///app/chaos/stpp.sock\"@listen = \"0.0.0.0:19001\"@;s@max_cache_size = [0-9]*@max_cache_size = 128@;s@item_count = [0-9]*@item_count = 1@;s@item_ttl = [0-9]*@item_ttl = 3600@' /tmp/diag/config.toml && exec env LD_PRELOAD=/diag/libheapdiag.so /app/chaos-serve -r /tmp/diag/"
run(['run','-d','--platform','linux/amd64','--name',name,'--label','codex.owner=run3716','--label','codex.disposable=true','-v',str(pathlib.Path.cwd()/'libheapdiag.so')+':/diag/libheapdiag.so:ro','-p','127.0.0.1:19000:9000','-p','127.0.0.1:19001:19001','--entrypoint','/bin/sh',IMAGE,'-c',command])
for _ in range(40):
try:urllib.request.urlopen('http://127.0.0.1:19000/',timeout=1);break
except urllib.error.HTTPError:break
except OSError:time.sleep(.25)
req=urllib.request.Request('http://127.0.0.1:19000/config/1',data=b'{"water_mark":""}',method='PUT',headers={'Content-Type':'application/json'})
with urllib.request.urlopen(req,timeout=4) as response:assert response.status==200
def clear():
req=urllib.request.Request('http://127.0.0.1:19000/cache/all',method='DELETE')
with urllib.request.urlopen(req,timeout=4) as response:assert response.status==200
time.sleep(.2)
emit('minimal_allocator_identity',{'digest':IMAGE,'application_sha256':SHA,'capacity':128,'item_count':1,'ttl':3600,'extra_observer_thread':True,'synthetic_only':True})
emit('minimal_baseline',snap(name))
for i in range(4):
clear();emit('empty_control',{'iteration':i+1,'phase_counts':counters(name),'snapshot':snap(name,True)})
for batch in range(4):
start=time.monotonic()
for i in range(100):
key=batch*100+i;body=('<p>synthetic-'+str(key)+'</p>').encode()
request(body);request(body)
time.sleep(.5);filled=snap(name);clear();empty=snap(name);trim=snap(name,True)
# A second no-input snapshot verifies no observation-only drift at the checkpoint.
time.sleep(.2);idle=snap(name)
emit('minimal_allocator_batch',{'new_keys':(batch+1)*100,'requests':200,'elapsed_seconds':round(time.monotonic()-start,3),'phase_counts':counters(name),'filled':filled,'cleared':empty,'trimmed':trim,'idle':idle})
logs=run(['logs',name]);text=re.sub(r'\x1b\[[0-9;]*m','',logs.stdout+'\n'+logs.stderr)
emit('minimal_actual_config',[x.strip() for x in text.splitlines() if re.fullmatch(r'\s*(?:heavy_worker|max_cache_size|item_count|item_ttl):\s*\d+,?\s*',x)])
finally:
for name in owned:
result=run(['rm','-f','-v',name],check=False);emit('cleanup',{'name':name,'rc':result.returncode})
统计接口语义参见 malloc_info 和 malloc_trim。
@heyecao 目前初步测试暂未复现您反馈的问题,清缓存后的内存保留情况还需进一步验证。请提供本次复现的完整测试输出、各批清缓存及 malloc_trim 前后的原始 malloc_info XML,以及对应时间段的编译日志;如方便,也请补充原生 x86_64 环境下的复测结果,以便进一步排查