{
  "commit": "54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7",
  "date": "2026-11-06",
  "sources": [
    {
      "id": "S01",
      "title": "SDK 生命周期 REST 入口",
      "path": "py-sdk/e2b/sandbox_sync/sandbox_api.py",
      "start": 183,
      "end": 202,
      "kind": "code",
      "chapter": 1,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/py-sdk/e2b/sandbox_sync/sandbox_api.py#L183",
      "excerpt": "183:         body = NewSandbox(\n184:             template_id=template,\n185:             auto_pause=(should_auto_pause if should_auto_pause is not None else UNSET),\n186:             metadata=metadata or {},\n187:             timeout=timeout,\n188:             env_vars=env_vars or {},\n189:             mcp=cast(Any, mcp) or UNSET,\n190:             secure=secure,\n191:             allow_internet_access=allow_internet_access,\n192:             network=SandboxNetworkConfig(**network) if network else UNSET,\n193:             volume_mounts=volume_mounts if volume_mounts else UNSET,\n194:         )\n195:         if auto_resume_enabled is not None:\n196:             body.auto_resume = SandboxAutoResumeConfig(enabled=auto_resume_enabled)\n197: \n198:         api_client = get_api_client(config)\n199:         res = post_sandboxes.sync_detailed(\n200:             body=body,\n201:             client=api_client,\n202:         )",
      "claim": "创建请求交给平台 API 客户端；它与 VM 内 envd 的文件/进程接口分开。"
    },
    {
      "id": "S02",
      "title": "沙箱文件与进程直连 envd",
      "path": "py-sdk/e2b/sandbox_sync/main.py",
      "start": 104,
      "end": 126,
      "kind": "code",
      "chapter": 1,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/py-sdk/e2b/sandbox_sync/main.py#L104",
      "excerpt": "104:         self._envd_api = httpx.Client(\n105:             base_url=self.envd_api_url,\n106:             transport=self._transport,\n107:             headers=self.connection_config.sandbox_headers,\n108:         )\n109:         self._filesystem = Filesystem(\n110:             self.envd_api_url,\n111:             self._envd_version,\n112:             self.connection_config,\n113:             self._transport.pool,\n114:             self._envd_api,\n115:         )\n116:         self._commands = Commands(\n117:             self.envd_api_url,\n118:             self.connection_config,\n119:             self._transport.pool,\n120:             self._envd_version,\n121:         )\n122:         self._pty = Pty(\n123:             self.envd_api_url,\n124:             self.connection_config,\n125:             self._transport.pool,\n126:             self._envd_version,",
      "claim": "Filesystem、Commands 和 Pty 都使用 envd_api_url。"
    },
    {
      "id": "S03",
      "title": "API 节点选择与亲和性",
      "path": "packages/api/internal/orchestrator/create_instance.go",
      "start": 258,
      "end": 279,
      "kind": "code",
      "chapter": 1,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/api/internal/orchestrator/create_instance.go#L258",
      "excerpt": "258: \tvar node *nodemanager.Node\n259: \n260: \tif isResume && nodeID != nil {\n261: \t\ttelemetry.ReportEvent(ctx, \"Placing sandbox on the node where the snapshot was taken\")\n262: \n263: \t\tclusterID := clusters.WithClusterFallback(team.ClusterID)\n264: \t\tnode = o.GetNode(clusterID, *nodeID)\n265: \t\tif node != nil && node.Status() != api.NodeStatusReady {\n266: \t\t\tnode = nil\n267: \t\t}\n268: \t}\n269: \n270: \tnodeClusterID := clusters.WithClusterFallback(team.ClusterID)\n271: \tclusterNodes := o.GetClusterNodes(nodeClusterID)\n272: \n273: \tnode, err = placement.PlaceSandbox(ctx, o.placementAlgorithm, clusterNodes, node, sbxRequest, builds.ToMachineInfo(build))\n274: \tif err != nil {\n275: \t\treturn sandbox.Sandbox{}, &api.APIError{\n276: \t\t\tCode:      http.StatusInternalServerError,\n277: \t\t\tClientMsg: \"Failed to place sandbox\",\n278: \t\t\tErr:       fmt.Errorf(\"failed to place sandbox: %w\", err),\n279: \t\t}",
      "claim": "恢复可优先使用原节点；API 随后调用 placement 选择承载节点。"
    },
    {
      "id": "S04",
      "title": "Placement 调用节点 gRPC",
      "path": "packages/api/internal/orchestrator/placement/placement.go",
      "start": 173,
      "end": 199,
      "kind": "code",
      "chapter": 1,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/api/internal/orchestrator/placement/placement.go#L173",
      "excerpt": "173: \t\t\tnode, err = algorithm.chooseNode(ctx, clusterNodes, nodesExcluded, nodemanager.SandboxResources{CPUs: sbxRequest.GetSandbox().GetVcpu(), MiBMemory: sbxRequest.GetSandbox().GetRamMb()}, buildMachineInfo)\n174: \t\t\tif err != nil {\n175: \t\t\t\treturn nil, err\n176: \t\t\t}\n177: \n178: \t\t\ttelemetry.ReportEvent(ctx, \"Placing sandbox on the node\", telemetry.WithNodeID(node.ID))\n179: \t\t}\n180: \n181: \t\tnode.PlacementMetrics.StartPlacing(sbxRequest.GetSandbox().GetSandboxId(), nodemanager.SandboxResources{\n182: \t\t\tCPUs:      sbxRequest.GetSandbox().GetVcpu(),\n183: \t\t\tMiBMemory: sbxRequest.GetSandbox().GetRamMb(),\n184: \t\t})\n185: \n186: \t\tctx, span := tracer.Start(ctx, \"create-sandbox\")\n187: \t\tspan.SetAttributes(\n188: \t\t\ttelemetry.WithNodeID(node.ID),\n189: \t\t\ttelemetry.WithClusterID(node.ClusterID),\n190: \t\t)\n191: \t\t// orchestrator 侧同一沙箱的耗时分解由采集方挂到这个阶段下面\n192: \t\t_, endNodeCreate := perftrace.Phase(ctx, \"node.SandboxCreate (gRPC)\")\n193: \t\terr = node.SandboxCreate(ctx, sbxRequest)\n194: \t\tendNodeCreate()\n195: \t\tspan.End()\n196: \t\tif err == nil {\n197: \t\t\tnode.PlacementMetrics.Success(sbxRequest.GetSandbox().GetSandboxId())\n198: \n199: \t\t\treturn node, nil",
      "claim": "节点选择后调用 SandboxCreate；平台服务的部署调度与该沙箱 placement 是两个层面。"
    },
    {
      "id": "S05",
      "title": "三类节点发现方式",
      "path": "packages/api/internal/orchestrator/orchestrator.go",
      "start": 136,
      "end": 146,
      "kind": "code",
      "chapter": 1,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/api/internal/orchestrator/orchestrator.go#L136",
      "excerpt": "136: \tswitch env.GetEnv(\"ORCHESTRATOR_TYPE\", \"nomad\") {\n137: \tcase \"systemd\":\n138: \t\t// systemd 承载：sandbox 节点池与模板构建共用 ORCHESTRATOR_STATIC_NODES\n139: \t\t// 静态清单（含 grpc_health_v1 探活），不再依赖 K8s sandbox 标签\n140: \t\to.discovery = NewStaticNodeDiscovery(ctx)\n141: \tcase \"k8s\":\n142: \t\to.discovery = NewK8sDiscovery(kubeClient)\n143: \tcase \"nomad\":\n144: \t\tfallthrough\n145: \tdefault:\n146: \t\to.discovery = NewNomadDiscovery(nomadClient)",
      "claim": "支持 systemd 静态节点、K8s 和 Nomad 的节点发现。"
    },
    {
      "id": "S06",
      "title": "Sandbox 与 Template 服务装配",
      "path": "packages/orchestrator/main.go",
      "start": 522,
      "end": 549,
      "kind": "code",
      "chapter": 1,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/orchestrator/main.go#L522",
      "excerpt": "522: \tgrpcServer := e2bgrpc.NewGRPCServer(tel)\n523: \torchestrator.RegisterSandboxServiceServer(grpcServer, orchestratorService)\n524: \torchestrator.RegisterVolumeServiceServer(grpcServer, volumeService)\n525: \n526: \t// template manager\n527: \tvar tmpl *tmplserver.ServerStore\n528: \tif slices.Contains(services, cfg.TemplateManager) {\n529: \t\ttmpl, err = tmplserver.New(\n530: \t\t\tctx,\n531: \t\t\tconfig,\n532: \t\t\tfeatureFlags,\n533: \t\t\ttel.MeterProvider,\n534: \t\t\tglobalLogger,\n535: \t\t\ttmplSbxLoggerExternal,\n536: \t\t\tsandboxFactory,\n537: \t\t\tsandboxProxy,\n538: \t\t\tsandboxes,\n539: \t\t\ttemplateCache,\n540: \t\t\tpersistence,\n541: \t\t\tlimiter,\n542: \t\t)\n543: \t\tif err != nil {\n544: \t\t\tlogger.L().Fatal(ctx, \"failed to create template manager\", zap.Error(err))\n545: \t\t}\n546: \n547: \t\ttemplatemanager.RegisterTemplateServiceServer(grpcServer, tmpl)\n548: \n549: \t\tclosers = append(closers, closer{\"template server\", tmpl.Close})",
      "claim": "同一程序注册 SandboxService；TemplateService 根据服务角色配置启用。"
    },
    {
      "id": "S07",
      "title": "CRI RuntimeHandler 选路",
      "path": "cri-multiplex/pkg/server/mux.go",
      "start": 214,
      "end": 243,
      "kind": "code",
      "chapter": 1,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/cri-multiplex/pkg/server/mux.go#L214",
      "excerpt": "214: func (s *MuxServer) RunPodSandbox(ctx context.Context, req *runtime.RunPodSandboxRequest) (*runtime.RunPodSandboxResponse, error) {\n215: \thandler := req.GetRuntimeHandler()\n216: \n217: \tmod, ok := s.reg.ResolveHandler(handler)\n218: \tif !ok {\n219: \t\tif s.opts.UnknownHandlerPolicy == UnknownHandlerReject {\n220: \t\t\treturn nil, status.Errorf(codes.InvalidArgument, \"unknown runtime handler %q\", handler)\n221: \t\t}\n222: \t\tmod = s.reg.Default()\n223: \t\tif mod == nil {\n224: \t\t\treturn nil, status.Error(codes.Internal, \"no default backend registered\")\n225: \t\t}\n226: \t}\n227: \n228: \teng := mod.Engine\n229: \tlog.Printf(\"[MuxServer] RunPodSandbox routing: handler=%q -> %s\", handler, eng.Type())\n230: \n231: \tresp, err := eng.RunPodSandbox(ctx, req)\n232: \tif err != nil {\n233: \t\treturn nil, err\n234: \t}\n235: \n236: \troutePersistStart := time.Now()\n237: \tif err := s.routes.SetPod(resp.PodSandboxId, eng.Type()); err != nil {\n238: \t\tlog.Printf(\"[MuxServer] ERROR: persist pod route failed sandbox=%s engine=%s: %v\", resp.PodSandboxId, eng.Type(), err)\n239: \t\ts.scheduleCleanup(ctx, eng.Type(), resp.PodSandboxId, \"route\", \"persist-route-failed\")\n240: \t\treturn nil, status.Errorf(codes.Internal, \"persist route for pod sandbox %s: %v\", resp.PodSandboxId, err)\n241: \t}\n242: \tlog.Printf(\"[PerfTrace] sandbox=%s route_persist_ms=%d\", resp.PodSandboxId, time.Since(routePersistStart).Milliseconds())\n243: \tlog.Printf(\"[MuxServer] registered pod %s -> %s\", resp.PodSandboxId, eng.Type())",
      "claim": "CRI 按 handler 解析后端并持久化路由；这是独立北向入口。"
    },
    {
      "id": "S08",
      "title": "CRI E2B 分支汇入 orchestrator",
      "path": "cri-multiplex/pkg/engine/e2b/create.go",
      "start": 116,
      "end": 131,
      "kind": "code",
      "chapter": 1,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/cri-multiplex/pkg/engine/e2b/create.go#L116",
      "excerpt": "116: \te2bReq := &orchestrator.SandboxCreateRequest{\n117: \t\tSandbox:   cfg,\n118: \t\tStartTime: timestamppb.New(p.startTime),\n119: \t\tEndTime:   timestamppb.New(endTime),\n120: \t}\n121: \torchCreateStart := time.Now()\n122: \tresp, err := e.client.Create(ctx, e2bReq)\n123: \torchCreateMs = time.Since(orchCreateStart).Milliseconds()\n124: \tif err != nil {\n125: \t\tlog.Printf(\"[GrpcE2BEngine] createE2BSandbox: orchestrator.Create FAILED: %v\", err)\n126: \t\tif cniRecord != nil {\n127: \t\t\tif delErr := e.cniManager.Del(context.Background(), cniRecord, p.cniConfig); delErr != nil {\n128: \t\t\t\tlog.Printf(\"[GrpcE2BEngine] WARNING: CNI DEL rollback failed for %s: %v\", sandboxID, delErr)\n129: \t\t\t}\n130: \t\t}\n131: \t\treturn nil, mapE2BError(err)",
      "claim": "E2B 引擎直接调用 orchestrator Create；失败时尝试回滚 CNI。"
    },
    {
      "id": "S09",
      "title": "Firecracker 的 UFFD 内存后端",
      "path": "packages/orchestrator/internal/sandbox/fc/client.go",
      "start": 37,
      "end": 63,
      "kind": "code",
      "chapter": 1,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/orchestrator/internal/sandbox/fc/client.go#L37",
      "excerpt": "37: func (c *apiClient) loadSnapshot(\n38: \tctx context.Context,\n39: \tuffdSocketPath string,\n40: \tuffdReady chan struct{},\n41: \tsnapfile template.File,\n42: ) error {\n43: \tctx, span := tracer.Start(ctx, \"load-snapshot\")\n44: \tdefer span.End()\n45: \n46: \tbackendType := models.MemoryBackendBackendTypeUffd\n47: \tbackend := &models.MemoryBackend{\n48: \t\tBackendPath: &uffdSocketPath,\n49: \t\tBackendType: &backendType,\n50: \t}\n51: \n52: \t_, endSnapPath := perftrace.Phase(ctx, \"fc.loadSnapshot get snapfile-path\")\n53: \tsnapfilePath := snapfile.Path()\n54: \tendSnapPath()\n55: \n56: \tsnapshotConfig := operations.LoadSnapshotParams{\n57: \t\tContext: ctx,\n58: \t\tBody: &models.SnapshotLoadParams{\n59: \t\t\tResumeVM:            false,\n60: \t\t\tEnableDiffSnapshots: false,\n61: \t\t\tMemBackend:          backend,\n62: \t\t\tSnapshotPath:        &snapfilePath,\n63: \t\t},",
      "claim": "LoadSnapshot 使用 UFFD backend 和 snapfile；磁盘 NBD 是另一条数据通路。"
    },
    {
      "id": "S10",
      "title": "统一 StorageProvider 与对象接口",
      "path": "packages/shared/pkg/storage/storage.go",
      "start": 63,
      "end": 90,
      "kind": "code",
      "chapter": 2,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/shared/pkg/storage/storage.go#L63",
      "excerpt": "63: type StorageProvider interface {\n64: \tDeleteObjectsWithPrefix(ctx context.Context, prefix string) error\n65: \tUploadSignedURL(ctx context.Context, path string, ttl time.Duration) (string, error)\n66: \tOpenBlob(ctx context.Context, path string, objectType ObjectType) (Blob, error)\n67: \tOpenSeekable(ctx context.Context, path string, seekableObjectType SeekableObjectType) (Seekable, error)\n68: \tGetDetails() string\n69: }\n70: \n71: type Blob interface {\n72: \tWriteTo(ctx context.Context, dst io.Writer) (int64, error)\n73: \tPut(ctx context.Context, data []byte) error\n74: \tExists(ctx context.Context) (bool, error)\n75: }\n76: \n77: type SeekableReader interface {\n78: \t// Random slice access, off and buffer length must be aligned to block size\n79: \tReadAt(ctx context.Context, buffer []byte, off int64) (int, error)\n80: \tSize(ctx context.Context) (int64, error)\n81: }\n82: \n83: // StreamingReader supports progressive reads via a streaming range reader.\n84: type StreamingReader interface {\n85: \tOpenRangeReader(ctx context.Context, off, length int64) (io.ReadCloser, error)\n86: }\n87: \n88: type SeekableWriter interface {\n89: \t// Store entire file\n90: \tStoreFile(ctx context.Context, path string) error",
      "claim": "上层依赖 Blob 和 Seekable 契约，前者整体访问，后者按 offset 读取或存整个文件。"
    },
    {
      "id": "S11",
      "title": "选择 MooncakeBucket 后端",
      "path": "packages/shared/pkg/storage/storage.go",
      "start": 146,
      "end": 171,
      "kind": "code",
      "chapter": 2,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/shared/pkg/storage/storage.go#L146",
      "excerpt": "146: func GetTemplateStorageProvider(ctx context.Context, limiter *limit.Limiter) (StorageProvider, error) {\n147: \tprovider := Provider(env.GetEnv(storageProviderEnv, string(DefaultStorageProvider)))\n148: \n149: \tif provider == LocalStorageProvider {\n150: \t\tbasePath := env.GetEnv(\"LOCAL_TEMPLATE_STORAGE_BASE_PATH\", \"/tmp/templates\")\n151: \n152: \t\treturn newFileSystemStorage(basePath), nil\n153: \t}\n154: \n155: \tbucketName := utils.RequiredEnv(\"TEMPLATE_BUCKET_NAME\", \"Bucket for storing template files\")\n156: \n157: \t// cloud bucket-based storage\n158: \tswitch provider {\n159: \tcase AWSStorageProvider:\n160: \t\treturn newAWSStorage(ctx, bucketName)\n161: \tcase GCPStorageProvider:\n162: \t\treturn NewGCP(ctx, bucketName, limiter)\n163: \tcase MINIOStorageProvider:\n164: \t\treturn NewMinioBucketStorageProvider(ctx, bucketName)\n165: \tcase MooncakeStorageProvider:\n166: \t\t//dsnPath := env.GetEnv(\"POSTGRESQL_DSN_PATH\", \"\")\n167: \t\t//return NewMooncakeStorageProvider(ctx, bucketName, dsnPath)\n168: \t\treturn NewMooncakeStorageProvider(ctx, bucketName)\n169: \t}\n170: \n171: \treturn nil, fmt.Errorf(\"unknown storage provider: %s\", provider)",
      "claim": "STORAGE_PROVIDER 选择单个实现；Mooncake 与 S3、MinIO、Local 并非默认串联缓存层。"
    },
    {
      "id": "S12",
      "title": "Mooncake Store Setup 参数",
      "path": "packages/shared/pkg/storage/storage_mooncake.go",
      "start": 337,
      "end": 357,
      "kind": "code",
      "chapter": 2,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/shared/pkg/storage/storage_mooncake.go#L337",
      "excerpt": "337: \t\tlocalHostname := env.GetEnv(\"MOONCAKE_LOCAL_HOSTNAME\", \"localhost\")\n338: \t\tmetadataServer := env.GetEnv(\"MOONCAKE_METADATA_SERVER\", \"http://localhost:8080/metadata\")\n339: \t\tval, err := env.GetEnvAsInt(\"MOONCAKE_GLOBAL_SEGMENT_SIZE\", 1073741824)\n340: \t\tif err != nil {\n341: \t\t\tglobalStoreFactory.err = fmt.Errorf(\"invalid MOONCAKE_GLOBAL_SEGMENT_SIZE: %w\", err)\n342: \t\t\treturn\n343: \t\t}\n344: \t\tglobalSegSize := uint64(val)\n345: \t\tvalBufferSize, err := env.GetEnvAsInt(\"MOONCAKE_LOCAL_BUFFER_SIZE\", 134217728)\n346: \t\tif err != nil {\n347: \t\t\tglobalStoreFactory.err = fmt.Errorf(\"invalid MOONCAKE_LOCAL_BUFFER_SIZE: %w\", err)\n348: \t\t\treturn\n349: \t\t}\n350: \t\tlocalBufSize := uint64(valBufferSize)\n351: \t\tprotocol := env.GetEnv(\"MOONCAKE_PROTOCOL\", \"tcp\")\n352: \t\tdeviceName := env.GetEnv(\"MOONCAKE_DEVICE_NAME\", \"\")\n353: \t\tmasterAddr := env.GetEnv(\"MOONCAKE_MASTER_ADDR\", \"localhost:50051\")\n354: \n355: \t\tif err := store.Setup(localHostname, metadataServer, globalSegSize, localBufSize,\n356: \t\t\tprotocol, deviceName, masterAddr); err != nil {\n357: \t\t\tglobalStoreFactory.err = fmt.Errorf(\"failed to setup mooncake store: %w\", err)",
      "claim": "实际传输协议、metadata/master 和内存容量来自环境设置；源码 fallback 为 tcp，部署示例可覆盖。"
    },
    {
      "id": "S13",
      "title": "Mooncake 编译与 CGo 依赖",
      "path": "build.sh",
      "start": 169,
      "end": 188,
      "kind": "code",
      "chapter": 2,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/build.sh#L169",
      "excerpt": "169: setup_mooncake() {\n170:     log_section \"Mooncake Store 依赖准备\"\n171:     \n172:     BUILD_TAGS=\"-tags mooncake\"\n173:     \n174:     # 构建 CGo 编译器标志\n175:     local cgo_cflags=(\n176:         \"-I/usr/include\"\n177:         \"-I/usr/include/mooncake\"\n178:         \"-I/usr/include/ub/umdk/urma\"\n179:         \"-I/usr/include/ub/umdk/urma/udma\"\n180:     )\n181:     \n182:     # 构建 CGo 链接器标志\n183:     local cgo_ldflags=(\n184:         \"-L/usr/lib64/urma\"\n185:         \"-L/usr/lib64\"\n186:         \"-lmooncake_store -lmooncake_common\"\n187:         \"-lstdc++ -lnuma -lglog -lgflags -libverbs -ljsoncpp -lzstd -lcurl -luring\"\n188:         \"-lurma -letcd_wrapper -lspdiag\"",
      "claim": "Mooncake 构建添加 build tag 并链接 native 库；仅设置运行环境变量不足以完成接入。"
    },
    {
      "id": "S14",
      "title": "签名上传地址生成",
      "path": "packages/shared/pkg/storage/storage_mooncake.go",
      "start": 1040,
      "end": 1054,
      "kind": "code",
      "chapter": 2,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/shared/pkg/storage/storage_mooncake.go#L1040",
      "excerpt": "1040: func (s *mooncakeStorage) UploadSignedURL(_ context.Context, path string, ttl time.Duration) (string, error) {\n1041: \tif s.upload == nil {\n1042: \t\treturn \"\", fmt.Errorf(\"mooncake signed upload is not configured\")\n1043: \t}\n1044: \n1045: \texpires := time.Now().Add(ttl).Unix()\n1046: \tv := url.Values{}\n1047: \t// Use the path without the bucket prefix: the handler resolves it through the\n1048: \t// provider's OpenBlob, so the bucket name is never leaked and the handler does\n1049: \t// not need to know about the key layout.\n1050: \tv.Set(\"path\", path)\n1051: \tv.Set(\"expires\", strconv.FormatInt(expires, 10))\n1052: \tv.Set(\"sig\", s.upload.sign(path, expires))\n1053: \n1054: \treturn s.upload.publicURL + SignedUploadPath + \"?\" + v.Encode(), nil",
      "claim": "Mooncake provider 生成指向 template-manager HTTP 通道的上传 URL。"
    },
    {
      "id": "S15",
      "title": "上传端点及随机签名密钥",
      "path": "packages/shared/pkg/storage/storage_mooncake_upload.go",
      "start": 34,
      "end": 66,
      "kind": "code",
      "chapter": 2,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/shared/pkg/storage/storage_mooncake_upload.go#L34",
      "excerpt": "34: func newMooncakeUploadConfig() (*mooncakeUploadConfig, error) {\n35: \thost := env.GetEnv(\"MOONCAKE_LOCAL_HOSTNAME\", \"localhost\")\n36: \tport, err := env.GetEnvAsInt(\"GRPC_PORT\", defaultMooncakeUploadPort)\n37: \tif err != nil {\n38: \t\treturn nil, fmt.Errorf(\"invalid GRPC_PORT: %w\", err)\n39: \t}\n40: \tif port < 1 || port > 65535 {\n41: \t\treturn nil, fmt.Errorf(\"GRPC_PORT must be between 1 and 65535, got %d\", port)\n42: \t}\n43: \n44: \tsecret := []byte(env.GetEnv(\"MOONCAKE_UPLOAD_SIGNING_SECRET\", \"\"))\n45: \tif len(secret) == 0 {\n46: \t\t// Process-scoped random secret: InitLayerFileUpload is routed by nodeID, so\n47: \t\t// signing and verification happen in the same process and no external\n48: \t\t// configuration is needed. A process restart invalidates old URLs, which is\n49: \t\t// compatible with the 30min TTL semantics.\n50: \t\tsecret = make([]byte, 32)\n51: \t\tif _, err := rand.Read(secret); err != nil {\n52: \t\t\treturn nil, fmt.Errorf(\"failed to generate upload signing secret: %w\", err)\n53: \t\t}\n54: \t}\n55: \n56: \treturn &mooncakeUploadConfig{\n57: \t\tsecret:    secret,\n58: \t\tpublicURL: \"http://\" + net.JoinHostPort(host, strconv.Itoa(port)),\n59: \t}, nil\n60: }\n61: \n62: func (c *mooncakeUploadConfig) sign(path string, expires int64) string {\n63: \tmac := hmac.New(sha256.New, c.secret)\n64: \tfmt.Fprintf(mac, \"PUT\\n%s\\n%d\", path, expires)\n65: \n66: \treturn base64.RawURLEncoding.EncodeToString(mac.Sum(nil))",
      "claim": "端点由节点地址与 GRPC_PORT 生成；未配置密钥时进程内随机生成，HMAC 绑定 PUT、路径与过期时间。"
    },
    {
      "id": "S16",
      "title": "COPY 层文件上传协商",
      "path": "packages/orchestrator/internal/template/server/upload_layer_files_template.go",
      "start": 13,
      "end": 44,
      "kind": "code",
      "chapter": 2,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/orchestrator/internal/template/server/upload_layer_files_template.go#L13",
      "excerpt": "13: const signedUrlExpiration = time.Minute * 30\n14: \n15: func (s *ServerStore) InitLayerFileUpload(ctx context.Context, in *templatemanager.InitLayerFileUploadRequest) (*templatemanager.InitLayerFileUploadResponse, error) {\n16: \tctx, childSpan := tracer.Start(ctx, \"template-create\")\n17: \tdefer childSpan.End()\n18: \n19: \t// default to scope by template ID\n20: \tcacheScope := in.GetTemplateID()\n21: \tif in.CacheScope != nil {\n22: \t\tcacheScope = in.GetCacheScope()\n23: \t}\n24: \n25: \tpath := paths.GetLayerFilesCachePath(cacheScope, in.GetHash())\n26: \tobj, err := s.buildStorage.OpenBlob(ctx, path, storage.BuildLayerFileObjectType)\n27: \tif err != nil {\n28: \t\treturn nil, fmt.Errorf(\"failed to open layer files cache: %w\", err)\n29: \t}\n30: \n31: \tsignedUrl, err := s.buildStorage.UploadSignedURL(ctx, path, signedUrlExpiration)\n32: \tif err != nil {\n33: \t\treturn nil, fmt.Errorf(\"failed to get signed url: %w\", err)\n34: \t}\n35: \n36: \texists, err := obj.Exists(ctx)\n37: \tif err != nil {\n38: \t\treturn nil, fmt.Errorf(\"failed to check if layer files exists: %w\", err)\n39: \t}\n40: \n41: \treturn &templatemanager.InitLayerFileUploadResponse{\n42: \t\tPresent: exists,\n43: \t\tUrl:     &signedUrl,\n44: \t}, nil",
      "claim": "template-manager 在请求未指定 cacheScope 时退回 TemplateID；正常平台 API 会显式传入 teamID，见 S56。返回 Present 与 URL，URL 有效期 30 分钟。"
    },
    {
      "id": "S17",
      "title": "HTTP 上传验签与体积限制",
      "path": "packages/orchestrator/internal/template/server/upload_http.go",
      "start": 19,
      "end": 78,
      "kind": "code",
      "chapter": 2,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/orchestrator/internal/template/server/upload_http.go#L19",
      "excerpt": "19: \t\tif r.Method != http.MethodPut {\n20: \t\t\thttp.Error(w, \"method not allowed\", http.StatusMethodNotAllowed)\n21: \n22: \t\t\treturn\n23: \t\t}\n24: \n25: \t\tverifier, ok := s.buildStorage.(storage.SignedUploadVerifier)\n26: \t\tif !ok {\n27: \t\t\thttp.Error(w, \"signed uploads not supported\", http.StatusNotFound)\n28: \n29: \t\t\treturn\n30: \t\t}\n31: \n32: \t\tq := r.URL.Query()\n33: \t\tpath := q.Get(\"path\")\n34: \t\texpires, err := strconv.ParseInt(q.Get(\"expires\"), 10, 64)\n35: \t\tif path == \"\" || err != nil {\n36: \t\t\thttp.Error(w, \"bad request\", http.StatusBadRequest)\n37: \n38: \t\t\treturn\n39: \t\t}\n40: \t\tif err := verifier.VerifySignedUpload(path, expires, q.Get(\"sig\")); err != nil {\n41: \t\t\thttp.Error(w, \"forbidden: \"+err.Error(), http.StatusForbidden)\n42: \n43: \t\t\treturn\n44: \t\t}\n45: \n46: \t\tblob, err := s.buildStorage.OpenBlob(r.Context(), path, storage.BuildLayerFileObjectType)\n47: \t\tif err != nil {\n48: \t\t\thttp.Error(w, \"storage error\", http.StatusInternalServerError)\n49: \n50: \t\t\treturn\n51: \t\t}\n52: \t\tstorer, ok := blob.(storage.StreamStorer)\n53: \t\tif !ok {\n54: \t\t\thttp.Error(w, \"streaming store not supported\", http.StatusInternalServerError)\n55: \n56: \t\t\treturn\n57: \t\t}\n58: \n59: \t\tmaxBytes := defaultSignedUploadMaxBytes\n60: \t\tif v, err := env.GetEnvAsInt(\"MOONCAKE_UPLOAD_MAX_BYTES\", defaultSignedUploadMaxBytes); err == nil && v > 0 {\n61: \t\t\tmaxBytes = v\n62: \t\t}\n63: \t\tbody := http.MaxBytesReader(w, r.Body, int64(maxBytes))\n64: \t\tdefer r.Body.Close()\n65: \n66: \t\tif err := storer.StoreReader(r.Context(), body); err != nil {\n67: \t\t\tvar maxErr *http.MaxBytesError\n68: \t\t\tif errors.As(err, &maxErr) {\n69: \t\t\t\thttp.Error(w, \"upload too large\", http.StatusRequestEntityTooLarge)\n70: \n71: \t\t\t\treturn\n72: \t\t\t}\n73: \t\t\thttp.Error(w, \"upload failed\", http.StatusInternalServerError)\n74: \n75: \t\t\treturn\n76: \t\t}\n77: \n78: \t\tw.WriteHeader(http.StatusOK)",
      "claim": "上传 handler 验证 PUT、path/expiry/HMAC 并限制体积；这不等于后端耐久保证。"
    },
    {
      "id": "S18",
      "title": "HTTP 与 gRPC 共享监听端口",
      "path": "packages/orchestrator/main.go",
      "start": 558,
      "end": 567,
      "kind": "code",
      "chapter": 2,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/orchestrator/main.go#L558",
      "excerpt": "558: \t// cmux server, allows us to reuse the same TCP port between grpc and HTTP requests\n559: \tcmuxServer, err := factories.NewCMUXServer(ctx, config.GRPCPort)\n560: \tif err != nil {\n561: \t\tlogger.L().Fatal(ctx, \"failed to create cmux server\", zap.Error(err))\n562: \t}\n563: \n564: \t// Create all matchers BEFORE starting Serve() to avoid data race.\n565: \t// cmux.Match() modifies internal state that Serve() reads from.\n566: \thttpListener := cmuxServer.Match(cmux.HTTP1Fast())\n567: \tgrpcListener := cmuxServer.Match(cmux.Any()) // the rest are GRPC requests",
      "claim": "cmux 区分 HTTP1 与 gRPC；签名上传不通过 Mooncake 服务端自带对象 HTTP 接口。"
    },
    {
      "id": "S19",
      "title": "BuildID 下的六类模板对象",
      "path": "packages/shared/pkg/storage/template.go",
      "start": 10,
      "end": 52,
      "kind": "code",
      "chapter": 3,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/shared/pkg/storage/template.go#L10",
      "excerpt": "10: \tMemfileName  = \"memfile\"\n11: \tRootfsName   = \"rootfs.ext4\"\n12: \tSnapfileName = \"snapfile\"\n13: \tMetadataName = \"metadata.json\"\n14: \n15: \tHeaderSuffix = \".header\"\n16: )\n17: \n18: type TemplateFiles struct {\n19: \tBuildID string `json:\"build_id\"`\n20: }\n21: \n22: // Key for the cache. Unique for template-build pair.\n23: func (t TemplateFiles) CacheKey() string {\n24: \treturn t.BuildID\n25: }\n26: \n27: func (t TemplateFiles) StorageDir() string {\n28: \treturn t.BuildID\n29: }\n30: \n31: func (t TemplateFiles) StorageMemfilePath() string {\n32: \treturn fmt.Sprintf(\"%s/%s\", t.StorageDir(), MemfileName)\n33: }\n34: \n35: func (t TemplateFiles) StorageMemfileHeaderPath() string {\n36: \treturn fmt.Sprintf(\"%s/%s%s\", t.StorageDir(), MemfileName, HeaderSuffix)\n37: }\n38: \n39: func (t TemplateFiles) StorageRootfsPath() string {\n40: \treturn fmt.Sprintf(\"%s/%s\", t.StorageDir(), RootfsName)\n41: }\n42: \n43: func (t TemplateFiles) StorageRootfsHeaderPath() string {\n44: \treturn fmt.Sprintf(\"%s/%s%s\", t.StorageDir(), RootfsName, HeaderSuffix)\n45: }\n46: \n47: func (t TemplateFiles) StorageSnapfilePath() string {\n48: \treturn fmt.Sprintf(\"%s/%s\", t.StorageDir(), SnapfileName)\n49: }\n50: \n51: func (t TemplateFiles) StorageMetadataPath() string {\n52: \treturn fmt.Sprintf(\"%s/%s\", t.StorageDir(), MetadataName)",
      "claim": "memfile、rootfs、两类 header、snapfile 和 metadata.json 以 BuildID 组织。"
    },
    {
      "id": "S20",
      "title": "逻辑段映射的数据结构",
      "path": "packages/shared/pkg/storage/header/mapping.go",
      "start": 11,
      "end": 20,
      "kind": "code",
      "chapter": 3,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/shared/pkg/storage/header/mapping.go#L11",
      "excerpt": "11: // Start, Length and SourceStart are in bytes of the data file\n12: // Length will be a multiple of BlockSize\n13: // The list of block mappings will be in order of increasing Start, covering the entire file\n14: type BuildMap struct {\n15: \t// Offset defines which block of the current layer this mapping starts at\n16: \tOffset             uint64\n17: \tLength             uint64\n18: \tBuildId            uuid.UUID\n19: \tBuildStorageOffset uint64\n20: }",
      "claim": "BuildMap 记录逻辑 Offset/Length、源 BuildId 和源对象 BuildStorageOffset。"
    },
    {
      "id": "S21",
      "title": "脏块压实与源对象偏移",
      "path": "packages/shared/pkg/storage/header/mapping.go",
      "start": 42,
      "end": 59,
      "kind": "code",
      "chapter": 3,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/shared/pkg/storage/header/mapping.go#L42",
      "excerpt": "42: \tfor blockIdx, e := dirty.NextSet(0); e; blockIdx, e = dirty.NextSet(blockIdx + 1) {\n43: \t\tif startBlock+blockLength == blockIdx {\n44: \t\t\tblockLength++\n45: \n46: \t\t\tcontinue\n47: \t\t}\n48: \n49: \t\tif blockLength > 0 {\n50: \t\t\tm := &BuildMap{\n51: \t\t\t\tOffset:             uint64(startBlock) * uint64(blockSize),\n52: \t\t\t\tBuildId:            *buildId,\n53: \t\t\t\tLength:             uint64(blockLength) * uint64(blockSize),\n54: \t\t\t\tBuildStorageOffset: buildStorageOffset,\n55: \t\t\t}\n56: \n57: \t\t\tmappings = append(mappings, m)\n58: \n59: \t\t\tbuildStorageOffset += m.Length",
      "claim": "映射按脏块区间构造，存储偏移累计已打包长度，不等于 VM 的逻辑偏移。"
    },
    {
      "id": "S22",
      "title": "逻辑 offset 转源对象 offset",
      "path": "packages/shared/pkg/storage/header/header.go",
      "start": 64,
      "end": 86,
      "kind": "code",
      "chapter": 3,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/shared/pkg/storage/header/header.go#L64",
      "excerpt": "64: func (t *Header) GetShiftedMapping(ctx context.Context, offset int64) (mappedOffset int64, mappedLength int64, buildID *uuid.UUID, err error) {\n65: \tmapping, shift, err := t.getMapping(ctx, offset)\n66: \tif err != nil {\n67: \t\treturn 0, 0, nil, err\n68: \t}\n69: \n70: \tmappedOffset = int64(mapping.BuildStorageOffset) + shift\n71: \tmappedLength = int64(mapping.Length) - shift\n72: \tbuildID = &mapping.BuildId\n73: \n74: \tif mappedLength < 0 {\n75: \t\tif t.IsNormalizeFixApplied() {\n76: \t\t\treturn 0, 0, nil, fmt.Errorf(\"mapped length for offset %d is negative: %d\", offset, mappedLength)\n77: \t\t}\n78: \n79: \t\tlogger.L().Warn(ctx, \"mapped length is negative, but normalize fix is not applied\",\n80: \t\t\tzap.Int64(\"offset\", offset),\n81: \t\t\tzap.Int64(\"mappedLength\", mappedLength),\n82: \t\t\tlogger.WithBuildID(mapping.BuildId.String()),\n83: \t\t)\n84: \t}\n85: \n86: \treturn mappedOffset, mappedLength, buildID, nil",
      "claim": "源对象偏移为 BuildStorageOffset 加段内 shift，同时返回源 BuildID 与本段剩余长度。"
    },
    {
      "id": "S23",
      "title": "按映射拆分跨 Build 读取",
      "path": "packages/orchestrator/internal/sandbox/build/build.go",
      "start": 40,
      "end": 95,
      "kind": "code",
      "chapter": 3,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/orchestrator/internal/sandbox/build/build.go#L40",
      "excerpt": "40: func (b *File) ReadAt(ctx context.Context, p []byte, off int64) (n int, err error) {\n41: \tfor n < len(p) {\n42: \t\tmappedOffset, mappedLength, buildID, err := b.header.GetShiftedMapping(ctx, off+int64(n))\n43: \t\tif err != nil {\n44: \t\t\treturn 0, fmt.Errorf(\"failed to get mapping: %w\", err)\n45: \t\t}\n46: \n47: \t\tremainingReadLength := int64(len(p)) - int64(n)\n48: \n49: \t\treadLength := min(mappedLength, remainingReadLength)\n50: \n51: \t\tif readLength <= 0 {\n52: \t\t\tlogger.L().Error(ctx, fmt.Sprintf(\n53: \t\t\t\t\"(%d bytes left to read, off %d) reading %d bytes from %+v/%+v: [%d:] -> [%d:%d] <> %d (mapped length: %d, remaining read length: %d)\\n>>> EOF\\n\",\n54: \t\t\t\tlen(p)-n,\n55: \t\t\t\toff,\n56: \t\t\t\treadLength,\n57: \t\t\t\tbuildID,\n58: \t\t\t\tb.fileType,\n59: \t\t\t\tmappedOffset,\n60: \t\t\t\tn,\n61: \t\t\t\tint64(n)+readLength,\n62: \t\t\t\tn,\n63: \t\t\t\tmappedLength,\n64: \t\t\t\tremainingReadLength,\n65: \t\t\t))\n66: \n67: \t\t\treturn n, io.EOF\n68: \t\t}\n69: \n70: \t\t// Skip reading when the uuid is nil.\n71: \t\t// We will use this to handle base builds that are already diffs.\n72: \t\t// The passed slice p must start as empty, otherwise we would need to copy the empty values there.\n73: \t\tif *buildID == uuid.Nil {\n74: \t\t\tn += int(readLength)\n75: \n76: \t\t\tcontinue\n77: \t\t}\n78: \n79: \t\tmappedBuild, err := b.getBuild(ctx, buildID)\n80: \t\tif err != nil {\n81: \t\t\treturn 0, fmt.Errorf(\"failed to get build: %w\", err)\n82: \t\t}\n83: \n84: \t\tbuildN, err := mappedBuild.ReadAt(ctx,\n85: \t\t\tp[n:int64(n)+readLength],\n86: \t\t\tmappedOffset,\n87: \t\t)\n88: \t\tif err != nil {\n89: \t\t\treturn 0, fmt.Errorf(\"failed to read from source: %w\", err)\n90: \t\t}\n91: \n92: \t\tn += buildN\n93: \t}\n94: \n95: \treturn n, nil",
      "claim": "按 header 定位源 build/diff；Nil UUID 的区间跳过远端读取，调用方遵守零初始化前提。"
    },
    {
      "id": "S24",
      "title": "4 MiB 分块常量",
      "path": "packages/shared/pkg/storage/storage.go",
      "start": 29,
      "end": 40,
      "kind": "code",
      "chapter": 3,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/shared/pkg/storage/storage.go#L29",
      "excerpt": "29: const (\n30: \tGCPStorageProvider     Provider = \"GCPBucket\"\n31: \tAWSStorageProvider     Provider = \"AWSBucket\"\n32: \tLocalStorageProvider   Provider = \"Local\"\n33: \tMINIOStorageProvider   Provider = \"MinioBucket\"\n34: \tMooncakeStorageProvider   Provider = \"MooncakeBucket\"\n35: \tDefaultStorageProvider Provider = MINIOStorageProvider\n36: \n37: \tstorageProviderEnv = \"STORAGE_PROVIDER\"\n38: \n39: \t// MemoryChunkSize must always be bigger or equal to the block size.\n40: \tMemoryChunkSize = 4 * 1024 * 1024 // 4 MB",
      "claim": "MemoryChunkSize 为 4 MiB；它是内容传输/切片粒度，不能与 Guest 页粒度混淆。"
    },
    {
      "id": "S25",
      "title": "主 key 目录与 chunk key 前缀",
      "path": "packages/shared/pkg/storage/storage_mooncake.go",
      "start": 1389,
      "end": 1418,
      "kind": "code",
      "chapter": 3,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/shared/pkg/storage/storage_mooncake.go#L1389",
      "excerpt": "1389: type mooncakeObjectMeta struct {\n1390: \tSize      int64 `json:\"size\"`\n1391: \tChunkSize int64 `json:\"chunk_size\"`\n1392: }\n1393: \n1394: type mooncakeSeekable struct {\n1395: \tstore          *mooncakestore.Store\n1396: \tpath           string\n1397: \tchunkKeyPrefix string\n1398: \tmetaMu         sync.Mutex\n1399: \tmeta           *mooncakeObjectMeta\n1400: \tmetaErr        error\n1401: \tmetaLoaded     bool\n1402: \tmetaLoading    bool\n1403: \tmetaWait       chan struct{}\n1404: }\n1405: \n1406: var (\n1407: \t_ Seekable        = (*mooncakeSeekable)(nil)\n1408: \t_ StreamingReader = (*mooncakeSeekable)(nil)\n1409: \t//_ BufferRegistrar = (*mooncakeSeekable)(nil)\n1410: \t//_ BatchReader     = (*mooncakeSeekable)(nil)\n1411: )\n1412: \n1413: func newMooncakeSeekable(store *mooncakestore.Store, path string) *mooncakeSeekable {\n1414: \treturn &mooncakeSeekable{\n1415: \t\tstore:          store,\n1416: \t\tpath:           path,\n1417: \t\tchunkKeyPrefix: path + \"#c#\",\n1418: \t}",
      "claim": "主 key JSON 仅保存 size/chunk_size；分块 key 前缀为 path 加 #c#。"
    },
    {
      "id": "S26",
      "title": "Bucket 变为 Mooncake key 命名空间",
      "path": "packages/shared/pkg/storage/storage_mooncake.go",
      "start": 1014,
      "end": 1018,
      "kind": "code",
      "chapter": 3,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/shared/pkg/storage/storage_mooncake.go#L1014",
      "excerpt": "1014: func (s *mooncakeStorage) key(path string) string {\n1015: \tif s.bucketName == \"\" {\n1016: \t\treturn path\n1017: \t}\n1018: \treturn s.bucketName + \"/\" + path",
      "claim": "对象 key 由 bucket 与逻辑 path 拼成，不意味着每个 bucket 是独立物理存储服务。"
    },
    {
      "id": "S27",
      "title": "对象偏移转 chunk key",
      "path": "packages/shared/pkg/storage/storage_mooncake.go",
      "start": 1537,
      "end": 1569,
      "kind": "code",
      "chapter": 3,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/shared/pkg/storage/storage_mooncake.go#L1537",
      "excerpt": "1537: func (o *mooncakeSeekable) readAtSingleChunk(ctx context.Context, buff []byte, off int64, remaining int64, meta *mooncakeObjectMeta) (int, error) {\n1538: \tchunkOffset := (off / meta.ChunkSize) * meta.ChunkSize\n1539: \tchunkEnd := min(chunkOffset+meta.ChunkSize, meta.Size)\n1540: \tchunkSize := chunkEnd - chunkOffset\n1541: \n1542: \tstartInChunk := off - chunkOffset\n1543: \tdata, err := o.readChunk(ctx, chunkOffset, chunkSize, buff, startInChunk)\n1544: \tif err != nil {\n1545: \t\treturn 0, fmt.Errorf(\"failed to read chunk at %d: %w\", chunkOffset, err)\n1546: \t}\n1547: \n1548: \tcopied := min(len(data), int(remaining))\n1549: \n1550: \tif copied < len(buff) && off+int64(copied) >= meta.Size {\n1551: \t\treturn copied, io.EOF\n1552: \t}\n1553: \treturn copied, nil\n1554: }\n1555: \n1556: func (o *mooncakeSeekable) readChunk(ctx context.Context, chunkOffset, chunkSize int64, buff []byte, startInChunk int64) ([]byte, error) {\n1557: \tkey := o.chunkKey(chunkOffset)\n1558: \n1559: \tnumaBuf, n, release, err := getIntoNumaBuffer(ctx, o.store, key, uint64(chunkSize))\n1560: \tif err != nil {\n1561: \t\treturn nil, err\n1562: \t}\n1563: \tif startInChunk >= int64(n) {\n1564: \t\trelease()\n1565: \t\treturn nil, io.EOF\n1566: \t}\n1567: \n1568: \tendInChunk := min(int64(n), startInChunk+int64(len(buff)))\n1569: \tcopied := copy(buff, numaBuf.buf[startInChunk:endInChunk])",
      "claim": "chunkOffset 按 chunk_size 向下取整；key 后缀是绝对字节 offset 的十进制，读取后复制所需区间。"
    },
    {
      "id": "S28",
      "title": "Blob 小对象与分块布局",
      "path": "packages/shared/pkg/storage/storage_mooncake.go",
      "start": 1087,
      "end": 1134,
      "kind": "code",
      "chapter": 3,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/shared/pkg/storage/storage_mooncake.go#L1087",
      "excerpt": "1087: \terrNotChunkedBlob     = errors.New(\"not a chunked Mooncake blob\")\n1088: \terrLegacyBlobTooLarge = errors.New(\"legacy single-object Mooncake blob exceeds the 4 MiB registered buffer limit\")\n1089: )\n1090: \n1091: func (o *mooncakeBlob) Put(ctx context.Context, data []byte) error {\n1092: \tinvalidateCachedMetadata(o.path)\n1093: \tif len(data) <= MemoryChunkSize {\n1094: \t\treturn o.store.Put(o.path, data, nil)\n1095: \t}\n1096: \n1097: \tif err := o.deleteObjectAndChunks(); err != nil {\n1098: \t\treturn fmt.Errorf(\"failed to clean up old object %s: %w\", o.path, err)\n1099: \t}\n1100: \n1101: \tg, groupCtx := errgroup.WithContext(ctx)\n1102: \tg.SetLimit(mooncakeUploadConcurrency)\n1103: \n1104: \tsize := int64(len(data))\n1105: \tfor offset := int64(0); offset < size; offset += MemoryChunkSize {\n1106: \t\toff := offset\n1107: \t\tg.Go(func() error {\n1108: \t\t\tif err := groupCtx.Err(); err != nil {\n1109: \t\t\t\treturn err\n1110: \t\t\t}\n1111: \n1112: \t\t\tend := min(off+MemoryChunkSize, size)\n1113: \t\t\tchunk := data[off:end]\n1114: \t\t\tcChunk := C.CBytes(chunk)\n1115: \t\t\tdefer C.free(cChunk)\n1116: \n1117: \t\t\treturn o.store.Put(o.chunkKey(off), unsafe.Slice((*byte)(cChunk), len(chunk)), nil)\n1118: \t\t})\n1119: \t}\n1120: \n1121: \tif err := g.Wait(); err != nil {\n1122: \t\treturn fmt.Errorf(\"failed to upload chunks: %w\", err)\n1123: \t}\n1124: \n1125: \tmeta := &mooncakeObjectMeta{Size: size, ChunkSize: MemoryChunkSize}\n1126: \tmetaBytes, err := json.Marshal(meta)\n1127: \tif err != nil {\n1128: \t\treturn fmt.Errorf(\"failed to marshal metadata: %w\", err)\n1129: \t}\n1130: \tif err := o.store.Put(o.path, metaBytes, nil); err != nil {\n1131: \t\treturn fmt.Errorf(\"failed to write metadata: %w\", err)\n1132: \t}\n1133: \tstoreCachedMetadata(o.path, meta)\n1134: \treturn nil",
      "claim": "小 Blob 直接写单 key；大 Blob 分块并写 JSON 目录。大 Blob 更新前会删除旧对象，不能声称原子覆盖。"
    },
    {
      "id": "S29",
      "title": "COPY tar 与层 hash 索引路径",
      "path": "packages/orchestrator/internal/template/build/storage/paths/paths.go",
      "start": 7,
      "end": 17,
      "kind": "code",
      "chapter": 3,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/orchestrator/internal/template/build/storage/paths/paths.go#L7",
      "excerpt": "7: func buildStoragePath(cacheScope string, saveType string, file string) string {\n8: \treturn path.Join(cacheScope, saveType, file)\n9: }\n10: \n11: func GetLayerFilesCachePath(cacheScope string, hash string) string {\n12: \treturn buildStoragePath(cacheScope, \"files\", hash+\".tar\")\n13: }\n14: \n15: func HashToPath(cacheScope, hash string) string {\n16: \treturn buildStoragePath(cacheScope, \"index\", hash)\n17: }",
      "claim": "构建文件存于 cacheScope/files/hash.tar，层索引位于 cacheScope/index/hash；不同于 BuildID 的模板对象。"
    },
    {
      "id": "S30",
      "title": "Guest 页与 rootfs 块粒度",
      "path": "packages/orchestrator/internal/template/build/config/config.go",
      "start": 69,
      "end": 89,
      "kind": "code",
      "chapter": 3,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/orchestrator/internal/template/build/config/config.go#L69",
      "excerpt": "69: func MemfilePageSize(hugePages bool) int64 {\n70: \tif hugePages {\n71: \t\treturn header.HugepageSize\n72: \t}\n73: \n74: \t// Keep the memfile block size at the granularity Firecracker uses for its\n75: \t// dirty/resident/empty bitmaps. With hugepages disabled Firecracker always\n76: \t// reports these bitmaps at 4 KiB per bit (HugePageConfig::None => 4096),\n77: \t// independent of the host base-page size. The memfile block size must match\n78: \t// that granularity: CreateMapping() converts bit indexes to offsets with\n79: \t// `index * blockSize`, so a larger block size would scale the 4 KiB indexes\n80: \t// by the host page size and produce out-of-range mappings.\n81: \t//\n82: \t// Hosts with a base page larger than 4 KiB (e.g. 64 KiB ARM64) are handled\n83: \t// on the I/O side instead: UFFD copies use the host page size as copy unit\n84: \t// and read it from multiple 4 KiB blocks (see uffd/prefetch and block.ReadSlice).\n85: \treturn header.PageSize\n86: }\n87: \n88: func (e TemplateConfig) RootfsBlockSize() int64 {\n89: \treturn header.RootfsBlockSize",
      "claim": "rootfs 与内存块粒度由配置确定；hugepage 内存页与 4 MiB 传输分块是不同层级。"
    },
    {
      "id": "S31",
      "title": "旧 header 的兼容读取",
      "path": "packages/orchestrator/internal/sandbox/template/storage.go",
      "start": 57,
      "end": 91,
      "kind": "code",
      "chapter": 4,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/orchestrator/internal/sandbox/template/storage.go#L57",
      "excerpt": "57: \tif h == nil {\n58: \t\theaderObjectPath := buildId + \"/\" + string(fileType) + storage.HeaderSuffix\n59: \t\theaderObjectType, ok := storageHeaderObjectType(fileType)\n60: \t\tif !ok {\n61: \t\t\treturn nil, build.UnknownDiffTypeError{DiffType: fileType}\n62: \t\t}\n63: \n64: \t\theaderObject, err := persistence.OpenBlob(ctx, headerObjectPath, headerObjectType)\n65: \t\tif err != nil {\n66: \t\t\treturn nil, err\n67: \t\t}\n68: \n69: \t\tdiffHeader, err := header.Deserialize(ctx, headerObject)\n70: \n71: \t\t// If we can't find the diff header in storage, we switch to templates without a headers\n72: \t\tif err != nil && !errors.Is(err, storage.ErrObjectNotExist) {\n73: \t\t\treturn nil, fmt.Errorf(\"failed to deserialize header: %w\", err)\n74: \t\t}\n75: \n76: \t\tif err == nil {\n77: \t\t\th = diffHeader\n78: \t\t}\n79: \t}\n80: \n81: \t// If we can't find the diff header in storage, we try to find the \"old\" style template without a header as a fallback.\n82: \tif h == nil {\n83: \t\tobjectPath := buildId + \"/\" + string(fileType)\n84: \t\tobjectType, ok := objectType(fileType)\n85: \t\tif !ok {\n86: \t\t\treturn nil, build.UnknownDiffTypeError{DiffType: fileType}\n87: \t\t}\n88: \t\tobject, err := persistence.OpenSeekable(ctx, objectPath, objectType)\n89: \t\tif err != nil {\n90: \t\t\treturn nil, err\n91: \t\t}",
      "claim": "header 不存在时尝试旧模板格式；这是同后端格式兼容，不能解释为 Mooncake 故障后回源 S3。"
    },
    {
      "id": "S32",
      "title": "源 diff 初始化与本地 chunker",
      "path": "packages/orchestrator/internal/sandbox/build/storage_diff.go",
      "start": 87,
      "end": 109,
      "kind": "code",
      "chapter": 4,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/orchestrator/internal/sandbox/build/storage_diff.go#L87",
      "excerpt": "87: func (b *StorageDiff) Init(ctx context.Context) error {\n88: \tobj, err := b.persistence.OpenSeekable(ctx, b.storagePath, b.storageObjectType)\n89: \tif err != nil {\n90: \t\treturn err\n91: \t}\n92: \n93: \tsize, err := obj.Size(ctx)\n94: \tif err != nil {\n95: \t\terrMsg := fmt.Errorf(\"failed to get object size: %w\", err)\n96: \t\tb.chunker.SetError(errMsg)\n97: \n98: \t\treturn errMsg\n99: \t}\n100: \n101: \tc, err := block.NewChunker(ctx, b.featureFlags, size, b.blockSize, obj, b.cachePath, b.metrics)\n102: \tif err != nil {\n103: \t\terrMsg := fmt.Errorf(\"failed to create chunker: %w\", err)\n104: \t\tb.chunker.SetError(errMsg)\n105: \n106: \t\treturn errMsg\n107: \t}\n108: \n109: \treturn b.chunker.SetValue(c)",
      "claim": "OpenSeekable 与 Size 获取源对象，并建立本地读取 chunker。"
    },
    {
      "id": "S33",
      "title": "本地块命中与缺失探测",
      "path": "packages/orchestrator/internal/sandbox/block/chunk.go",
      "start": 161,
      "end": 201,
      "kind": "code",
      "chapter": 4,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/orchestrator/internal/sandbox/block/chunk.go#L161",
      "excerpt": "161: func (c *FullFetchChunker) Slice(ctx context.Context, off, length int64) ([]byte, error) {\n162: \ttimer := c.metrics.SlicesTimerFactory.Begin()\n163: \n164: \tb, err := c.cache.Slice(off, length)\n165: \tif err == nil {\n166: \t\ttimer.Success(ctx, length,\n167: \t\t\tattribute.String(pullType, pullTypeLocal))\n168: \n169: \t\treturn b, nil\n170: \t}\n171: \n172: \tif !errors.As(err, &BytesNotAvailableError{}) {\n173: \t\ttimer.Failure(ctx, length,\n174: \t\t\tattribute.String(pullType, pullTypeLocal),\n175: \t\t\tattribute.String(failureReason, failureTypeLocalRead))\n176: \n177: \t\treturn nil, fmt.Errorf(\"failed read from cache at offset %d: %w\", off, err)\n178: \t}\n179: \n180: \tchunkErr := c.fetchToCache(ctx, off, length)\n181: \tif chunkErr != nil {\n182: \t\ttimer.Failure(ctx, length,\n183: \t\t\tattribute.String(pullType, pullTypeRemote),\n184: \t\t\tattribute.String(failureReason, failureTypeCacheFetch))\n185: \n186: \t\treturn nil, fmt.Errorf(\"failed to ensure data at %d-%d: %w\", off, off+length, chunkErr)\n187: \t}\n188: \n189: \tb, cacheErr := c.cache.Slice(off, length)\n190: \tif cacheErr != nil {\n191: \t\ttimer.Failure(ctx, length,\n192: \t\t\tattribute.String(pullType, pullTypeLocal),\n193: \t\t\tattribute.String(failureReason, failureTypeLocalReadAgain))\n194: \n195: \t\treturn nil, fmt.Errorf(\"failed to read from cache after ensuring data at %d-%d: %w\", off, off+length, cacheErr)\n196: \t}\n197: \n198: \ttimer.Success(ctx, length,\n199: \t\tattribute.String(pullType, pullTypeRemote))\n200: \n201: \treturn b, nil",
      "claim": "读取先查询本地 cache，对未缓存的块再触发 fetch。"
    },
    {
      "id": "S34",
      "title": "FullFetch 合并与完整长度门槛",
      "path": "packages/orchestrator/internal/sandbox/block/chunk.go",
      "start": 237,
      "end": 271,
      "kind": "code",
      "chapter": 4,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/orchestrator/internal/sandbox/block/chunk.go#L237",
      "excerpt": "237: \t\t\terr = c.fetchers.Wait(fetchOff, func() error {\n238: \t\t\t\tselect {\n239: \t\t\t\tcase <-ctx.Done():\n240: \t\t\t\t\treturn fmt.Errorf(\"error fetching range %d-%d: %w\", fetchOff, fetchOff+storage.MemoryChunkSize, ctx.Err())\n241: \t\t\t\tdefault:\n242: \t\t\t\t}\n243: \n244: \t\t\t\t// The size of the buffer is adjusted if the last chunk is not a multiple of the block size.\n245: \t\t\t\tb, releaseCacheCloseLock, err := c.cache.addressBytes(fetchOff, storage.MemoryChunkSize)\n246: \t\t\t\tif err != nil {\n247: \t\t\t\t\treturn err\n248: \t\t\t\t}\n249: \n250: \t\t\t\tdefer releaseCacheCloseLock()\n251: \n252: \t\t\t\tfetchSW := c.metrics.RemoteReadsTimerFactory.Begin()\n253: \n254: \t\t\t\treadBytes, err := c.base.ReadAt(ctx, b, fetchOff)\n255: \t\t\t\tif err != nil {\n256: \t\t\t\t\tfetchSW.Failure(ctx, int64(readBytes),\n257: \t\t\t\t\t\tattribute.String(failureReason, failureTypeRemoteRead),\n258: \t\t\t\t\t)\n259: \n260: \t\t\t\t\treturn fmt.Errorf(\"failed to read chunk from base %d: %w\", fetchOff, err)\n261: \t\t\t\t}\n262: \n263: \t\t\t\tif readBytes != len(b) {\n264: \t\t\t\t\tfetchSW.Failure(ctx, int64(readBytes),\n265: \t\t\t\t\t\tattribute.String(failureReason, failureTypeRemoteRead),\n266: \t\t\t\t\t)\n267: \n268: \t\t\t\t\treturn fmt.Errorf(\"failed to read chunk from base %d: expected %d bytes, got %d bytes\", fetchOff, len(b), readBytes)\n269: \t\t\t\t}\n270: \n271: \t\t\t\tc.cache.setIsCached(fetchOff, int64(readBytes))",
      "claim": "同 chunk 的 fetch 合并；只有后端返回长度等于期望长度后才标记缓存可用。"
    },
    {
      "id": "S35",
      "title": "WaitMap 首次结果复用",
      "path": "packages/shared/pkg/utils/wait_map.go",
      "start": 20,
      "end": 36,
      "kind": "code",
      "chapter": 4,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/shared/pkg/utils/wait_map.go#L20",
      "excerpt": "20: func (m *WaitMap) Wait(key int64, fn func() error) error {\n21: \tm.mu.Lock()\n22: \n23: \tonce, ok := m.m[key]\n24: \tif ok {\n25: \t\tm.mu.Unlock()\n26: \n27: \t\treturn once()\n28: \t}\n29: \n30: \tonce = sync.OnceValue(fn)\n31: \n32: \tm.m[key] = once\n33: \n34: \tm.mu.Unlock()\n35: \n36: \treturn once()",
      "claim": "sync.OnceValue 复用同 key 的首次执行结果，包括最终错误；该性质只适用于使用此 WaitMap 的路径。"
    },
    {
      "id": "S36",
      "title": "Mooncake 元数据并发装载",
      "path": "packages/shared/pkg/storage/storage_mooncake.go",
      "start": 1441,
      "end": 1485,
      "kind": "code",
      "chapter": 4,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/shared/pkg/storage/storage_mooncake.go#L1441",
      "excerpt": "1441: func (o *mooncakeSeekable) getMeta(ctx context.Context) (*mooncakeObjectMeta, error) {\n1442: \tif meta, ok := loadCachedMetadata(o.path); ok {\n1443: \t\treturn meta, nil\n1444: \t}\n1445: \n1446: \tfor {\n1447: \t\to.metaMu.Lock()\n1448: \t\tif o.metaLoaded {\n1449: \t\t\tmeta, err := o.meta, o.metaErr\n1450: \t\t\to.metaMu.Unlock()\n1451: \t\t\treturn meta, err\n1452: \t\t}\n1453: \t\tif o.metaLoading {\n1454: \t\t\twait := o.metaWait\n1455: \t\t\to.metaMu.Unlock()\n1456: \t\t\tselect {\n1457: \t\t\tcase <-wait:\n1458: \t\t\t\tcontinue\n1459: \t\t\tcase <-ctx.Done():\n1460: \t\t\t\treturn nil, ctx.Err()\n1461: \t\t\t}\n1462: \t\t}\n1463: \n1464: \t\to.metaLoading = true\n1465: \t\to.metaWait = make(chan struct{})\n1466: \t\twait := o.metaWait\n1467: \t\to.metaMu.Unlock()\n1468: \n1469: \t\tmeta, err, cache := o.loadMeta(ctx)\n1470: \n1471: \t\to.metaMu.Lock()\n1472: \t\tif cache {\n1473: \t\t\to.meta = meta\n1474: \t\t\to.metaErr = err\n1475: \t\t\to.metaLoaded = true\n1476: \t\t\tif err == nil {\n1477: \t\t\t\tstoreCachedMetadata(o.path, meta)\n1478: \t\t\t}\n1479: \t\t}\n1480: \t\to.metaLoading = false\n1481: \t\to.metaWait = nil\n1482: \t\tclose(wait)\n1483: \t\to.metaMu.Unlock()\n1484: \t\treturn meta, err\n1485: \t}",
      "claim": "对象内加载状态合并并发元数据请求；这不提供跨进程失效协议。"
    },
    {
      "id": "S37",
      "title": "临时元数据错误与格式错误",
      "path": "packages/shared/pkg/storage/storage_mooncake.go",
      "start": 1488,
      "end": 1509,
      "kind": "code",
      "chapter": 4,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/shared/pkg/storage/storage_mooncake.go#L1488",
      "excerpt": "1488: func (o *mooncakeSeekable) loadMeta(ctx context.Context) (*mooncakeObjectMeta, error, bool) {\n1489: \tnumaBuf, n, release, err := getIntoNumaBuffer(ctx, o.store, o.path, uint64(4096))\n1490: \tif err != nil {\n1491: \t\texists, existsErr := o.store.Exists(o.path)\n1492: \t\tif existsErr == nil && !exists {\n1493: \t\t\t// A high-concurrency Mooncake lookup can transiently report a\n1494: \t\t\t// missing object. Return the state to this caller, but do not poison\n1495: \t\t\t// the seekable instance's metadata cache permanently.\n1496: \t\t\treturn nil, ErrObjectNotExist, false\n1497: \t\t}\n1498: \t\treturn nil, fmt.Errorf(\"failed to read metadata for %s: %w\", o.path, err), false\n1499: \t}\n1500: \tdefer release()\n1501: \n1502: \tvar meta mooncakeObjectMeta\n1503: \tif err := json.Unmarshal(numaBuf.buf[:n], &meta); err != nil {\n1504: \t\treturn nil, fmt.Errorf(\"failed to parse metadata for %s: %w\", o.path, err), true\n1505: \t}\n1506: \tif meta.ChunkSize <= 0 || meta.ChunkSize > numaBufferSize || meta.Size < 0 {\n1507: \t\treturn nil, fmt.Errorf(\"invalid metadata for %s: %+v\", o.path, meta), true\n1508: \t}\n1509: \treturn &meta, nil, true",
      "claim": "暂时读取失败不永久缓存；已判定的格式错误会在对象内缓存。"
    },
    {
      "id": "S38",
      "title": "Mooncake RangeReader 的实际分块",
      "path": "packages/shared/pkg/storage/storage_mooncake.go",
      "start": 1641,
      "end": 1688,
      "kind": "code",
      "chapter": 4,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/shared/pkg/storage/storage_mooncake.go#L1641",
      "excerpt": "1641: \tvar total int\n1642: \tfor want > 0 && r.off < r.end {\n1643: \t\t// Load the chunk containing the current offset\n1644: \t\tchunkOffset := (r.off / r.meta.ChunkSize) * r.meta.ChunkSize\n1645: \t\tif r.chunkBuf == nil || r.chunkOff != chunkOffset {\n1646: \t\t\tr.releaseChunkBuffer()\n1647: \n1648: \t\t\tchunkEnd := min(chunkOffset+r.meta.ChunkSize, r.meta.Size)\n1649: \t\t\tchunkSize := chunkEnd - chunkOffset\n1650: \n1651: \t\t\tbuf, releaseBuf, err := getChunkBuffer(r.ctx)\n1652: \t\t\tif err != nil {\n1653: \t\t\t\tif total > 0 {\n1654: \t\t\t\t\treturn total, nil\n1655: \t\t\t\t}\n1656: \t\t\t\treturn 0, err\n1657: \t\t\t}\n1658: \t\t\tbuf = buf[:int(chunkSize)]\n1659: \t\t\tdata, err := r.o.readChunk(r.ctx, chunkOffset, chunkSize, buf, 0)\n1660: \t\t\tif err != nil {\n1661: \t\t\t\treleaseBuf()\n1662: \t\t\t\tif total > 0 {\n1663: \t\t\t\t\treturn total, nil\n1664: \t\t\t\t}\n1665: \t\t\t\treturn 0, err\n1666: \t\t\t}\n1667: \t\t\tr.chunkBuf = data\n1668: \t\t\tr.releaseBuf = releaseBuf\n1669: \t\t\tr.chunkOff = chunkOffset\n1670: \t\t}\n1671: \n1672: \t\tstartInChunk := r.off - r.chunkOff\n1673: \t\tif startInChunk >= int64(len(r.chunkBuf)) {\n1674: \t\t\tif total > 0 {\n1675: \t\t\t\treturn total, nil\n1676: \t\t\t}\n1677: \t\t\treturn 0, io.EOF\n1678: \t\t}\n1679: \t\tendInChunk := min(int64(len(r.chunkBuf)), startInChunk+want)\n1680: \t\tcopied := copy(p[total:], r.chunkBuf[startInChunk:endInChunk])\n1681: \t\ttotal += copied\n1682: \t\tr.off += int64(copied)\n1683: \t\twant -= int64(copied)\n1684: \n1685: \t\tif endInChunk >= int64(len(r.chunkBuf)) {\n1686: \t\t\tr.releaseChunkBuffer()\n1687: \t\t}\n1688: \t}",
      "claim": "流式 reader 仍按完整 chunk 拉入缓冲后分段复制；不代表远端只传一个 Guest 小页。"
    },
    {
      "id": "S39",
      "title": "暂停先冻结 VM 并生成增量",
      "path": "packages/orchestrator/internal/sandbox/sandbox.go",
      "start": 939,
      "end": 983,
      "kind": "code",
      "chapter": 4,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/orchestrator/internal/sandbox/sandbox.go#L939",
      "excerpt": "939: \t// Stop the health check before pausing the VM\n940: \ts.Checks.Stop()\n941: \n942: \tif err := s.process.Pause(ctx); err != nil {\n943: \t\treturn nil, fmt.Errorf(\"failed to pause VM: %w\", err)\n944: \t}\n945: \n946: \t// Snapfile is not closed as it's returned and cached for later use (like resume)\n947: \tsnapfile := template.NewLocalFileLink(snapshotTemplateFiles.CacheSnapfilePath())\n948: \tcleanup.AddNoContext(ctx, snapfile.Close)\n949: \n950: \terr = s.process.CreateSnapshot(ctx, snapfile.Path())\n951: \tif err != nil {\n952: \t\treturn nil, fmt.Errorf(\"error creating snapshot: %w\", err)\n953: \t}\n954: \n955: \t// Gather data for postprocessing\n956: \toriginalMemfile, err := s.Template.Memfile(ctx)\n957: \tif err != nil {\n958: \t\treturn nil, fmt.Errorf(\"failed to get original memfile: %w\", err)\n959: \t}\n960: \n961: \toriginalRootfs, err := s.Template.Rootfs()\n962: \tif err != nil {\n963: \t\treturn nil, fmt.Errorf(\"failed to get original rootfs: %w\", err)\n964: \t}\n965: \n966: \tmemfileDiffMetadata, err := s.Resources.memory.DiffMetadata(ctx, s.process)\n967: \tif err != nil {\n968: \t\treturn nil, fmt.Errorf(\"failed to get memfile metadata: %w\", err)\n969: \t}\n970: \n971: \t// Start POSTPROCESSING\n972: \tmemfileDiff, memfileDiffHeader, err := pauseProcessMemory(\n973: \t\tctx,\n974: \t\tbuildID,\n975: \t\toriginalMemfile.Header(),\n976: \t\tmemfileDiffMetadata,\n977: \t\ts.config.DefaultCacheDir,\n978: \t\ts.process,\n979: \t)\n980: \tif err != nil {\n981: \t\treturn nil, fmt.Errorf(\"error while post processing: %w\", err)\n982: \t}\n983: \tcleanup.AddNoContext(ctx, memfileDiff.Close)",
      "claim": "Pause VM 后创建状态 snapshot，再生成 memory diff；未由此证明 Guest 应用事务 quiesce。",
      "legacyChapter": 5
    },
    {
      "id": "S40",
      "title": "后台上传与等待函数",
      "path": "packages/orchestrator/internal/server/sandboxes.go",
      "start": 611,
      "end": 653,
      "kind": "code",
      "chapter": 4,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/orchestrator/internal/server/sandboxes.go#L611",
      "excerpt": "611: \tsnapshot, err := sbx.Pause(ctx, meta)\n612: \tif err != nil {\n613: \t\treturn metadata.Template{}, nil, fmt.Errorf(\"error snapshotting sandbox: %w\", err)\n614: \t}\n615: \n616: \terr = s.templateCache.AddSnapshot(\n617: \t\tctx,\n618: \t\tmeta.Template.BuildID,\n619: \t\tsnapshot.MemfileDiffHeader,\n620: \t\tsnapshot.RootfsDiffHeader,\n621: \t\tsnapshot.Snapfile,\n622: \t\tsnapshot.Metafile,\n623: \t\tsnapshot.MemfileDiff,\n624: \t\tsnapshot.RootfsDiff,\n625: \t)\n626: \tif err != nil {\n627: \t\treturn metadata.Template{}, nil, fmt.Errorf(\"error adding snapshot to template cache: %w\", err)\n628: \t}\n629: \n630: \ttelemetry.ReportEvent(ctx, \"added snapshot to template cache\")\n631: \n632: \t// Start upload in background, return a wait function\n633: \tuploadCtx := context.WithoutCancel(ctx)\n634: \terrCh := make(chan error, 1)\n635: \n636: \tgo func() {\n637: \t\terr := snapshot.Upload(uploadCtx, s.persistence, storage.TemplateFiles{BuildID: meta.Template.BuildID})\n638: \t\tif err != nil {\n639: \t\t\tsbxlogger.I(sbx).Error(uploadCtx, \"error uploading snapshot\", zap.Error(err))\n640: \t\t\terrCh <- err\n641: \n642: \t\t\treturn\n643: \t\t}\n644: \n645: \t\tlogger.L().Info(uploadCtx, \"Snapshot uploaded successfully\", logger.WithSandboxID(sbx.Runtime.SandboxID))\n646: \t\terrCh <- nil\n647: \t}()\n648: \n649: \twaitForUpload := func() error {\n650: \t\treturn <-errCh\n651: \t}\n652: \n653: \treturn meta, waitForUpload, nil",
      "claim": "本地快照入 cache 后启动后台上传，返回 waitForUpload 供调用者等待最终完成。",
      "legacyChapter": 5
    },
    {
      "id": "S41",
      "title": "六类对象并行上传",
      "path": "packages/orchestrator/internal/sandbox/template_build.go",
      "start": 156,
      "end": 229,
      "kind": "code",
      "chapter": 4,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/orchestrator/internal/sandbox/template_build.go#L156",
      "excerpt": "156: func (t *TemplateBuild) Upload(ctx context.Context, metadataPath string, fcSnapfilePath string, memfilePath *string, rootfsPath *string) chan error {\n157: \teg, ctx := errgroup.WithContext(ctx)\n158: \n159: \teg.Go(func() error {\n160: \t\tif t.rootfsHeader == nil {\n161: \t\t\treturn nil\n162: \t\t}\n163: \n164: \t\terr := t.uploadRootfsHeader(ctx, t.rootfsHeader)\n165: \t\tif err != nil {\n166: \t\t\treturn err\n167: \t\t}\n168: \n169: \t\treturn nil\n170: \t})\n171: \n172: \teg.Go(func() error {\n173: \t\tif rootfsPath == nil {\n174: \t\t\treturn nil\n175: \t\t}\n176: \n177: \t\terr := t.uploadRootfs(ctx, *rootfsPath)\n178: \t\tif err != nil {\n179: \t\t\treturn err\n180: \t\t}\n181: \n182: \t\treturn nil\n183: \t})\n184: \n185: \teg.Go(func() error {\n186: \t\tif t.memfileHeader == nil {\n187: \t\t\treturn nil\n188: \t\t}\n189: \n190: \t\terr := t.uploadMemfileHeader(ctx, t.memfileHeader)\n191: \t\tif err != nil {\n192: \t\t\treturn err\n193: \t\t}\n194: \n195: \t\treturn nil\n196: \t})\n197: \n198: \teg.Go(func() error {\n199: \t\tif memfilePath == nil {\n200: \t\t\treturn nil\n201: \t\t}\n202: \n203: \t\terr := t.uploadMemfile(ctx, *memfilePath)\n204: \t\tif err != nil {\n205: \t\t\treturn err\n206: \t\t}\n207: \n208: \t\treturn nil\n209: \t})\n210: \n211: \teg.Go(func() error {\n212: \t\tif err := t.uploadSnapfile(ctx, fcSnapfilePath); err != nil {\n213: \t\t\treturn fmt.Errorf(\"error when uploading snapfile: %w\", err)\n214: \t\t}\n215: \n216: \t\treturn nil\n217: \t})\n218: \n219: \teg.Go(func() error {\n220: \t\treturn t.uploadMetadata(ctx, metadataPath)\n221: \t})\n222: \n223: \tdone := make(chan error)\n224: \n225: \tgo func() {\n226: \t\tdone <- eg.Wait()\n227: \t}()\n228: \n229: \treturn done",
      "claim": "两个 header、两类数据、snapfile 和 metadata 并行上传，eg.Wait 汇总；单文件 JSON 不是整个快照的提交标记。",
      "legacyChapter": 5
    },
    {
      "id": "S42",
      "title": "Seekable 分片后发布主 key",
      "path": "packages/shared/pkg/storage/storage_mooncake.go",
      "start": 1750,
      "end": 1795,
      "kind": "code",
      "chapter": 4,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/shared/pkg/storage/storage_mooncake.go#L1750",
      "excerpt": "1750: \t// Upload chunks in parallel.\n1751: \tg, groupCtx := errgroup.WithContext(ctx)\n1752: \tg.SetLimit(mooncakeUploadConcurrency)\n1753: \n1754: \tfor offset := int64(0); offset < size; offset += MemoryChunkSize {\n1755: \t\toff := offset\n1756: \t\tg.Go(func() error {\n1757: \t\t\tif err := groupCtx.Err(); err != nil {\n1758: \t\t\t\treturn err\n1759: \t\t\t}\n1760: \n1761: \t\t\tend := min(off+MemoryChunkSize, size)\n1762: \t\t\tbuf, releaseBuf, err := getChunkBuffer(groupCtx)\n1763: \t\t\tif err != nil {\n1764: \t\t\t\treturn err\n1765: \t\t\t}\n1766: \t\t\tdefer releaseBuf()\n1767: \t\t\tchunk := buf[:int(end-off)]\n1768: \n1769: \t\t\tif _, err := file.ReadAt(chunk, off); err != nil && !errors.Is(err, io.EOF) {\n1770: \t\t\t\treturn fmt.Errorf(\"failed to read chunk at %d from %s: %w\", off, localPath, err)\n1771: \t\t\t}\n1772: \n1773: \t\t\tcChunk := C.CBytes(chunk)\n1774: \t\t\tdefer C.free(cChunk)\n1775: \t\t\treturn o.store.Put(o.chunkKey(off), unsafe.Slice((*byte)(cChunk), len(chunk)), nil)\n1776: \t\t})\n1777: \t}\n1778: \n1779: \tif err := g.Wait(); err != nil {\n1780: \t\treturn fmt.Errorf(\"failed to upload chunks: %w\", err)\n1781: \t}\n1782: \n1783: \t// Write metadata last so that readers see a consistent object only when fully written.\n1784: \tmeta := &mooncakeObjectMeta{Size: size, ChunkSize: MemoryChunkSize}\n1785: \tmetaBytes, err := json.Marshal(meta)\n1786: \tif err != nil {\n1787: \t\treturn fmt.Errorf(\"failed to marshal metadata: %w\", err)\n1788: \t}\n1789: \n1790: \tif err := o.store.Put(o.path, metaBytes, nil); err != nil {\n1791: \t\treturn fmt.Errorf(\"failed to write metadata: %w\", err)\n1792: \t}\n1793: \tstoreCachedMetadata(o.path, meta)\n1794: \n1795: \treturn nil",
      "claim": "最多固定并发上传分片，全部成功后写主 key JSON；StoreFile 本体未实现已写分片回滚。",
      "legacyChapter": 5
    },
    {
      "id": "S43",
      "title": "Pause RPC 等待上传结果",
      "path": "packages/orchestrator/internal/server/sandboxes.go",
      "start": 416,
      "end": 429,
      "kind": "code",
      "chapter": 4,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/orchestrator/internal/server/sandboxes.go#L416",
      "excerpt": "416: \t// Wait for the snapshot upload to complete before returning - the snapshot\n417: \t// metadata must not be marked as ready before the data is actually persisted.\n418: \t_, waitForUpload, err := s.snapshotAndCacheSandbox(ctx, sbx, in.GetBuildId())\n419: \tif err != nil {\n420: \t\ttelemetry.ReportCriticalError(ctx, \"error snapshotting sandbox\", err, telemetry.WithSandboxID(in.GetSandboxId()))\n421: \n422: \t\treturn nil, status.Errorf(codes.Internal, \"error snapshotting sandbox '%s': %s\", in.GetSandboxId(), err)\n423: \t}\n424: \n425: \tif err := waitForUpload(); err != nil {\n426: \t\ttelemetry.ReportCriticalError(ctx, \"error uploading sandbox snapshot\", err, telemetry.WithSandboxID(in.GetSandboxId()))\n427: \n428: \t\treturn nil, status.Errorf(codes.Internal, \"error uploading snapshot for sandbox '%s': %s\", in.GetSandboxId(), err)\n429: \t}",
      "claim": "Pause 返回成功前必须 waitForUpload；Put 成功仍不等于介质持久化。",
      "legacyChapter": 5
    },
    {
      "id": "S44",
      "title": "API 将成功快照更新为可用",
      "path": "packages/api/internal/orchestrator/pause_instance.go",
      "start": 41,
      "end": 60,
      "kind": "code",
      "chapter": 4,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/api/internal/orchestrator/pause_instance.go#L41",
      "excerpt": "41: \terr = snapshotInstance(ctx, node, sbx, result.TemplateID, result.BuildID.String())\n42: \tif errors.Is(err, PauseQueueExhaustedError{}) {\n43: \t\ttelemetry.ReportCriticalError(ctx, \"pause queue exhausted\", err)\n44: \n45: \t\treturn PauseQueueExhaustedError{}\n46: \t}\n47: \n48: \tif err != nil && !errors.Is(err, PauseQueueExhaustedError{}) {\n49: \t\ttelemetry.ReportCriticalError(ctx, \"error pausing sandbox\", err)\n50: \n51: \t\treturn fmt.Errorf(\"error pausing sandbox: %w\", err)\n52: \t}\n53: \n54: \tnow := time.Now()\n55: \terr = o.sqlcDB.UpdateEnvBuildStatus(ctx, queries.UpdateEnvBuildStatusParams{\n56: \t\tStatus:     types.BuildStatusSuccess,\n57: \t\tFinishedAt: &now,\n58: \t\tReason:     types.BuildReason{},\n59: \t\tBuildID:    result.BuildID,\n60: \t})",
      "claim": "只有 orchestrator Pause 成功后才 UpdateBuild 为 success；与对象发布门槛共同构成正常写流程。",
      "legacyChapter": 5
    },
    {
      "id": "S45",
      "title": "流式上传失败时尝试清理",
      "path": "packages/shared/pkg/storage/storage_mooncake.go",
      "start": 1141,
      "end": 1165,
      "kind": "code",
      "chapter": 4,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/shared/pkg/storage/storage_mooncake.go#L1141",
      "excerpt": "1141: func (o *mooncakeBlob) StoreReader(ctx context.Context, r io.Reader) error {\n1142: \tinvalidateCachedMetadata(o.path)\n1143: \n1144: \tctx, cancel := context.WithCancel(ctx)\n1145: \tdefer cancel()\n1146: \n1147: \tg, groupCtx := errgroup.WithContext(ctx)\n1148: \tg.SetLimit(mooncakeUploadConcurrency)\n1149: \n1150: \tvar size int64\n1151: \t// A failed upload must not leave a partially written object behind: cancel any\n1152: \t// in-flight chunk uploads, wait for them, then delete everything written so\n1153: \t// far. Metadata is written only at the very end, so a successful return never\n1154: \t// triggers the cleanup.\n1155: \tcompleted := false\n1156: \tdefer func() {\n1157: \t\tif completed {\n1158: \t\t\treturn\n1159: \t\t}\n1160: \t\tcancel()\n1161: \t\t_ = g.Wait()\n1162: \t\tif size > 0 {\n1163: \t\t\t_ = o.deleteObjectAndChunks()\n1164: \t\t}\n1165: \t}()",
      "claim": "StoreReader 失败先取消并等待在途上传，再尝试删除已写对象；清理错误被忽略，不能推广到 StoreFile。",
      "legacyChapter": 5
    },
    {
      "id": "S46",
      "title": "GetInto 有界重试",
      "path": "packages/shared/pkg/storage/storage_mooncake.go",
      "start": 169,
      "end": 224,
      "kind": "code",
      "chapter": 5,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/shared/pkg/storage/storage_mooncake.go#L169",
      "excerpt": "169: func waitForMooncakeReadRetry(ctx context.Context, attempt int) error {\n170: \tdelay := time.Duration(attempt) * mooncakeReadRetryBaseDelay\n171: \ttimer := time.NewTimer(delay)\n172: \tdefer timer.Stop()\n173: \n174: \tselect {\n175: \tcase <-timer.C:\n176: \t\treturn nil\n177: \tcase <-ctx.Done():\n178: \t\treturn ctx.Err()\n179: \t}\n180: }\n181: \n182: func getIntoWithRetry(\n183: \tctx context.Context,\n184: \tstore *mooncakestore.Store,\n185: \tkey string,\n186: \tptr uintptr,\n187: \tsize uint64,\n188: ) (int64, error) {\n189: \tvar (\n190: \t\tn        int64\n191: \t\tlastErr  error\n192: \t\tattempts int\n193: \t)\n194: \tfor attempt := 1; attempt <= mooncakeReadMaxAttempts; attempt++ {\n195: \t\tif err := ctx.Err(); err != nil {\n196: \t\t\treturn n, err\n197: \t\t}\n198: \t\tattempts = attempt\n199: \n200: \t\treleaseSlot, err := acquireGetIntoSlot(ctx)\n201: \t\tif err != nil {\n202: \t\t\treturn n, err\n203: \t\t}\n204: \t\tn, lastErr = store.GetInto(key, ptr, size)\n205: \t\treleaseSlot()\n206: \t\tif lastErr == nil {\n207: \t\t\treturn n, nil\n208: \t\t}\n209: \t\tif !errors.Is(lastErr, mooncakestore.ErrGet) || attempt == mooncakeReadMaxAttempts {\n210: \t\t\tbreak\n211: \t\t}\n212: \t\tif err := waitForMooncakeReadRetry(ctx, attempt); err != nil {\n213: \t\t\treturn n, err\n214: \t\t}\n215: \t}\n216: \n217: \tzap.L().Sugar().Warnf(\n218: \t\t\"[MooncakeStorage] GetInto failed after %d attempts: key=%s size=%d err=%v\",\n219: \t\tattempts,\n220: \t\tkey,\n221: \t\tsize,\n222: \t\tlastErr,\n223: \t)\n224: \treturn n, lastErr",
      "claim": "仅特定 ErrGet 进行有限重试，排队与重试等待检查 ctx；同步 SDK GetInto 不接收 ctx。",
      "legacyChapter": 6
    },
    {
      "id": "S47",
      "title": "默认读取限流与容量参数",
      "path": "packages/shared/pkg/storage/storage_mooncake.go",
      "start": 75,
      "end": 94,
      "kind": "code",
      "chapter": 5,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/shared/pkg/storage/storage_mooncake.go#L75",
      "excerpt": "75: \tmooncakeOperationTimeout  = 30 * time.Second\n76: \tmooncakeUploadConcurrency = 16\n77: \tnumaBufferSize            = 4 * 1024 * 1024 // 4 MB default buffer size\n78: \n79: \t// MOONCAKE_NUMA_POOL_SIZE controls the per-NUMA reserve total. A reserve\n80: \t// buffer is assigned to an OS thread once and stays thread-local afterward.\n81: \t// The pool is bounded only by its ready capacity (the pool total): a\n82: \t// background reconciler refills the reserve when the ready count drops\n83: \t// below the configured low watermark, pausing while foreground GetInto\n84: \t// reads are in flight.\n85: \tdefaultNumaPoolSize           = 512\n86: \tmaxNumaPoolSize               = 4096\n87: \tdefaultNumaPoolRefillInterval = time.Second\n88: \tdefaultNumaPoolRefillBatch    = 8\n89: \tnumaPoolRefillBackoffInitial  = 250 * time.Millisecond\n90: \tnumaPoolRefillBackoffMax      = 30 * time.Second\n91: \tdefaultGetIntoMaxConcurrency  = 128\n92: \tmaxGetIntoMaxConcurrency      = 4096\n93: \tmooncakeReadMaxAttempts       = 3\n94: \tmooncakeReadRetryBaseDelay    = time.Millisecond",
      "claim": "分片上传并发16、reserve buffer 512、GetInto 默认并发128是进程内控制参数，不是性能实测。",
      "legacyChapter": 6
    },
    {
      "id": "S48",
      "title": "主路径未启用批量直写接口",
      "path": "packages/orchestrator/internal/sandbox/block/chunk.go",
      "start": 208,
      "end": 236,
      "kind": "code",
      "chapter": 5,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/orchestrator/internal/sandbox/block/chunk.go#L208",
      "excerpt": "208: func (c *FullFetchChunker) fetchToCache(ctx context.Context, off, length int64) error {\n209: \tstartingChunk := header.BlockIdx(off, storage.MemoryChunkSize)\n210: \tstartingChunkOffset := header.BlockOffset(startingChunk, storage.MemoryChunkSize)\n211: \n212: \t// 要拉的块必须盖住 [off, off+length) 整段。off 不在块边界上时（64 KiB 宿主页在\n213: \t// 4 KiB 粒度压实的 memfile 里经常如此），只按 length 算块数会漏掉后半截所在的那一块，\n214: \t// Slice 随即报 BytesNotAvailableError、沙箱被杀（10-09 预热模板 24a1cbb3 实测）。\n215: \tchunks := header.BlocksOffsets(off+length-startingChunkOffset, storage.MemoryChunkSize)\n216: \n217: \t// Try the Mooncake fast-path: a single batched backend call.\n218: \t/*if batchReader, ok := c.base.(storage.BatchReader); ok {\n219: \t\treturn c.fetchToCacheBatch(ctx, startingChunkOffset, chunks, batchReader)\n220: \t}*/\n221: \n222: \t// Slow path: one goroutine per chunk (works for any SeekableReader backend).\n223: \tvar eg errgroup.Group\n224: \n225: \tfor _, chunkOff := range chunks {\n226: \t\t// Ensure the closure captures the correct block offset.\n227: \t\tfetchOff := startingChunkOffset + chunkOff\n228: \n229: \t\teg.Go(func() (err error) {\n230: \t\t\tdefer func() {\n231: \t\t\t\tif r := recover(); r != nil {\n232: \t\t\t\t\tlogger.L().Error(ctx, \"recovered from panic in the fetch handler\", zap.Any(\"error\", r))\n233: \t\t\t\t\terr = fmt.Errorf(\"recovered from panic in the fetch handler: %v\", r)\n234: \t\t\t\t}\n235: \t\t\t}()\n236: ",
      "claim": "FullFetch 的 batch dispatch 被注释，实际逐 chunk 调用 ReadAt；不能宣称主链 BatchGetInto 零拷贝。",
      "legacyChapter": 6
    },
    {
      "id": "S49",
      "title": "非 Mooncake 构建的 stub",
      "path": "packages/shared/pkg/storage/storage_mooncake_stub.go",
      "start": 1,
      "end": 32,
      "kind": "code",
      "chapter": 5,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/shared/pkg/storage/storage_mooncake_stub.go#L1",
      "excerpt": "1: //go:build !mooncake\n2: package storage\n3: import(\n4:     \"context\"\n5:     \"fmt\"\n6:     \"time\"\n7: )\n8: \n9: type mooncakeStorage struct {\n10: \n11: }\n12: \n13: var _ StorageProvider = (*mooncakeStorage)(nil)\n14: \n15: func NewMooncakeStorageProvider(_ context.Context, bucketName string) (*mooncakeStorage, error) {\n16: \treturn nil, nil\n17: }\n18: \n19: func (s *mooncakeStorage) DeleteObjectsWithPrefix(ctx context.Context, prefix string) error {\n20: \treturn nil\n21: }\n22: \n23: func (s *mooncakeStorage) UploadSignedURL(_ context.Context, _ string, _ time.Duration) (string, error) {\n24: \treturn \"\", fmt.Errorf(\"mooncake storage does not support signed URLs\")\n25: }\n26: \n27: func (s *mooncakeStorage) OpenSeekable(_ context.Context, path string, _ SeekableObjectType) (Seekable, error) {\n28: \treturn nil, fmt.Errorf(\"mooncake storage does not support seekable objects\")\n29: }\n30: \n31: func (s *mooncakeStorage) OpenBlob(_ context.Context, path string, _ ObjectType) (Blob, error) {\n32: \treturn nil, fmt.Errorf(\"mooncake storage does not support blobs\")",
      "claim": "未启用 mooncake tag 使用 stub；构造函数返回 nil,nil，不能仅靠环境变量认定实际链接到 Mooncake。",
      "legacyChapter": 6
    },
    {
      "id": "S50",
      "title": "按前缀删除对象",
      "path": "packages/shared/pkg/storage/storage_mooncake.go",
      "start": 1021,
      "end": 1037,
      "kind": "code",
      "chapter": 5,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/shared/pkg/storage/storage_mooncake.go#L1021",
      "excerpt": "1021: func (s *mooncakeStorage) DeleteObjectsWithPrefix(ctx context.Context, prefix string) error {\n1022: \tctx, cancel := context.WithTimeout(ctx, mooncakeOperationTimeout)\n1023: \tdefer cancel()\n1024: \n1025: \t// Mooncake has flat keys, so use regex matching over the prefix.\n1026: \t// WARNING: This may scan all keys; avoid frequent use with large buckets.\n1027: \tpattern := \"^\" + regexp.QuoteMeta(s.key(prefix))\n1028: \tif !strings.HasSuffix(prefix, \"/\") {\n1029: \t\tpattern += \".*\"\n1030: \t}\n1031: \n1032: \t_, err := s.store.RemoveByRegex(pattern, true)\n1033: \tif err != nil {\n1034: \t\treturn fmt.Errorf(\"failed to delete objects with prefix %s: %w\", prefix, err)\n1035: \t}\n1036: \tinvalidateCachedMetadataPrefix(s.key(prefix))\n1037: \treturn nil",
      "claim": "删除经正则匹配 namespace 前缀；此 helper 不读取 header 验证仍被引用的源 Build。",
      "legacyChapter": 6
    },
    {
      "id": "S51",
      "title": "迁移客户端不承载数据段",
      "path": "migrate-tool/internal/targetstore/mooncake_native.go",
      "start": 92,
      "end": 105,
      "kind": "code",
      "chapter": 5,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/migrate-tool/internal/targetstore/mooncake_native.go#L92",
      "excerpt": "92: \t\t}\n93: \t\tstore, err := mooncakestore.New()\n94: \t\tif err != nil {\n95: \t\t\treturn nil, fmt.Errorf(\"create Mooncake store: %w\", err)\n96: \t\t}\n97: \t\t// Always zero storage capacity; never call InitAll in this tool.\n98: \t\tif err := store.Setup(config.localHostname, config.metadataServer, 0, config.localBufferSize,\n99: \t\t\tconfig.protocol, config.deviceName, config.masterAddr); err != nil {\n100: \t\t\tstore.Close()\n101: \t\t\treturn nil, fmt.Errorf(\"setup Mooncake store: %w\", err)\n102: \t\t}\n103: \t\treturn &nativeMooncakeClient{store: store}, nil\n104: \t}\n105: \tclient, err := open(ctx)",
      "claim": "迁移 writer 使用零全局存储容量且不调用 InitAll，避免短生命周期客户端承载唯一数据。",
      "legacyChapter": 6
    },
    {
      "id": "S52",
      "title": "迁移完整读回与 SHA256",
      "path": "migrate-tool/internal/targetstore/mooncake.go",
      "start": 115,
      "end": 151,
      "kind": "code",
      "chapter": 5,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/migrate-tool/internal/targetstore/mooncake.go#L115",
      "excerpt": "115: func (s *mooncakeStore) digest(ctx context.Context, object bundle.ObjectRecord) (string, error) {\n116: \thash := sha256.New()\n117: \tif artifact.IsDataType(object.Type) {\n118: \t\tdata, err := s.read(ctx, object.LogicalKey, 4096)\n119: \t\tif err != nil {\n120: \t\t\treturn \"\", err\n121: \t\t}\n122: \t\tvar metadata mooncakeObjectMetadata\n123: \t\tif err := json.Unmarshal(data, &metadata); err != nil {\n124: \t\t\treturn \"\", fmt.Errorf(\"decode Mooncake metadata %q: %w\", object.LogicalKey, err)\n125: \t\t}\n126: \t\tif metadata.Size != object.Size || metadata.ChunkSize != mooncakeChunkSize {\n127: \t\t\treturn \"\", fmt.Errorf(\"Mooncake metadata %q does not match Bundle size/chunk layout\", object.LogicalKey)\n128: \t\t}\n129: \t\tfor offset := int64(0); offset < object.Size; offset += mooncakeChunkSize {\n130: \t\t\twant := min(mooncakeChunkSize, object.Size-offset)\n131: \t\t\tkey := fmt.Sprintf(\"%s#c#%d\", object.LogicalKey, offset)\n132: \t\t\tdata, err := s.read(ctx, key, want)\n133: \t\t\tif err != nil {\n134: \t\t\t\treturn \"\", err\n135: \t\t\t}\n136: \t\t\tif int64(len(data)) != want {\n137: \t\t\t\treturn \"\", fmt.Errorf(\"Mooncake chunk %q has %d bytes, want %d\", key, len(data), want)\n138: \t\t\t}\n139: \t\t\t_, _ = hash.Write(data)\n140: \t\t}\n141: \t} else {\n142: \t\tdata, err := s.read(ctx, object.LogicalKey, object.Size)\n143: \t\tif err != nil {\n144: \t\t\treturn \"\", err\n145: \t\t}\n146: \t\tif int64(len(data)) != object.Size {\n147: \t\t\treturn \"\", fmt.Errorf(\"Mooncake blob %q has %d bytes, want %d\", object.LogicalKey, len(data), object.Size)\n148: \t\t}\n149: \t\t_, _ = hash.Write(data)\n150: \t}\n151: \treturn hex.EncodeToString(hash.Sum(nil)), nil",
      "claim": "迁移重读分片，验证元数据与长度并计算完整 SHA256；运行时 adapter 不自动获得同等 checksum 保护。",
      "legacyChapter": 6
    },
    {
      "id": "S53",
      "title": "关闭 writer 后重新建立 reader",
      "path": "migrate-tool/internal/targetstore/mooncake.go",
      "start": 154,
      "end": 170,
      "kind": "code",
      "chapter": 5,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/migrate-tool/internal/targetstore/mooncake.go#L154",
      "excerpt": "154: func (s *mooncakeStore) VerifyAfterClose(ctx context.Context, objects []bundle.ObjectRecord) error {\n155: \ts.Close()\n156: \tif s.reopen == nil {\n157: \t\treturn fmt.Errorf(\"Mooncake verification requires a fresh client factory\")\n158: \t}\n159: \tclient, err := s.reopen(ctx)\n160: \tif err != nil {\n161: \t\treturn fmt.Errorf(\"open independent Mooncake reader: %w\", err)\n162: \t}\n163: \treader := newMooncakeStore(client, s.namespace)\n164: \tdefer reader.Close()\n165: \tfor _, object := range objects {\n166: \t\tif err := reader.Recheck(ctx, object, Observation{}); err != nil {\n167: \t\t\treturn fmt.Errorf(\"verify after closing Mooncake writer: %w\", err)\n168: \t\t}\n169: \t}\n170: \treturn nil",
      "claim": "VerifyAfterClose 关闭写者并创建新客户端逐对象复核，覆盖写者退出后的可读性门槛。",
      "legacyChapter": 6
    },
    {
      "id": "S54",
      "title": "独立复核通过才提交 Catalog",
      "path": "migrate-tool/internal/importer/importer.go",
      "start": 130,
      "end": 149,
      "kind": "code",
      "chapter": 5,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/migrate-tool/internal/importer/importer.go#L130",
      "excerpt": "130: \t// 对象写入和数据库事务无法组成跨存储原子提交。至少在提交 Catalog 前\n131: \t// 再确认本次新建和计划复用的对象仍是刚刚校验过的版本。\n132: \tif verifier, ok := i.Target.(targetstore.ClosedWriterVerifier); ok {\n133: \t\tobjects := make([]bundle.ObjectRecord, 0, len(observed))\n134: \t\tfor _, object := range observed {\n135: \t\t\tobjects = append(objects, object.record)\n136: \t\t}\n137: \t\tif err := verifier.VerifyAfterClose(ctx, objects); err != nil {\n138: \t\t\treturn nil, err\n139: \t\t}\n140: \t} else {\n141: \t\tfor _, object := range observed {\n142: \t\t\tif err := i.Target.Recheck(ctx, object.record, object.observation); err != nil {\n143: \t\t\t\treturn nil, err\n144: \t\t\t}\n145: \t\t}\n146: \t}\n147: \tif err := i.Catalog.Commit(ctx, prepared.target); err != nil {\n148: \t\treturn nil, fmt.Errorf(\"commit target catalog: %w\", err)\n149: \t}",
      "claim": "对象复核后才提交 Catalog；对象存储与数据库之间仍不是原子事务。",
      "legacyChapter": 6
    },
    {
      "id": "S55",
      "title": "迁移文档明确非原子与残留风险",
      "path": "migrate-tool/design.md",
      "start": 366,
      "end": 383,
      "kind": "doc",
      "chapter": 5,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/migrate-tool/design.md#L366",
      "excerpt": "366: 对象存储与数据库无法组成跨存储原子事务,导入按固定顺序把风险压到最低:\n367: \n368: 1. **对象先行**:先发布全部计划新建的对象。对象 `Put` 只创建不覆盖\n369:    (S3 `If-None-Match:*`,File 硬链接原子发布);Mooncake 无仅创建语义,\n370:    改为发布前 `Exists` 检查 + 逻辑 key 最后写(作为完整性提交点)。\n371: 2. **Recheck**:提交 Catalog 前复核每个新建/复用对象仍是刚校验过的版本\n372:    (File/S3 比对对象身份；Mooncake 关闭写入客户端后重建客户端，全量读取 Blob、\n373:    校验 Seekable 元数据及所有 4 MiB 分片并比对 SHA-256)。\n374: 3. **Catalog 最后提交**:PostgreSQL 用 Serializable 事务:preflight\n375:    (版本/schema/列/约束/触发器/RLS 逐项核对)→ 重新读取目标现状 →\n376:    `ensureAdditive` 检查当前读到的记录是否都在计划结果中且内容一致，不一致\n377:    时报 `target changed after dry-run` → 仅 INSERT 缺失行。该检查不是从首次\n378:    读取起的完整变更检测；期间被删除的记录可能被重新插入，仍需遵守串行使用前提。\n379: \n380: 执行中发生写入、复核或提交错误时返回退出码 `1`。对象写入不会自动回滚，\n381: 可能留下未被 Catalog 引用的完整对象或分片；处理错误原因后重跑，完整一致的\n382: 对象可用 `skip-identical` 复用，损坏或不同的对象仍需核对处理。先复核再提交\n383: Catalog，目的是避免新增元数据引用已知不完整的对象；它不是跨存储原子事务。",
      "claim": "文档明确 Mooncake 无仅创建语义，错误时对象不自动回滚；提交顺序不能替代跨存储事务。",
      "legacyChapter": 6
    },
    {
      "id": "S56",
      "title": "正常 API 按 teamID 隔离 COPY 缓存",
      "path": "packages/api/internal/template-manager/upload_template_layer_files.go",
      "start": 14,
      "end": 25,
      "kind": "code",
      "chapter": 2,
      "claim": "正常 API 调用显式设置 CacheScope=teamID.String()；因此 TemplateID 是 template-manager 的缺省回退，不能当作通常 API 的缓存命名空间。",
      "excerpt": "14: func (tm *TemplateManager) InitLayerFileUpload(ctx context.Context, clusterID uuid.UUID, nodeID string, teamID uuid.UUID, templateID string, hash string) (*templatemanager.InitLayerFileUploadResponse, error) {\n15: \tclient, err := tm.GetClusterBuildClient(clusterID, nodeID)\n16: \tif err != nil {\n17: \t\treturn nil, fmt.Errorf(\"failed to get build client for template '%s': %w\", templateID, err)\n18: \t}\n19: \n20: \tresp, err := client.Template.InitLayerFileUpload(\n21: \t\tctx, &templatemanager.InitLayerFileUploadRequest{\n22: \t\t\tCacheScope: ut.ToPtr(teamID.String()),\n23: \t\t\tTemplateID: templateID,\n24: \t\t\tHash:       hash,\n25: \t\t},",
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/api/internal/template-manager/upload_template_layer_files.go#L14"
    },
    {
      "id": "S57",
      "title": "Exists 只检查主 key",
      "path": "packages/shared/pkg/storage/storage_mooncake.go",
      "start": 1241,
      "end": 1242,
      "kind": "code",
      "chapter": 2,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/shared/pkg/storage/storage_mooncake.go#L1241",
      "excerpt": "1241: func (o *mooncakeBlob) Exists(_ context.Context) (bool, error) {\n1242: \treturn o.store.Exists(o.path)",
      "claim": "Blob.Exists 直接调用 Store.Exists(mainKey)，不遍历分片；不能把存在性当作完整分片或整快照恢复证明。"
    },
    {
      "id": "S58",
      "title": "Blob 读取先探测主 KV 大小和布局",
      "path": "packages/shared/pkg/storage/storage_mooncake.go",
      "start": 1260,
      "end": 1294,
      "kind": "code",
      "chapter": 2,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/shared/pkg/storage/storage_mooncake.go#L1260",
      "excerpt": "1260: func (o *mooncakeBlob) readMeta(ctx context.Context) (*mooncakeObjectMeta, int64, error) {\n1261: \tif meta, ok := loadCachedMetadata(o.path); ok {\n1262: \t\treturn meta, 0, nil\n1263: \t}\n1264: \n1265: \tsize, err := o.store.GetSize(o.path)\n1266: \tif err != nil {\n1267: \t\texists, existsErr := o.store.Exists(o.path)\n1268: \t\tif existsErr == nil && !exists {\n1269: \t\t\treturn nil, 0, ErrObjectNotExist\n1270: \t\t}\n1271: \t\treturn nil, 0, fmt.Errorf(\"failed to get object size for %s: %w\", o.path, err)\n1272: \t}\n1273: \tif size > 4096 {\n1274: \t\treturn nil, size, errNotChunkedBlob\n1275: \t}\n1276: \tif size == 0 {\n1277: \t\treturn nil, size, errNotChunkedBlob\n1278: \t}\n1279: \n1280: \tnumaBuf, n, release, err := getIntoNumaBuffer(ctx, o.store, o.path, uint64(size))\n1281: \tif err != nil {\n1282: \t\treturn nil, size, fmt.Errorf(\"failed to read potential metadata for %s: %w\", o.path, err)\n1283: \t}\n1284: \tdefer release()\n1285: \n1286: \tvar meta mooncakeObjectMeta\n1287: \tif err := json.Unmarshal(numaBuf.buf[:n], &meta); err != nil {\n1288: \t\treturn nil, size, errNotChunkedBlob\n1289: \t}\n1290: \tif meta.ChunkSize <= 0 || meta.ChunkSize > numaBufferSize || meta.Size < 0 {\n1291: \t\treturn nil, size, errNotChunkedBlob\n1292: \t}\n1293: \tstoreCachedMetadata(o.path, &meta)\n1294: \treturn &meta, size, nil",
      "claim": "Blob.WriteTo 的格式探测先 GetSize(mainKey)，必要时 GetInto 小主值并解析分块元数据；主 value 大小不等于分块文件内容大小。"
    },
    {
      "id": "S59",
      "title": "GetInto 使用已注册 NUMA 目的缓冲",
      "path": "packages/shared/pkg/storage/storage_mooncake.go",
      "start": 227,
      "end": 249,
      "kind": "code",
      "chapter": 2,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/shared/pkg/storage/storage_mooncake.go#L227",
      "excerpt": "227: func getIntoNumaBuffer(\n228: \tctx context.Context,\n229: \tstore *mooncakestore.Store,\n230: \tkey string,\n231: \tsize uint64,\n232: ) (*numaBuffer, int64, func(), error) {\n233: \tnumaBuf, releaseBuffer, err := getOrCreateNumaBuffer(ctx, store)\n234: \tif err != nil {\n235: \t\treturn nil, 0, nil, err\n236: \t}\n237: \n238: \tn, getErr := getIntoWithRetry(\n239: \t\tctx,\n240: \t\tstore,\n241: \t\tkey,\n242: \t\tuintptr(unsafe.Pointer(&numaBuf.buf[0])),\n243: \t\tsize,\n244: \t)\n245: \tif getErr != nil {\n246: \t\treleaseBuffer()\n247: \t\treturn nil, n, nil, getErr\n248: \t}\n249: \treturn numaBuf, n, releaseBuffer, nil",
      "claim": "数据读取包装器先取得线程 NUMA buffer，将其指针和期望读取长度交给 getIntoWithRetry；与 S46 中真实 Store.GetInto 调用组成主读取链。"
    },
    {
      "id": "S60",
      "title": "NUMA staging 的 RegisterBuffer 已启用",
      "path": "packages/shared/pkg/storage/storage_mooncake.go",
      "start": 746,
      "end": 771,
      "kind": "code",
      "chapter": 2,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/shared/pkg/storage/storage_mooncake.go#L746",
      "excerpt": "746: func allocAndRegisterOnNode(store *mooncakestore.Store, node int) (*numaBuffer, error) {\n747: \tif node < 0 || node >= nrSockets {\n748: \t\tnode = 0\n749: \t}\n750: \n751: \tcptr := C.numa_alloc_onnode_wrapper(C.size_t(numaBufferSize), C.int(node))\n752: \tif cptr == nil {\n753: \t\treturn nil, fmt.Errorf(\"numa_alloc_onnode failed: size=%d, node=%d\", numaBufferSize, node)\n754: \t}\n755: \n756: \tnb := &numaBuffer{\n757: \t\tbuf:   unsafe.Slice((*byte)(cptr), numaBufferSize),\n758: \t\tcptr:  cptr,\n759: \t\tsize:  numaBufferSize,\n760: \t\tnode:  node,\n761: \t\tstore: store,\n762: \t}\n763: \n764: \tif err := store.RegisterBuffer(uintptr(cptr), uint64(numaBufferSize)); err != nil {\n765: \t\tC.numa_free_wrapper(cptr, C.size_t(numaBufferSize))\n766: \t\tnb.cptr = nil\n767: \t\tnb.buf = nil\n768: \t\tnb.store = nil\n769: \t\treturn nil, fmt.Errorf(\"failed to register buffer on node %d: %w\", node, err)\n770: \t}\n771: \treturn nb, nil",
      "claim": "adapter 实际在 NUMA 节点分配 4 MiB C 内存并注册给 Mooncake Store；这条 staging 注册与被注释的调用方 mmap 直写注册是不同路径。"
    },
    {
      "id": "S61",
      "title": "Guest 磁盘写入本地 COW Overlay",
      "path": "packages/orchestrator/internal/sandbox/block/overlay.go",
      "start": 31,
      "end": 71,
      "kind": "code",
      "chapter": 4,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/orchestrator/internal/sandbox/block/overlay.go#L31",
      "excerpt": "31: func (o *Overlay) ReadAt(ctx context.Context, p []byte, off int64) (int, error) {\n32: \tblocks := header.BlocksOffsets(int64(len(p)), o.blockSize)\n33: \n34: \tfor _, blockOff := range blocks {\n35: \t\tn, err := o.cache.ReadAt(p[blockOff:blockOff+o.blockSize], off+blockOff)\n36: \t\tif err == nil {\n37: \t\t\tcontinue\n38: \t\t}\n39: \n40: \t\tif !errors.As(err, &BytesNotAvailableError{}) {\n41: \t\t\treturn n, fmt.Errorf(\"error reading from cache: %w\", err)\n42: \t\t}\n43: \n44: \t\tn, err = o.device.ReadAt(ctx, p[blockOff:blockOff+o.blockSize], off+blockOff)\n45: \t\tif err != nil {\n46: \t\t\treturn n, fmt.Errorf(\"error reading from device: %w\", err)\n47: \t\t}\n48: \t}\n49: \n50: \treturn len(p), nil\n51: }\n52: \n53: func (o *Overlay) EjectCache() (*Cache, error) {\n54: \tif !o.cacheEjected.CompareAndSwap(false, true) {\n55: \t\treturn nil, fmt.Errorf(\"cache already ejected\")\n56: \t}\n57: \n58: \treturn o.cache, nil\n59: }\n60: \n61: // This method will not be very optimal if the length is not the same as the block size, because we cannot be just exposing the cache slice,\n62: // but creating and copying the bytes from the cache and device to the new slice.\n63: //\n64: // When we are implementing this we might want to just enforce the length to be the same as the block size.\n65: func (o *Overlay) Slice(_ context.Context, _, _ int64) ([]byte, error) {\n66: \treturn nil, fmt.Errorf(\"not implemented\")\n67: }\n68: \n69: func (o *Overlay) WriteAt(p []byte, off int64) (int, error) {\n70: \treturn o.cache.WriteAt(p, off)\n71: }",
      "claim": "Overlay 读取先看本地写缓存，未命中再读模板只读设备；WriteAt 只调用本地 cache.WriteAt，不直接触发 Mooncake Put。",
      "legacyChapter": 5
    },
    {
      "id": "S62",
      "title": "本地脏块在导出时形成增量文件",
      "path": "packages/orchestrator/internal/sandbox/block/cache.go",
      "start": 134,
      "end": 169,
      "kind": "code",
      "chapter": 4,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/orchestrator/internal/sandbox/block/cache.go#L134",
      "excerpt": "134: func (c *Cache) ExportToDiff(ctx context.Context, out io.Writer) (*header.DiffMetadata, error) {\n135: \tctx, childSpan := tracer.Start(ctx, \"export-to-diff\")\n136: \tdefer childSpan.End()\n137: \n138: \tc.mu.Lock()\n139: \tdefer c.mu.Unlock()\n140: \n141: \tif c.isClosed() {\n142: \t\treturn nil, NewErrCacheClosed(c.filePath)\n143: \t}\n144: \n145: \tif c.mmap == nil {\n146: \t\treturn &header.DiffMetadata{\n147: \t\t\tDirty:     bitset.New(0),\n148: \t\t\tEmpty:     bitset.New(0),\n149: \t\t\tBlockSize: c.blockSize,\n150: \t\t}, nil\n151: \t}\n152: \n153: \terr := c.mmap.Flush()\n154: \tif err != nil {\n155: \t\treturn nil, fmt.Errorf(\"error flushing mmap: %w\", err)\n156: \t}\n157: \n158: \tbuilder := header.NewDiffMetadataBuilder(c.size, c.blockSize)\n159: \n160: \tfor _, offset := range c.dirtySortedKeys() {\n161: \t\tblock := (*c.mmap)[offset : offset+c.blockSize]\n162: \n163: \t\terr := builder.Process(ctx, block, out, offset)\n164: \t\tif err != nil {\n165: \t\t\treturn nil, fmt.Errorf(\"error processing block %d: %w\", offset, err)\n166: \t\t}\n167: \t}\n168: \n169: \treturn builder.Build(), nil",
      "claim": "ExportToDiff flush 本地 mmap，按排序后的脏块偏移调用 DiffMetadataBuilder.Process；在线 Guest 写与之后快照的分片 KV 上传是两个阶段。",
      "legacyChapter": 5
    },
    {
      "id": "S63",
      "title": "写入缺失内存页先读取原页",
      "path": "packages/orchestrator/internal/sandbox/uffd/userfaultfd/userfaultfd.go",
      "start": 264,
      "end": 280,
      "kind": "code",
      "chapter": 4,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/orchestrator/internal/sandbox/uffd/userfaultfd/userfaultfd.go#L264",
      "excerpt": "264: \t\t// Handle write to missing page (WRITE flag)\n265: \t\t// If the event has WRITE flag, it was a write to a missing page.\n266: \t\t// For the write to be executed, we first need to copy the page from the source to the guest memory.\n267: \t\tif flags&UFFD_PAGEFAULT_FLAG_WRITE != 0 {\n268: \t\t\tu.wg.Go(func() error {\n269: \t\t\t\treturn u.faultPage(ctx, addr, offset, copySize, u.src, fdExit.SignalExit, block.Write)\n270: \t\t\t})\n271: \n272: \t\t\tcontinue\n273: \t\t}\n274: \n275: \t\t// Handle read to missing page (\"MISSING\" flag)\n276: \t\t// If the event has no flags, it was a read to a missing page and we need to copy the page from the source to the guest memory.\n277: \t\tif flags == 0 {\n278: \t\t\tu.wg.Go(func() error {\n279: \t\t\t\treturn u.faultPage(ctx, addr, offset, copySize, u.src, fdExit.SignalExit, block.Read)\n280: \t\t\t})",
      "claim": "UFFD WRITE 缺页会以 block.Write 进入同一 faultPage 并先填充源页；因此 Guest 写也可能先触发模板读取，不代表每次写都立即远端 Put。"
    },
    {
      "id": "S64",
      "title": "UFFD faultPage 实际读取源数据",
      "path": "packages/orchestrator/internal/sandbox/uffd/userfaultfd/userfaultfd.go",
      "start": 376,
      "end": 388,
      "kind": "code",
      "chapter": 4,
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/orchestrator/internal/sandbox/uffd/userfaultfd/userfaultfd.go#L376",
      "excerpt": "376: \tb, dataErr := block.ReadSlice(ctx, source, offset, int64(copySize))\n377: \tif dataErr != nil {\n378: \t\tvar signalErr error\n379: \t\tif onFailure != nil {\n380: \t\t\tsignalErr = onFailure()\n381: \t\t}\n382: \n383: \t\tjoinedErr := errors.Join(dataErr, signalErr)\n384: \n385: \t\tspan.RecordError(joinedErr)\n386: \t\tu.logger.Error(ctx, \"UFFD serve data fetch error\", zap.Error(joinedErr))\n387: \n388: \t\treturn fmt.Errorf(\"failed to read from source: %w\", joinedErr)",
      "claim": "faultPage 调用 block.ReadSlice 读取原页并传播源数据读取错误；与 S63 的 WRITE 分支共同证明缺失页的写前取数。"
    },
    {
      "id": "D01",
      "title": "已有 Go/CGO 客户端",
      "repo": "yuanrong-datasystem",
      "commit": "c0bbb1582e49ecc2d2d925836d1288633d322012",
      "path": "go/kv/kv_client.go",
      "start": 20,
      "end": 46,
      "kind": "code",
      "chapter": 6,
      "url": "kasandbox-architecture-20261106/datasystem-source-evidence.json#D01",
      "sourceType": "pinned-local-git-blob",
      "excerpt": "20: /*\n21: #cgo CFLAGS: -I../include/\n22: #cgo LDFLAGS: -L../lib -ldatasystem_c\n23: #include <stdlib.h>\n24: #include <string.h>\n25: #include \"datasystem/c_api/kv_client_c_wrapper.h\"\n26: #include \"datasystem/c_api/utilC.h\"\n27: */\n28: import \"C\"\n29: \n30: import (\n31: \t\"errors\"\n32: \t\"fmt\"\n33: \t\"math\"\n34: \t\"strconv\"\n35: \t\"sync\"\n36: \t\"unsafe\"\n37: \n38: \t\"clients/common\"\n39: )\n40: \n41: // KVClient is the main handle object that allows you to make calls into the client API's.\n42: // Create it with the call to CreateClient(), and then all subsequent api calls will flow through this handle.\n43: type KVClient struct {\n44: \tclient C.KVClient_p\n45: \t// lock Protect the KVClient\n46: \tmutex *sync.RWMutex",
      "claim": "Go SDK链接libdatasystem_c，使用现有C ABI；不是从零补Go客户端。",
      "legacyChapter": 7
    },
    {
      "id": "D02",
      "title": "Go Set 的现有通路",
      "repo": "yuanrong-datasystem",
      "commit": "c0bbb1582e49ecc2d2d925836d1288633d322012",
      "path": "go/kv/kv_client.go",
      "start": 228,
      "end": 264,
      "kind": "code",
      "chapter": 6,
      "url": "kasandbox-architecture-20261106/datasystem-source-evidence.json#D02",
      "sourceType": "pinned-local-git-blob",
      "excerpt": "228: // Set function sets a string of data (value) into the worker.  The data is uniquely identified by key.\n229: func (t *KVClient) Set(key string, value string, param SetParam) common.Status {\n230: \trc := checkNullPtr(t)\n231: \tif int(rc.Code) != common.Ok {\n232: \t\treturn rc\n233: \t}\n234: \tcKey := C.CString(key)\n235: \tdefer C.free(unsafe.Pointer(cKey))\n236: \tkeyLen := C.size_t(len(key))\n237: \ttype MyString struct {\n238: \t\tStr *C.char\n239: \t\tLen int\n240: \t}\n241: \tmyString := (*MyString)(unsafe.Pointer(&value))\n242: \tcValue := myString.Str\n243: \tvalueLen := C.size_t(len(value))\n244: \t// WriteMode\n245: \tcWriteMode, err := getWriteMode(param.WriteMode)\n246: \tdefer C.free(unsafe.Pointer(cWriteMode))\n247: \tif err != nil {\n248: \t\treturn common.CreateStatus(common.InvalidParam, err.Error())\n249: \t}\n250: \tcTTLSecond := C.uint(param.TTLSecond)\n251: \t// ExistenceOpt\n252: \tcExistenceOpt, err := getExistenceOpt(param.ExistenceOpt)\n253: \tdefer C.free(unsafe.Pointer(cExistenceOpt))\n254: \tif err != nil {\n255: \t\treturn common.CreateStatus(common.InvalidParam, err.Error())\n256: \t}\n257: \tt.mutex.RLock()\n258: \tdefer t.mutex.RUnlock()\n259: \tstatusC := C.SCSet(t.client, cKey, keyLen, cValue, valueLen, cWriteMode, cTTLSecond, cExistenceOpt)\n260: \tif int(statusC.code) != common.Ok {\n261: \t\treturn common.CreateStatus(int(statusC.code),\n262: \t\t\tfmt.Sprintf(\"State cache client failed to Set. msg: %s\", C.GoString(&statusC.errMsg[0])))\n263: \t}\n264: \treturn common.CreateStatus(common.Ok, \"\")",
      "claim": "Set经SCSet传二进制长度与写入参数；首版Provider可复用现有调用。",
      "legacyChapter": 7
    },
    {
      "id": "D03",
      "title": "Go Get 返回字符串",
      "repo": "yuanrong-datasystem",
      "commit": "c0bbb1582e49ecc2d2d925836d1288633d322012",
      "path": "go/kv/kv_client.go",
      "start": 317,
      "end": 348,
      "kind": "code",
      "chapter": 6,
      "url": "kasandbox-architecture-20261106/datasystem-source-evidence.json#D03",
      "sourceType": "pinned-local-git-blob",
      "excerpt": "317: // Get function takes key identifier as input and fetches the string of data for that key and returns it.\n318: func (t *KVClient) Get(key string, timeoutms ...uint32) (string, common.Status) {\n319: \trc := checkNullPtr(t)\n320: \tif int(rc.Code) != common.Ok {\n321: \t\treturn \"\", rc\n322: \t}\n323: \tcKey := C.CString(key)\n324: \tdefer C.free(unsafe.Pointer(cKey))\n325: \tvar cVal *C.char = nil\n326: \tdefer func() {\n327: \t\tC.free(unsafe.Pointer(cVal))\n328: \t}()\n329: \tkeyLen := C.size_t(len(key))\n330: \tvar valLen C.size_t\n331: \tctimeoutms := C.uint(0)\n332: \tif len(timeoutms) > 0 {\n333: \t\tctimeoutms = C.uint(timeoutms[0])\n334: \t}\n335: \tt.mutex.RLock()\n336: \tdefer t.mutex.RUnlock()\n337: \tstatusC := C.SCGet(t.client, cKey, keyLen, ctimeoutms, &cVal, &valLen)\n338: \tif int(statusC.code) != common.Ok {\n339: \t\treturn \"\", common.CreateStatus(int(statusC.code),\n340: \t\t\tfmt.Sprintf(\"State cache client failed to Get. msg: %s\", C.GoString(&statusC.errMsg[0])))\n341: \t}\n342: \n343: \tif math.MaxInt32 < valLen {\n344: \t\treturn \"\", common.CreateStatus(common.InvalidParam,\n345: \t\t\tfmt.Sprintf(\"Invalid value size %d is get, which should be between (0, %d]\", valLen, math.MaxInt32))\n346: \t}\n347: \tvalue := C.GoStringN(cVal, C.int(valLen))\n348: \treturn value, common.CreateStatus(common.Ok, \"\")",
      "claim": "SCGet得到C缓冲后C.GoStringN复制成Go字符串；并非任意调用方内存GetInto。",
      "legacyChapter": 7
    },
    {
      "id": "D04",
      "title": "C Get 分配并复制",
      "repo": "yuanrong-datasystem",
      "commit": "c0bbb1582e49ecc2d2d925836d1288633d322012",
      "path": "src/datasystem/c_api/util.cpp",
      "start": 137,
      "end": 159,
      "kind": "code",
      "chapter": 6,
      "url": "kasandbox-architecture-20261106/datasystem-source-evidence.json#D04",
      "sourceType": "pinned-local-git-blob",
      "excerpt": "137: StatusC BufferToCString(datasystem::Optional<datasystem::Buffer> input,\n138:                         const std::shared_ptr<datasystem::ThreadPool> &copyThreads, char **valPointer, size_t *valLen)\n139: {\n140:     size_t destSize = input->GetSize();\n141:     *valPointer = (char *)malloc(destSize);\n142:     if (*valPointer == nullptr) {\n143:         return StatusC{ datasystem::K_RUNTIME_ERROR, \"Memory allocation failed\" };\n144:     }\n145:     // Use the SDK-internal helper so the copy still happens when the buffer was\n146:     // returned with oc_metadata_header disabled (DisabledLock — no latch frame in\n147:     // the shm layout). Explicit user calls to Buffer::RLatch() continue to fail\n148:     // with K_NOT_SUPPORTED, but internal Get-and-copy paths must not.\n149:     datasystem::Status rc = input->CopyDataWithRLatch([&] {\n150:         *valLen = input->GetSize();\n151:         return datasystem::MemoryCopy(reinterpret_cast<uint8_t *>(*valPointer), destSize,\n152:                                       static_cast<const uint8_t *>(input->ImmutableData()), *valLen, copyThreads);\n153:     });\n154:     if (rc.IsError()) {\n155:         free(*valPointer);\n156:         *valPointer = nullptr;\n157:         return ToStatusC(rc);\n158:     }\n159:     return StatusC{ datasystem::K_OK, {} };",
      "claim": "BufferToCString malloc并MemoryCopy；返回值所有权需正确释放，SDK缓冲不直接暴露给Go。",
      "legacyChapter": 7
    },
    {
      "id": "D05",
      "title": "Go批读对应C层的逐项复制",
      "repo": "yuanrong-datasystem",
      "commit": "c0bbb1582e49ecc2d2d925836d1288633d322012",
      "path": "src/datasystem/c_api/util.cpp",
      "start": 337,
      "end": 365,
      "kind": "code",
      "chapter": 6,
      "url": "kasandbox-architecture-20261106/datasystem-source-evidence.json#D05",
      "sourceType": "pinned-local-git-blob",
      "excerpt": "337: struct StatusC ExecuteGetArray(void *clientPtr, const char **cObjKeys, const size_t *cObjKeysLen, uint64_t cObjKeysNum,\n338:                                uint32_t ctimeoutms, char **cVals, size_t *valsLen, size_t *totalSize)\n339: {\n340:     std::string errorMsg;\n341:     CheckNullptr(clientPtr, \"clientPtr\", errorMsg);\n342:     CheckNullptr(cObjKeys, \"cObjKeys\", errorMsg);\n343:     CheckNullptr(cVals, \"cVals\", errorMsg);\n344:     CheckNullptr(valsLen, \"valsLen\", errorMsg);\n345:     CheckNullptr(totalSize, \"totalSize\", errorMsg);\n346:     if (!errorMsg.empty()) {\n347:         return MakeStatusC(datasystem::K_INVALID, errorMsg);\n348:     }\n349:     auto client = reinterpret_cast<std::shared_ptr<datasystem::object_cache::ObjectClientImpl> *>(clientPtr);\n350:     std::vector<std::string> objsVec = GetObjKeysVector(cObjKeys, cObjKeysLen, cObjKeysNum);\n351:     std::vector<datasystem::Optional<datasystem::Buffer>> buffers;\n352:     datasystem::Status rc = (*client)->Get(objsVec, ctimeoutms, buffers);\n353:     // Even with errors we can have partial results\n354:     // send the results back as const char\n355:     for (size_t i = 0; i < buffers.size(); ++i) {\n356:         if (buffers[i]) {\n357:             StatusC s =\n358:                 BufferToCString(std::move(buffers[i]), (*client)->GetMemoryCopyThreadPool(), &cVals[i], &valsLen[i]);\n359:             if (s.code != datasystem::K_OK) {\n360:                 LOG(ERROR) << \"Converts buffer to c style char * failed, \" << s.errMsg;\n361:             }\n362:             *totalSize += valsLen[i];\n363:         }\n364:     }\n365:     return ToStatusC(rc);",
      "claim": "GetArray的C层只处理存在的Buffer；缺失项保持空槽。转换失败仅记录日志，最终仍返回底层批读rc，不能仅凭空字符串区分missing与本地转换失败。",
      "legacyChapter": 7
    },
    {
      "id": "D06",
      "title": "Go 批删与失败清单",
      "repo": "yuanrong-datasystem",
      "commit": "c0bbb1582e49ecc2d2d925836d1288633d322012",
      "path": "go/kv/kv_client.go",
      "start": 427,
      "end": 471,
      "kind": "code",
      "chapter": 6,
      "url": "kasandbox-architecture-20261106/datasystem-source-evidence.json#D06",
      "sourceType": "pinned-local-git-blob",
      "excerpt": "427: // DelArray function is similar to Del(), except that it takes an array of keys\n428: // to delete as an argument instead of a single key.\n429: func (t *KVClient) DelArray(keys []string) ([]string, common.Status) {\n430: \trc := checkNullPtr(t)\n431: \tif int(rc.Code) != common.Ok {\n432: \t\treturn nil, rc\n433: \t}\n434: \tif len(keys) == 0 {\n435: \t\treturn nil, common.CreateStatus(common.InvalidParam, \"invalid param: objectKeys is null\")\n436: \t}\n437: \n438: \t// keys golang string array to c string array\n439: \tfailedKeysC := C.MakeCharsArray(C.int(len(keys)))\n440: \tdefer C.FreeCharsArray(failedKeysC, C.int(len(keys)))\n441: \n442: \t// converting from golang to cstyle strings\n443: \tkeyArray := C.MakeCharsArray(C.int(len(keys)))\n444: \tdefer C.FreeCharsArray(keyArray, C.int(len(keys)))\n445: \n446: \tfor idx, str := range keys {\n447: \t\tcstr := C.CString(str)\n448: \t\tC.SetCharsAtIdx(keyArray, cstr, C.int(idx))\n449: \t}\n450: \n451: \tvar failedCount C.ulong\n452: \tt.mutex.RLock()\n453: \tdefer t.mutex.RUnlock()\n454: \tstatusC := C.SCDelArray(t.client, keyArray, C.ulong(len(keys)), failedKeysC, &failedCount)\n455: \n456: \tif failedCount > C.ulong(len(keys)) {\n457: \t\treturn nil, common.CreateStatus(common.UnexpectedError,\n458: \t\t\tfmt.Sprintf(\"Unexpected failed key count %d.\", failedCount))\n459: \t}\n460: \t// We can have partial results even if their is an error on a key\n461: \tfailedKeys := make([]string, failedCount)\n462: \tfor i := C.ulong(0); i < failedCount; i++ {\n463: \t\tfailedKeys[i] = C.GoString(C.GetCharsAtIdx(failedKeysC, C.int(i)))\n464: \t}\n465: \n466: \tif int(statusC.code) != common.Ok {\n467: \t\treturn failedKeys, common.CreateStatus(int(statusC.code),\n468: \t\t\tfmt.Sprintf(\"State cache client failed to Del. msg: %s\", C.GoString(&statusC.errMsg[0])))\n469: \t}\n470: \n471: \treturn failedKeys, common.CreateStatus(common.Ok, \"\")",
      "claim": "DelArray返回failedKeys，不等同按prefix/regex扫描删除。",
      "legacyChapter": 7
    },
    {
      "id": "D07",
      "title": "写参数默认、NX与范围参数",
      "repo": "yuanrong-datasystem",
      "commit": "c0bbb1582e49ecc2d2d925836d1288633d322012",
      "path": "include/datasystem/kv_client.h",
      "start": 48,
      "end": 72,
      "kind": "code",
      "chapter": 6,
      "url": "kasandbox-architecture-20261106/datasystem-source-evidence.json#D07",
      "sourceType": "pinned-local-git-blob",
      "excerpt": "48: enum class ExistenceOpt : int {\n49:     NONE = 0,  // Does not check for existence.\n50:     NX = 1,    // Set if key does not exist; if key exists, return success and keep existing value unchanged.\n51: };\n52: struct SetParam {\n53:     WriteMode writeMode = WriteMode::NONE_L2_CACHE;  // The default value of writeMode is WriteMode::NONE_L2_CACHE.\n54:     // The default value 0 means the key will keep alive until you call Del api to delete the key explicitly.\n55:     uint32_t ttlSecond = 0;\n56:     ExistenceOpt existence = ExistenceOpt::NONE;\n57:     CacheType cacheType = CacheType::MEMORY;\n58: };\n59: \n60: struct MSetParam {\n61:     WriteMode writeMode = WriteMode::NONE_L2_CACHE;  // The default value of writeMode is WriteMode::NONE_L2_CACHE.\n62:     uint32_t ttlSecond =\n63:         0;  // The default value means the key will keep alive until you call Del api to delete the key.\n64:     ExistenceOpt existence = ExistenceOpt::NONE;\n65:     CacheType cacheType = CacheType::MEMORY;\n66: };\n67: \n68: struct ReadParam {\n69:     std::string key;\n70:     uint64_t offset = 0;\n71:     uint64_t size = 0;\n72: };",
      "claim": "默认无L2、TTL0；NX命中已有key也返回成功；ReadParam有key/offset/size。",
      "legacyChapter": 7
    },
    {
      "id": "D08",
      "title": "批量写部分成功及废弃事务API",
      "repo": "yuanrong-datasystem",
      "commit": "c0bbb1582e49ecc2d2d925836d1288633d322012",
      "path": "include/datasystem/kv_client.h",
      "start": 212,
      "end": 236,
      "kind": "code",
      "chapter": 6,
      "url": "kasandbox-architecture-20261106/datasystem-source-evidence.json#D08",
      "sourceType": "pinned-local-git-blob",
      "excerpt": "212:     /// \\brief Batch setter for multiple buffers.\n213:     ///\n214:     /// This interface is used together with MCreate to cache a batch of\n215:     /// shared-memory Buffers into the data system.\n216:     ///\n217:     /// \\param[in] buffers The buffers to set.\n218:     ///\n219:     /// \\return K_OK on success; the error code otherwise.\n220:     ///         K_INVALID: buffers is empty.\n221:     ///         K_RUNTIME_ERROR: client fd mmap failed\n222:     ///         K_METADATA_OWNER_UNAVAILABLE: all objects failed and metadata publication result is unknown; do not\n223:     ///         automatically replay. Partial success returns K_OK; this overload does not report failed keys.\n224:     Status MSet(const std::vector<std::shared_ptr<Buffer>> &buffers);\n225: \n226:     /// \\brief Deprecated transactional multi-key set interface.\n227:     ///\n228:     /// This API is kept only for SDK API compatibility and always returns K_RUNTIME_ERROR.\n229:     ///\n230:     /// \\param[in] keys The keys to be set.\n231:     /// \\param[in] vals The values for the keys.\n232:     /// \\param[in] param The set parameters.\n233:     ///\n234:     /// \\return K_RUNTIME_ERROR because MSetTx is a deprecated API.\n235:     Status MSetTx(const std::vector<std::string> &keys, const std::vector<StringView> &vals,\n236:                   const MSetParam &param = {});",
      "claim": "MSet(Buffer)部分成功可返回K_OK且不返回failedKeys；MSetTx已废弃，不能做跨分片事务。",
      "legacyChapter": 7
    },
    {
      "id": "D09",
      "title": "C++ 部分读取与批次语义",
      "repo": "yuanrong-datasystem",
      "commit": "c0bbb1582e49ecc2d2d925836d1288633d322012",
      "path": "include/datasystem/kv_client.h",
      "start": 341,
      "end": 373,
      "kind": "code",
      "chapter": 6,
      "url": "kasandbox-architecture-20261106/datasystem-source-evidence.json#D09",
      "sourceType": "pinned-local-git-blob",
      "excerpt": "341:     /// \\brief Invoke worker client to get the values of all the given keys.\n342:     ///\n343:     /// \\param[in] keys The vector of the keys.\n344:     /// \\param[in] subTimeoutMs timeoutMs of waiting for the result return if object not ready. A positive integer\n345:     ///  number required. 0 means no waiting time allowed.\n346:     /// \\param[out] readOnlyBuffers The vector of the values.\n347:     ///\n348:     /// \\return K_OK on any key success; the error code otherwise.\n349:     ///         K_INVALID: the vector of keys is empty or include empty key.\n350:     ///         K_NOT_FOUND: the key not found.\n351:     ///         K_RUNTIME_ERROR: Cannot get values from worker.\n352:     /// \\verbatim\n353:     ///  If some keys are not found, The Status OK will return,\n354:     ///  and the existing keys will set the vals with the same index of keys.\n355:     /// \\endverbatim\n356:     Status Get(const std::vector<std::string> &keys, std::vector<Optional<ReadOnlyBuffer>> &readOnlyBuffers,\n357:                int32_t subTimeoutMs = 0);\n358: \n359:     /// \\brief Some data in an object can be read based on the specified key and parameters.\n360:     ///         In some scenarios, read amplification can be avoided.\n361:     ///\n362:     /// \\param[in] readParams The vector of the keys and offset.\n363:     /// \\param[out] readOnlyBuffers The vector of the values.\n364:     ///\n365:     /// \\return K_OK on any key success; the error code otherwise.\n366:     ///         K_INVALID: the vector of keys is empty or include empty key.\n367:     ///         K_NOT_FOUND: the key not found.\n368:     ///         K_RUNTIME_ERROR: Cannot get values from worker.\n369:     /// \\verbatim\n370:     ///  If some keys are not found, The Status OK will return,\n371:     ///  and the existing keys will set the vals with the same index of keys.\n372:     /// \\endverbatim\n373:     Status Read(const std::vector<ReadParam> &readParams, std::vector<Optional<ReadOnlyBuffer>> &readOnlyBuffers);",
      "claim": "Get/Read可部分成功，结果需按Optional逐项判断；Read提供指定offset/size。",
      "legacyChapter": 7
    },
    {
      "id": "D10",
      "title": "C++ QuerySize",
      "repo": "yuanrong-datasystem",
      "commit": "c0bbb1582e49ecc2d2d925836d1288633d322012",
      "path": "include/datasystem/kv_client.h",
      "start": 422,
      "end": 433,
      "kind": "code",
      "chapter": 6,
      "url": "kasandbox-architecture-20261106/datasystem-source-evidence.json#D10",
      "sourceType": "pinned-local-git-blob",
      "excerpt": "422:     /**\n423:      * @brief Invoke worker client to query the size of objectKeys.\n424:      * @param[in] objectKeys The objectKeys need to query size.\n425:      * @param[out] outSizes The size for the objectKeys in bytes.\n426:      * @return K_OK on success; the error code otherwise.\n427:      *         K_INVALID: The objectKeys are empty or invalid.\n428:      *         K_NOT_FOUND: All objectKeys not found.\n429:      *         K_RPC_UNAVAILABLE: Network error.\n430:      *         K_NOT_READY: Worker not ready.\n431:      *         K_RUNTIME_ERROR: Can not get objectKey size from worker.\n432:      */\n433:     Status QuerySize(const std::vector<std::string> &objectKeys, std::vector<uint64_t> &outSizes);",
      "claim": "QuerySize是已有C++ API，不是待研发的数据系统能力；现有Go未暴露。",
      "legacyChapter": 7
    },
    {
      "id": "D11",
      "title": "C++ Exist与Expire",
      "repo": "yuanrong-datasystem",
      "commit": "c0bbb1582e49ecc2d2d925836d1288633d322012",
      "path": "include/datasystem/kv_client.h",
      "start": 481,
      "end": 503,
      "kind": "code",
      "chapter": 6,
      "url": "kasandbox-architecture-20261106/datasystem-source-evidence.json#D11",
      "sourceType": "pinned-local-git-blob",
      "excerpt": "481:     /// \\brief Check whether the keys exist in the data system.\n482:     ///\n483:     /// \\param[in] keys The non-empty keys to be checked. Each key must have a valid object-key format, and the number\n484:     /// of keys cannot exceed 100000.\n485:     /// \\param[in] exists The existence of the corresponding key.\n486:     ///\n487:     /// \\return K_OK if at least one key is successfully processed; K_INVALID when keys are empty or contain an invalid\n488:     /// key; the error code otherwise.\n489:     Status Exist(const std::vector<std::string> &keys, std::vector<bool> &exists);\n490: \n491:     /// \\brief Sets expiration time for key list (in seconds)\n492:     ///\n493:     /// \\param[in] key The keys to set expiration for.\n494:     /// \\param[in] ttlSeconds TTL in seconds. If the value is greater than 0, the data will be deleted automatically\n495:     /// after expired. If set to 0, the data need to be manually deleted.\n496:     /// \\param[out] failedKeys The failed expire keys.\n497:     /// \\return K_OK on success; the error code otherwise.\n498:     ///         K_INVALID: The key is empty or contains invalid characters.\n499:     ///         K_NOT_FOUND: The key is not exist.\n500:     ///         K_NOT_READY: Worker is not ready.\n501:     ///         K_RPC_UNAVAILABLE: Network error.\n502:     ///         K_RUNTIME_ERROR: Inner error happen.\n503:     Status Expire(const std::vector<std::string> &keys, uint32_t ttlSeconds, std::vector<std::string> &failedKeys);",
      "claim": "Exist提供逐key布尔结果；TTL为秒，长期模板/祖先块不能随意过期。",
      "legacyChapter": 7
    },
    {
      "id": "D12",
      "title": "Key约束常量与实际正则",
      "repo": "yuanrong-datasystem",
      "commit": "c0bbb1582e49ecc2d2d925836d1288633d322012",
      "path": "src/datasystem/common/util/validator.h",
      "start": 42,
      "end": 69,
      "kind": "code",
      "chapter": 6,
      "url": "kasandbox-architecture-20261106/datasystem-source-evidence.json#D12",
      "sourceType": "pinned-local-git-blob",
      "excerpt": "42: constexpr int32_t THREAD_POOL_SIZE_LIMIT = 4096;\n43: constexpr int32_t OBJECT_KEYS_MAX_SIZE_LIMIT = 10000;\n44: constexpr int32_t EXIST_KEYS_MAX_SIZE_LIMIT = 100000;\n45: constexpr int32_t NODE_TIMEOUT_LIMIT = 1;\n46: constexpr int32_t MS_PER_SECOND = 1000;\n47: constexpr int32_t URMA_CONNECTION_LIMIT = 16384;\n48: static std::string ENCRYPT_KIT_PLAINTEXT = \"plaintext\";\n49: constexpr uint32_t MAX_KEY_LENGTH = 1024;\n50: \n51: \n52: DS_DECLARE_double(eviction_high_watermark_ratio);\n53: DS_DECLARE_double(eviction_low_watermark_ratio);\n54: DS_DECLARE_double(spill_high_watermark_ratio);\n55: DS_DECLARE_double(spill_low_watermark_ratio);\n56: \n57: using namespace datasystem;\n58: \n59: class Validator {\n60: public:\n61:     Validator() = default;\n62: \n63:     ~Validator() = default;\n64: \n65:     static const int threadMultiplier = 512;\n66:     static constexpr uint64_t MB_TO_BYTES = 1024 * 1024;  // mb to bytes;\n67:     static constexpr uint64_t MB_LIMIT = std::numeric_limits<uint64_t>::max() / MB_TO_BYTES;\n68:     inline static const std::string idFormat = \"^[a-zA-Z0-9\\\\~\\\\.\\\\-\\\\/_!@#%\\\\^\\\\&\\\\*\\\\(\\\\)\\\\+\\\\=\\\\:;]*$\";\n69:     inline static const std::string objKeyFormat = \"^[a-zA-Z0-9\\\\.\\\\-_!@#%\\\\^\\\\*\\\\(\\\\)\\\\+\\\\=\\\\:;]*$\";",
      "claim": "key最长1024字节；objKeyFormat不允许斜杠，KAS路径key需要编码。",
      "legacyChapter": 7
    },
    {
      "id": "D13",
      "title": "Key校验实际使用对象正则",
      "repo": "yuanrong-datasystem",
      "commit": "c0bbb1582e49ecc2d2d925836d1288633d322012",
      "path": "src/datasystem/common/util/validator.h",
      "start": 690,
      "end": 705,
      "kind": "code",
      "chapter": 6,
      "url": "kasandbox-architecture-20261106/datasystem-source-evidence.json#D13",
      "sourceType": "pinned-local-git-blob",
      "excerpt": "690:     /**\n691:      * @brief Check passed in string is a valid ID format. The ID format refers to\n692:      *        any IDs like objectKey, streamName, key, etc. used in the datasystem.\n693:      * @param[in] value The string to be checked.\n694:      * @return True if param is a valid ID format. Otherwise false.\n695:      */\n696:     static bool IsIdFormat(const std::string &value)\n697:     {\n698:         static const re2::RE2 re(objKeyFormat);\n699: \n700:         if (value.size() <= MAX_KEY_LENGTH && (re2::RE2::FullMatch(value, re) || value.empty())) {\n701:             return true;\n702:         }\n703:         LOG(ERROR) << value << \" is not a legal ID format, allowed format: \" << objKeyFormat;\n704:         return false;\n705:     }",
      "claim": "IsIdFormat使用objKeyFormat，不可把另一个允许斜杠的idFormat当KV key格式。",
      "legacyChapter": 7
    },
    {
      "id": "D14",
      "title": "Set/Put拒绝空Value并有请求deadline",
      "repo": "yuanrong-datasystem",
      "commit": "c0bbb1582e49ecc2d2d925836d1288633d322012",
      "path": "src/datasystem/client/object_cache/object_client_impl.cpp",
      "start": 2816,
      "end": 2837,
      "kind": "code",
      "chapter": 6,
      "url": "kasandbox-architecture-20261106/datasystem-source-evidence.json#D14",
      "sourceType": "pinned-local-git-blob",
      "excerpt": "2816: Status ObjectClientImpl::Put(const std::string &objectKey, const uint8_t *data, uint64_t size, const FullParam &param,\n2817:                              const std::unordered_set<std::string> &nestedObjectKeys, uint32_t ttlSecond, int existence,\n2818:                              int32_t requestTimeoutMs)\n2819: {\n2820:     std::shared_lock<std::shared_timed_mutex> shutdownLck(shutdownMux_);\n2821:     RETURN_IF_NOT_OK(IsClientReady());\n2822:     PerfPoint perfPoint(PerfKey::CLIENT_PUT_OBJECT);\n2823:     CHECK_FAIL_RETURN_STATUS(!objectKey.empty(), K_INVALID, \"The objectKey should not be empty.\");\n2824:     RETURN_IF_NOT_OK(CheckValidObjectKey(objectKey));\n2825:     CHECK_FAIL_RETURN_STATUS(data != nullptr, K_INVALID, \"The data pointer should not be null.\");\n2826:     CHECK_FAIL_RETURN_STATUS(size > 0, K_INVALID, \"The dataSize value should be bigger than zero.\");\n2827:     CHECK_FAIL_RETURN_STATUS(nestedObjectKeys.find(objectKey) == nestedObjectKeys.end(), K_UNKNOWN_ERROR,\n2828:                              \"Nested object references cannot be nested in a loop.\");\n2829:     RETURN_IF_NOT_OK(CheckLocalUbNodeAdmission());\n2830:     auto config = GetClientLatencyTraceConfig();\n2831:     const bool traceEnabled = ShouldCollectLatencyTrace(config);\n2832:     if (traceEnabled) {\n2833:         Trace::Instance().AddLatencyTick(LatencyTickKey::CLIENT_SET_START);\n2834:     }\n2835:     const int32_t effectiveTimeoutMs = requestTimeoutMs > 0 ? requestTimeoutMs : requestTimeoutMs_;\n2836:     ApiDeadlineGuard deadlineGuard(effectiveTimeoutMs);\n2837:     GetRequestContext()->reqTimeoutDuration.InitUs(ApiDeadline::Instance().ApiRemainingUs());",
      "claim": "Put要求非空key、非空data、size>0；合法空Blob需要适配层表示；请求timeout与连接timeout分开。",
      "legacyChapter": 7
    },
    {
      "id": "D15",
      "title": "Range实现当前仍经绑定Worker",
      "repo": "yuanrong-datasystem",
      "commit": "c0bbb1582e49ecc2d2d925836d1288633d322012",
      "path": "src/datasystem/client/object_cache/object_client_impl.cpp",
      "start": 3799,
      "end": 3827,
      "kind": "code",
      "chapter": 6,
      "url": "kasandbox-architecture-20261106/datasystem-source-evidence.json#D15",
      "sourceType": "pinned-local-git-blob",
      "excerpt": "3799: Status ObjectClientImpl::Read(const std::vector<ReadParam> &readParams, std::vector<Optional<Buffer>> &buffers)\n3800: {\n3801:     PerfPoint perfPoint(PerfKey::CLIENT_READ_OBJECT);\n3802:     RETURN_IF_NOT_OK(IsClientReady());\n3803:     CHECK_FAIL_RETURN_STATUS_PRINT_ERROR(Validator::IsBatchSizeUnderLimit(readParams.size()), K_INVALID,\n3804:                                          FormatString(\"The objectKeys size exceed %d.\", OBJECT_KEYS_MAX_SIZE_LIMIT));\n3805:     std::shared_ptr<IClientWorkerApi> workerApi;\n3806:     std::unique_ptr<Raii> raii;\n3807:     RETURN_IF_NOT_OK(GetAvailableWorkerApi(workerApi, raii));\n3808:     std::vector<std::shared_ptr<Buffer>> objectBuffers(readParams.size());\n3809:     std::vector<std::string> objectKeys;\n3810:     for (const auto &param : readParams) {\n3811:         objectKeys.emplace_back(param.key);\n3812:     }\n3813:     RETURN_IF_NOT_OK(CheckValidObjectKeyVector(objectKeys));\n3814:     ApiDeadlineGuard deadlineGuard(requestTimeoutMs_);\n3815:     GetParam getParam{ .objectKeys = objectKeys, .subTimeoutMs = 0, .readParams = readParams };\n3816:     Status rc = boundMode_->GetBuffersFromWorker(workerApi, getParam, objectBuffers);\n3817:     buffers.clear();\n3818:     for (auto &objectBuffer : objectBuffers) {\n3819:         if (objectBuffer == nullptr) {\n3820:             buffers.emplace_back();\n3821:         } else {\n3822:             buffers.emplace_back(std::move(*objectBuffer));\n3823:         }\n3824:     }\n3825:     perfPoint.Record();\n3826:     LOG(INFO) << \"Finish to Get objects \" << VectorToString(objectKeys);\n3827:     return rc;",
      "claim": "Read构造readParams并走boundMode.GetBuffersFromWorker，不可自动套用full-object direct-route结论。",
      "legacyChapter": 7
    },
    {
      "id": "D16",
      "title": "只读Buffer指针与所有权",
      "repo": "yuanrong-datasystem",
      "commit": "c0bbb1582e49ecc2d2d925836d1288633d322012",
      "path": "include/datasystem/kv/read_only_buffer.h",
      "start": 38,
      "end": 72,
      "kind": "code",
      "chapter": 6,
      "url": "kasandbox-architecture-20261106/datasystem-source-evidence.json#D16",
      "sourceType": "pinned-local-git-blob",
      "excerpt": "38:     /**\n39:      * @brief Get the data size of the buffer.\n40:      * @return The data size of the buffer.\n41:      */\n42:     int64_t GetSize() const;\n43: \n44:     /**\n45:      * @brief Get a immutable data pointer.\n46:      * @return A const void * to the data.\n47:      */\n48:     const void *ImmutableData();\n49: \n50:     /**\n51:      * @brief A Read lock is executed on the memory to protect the memory from concurrent writes (allow concurrent\n52:      * reads).\n53:      * @param[in] timeout Try-lock timeout, default value is 60 seconds.\n54:      * @return Status of the result.\n55:      */\n56:     Status RLatch(uint64_t timeout = 60 /* default is 60s */);\n57: \n58:     /**\n59:      * @brief Unlock the read latch on memory.\n60:      * @return Status of the result.\n61:      */\n62:     Status UnRLatch();\n63: \n64: private:\n65:     friend KVClient;\n66: \n67:     explicit ReadOnlyBuffer(std::shared_ptr<Buffer> &buffer)\n68:     {\n69:         buffer_ = buffer;\n70:     }\n71: \n72:     std::shared_ptr<Buffer> buffer_;",
      "claim": "ReadOnlyBuffer暴露ImmutableData/GetSize并持有shared Buffer；跨FFI需保留owner与明确release。",
      "legacyChapter": 7
    },
    {
      "id": "D17",
      "title": "Go连接Timeout不是请求预算",
      "repo": "yuanrong-datasystem",
      "commit": "c0bbb1582e49ecc2d2d925836d1288633d322012",
      "path": "src/datasystem/c_api/util.cpp",
      "start": 46,
      "end": 79,
      "kind": "code",
      "chapter": 6,
      "url": "kasandbox-architecture-20261106/datasystem-source-evidence.json#D17",
      "sourceType": "pinned-local-git-blob",
      "excerpt": "46: void ConstructConnectOptions(const int timeOut, const char *token, size_t tokenLen, const char *clientPublicKey,\n47:                              size_t cClientPublicKeyLen, const char *clientPrivateKey, size_t clientPrivateKeyLen,\n48:                              const char *serverPublicKey, size_t cServerPublicKeyLen, const char *accessKey,\n49:                              size_t cAccessKeyLen, const char *secretKey, size_t secretKeyLen, const char *tenantId,\n50:                              size_t cTenantIdLen, const char *enableCrossNodeConnection,\n51:                              datasystem::ConnectOptions &opts)\n52: {\n53:     if (timeOut > 0) {\n54:         opts.connectTimeoutMs = timeOut;\n55:     }\n56:     ExecHandlerIfParamValid(\n57:         token, [&opts, token, tokenLen]() { opts.token = datasystem::SensitiveValue(token, tokenLen); });\n58:     ExecHandlerIfParamValid(clientPublicKey, [&opts, clientPublicKey, cClientPublicKeyLen]() {\n59:         opts.clientPublicKey = std::string(clientPublicKey, cClientPublicKeyLen);\n60:     });\n61:     ExecHandlerIfParamValid(clientPrivateKey, [&opts, clientPrivateKey, clientPrivateKeyLen]() {\n62:         opts.clientPrivateKey = datasystem::SensitiveValue(clientPrivateKey, clientPrivateKeyLen);\n63:     });\n64:     ExecHandlerIfParamValid(serverPublicKey, [&opts, serverPublicKey, cServerPublicKeyLen]() {\n65:         opts.serverPublicKey = std::string(serverPublicKey, cServerPublicKeyLen);\n66:     });\n67:     ExecHandlerIfParamValid(\n68:         accessKey, [&opts, accessKey, cAccessKeyLen]() { opts.accessKey = std::string(accessKey, cAccessKeyLen); });\n69:     ExecHandlerIfParamValid(secretKey, [&opts, secretKey, secretKeyLen]() {\n70:         opts.secretKey = datasystem::SensitiveValue(secretKey, secretKeyLen);\n71:     });\n72:     ExecHandlerIfParamValid(tenantId,\n73:                             [&opts, tenantId, cTenantIdLen]() { opts.tenantId = std::string(tenantId, cTenantIdLen); });\n74: \n75:     // The default value of enableCrossNodeConnection is \"false\".\n76:     // If the value transferred from the Go is \"true\", assign a new value.\n77:     if (enableCrossNodeConnection != nullptr && strcmp(enableCrossNodeConnection, \"true\") == 0) {\n78:         opts.enableCrossNodeConnection = true;\n79:     }",
      "claim": "timeOut只赋connectTimeoutMs；不能将其表述为Go context端到端请求deadline。",
      "legacyChapter": 7
    },
    {
      "id": "D18",
      "title": "同步/异步L2写模式",
      "repo": "yuanrong-datasystem",
      "commit": "c0bbb1582e49ecc2d2d925836d1288633d322012",
      "path": "include/datasystem/object/object_enum.h",
      "start": 28,
      "end": 46,
      "kind": "code",
      "chapter": 6,
      "url": "kasandbox-architecture-20261106/datasystem-source-evidence.json#D18",
      "sourceType": "pinned-local-git-blob",
      "excerpt": "28: namespace datasystem {\n29: \n30: enum class WriteMode : int {\n31:     NONE_L2_CACHE = 0,\n32:     WRITE_THROUGH_L2_CACHE = 1,     // sync write\n33:     WRITE_BACK_L2_CACHE = 2,        // async write\n34:     NONE_L2_CACHE_EVICT = 3,        // evictable write\n35:     WRITE_BACK_L2_CACHE_EVICT = 4,  // evictable async write\n36: };\n37: \n38: enum class ConsistencyType : int {\n39:     PRAM = 0,\n40:     CAUSAL = 1,\n41: };\n42: \n43: enum class CacheType : int {\n44:     MEMORY = 0,\n45:     DISK = 1,\n46: };",
      "claim": "WRITE_THROUGH是同步L2，WRITE_BACK是异步L2；不凭枚举名承诺fsync或全系统HA。",
      "legacyChapter": 7
    },
    {
      "id": "D19",
      "title": "写穿先保存L2再设对象完成",
      "repo": "yuanrong-datasystem",
      "commit": "c0bbb1582e49ecc2d2d925836d1288633d322012",
      "path": "src/datasystem/worker/object_cache/service/worker_oc_service_publish_impl.cpp",
      "start": 529,
      "end": 564,
      "kind": "code",
      "chapter": 6,
      "url": "kasandbox-architecture-20261106/datasystem-source-evidence.json#D19",
      "sourceType": "pinned-local-git-blob",
      "excerpt": "529: Status WorkerOcServicePublishImpl::PublishObject(ObjectKV &objectKV, const PublishParams &params,\n530:                                                  std::vector<RpcMessage> &payloads)\n531: {\n532:     const auto &objectKey = objectKV.GetObjKey();\n533:     SafeObjType &safeObj = objectKV.GetObjEntry();\n534:     auto oldLifeState = safeObj->GetLifeState();\n535:     VLOG(1) << FormatString(\"Current life state: %d, next state: %d, ttl second: %u.\", (int)oldLifeState,\n536:                             (int)params.lifeState, params.ttlSecond);\n537:     // Step 1: Verify and request to master, object may be expired due to network latency.\n538:     RETURN_IF_NOT_OK(RequestingToMaster(objectKV, params));\n539: \n540:     if (!payloads.empty()) {\n541:         RETURN_IF_NOT_OK(SaveBinaryObjectToMemory(objectKV, payloads, evictionManager_, memCpyThreadPool_));\n542:     }\n543:     INJECT_POINT(\"worker.free_object_resource\", [&safeObj]() {\n544:         LOG_IF_ERROR(safeObj->FreeResources(), \"SafeObj free failed\");\n545:         return Status::OK();\n546:     });\n547:     if (safeObj->IsWriteThroughMode() && IsSupportL2Storage(supportL2Storage_)) {\n548:         LOG(INFO) << \"Save binary object to l2cache begin\";\n549:         Status res = SaveBinaryObjectToPersistence(objectKV);\n550:         if (res.IsError()) {\n551:             LOG(ERROR) << \"SaveBinaryObjectToPersistence failed. status:\" << res.ToString();\n552:             RETURN_IF_NOT_OK(RollbackPublishFailure(objectKV, oldLifeState, params.lifeState));\n553:             return res;\n554:         }\n555:     }\n556: \n557:     // Step 3: Notify GetRequest for subscription purpose.\n558:     safeObj->stateInfo.SetNeedToDelete(false);\n559:     RETURN_IF_NOT_OK(workerRequestManager_.NotifyPendingGetRequest(objectKV));\n560:     safeObj->SetLifeState(params.lifeState);\n561:     safeObj->stateInfo.SetPrimaryCopy(true);\n562:     safeObj->stateInfo.SetCacheInvalid(false);\n563:     safeObj->stateInfo.SetIncompleted(false);\n564:     if (safeObj->IsSpilled()) {",
      "claim": "WriteThrough调用SaveBinaryObjectToPersistence，失败会回滚本对象发布；其成功边界依赖具体L2实现与配置。",
      "legacyChapter": 7
    },
    {
      "id": "D20",
      "title": "Go SDK与C共享库的打包路径",
      "repo": "yuanrong-datasystem",
      "commit": "c0bbb1582e49ecc2d2d925836d1288633d322012",
      "path": "cmake/package.cmake",
      "start": 222,
      "end": 254,
      "kind": "code",
      "chapter": 6,
      "url": "kasandbox-architecture-20261106/datasystem-source-evidence.json#D20",
      "sourceType": "pinned-local-git-blob",
      "excerpt": "222: ############################################################\n223: # Datasystem go header files and share libraries.\n224: ############################################################\n225: if (BUILD_GO_API)\n226:     set(DATASYSTEM_GO_INCLUDEDIR datasystem/sdk/go/include)\n227:     set(DATASYSTEM_GO_LIBPATH datasystem/sdk/go/lib)\n228:     set(DATASYSTEM_GO_PATH datasystem/sdk)\n229: \n230:     install(DIRECTORY ${CMAKE_SOURCE_DIR}/go\n231:             DESTINATION ${DATASYSTEM_GO_PATH}\n232:             FILES_MATCHING PATTERN \"*\")\n233: \n234:     install(FILES ${CMAKE_SOURCE_DIR}/src/datasystem/c_api/status_definition.h\n235:             ${CMAKE_SOURCE_DIR}/src/datasystem/c_api/kv_client_c_wrapper.h\n236:             ${CMAKE_SOURCE_DIR}/src/datasystem/c_api/stream_client_c_wrapper.h\n237:             ${CMAKE_SOURCE_DIR}/src/datasystem/c_api/object_client_c_wrapper.h\n238:             ${CMAKE_SOURCE_DIR}/src/datasystem/c_api/utilC.h\n239:             DESTINATION ${DATASYSTEM_GO_INCLUDEDIR}/datasystem/c_api)\n240: \n241:     set(common_flags_INSTALL_LIBPATH ${DATASYSTEM_GO_LIBPATH})\n242:     install_datasystem_target(common_flags)\n243: \n244:     set(etcdapi_proto_INSTALL_LIBPATH ${DATASYSTEM_GO_LIBPATH})\n245:     install_datasystem_target(etcdapi_proto)\n246: \n247:     set(rpc_option_protos_INSTALL_LIBPATH ${DATASYSTEM_GO_LIBPATH})\n248:     install_datasystem_target(rpc_option_protos)\n249: \n250:     set(datasystem_c_INSTALL_LIBPATH ${DATASYSTEM_GO_LIBPATH})\n251:     install_datasystem_target(datasystem_c)\n252: \n253:     set(datasystem_INSTALL_LIBPATH ${DATASYSTEM_GO_LIBPATH})\n254:     install_datasystem_target(datasystem)",
      "claim": "BUILD_GO_API时安装Go源码、C头与datasystem_c/libdatasystem；部署需匹配SDK/库版本。",
      "legacyChapter": 7
    },
    {
      "id": "D21",
      "title": "Range 同批拒绝重复 key 与溢出",
      "repo": "yuanrong-datasystem",
      "commit": "c0bbb1582e49ecc2d2d925836d1288633d322012",
      "path": "src/datasystem/client/kv_cache/kv_client.cpp",
      "start": 465,
      "end": 483,
      "kind": "code",
      "chapter": 6,
      "url": "kasandbox-architecture-20261106/datasystem-source-evidence.json#D21",
      "sourceType": "pinned-local-git-blob",
      "excerpt": "465: Status ValidateReadParams(const std::vector<ReadParam> &readParams, ObjectAccessRecorder &access)\n466: {\n467:     std::unordered_set<std::string> keys;\n468:     for (const auto &param : readParams) {\n469:         if (keys.find(param.key) != keys.end()) {\n470:             auto status = Status(K_INVALID, FormatString(\"The input parameter contains duplicate key %s. Keys: %s\",\n471:                                                          param.key, VectorToString(keys)));\n472:             access.Result(K_INVALID, status.GetMsg()).Record();\n473:             return status;\n474:         }\n475:         if (UINT64_MAX - param.size < param.offset) {\n476:             auto status =\n477:                 Status(K_INVALID, FormatString(\"The %s's offset: %llu + size: %llu overflow\",\n478:                                                param.key, param.offset, param.size));\n479:             access.Result(K_INVALID, status.GetMsg()).Record();\n480:             return status;\n481:         }\n482:         keys.insert(param.key);\n483:     }",
      "claim": "ReadParam 批次要求 key 唯一，且检查 offset+size 溢出；同片多个小范围必须先合并或分批，不能原样逐页放进一个批次。",
      "legacyChapter": 7
    },
    {
      "id": "D22",
      "title": "WriteBack 写入异步 L2 管理器",
      "repo": "yuanrong-datasystem",
      "commit": "c0bbb1582e49ecc2d2d925836d1288633d322012",
      "path": "src/datasystem/worker/object_cache/service/worker_oc_service_publish_impl.cpp",
      "start": 621,
      "end": 625,
      "kind": "code",
      "chapter": 6,
      "url": "kasandbox-architecture-20261106/datasystem-source-evidence.json#D22",
      "sourceType": "pinned-local-git-blob",
      "excerpt": "621:     if ((*entry)->IsWriteBackMode() && IsSupportL2Storage(supportL2Storage_)) {\n622:         LOG(INFO) << \"Asyn save binary object to l2cache\";\n623:         return asyncSendManager_->Add(objectKey, entry, future);\n624:     }\n625:     return Status::OK();",
      "claim": "WriteBack 在发布后进入 asyncSendManager；此处不同于 WriteThrough 先等待 SaveBinaryObjectToPersistence，不能把普通写回成功直接等同 L2 已完成。",
      "legacyChapter": 7
    },
    {
      "id": "D23",
      "title": "元数据恢复默认关闭并筛选可恢复模式",
      "repo": "yuanrong-datasystem",
      "commit": "c0bbb1582e49ecc2d2d925836d1288633d322012",
      "path": "src/datasystem/worker/object_cache/metadata_recovery_manager.cpp",
      "start": 38,
      "end": 68,
      "kind": "code",
      "chapter": 6,
      "url": "kasandbox-architecture-20261106/datasystem-source-evidence.json#D23",
      "sourceType": "pinned-local-git-blob",
      "excerpt": "38: DS_DEFINE_bool(enable_metadata_recovery, false, \"enable metadata recovery when worker failed\");\n39: \n40: namespace datasystem {\n41: namespace object_cache {\n42: namespace {\n43: bool IsRestartRecoverableWriteMode(uint32_t writeMode)\n44: {\n45:     auto mode = static_cast<WriteMode>(writeMode);\n46:     return mode == WriteMode::WRITE_THROUGH_L2_CACHE || mode == WriteMode::WRITE_BACK_L2_CACHE\n47:            || mode == WriteMode::WRITE_BACK_L2_CACHE_EVICT;\n48: }\n49: \n50: bool CanRecoverRestartMeta(const ObjectMetaPb &meta)\n51: {\n52:     if (meta.object_key().empty()) {\n53:         LOG(WARNING) << \"Skip restart recovery metadata with empty object key.\";\n54:         return false;\n55:     }\n56:     if (static_cast<DataFormat>(meta.config().data_format()) != DataFormat::BINARY) {\n57:         LOG(INFO) << FormatString(\"[ObjectKey %s] Skip non-binary restart recovery metadata.\", meta.object_key());\n58:         return false;\n59:     }\n60:     if (!IsRestartRecoverableWriteMode(meta.config().write_mode())) {\n61:         LOG(INFO) << FormatString(\"[ObjectKey %s] Skip non-L2 restart recovery metadata.\", meta.object_key());\n62:         return false;\n63:     }\n64:     if (static_cast<ObjectLifeState>(meta.life_state()) == ObjectLifeState::OBJECT_INVALID) {\n65:         LOG(INFO) << FormatString(\"[ObjectKey %s] Skip invalid restart recovery metadata.\", meta.object_key());\n66:         return false;\n67:     }\n68:     return true;",
      "claim": "enable_metadata_recovery 缺省 false；重启恢复元数据还要求 Binary、L2-backed 写模式、非 invalid 等条件。这是该恢复路径的条件，不代表所有配置自动 HA，也不能概括所有恢复能力都关闭。",
      "legacyChapter": 7
    },
    {
      "id": "D24",
      "title": "数据复制开关描述本地副本缓存",
      "repo": "yuanrong-datasystem",
      "commit": "c0bbb1582e49ecc2d2d925836d1288633d322012",
      "path": "src/datasystem/common/flags/common_flag_define.cpp",
      "start": 235,
      "end": 236,
      "kind": "code",
      "chapter": 6,
      "url": "kasandbox-architecture-20261106/datasystem-source-evidence.json#D24",
      "sourceType": "pinned-local-git-blob",
      "excerpt": "235: DS_DEFINE_bool(enable_data_replication, true,\n236:                \"Allow data replica cache locally; mainly for performance validation, keep enabled unless needed.\");",
      "claim": "enable_data_replication 缺省 true，声明说明为允许数据 replica cache locally；此开关不能直接当作 Provider 每次写的同步 N 副本提交承诺。",
      "legacyChapter": 7
    },
    {
      "id": "D25",
      "title": "未配置 L2 时拒绝 L2 写模式",
      "repo": "yuanrong-datasystem",
      "commit": "c0bbb1582e49ecc2d2d925836d1288633d322012",
      "path": "src/datasystem/worker/object_cache/service/worker_oc_service_crud_common_api.cpp",
      "start": 430,
      "end": 441,
      "kind": "code",
      "chapter": 6,
      "url": "kasandbox-architecture-20261106/datasystem-source-evidence.json#D25",
      "sourceType": "pinned-local-git-blob",
      "excerpt": "430: Status WorkerOcServiceCrudCommonApi::CheckIfL2CacheNeededAndWritable(const L2StorageType &supportType,\n431:                                                                      WriteMode writeMode)\n432: {\n433:     if (supportType == L2StorageType::NONE) {\n434:         bool isSetWriteL2Cache =\n435:             (writeMode == WriteMode::WRITE_THROUGH_L2_CACHE || writeMode == WriteMode::WRITE_BACK_L2_CACHE\n436:              || writeMode == WriteMode::WRITE_BACK_L2_CACHE_EVICT);\n437:         CHECK_FAIL_RETURN_STATUS_PRINT_ERROR(!isSetWriteL2Cache, K_INVALID,\n438:                                              \"The key is set to WRITE_THROUGH_L2_CACHE, WRITE_BACK_L2_CACHE or \"\n439:                                              \"WRITE_BACK_L2_CACHE_EVICT, but L2_cache_type is set to none.\");\n440:     }\n441:     return Status::OK();",
      "claim": "L2StorageType::NONE 时，WriteThrough、WriteBack、WriteBackEvict 写模式返回 K_INVALID；不能只在客户端选择 L2 模式而省略 Worker 后端配置。",
      "legacyChapter": 7
    },
    {
      "id": "D26",
      "title": "Go GetArray 部分 missing 的测试源码",
      "repo": "yuanrong-datasystem",
      "commit": "c0bbb1582e49ecc2d2d925836d1288633d322012",
      "path": "go/kv/kv_client_test.go",
      "start": 444,
      "end": 470,
      "kind": "code",
      "chapter": 6,
      "url": "kasandbox-architecture-20261106/datasystem-source-evidence.json#D26",
      "sourceType": "pinned-local-git-blob",
      "excerpt": "444: func TestGetArrayFail(t *testing.T) {\n445: \tvar theClient *KVClient\n446: \tvar s common.Status\n447: \tconst TimeoutMs uint32 = 5 // Waiting 5ms for the result return if not ready.\n448: \tif theClient, s = CreateClientForTest(); theClient == nil {\n449: \t\tt.Fatalf(s.ToString())\n450: \t}\n451: \tdefer theClient.DestroyClient()\n452: \n453: \t// Set a value\n454: \tvar key2 string = \"key67789\"\n455: \tvar value2 string = \"data2\"\n456: \tvar setParam = SetParam{WriteMode: NoneL2Cache}\n457: \ts = theClient.Set(key2, value2, setParam)\n458: \tif s.IsError() {\n459: \t\tt.Fatalf(s.ToString())\n460: \t}\n461: \n462: \t// Getting multiple keys -> Key1 missing\n463: \toutputE, s := theClient.GetArray([]string{\"key12637\", \"key67789\"}, TimeoutMs)\n464: \tif s.IsError() {\n465: \t\tt.Fatalf(s.ToString())\n466: \t}\n467: \n468: \tif len(outputE[0]) != 0 || outputE[1] != value2 {\n469: \t\tt.Fatalf(\"Output Strings for GetArray Doesn't match\")\n470: \t}",
      "claim": "此测试源码期望第一个 key missing、第二个存在时批次状态不报错，结果位置分别为空字符串与 data2；说明批次 OK 不能代替逐项检查。本轮未运行该测试。",
      "legacyChapter": 7
    },
    {
      "id": "F01",
      "title": "文件对象抽象与可选流式能力",
      "repo": "KASandbox",
      "commit": "54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7",
      "chapter": 6,
      "path": "packages/shared/pkg/storage/storage.go",
      "start": 63,
      "end": 90,
      "kind": "code",
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/shared/pkg/storage/storage.go#L63",
      "excerpt": "63: type StorageProvider interface {\n64: \tDeleteObjectsWithPrefix(ctx context.Context, prefix string) error\n65: \tUploadSignedURL(ctx context.Context, path string, ttl time.Duration) (string, error)\n66: \tOpenBlob(ctx context.Context, path string, objectType ObjectType) (Blob, error)\n67: \tOpenSeekable(ctx context.Context, path string, seekableObjectType SeekableObjectType) (Seekable, error)\n68: \tGetDetails() string\n69: }\n70: \n71: type Blob interface {\n72: \tWriteTo(ctx context.Context, dst io.Writer) (int64, error)\n73: \tPut(ctx context.Context, data []byte) error\n74: \tExists(ctx context.Context) (bool, error)\n75: }\n76: \n77: type SeekableReader interface {\n78: \t// Random slice access, off and buffer length must be aligned to block size\n79: \tReadAt(ctx context.Context, buffer []byte, off int64) (int, error)\n80: \tSize(ctx context.Context) (int64, error)\n81: }\n82: \n83: // StreamingReader supports progressive reads via a streaming range reader.\n84: type StreamingReader interface {\n85: \tOpenRangeReader(ctx context.Context, off, length int64) (io.ReadCloser, error)\n86: }\n87: \n88: type SeekableWriter interface {\n89: \t// Store entire file\n90: \tStoreFile(ctx context.Context, path string) error",
      "claim": "Blob/Seekable将整体与随机内容访问分开；文件接口可抽，但ObjectType枚举与签名上传不应成为元戎KV核心必需。",
      "legacyChapter": 7
    },
    {
      "id": "F02",
      "title": "raw Blob与分片元数据的内容探测",
      "repo": "KASandbox",
      "commit": "54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7",
      "chapter": 6,
      "path": "packages/shared/pkg/storage/storage_mooncake.go",
      "start": 1260,
      "end": 1294,
      "kind": "code",
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/shared/pkg/storage/storage_mooncake.go#L1260",
      "excerpt": "1260: func (o *mooncakeBlob) readMeta(ctx context.Context) (*mooncakeObjectMeta, int64, error) {\n1261: \tif meta, ok := loadCachedMetadata(o.path); ok {\n1262: \t\treturn meta, 0, nil\n1263: \t}\n1264: \n1265: \tsize, err := o.store.GetSize(o.path)\n1266: \tif err != nil {\n1267: \t\texists, existsErr := o.store.Exists(o.path)\n1268: \t\tif existsErr == nil && !exists {\n1269: \t\t\treturn nil, 0, ErrObjectNotExist\n1270: \t\t}\n1271: \t\treturn nil, 0, fmt.Errorf(\"failed to get object size for %s: %w\", o.path, err)\n1272: \t}\n1273: \tif size > 4096 {\n1274: \t\treturn nil, size, errNotChunkedBlob\n1275: \t}\n1276: \tif size == 0 {\n1277: \t\treturn nil, size, errNotChunkedBlob\n1278: \t}\n1279: \n1280: \tnumaBuf, n, release, err := getIntoNumaBuffer(ctx, o.store, o.path, uint64(size))\n1281: \tif err != nil {\n1282: \t\treturn nil, size, fmt.Errorf(\"failed to read potential metadata for %s: %w\", o.path, err)\n1283: \t}\n1284: \tdefer release()\n1285: \n1286: \tvar meta mooncakeObjectMeta\n1287: \tif err := json.Unmarshal(numaBuf.buf[:n], &meta); err != nil {\n1288: \t\treturn nil, size, errNotChunkedBlob\n1289: \t}\n1290: \tif meta.ChunkSize <= 0 || meta.ChunkSize > numaBufferSize || meta.Size < 0 {\n1291: \t\treturn nil, size, errNotChunkedBlob\n1292: \t}\n1293: \tstoreCachedMetadata(o.path, &meta)\n1294: \treturn &meta, size, nil",
      "claim": "当前小主value通过JSON结构探测分片布局；通用文件层宜采用有magic/版本的独立descriptor，避免与任意用户Blob内容混淆。",
      "legacyChapter": 7
    },
    {
      "id": "F03",
      "title": "当前随机读只处理一个存储分片",
      "repo": "KASandbox",
      "commit": "54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7",
      "chapter": 6,
      "path": "packages/shared/pkg/storage/storage_mooncake.go",
      "start": 1520,
      "end": 1553,
      "kind": "code",
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/shared/pkg/storage/storage_mooncake.go#L1520",
      "excerpt": "1520: func (o *mooncakeSeekable) ReadAt(ctx context.Context, buff []byte, off int64) (int, error) {\n1521: \tmeta, err := o.getMeta(ctx)\n1522: \tif err != nil {\n1523: \t\treturn 0, err\n1524: \t}\n1525: \tif off >= meta.Size {\n1526: \t\treturn 0, io.EOF\n1527: \t}\n1528: \tif off < 0 {\n1529: \t\treturn 0, errors.New(\"negative offset\")\n1530: \t}\n1531: \n1532: \tremaining := min(int64(len(buff)), meta.Size-off)\n1533: \n1534: \treturn o.readAtSingleChunk(ctx, buff, off, remaining, meta)\n1535: }\n1536: \n1537: func (o *mooncakeSeekable) readAtSingleChunk(ctx context.Context, buff []byte, off int64, remaining int64, meta *mooncakeObjectMeta) (int, error) {\n1538: \tchunkOffset := (off / meta.ChunkSize) * meta.ChunkSize\n1539: \tchunkEnd := min(chunkOffset+meta.ChunkSize, meta.Size)\n1540: \tchunkSize := chunkEnd - chunkOffset\n1541: \n1542: \tstartInChunk := off - chunkOffset\n1543: \tdata, err := o.readChunk(ctx, chunkOffset, chunkSize, buff, startInChunk)\n1544: \tif err != nil {\n1545: \t\treturn 0, fmt.Errorf(\"failed to read chunk at %d: %w\", chunkOffset, err)\n1546: \t}\n1547: \n1548: \tcopied := min(len(data), int(remaining))\n1549: \n1550: \tif copied < len(buff) && off+int64(copied) >= meta.Size {\n1551: \t\treturn copied, io.EOF\n1552: \t}\n1553: \treturn copied, nil",
      "claim": "ReadAt当前落在readAtSingleChunk；通用任意长度ReadAt需显式补跨片循环与短读/错误契约。",
      "legacyChapter": 7
    },
    {
      "id": "F04",
      "title": "单对象分片写与描述最后发布",
      "repo": "KASandbox",
      "commit": "54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7",
      "chapter": 6,
      "path": "packages/shared/pkg/storage/storage_mooncake.go",
      "start": 1730,
      "end": 1795,
      "kind": "code",
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/shared/pkg/storage/storage_mooncake.go#L1730",
      "excerpt": "1730: func (o *mooncakeSeekable) StoreFile(ctx context.Context, localPath string) error {\n1731: \tinvalidateCachedMetadata(o.path)\n1732: \to.metaMu.Lock()\n1733: \to.meta = nil\n1734: \to.metaErr = nil\n1735: \to.metaLoaded = false\n1736: \to.metaMu.Unlock()\n1737: \n1738: \tfile, err := os.Open(localPath)\n1739: \tif err != nil {\n1740: \t\treturn fmt.Errorf(\"failed to open file %s: %w\", localPath, err)\n1741: \t}\n1742: \tdefer file.Close()\n1743: \n1744: \tinfo, err := file.Stat()\n1745: \tif err != nil {\n1746: \t\treturn fmt.Errorf(\"failed to stat file %s: %w\", localPath, err)\n1747: \t}\n1748: \tsize := info.Size()\n1749: \n1750: \t// Upload chunks in parallel.\n1751: \tg, groupCtx := errgroup.WithContext(ctx)\n1752: \tg.SetLimit(mooncakeUploadConcurrency)\n1753: \n1754: \tfor offset := int64(0); offset < size; offset += MemoryChunkSize {\n1755: \t\toff := offset\n1756: \t\tg.Go(func() error {\n1757: \t\t\tif err := groupCtx.Err(); err != nil {\n1758: \t\t\t\treturn err\n1759: \t\t\t}\n1760: \n1761: \t\t\tend := min(off+MemoryChunkSize, size)\n1762: \t\t\tbuf, releaseBuf, err := getChunkBuffer(groupCtx)\n1763: \t\t\tif err != nil {\n1764: \t\t\t\treturn err\n1765: \t\t\t}\n1766: \t\t\tdefer releaseBuf()\n1767: \t\t\tchunk := buf[:int(end-off)]\n1768: \n1769: \t\t\tif _, err := file.ReadAt(chunk, off); err != nil && !errors.Is(err, io.EOF) {\n1770: \t\t\t\treturn fmt.Errorf(\"failed to read chunk at %d from %s: %w\", off, localPath, err)\n1771: \t\t\t}\n1772: \n1773: \t\t\tcChunk := C.CBytes(chunk)\n1774: \t\t\tdefer C.free(cChunk)\n1775: \t\t\treturn o.store.Put(o.chunkKey(off), unsafe.Slice((*byte)(cChunk), len(chunk)), nil)\n1776: \t\t})\n1777: \t}\n1778: \n1779: \tif err := g.Wait(); err != nil {\n1780: \t\treturn fmt.Errorf(\"failed to upload chunks: %w\", err)\n1781: \t}\n1782: \n1783: \t// Write metadata last so that readers see a consistent object only when fully written.\n1784: \tmeta := &mooncakeObjectMeta{Size: size, ChunkSize: MemoryChunkSize}\n1785: \tmetaBytes, err := json.Marshal(meta)\n1786: \tif err != nil {\n1787: \t\treturn fmt.Errorf(\"failed to marshal metadata: %w\", err)\n1788: \t}\n1789: \n1790: \tif err := o.store.Put(o.path, metaBytes, nil); err != nil {\n1791: \t\treturn fmt.Errorf(\"failed to write metadata: %w\", err)\n1792: \t}\n1793: \tstoreCachedMetadata(o.path, meta)\n1794: \n1795: \treturn nil",
      "claim": "StoreFile分片并行Put，所有片成功后写size/chunk_size；可抽通用chunk writer，但现有代码不提供覆盖事务、崩溃孤儿清理或耐久承诺。",
      "legacyChapter": 7
    },
    {
      "id": "F05",
      "title": "稀疏增量Extent映射的数据模型",
      "repo": "KASandbox",
      "commit": "54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7",
      "chapter": 6,
      "path": "packages/shared/pkg/storage/header/mapping.go",
      "start": 11,
      "end": 20,
      "kind": "code",
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/shared/pkg/storage/header/mapping.go#L11",
      "excerpt": "11: // Start, Length and SourceStart are in bytes of the data file\n12: // Length will be a multiple of BlockSize\n13: // The list of block mappings will be in order of increasing Start, covering the entire file\n14: type BuildMap struct {\n15: \t// Offset defines which block of the current layer this mapping starts at\n16: \tOffset             uint64\n17: \tLength             uint64\n18: \tBuildId            uuid.UUID\n19: \tBuildStorageOffset uint64\n20: }",
      "claim": "BuildMap以逻辑Offset/Length和来源BuildId/BuildStorageOffset描述虚拟文件，适合泛化为可选ExtentMap。",
      "legacyChapter": 7
    },
    {
      "id": "F06",
      "title": "泛化合并需要源偏移连续性约束",
      "repo": "KASandbox",
      "commit": "54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7",
      "chapter": 6,
      "path": "packages/shared/pkg/storage/header/mapping.go",
      "start": 247,
      "end": 273,
      "kind": "code",
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/shared/pkg/storage/header/mapping.go#L247",
      "excerpt": "247: // NormalizeMappings joins adjacent mappings that have the same buildId.\n248: func NormalizeMappings(mappings []*BuildMap) []*BuildMap {\n249: \tif len(mappings) == 0 {\n250: \t\treturn nil\n251: \t}\n252: \n253: \tresult := make([]*BuildMap, 0, len(mappings))\n254: \n255: \t// Start with a copy of the first mapping\n256: \tcurrent := mappings[0].Copy()\n257: \n258: \tfor i := 1; i < len(mappings); i++ {\n259: \t\tmp := mappings[i]\n260: \t\tif mp.BuildId != current.BuildId {\n261: \t\t\t// BuildId changed, add the current map to results and start a new one\n262: \t\t\tresult = append(result, current)\n263: \t\t\tcurrent = mp.Copy() // New copy\n264: \t\t} else {\n265: \t\t\t// Same BuildId, just add the length\n266: \t\t\tcurrent.Length += mp.Length\n267: \t\t}\n268: \t}\n269: \n270: \t// Add the last mapping\n271: \tresult = append(result, current)\n272: \n273: \treturn result",
      "claim": "当前NormalizeMappings按BuildId相同合并长度；抽为任意extent算法前需明确逻辑/源偏移连续性，不把此KAS假设无条件带入。",
      "legacyChapter": 7
    },
    {
      "id": "F07",
      "title": "跨Build逻辑文件解析与零区",
      "repo": "KASandbox",
      "commit": "54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7",
      "chapter": 6,
      "path": "packages/orchestrator/internal/sandbox/build/build.go",
      "start": 40,
      "end": 96,
      "kind": "code",
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/orchestrator/internal/sandbox/build/build.go#L40",
      "excerpt": "40: func (b *File) ReadAt(ctx context.Context, p []byte, off int64) (n int, err error) {\n41: \tfor n < len(p) {\n42: \t\tmappedOffset, mappedLength, buildID, err := b.header.GetShiftedMapping(ctx, off+int64(n))\n43: \t\tif err != nil {\n44: \t\t\treturn 0, fmt.Errorf(\"failed to get mapping: %w\", err)\n45: \t\t}\n46: \n47: \t\tremainingReadLength := int64(len(p)) - int64(n)\n48: \n49: \t\treadLength := min(mappedLength, remainingReadLength)\n50: \n51: \t\tif readLength <= 0 {\n52: \t\t\tlogger.L().Error(ctx, fmt.Sprintf(\n53: \t\t\t\t\"(%d bytes left to read, off %d) reading %d bytes from %+v/%+v: [%d:] -> [%d:%d] <> %d (mapped length: %d, remaining read length: %d)\\n>>> EOF\\n\",\n54: \t\t\t\tlen(p)-n,\n55: \t\t\t\toff,\n56: \t\t\t\treadLength,\n57: \t\t\t\tbuildID,\n58: \t\t\t\tb.fileType,\n59: \t\t\t\tmappedOffset,\n60: \t\t\t\tn,\n61: \t\t\t\tint64(n)+readLength,\n62: \t\t\t\tn,\n63: \t\t\t\tmappedLength,\n64: \t\t\t\tremainingReadLength,\n65: \t\t\t))\n66: \n67: \t\t\treturn n, io.EOF\n68: \t\t}\n69: \n70: \t\t// Skip reading when the uuid is nil.\n71: \t\t// We will use this to handle base builds that are already diffs.\n72: \t\t// The passed slice p must start as empty, otherwise we would need to copy the empty values there.\n73: \t\tif *buildID == uuid.Nil {\n74: \t\t\tn += int(readLength)\n75: \n76: \t\t\tcontinue\n77: \t\t}\n78: \n79: \t\tmappedBuild, err := b.getBuild(ctx, buildID)\n80: \t\tif err != nil {\n81: \t\t\treturn 0, fmt.Errorf(\"failed to get build: %w\", err)\n82: \t\t}\n83: \n84: \t\tbuildN, err := mappedBuild.ReadAt(ctx,\n85: \t\t\tp[n:int64(n)+readLength],\n86: \t\t\tmappedOffset,\n87: \t\t)\n88: \t\tif err != nil {\n89: \t\t\treturn 0, fmt.Errorf(\"failed to read from source: %w\", err)\n90: \t\t}\n91: \n92: \t\tn += buildN\n93: \t}\n94: \n95: \treturn n, nil\n96: }",
      "claim": "build.File按header拆分读取并寻找来源build；Nil映射跳读且要求目标初始零，泛化需要显式Zero extent契约。",
      "legacyChapter": 7
    },
    {
      "id": "F08",
      "title": "Header格式与Generation不是写入fencing",
      "repo": "KASandbox",
      "commit": "54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7",
      "chapter": 6,
      "path": "packages/shared/pkg/storage/header/serialization.go",
      "start": 18,
      "end": 65,
      "kind": "code",
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/shared/pkg/storage/header/serialization.go#L18",
      "excerpt": "18: type Metadata struct {\n19: \tVersion    uint64\n20: \tBlockSize  uint64\n21: \tSize       uint64\n22: \tGeneration uint64\n23: \tBuildId    uuid.UUID\n24: \t// TODO: Use the base build id when setting up the snapshot rootfs\n25: \tBaseBuildId uuid.UUID\n26: }\n27: \n28: func NewTemplateMetadata(buildId uuid.UUID, blockSize, size uint64) *Metadata {\n29: \treturn &Metadata{\n30: \t\tVersion:     metadataVersion,\n31: \t\tGeneration:  0,\n32: \t\tBlockSize:   blockSize,\n33: \t\tSize:        size,\n34: \t\tBuildId:     buildId,\n35: \t\tBaseBuildId: buildId,\n36: \t}\n37: }\n38: \n39: func (m *Metadata) NextGeneration(buildID uuid.UUID) *Metadata {\n40: \treturn &Metadata{\n41: \t\tVersion:     m.Version,\n42: \t\tGeneration:  m.Generation + 1,\n43: \t\tBlockSize:   m.BlockSize,\n44: \t\tSize:        m.Size,\n45: \t\tBuildId:     buildID,\n46: \t\tBaseBuildId: m.BaseBuildId,\n47: \t}\n48: }\n49: \n50: func Serialize(metadata *Metadata, mappings []*BuildMap) ([]byte, error) {\n51: \tvar buf bytes.Buffer\n52: \n53: \terr := binary.Write(&buf, binary.LittleEndian, metadata)\n54: \tif err != nil {\n55: \t\treturn nil, fmt.Errorf(\"failed to write metadata: %w\", err)\n56: \t}\n57: \n58: \tfor _, mapping := range mappings {\n59: \t\terr := binary.Write(&buf, binary.LittleEndian, mapping)\n60: \t\tif err != nil {\n61: \t\t\treturn nil, fmt.Errorf(\"failed to write block mapping: %w\", err)\n62: \t\t}\n63: \t}\n64: \n65: \treturn buf.Bytes(), nil",
      "claim": "Header持久化Version/BlockSize/Size/Generation/BuildId/BaseBuildId及映射；Generation递增是映像元数据，不是CAS或分布式写隔离。",
      "legacyChapter": 7
    },
    {
      "id": "F09",
      "title": "Layer依赖集合与完整覆盖校验",
      "repo": "KASandbox",
      "commit": "54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7",
      "chapter": 6,
      "path": "packages/shared/pkg/storage/header/inspect.go",
      "start": 32,
      "end": 41,
      "kind": "code",
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/shared/pkg/storage/header/inspect.go#L32",
      "excerpt": "32: // Layers returns a map of buildIds that are present in the mappings.\n33: func Layers(mappings []*BuildMap) *map[uuid.UUID]struct{} {\n34: \tlayers := make(map[uuid.UUID]struct{})\n35: \n36: \tfor _, mapping := range mappings {\n37: \t\tlayers[mapping.BuildId] = struct{}{}\n38: \t}\n39: \n40: \treturn &layers\n41: }",
      "claim": "Layers仅提取映射中BuildID集合，可作为依赖枚举起点；本函数不提供持久引用计数或安全GC。",
      "legacyChapter": 7
    },
    {
      "id": "F10",
      "title": "块获取策略和cache-ready门槛",
      "repo": "KASandbox",
      "commit": "54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7",
      "chapter": 6,
      "path": "packages/orchestrator/internal/sandbox/block/chunk.go",
      "start": 208,
      "end": 287,
      "kind": "code",
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/orchestrator/internal/sandbox/block/chunk.go#L208",
      "excerpt": "208: func (c *FullFetchChunker) fetchToCache(ctx context.Context, off, length int64) error {\n209: \tstartingChunk := header.BlockIdx(off, storage.MemoryChunkSize)\n210: \tstartingChunkOffset := header.BlockOffset(startingChunk, storage.MemoryChunkSize)\n211: \n212: \t// 要拉的块必须盖住 [off, off+length) 整段。off 不在块边界上时（64 KiB 宿主页在\n213: \t// 4 KiB 粒度压实的 memfile 里经常如此），只按 length 算块数会漏掉后半截所在的那一块，\n214: \t// Slice 随即报 BytesNotAvailableError、沙箱被杀（10-09 预热模板 24a1cbb3 实测）。\n215: \tchunks := header.BlocksOffsets(off+length-startingChunkOffset, storage.MemoryChunkSize)\n216: \n217: \t// Try the Mooncake fast-path: a single batched backend call.\n218: \t/*if batchReader, ok := c.base.(storage.BatchReader); ok {\n219: \t\treturn c.fetchToCacheBatch(ctx, startingChunkOffset, chunks, batchReader)\n220: \t}*/\n221: \n222: \t// Slow path: one goroutine per chunk (works for any SeekableReader backend).\n223: \tvar eg errgroup.Group\n224: \n225: \tfor _, chunkOff := range chunks {\n226: \t\t// Ensure the closure captures the correct block offset.\n227: \t\tfetchOff := startingChunkOffset + chunkOff\n228: \n229: \t\teg.Go(func() (err error) {\n230: \t\t\tdefer func() {\n231: \t\t\t\tif r := recover(); r != nil {\n232: \t\t\t\t\tlogger.L().Error(ctx, \"recovered from panic in the fetch handler\", zap.Any(\"error\", r))\n233: \t\t\t\t\terr = fmt.Errorf(\"recovered from panic in the fetch handler: %v\", r)\n234: \t\t\t\t}\n235: \t\t\t}()\n236: \n237: \t\t\terr = c.fetchers.Wait(fetchOff, func() error {\n238: \t\t\t\tselect {\n239: \t\t\t\tcase <-ctx.Done():\n240: \t\t\t\t\treturn fmt.Errorf(\"error fetching range %d-%d: %w\", fetchOff, fetchOff+storage.MemoryChunkSize, ctx.Err())\n241: \t\t\t\tdefault:\n242: \t\t\t\t}\n243: \n244: \t\t\t\t// The size of the buffer is adjusted if the last chunk is not a multiple of the block size.\n245: \t\t\t\tb, releaseCacheCloseLock, err := c.cache.addressBytes(fetchOff, storage.MemoryChunkSize)\n246: \t\t\t\tif err != nil {\n247: \t\t\t\t\treturn err\n248: \t\t\t\t}\n249: \n250: \t\t\t\tdefer releaseCacheCloseLock()\n251: \n252: \t\t\t\tfetchSW := c.metrics.RemoteReadsTimerFactory.Begin()\n253: \n254: \t\t\t\treadBytes, err := c.base.ReadAt(ctx, b, fetchOff)\n255: \t\t\t\tif err != nil {\n256: \t\t\t\t\tfetchSW.Failure(ctx, int64(readBytes),\n257: \t\t\t\t\t\tattribute.String(failureReason, failureTypeRemoteRead),\n258: \t\t\t\t\t)\n259: \n260: \t\t\t\t\treturn fmt.Errorf(\"failed to read chunk from base %d: %w\", fetchOff, err)\n261: \t\t\t\t}\n262: \n263: \t\t\t\tif readBytes != len(b) {\n264: \t\t\t\t\tfetchSW.Failure(ctx, int64(readBytes),\n265: \t\t\t\t\t\tattribute.String(failureReason, failureTypeRemoteRead),\n266: \t\t\t\t\t)\n267: \n268: \t\t\t\t\treturn fmt.Errorf(\"failed to read chunk from base %d: expected %d bytes, got %d bytes\", fetchOff, len(b), readBytes)\n269: \t\t\t\t}\n270: \n271: \t\t\t\tc.cache.setIsCached(fetchOff, int64(readBytes))\n272: \n273: \t\t\t\tfetchSW.Success(ctx, int64(readBytes))\n274: \n275: \t\t\t\treturn nil\n276: \t\t\t})\n277: \n278: \t\t\treturn err\n279: \t\t})\n280: \t}\n281: \n282: \terr := eg.Wait()\n283: \tif err != nil {\n284: \t\treturn fmt.Errorf(\"failed to ensure data at %d-%d: %w\", off, off+length, err)\n285: \t}\n286: \n287: \treturn nil",
      "claim": "FullFetch分片并发抓取，WaitMap去重，读满后标cache可用；适合抽策略但需移除featureflag/telemetry耦合并重定error/lifetime。",
      "legacyChapter": 7
    },
    {
      "id": "F11",
      "title": "当前本地缓存回收采用延迟删除",
      "repo": "KASandbox",
      "commit": "54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7",
      "chapter": 6,
      "path": "packages/orchestrator/internal/sandbox/build/cache.go",
      "start": 270,
      "end": 290,
      "kind": "code",
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/packages/orchestrator/internal/sandbox/build/cache.go#L270",
      "excerpt": "270: func (s *DiffStore) scheduleDelete(ctx context.Context, key DiffStoreKey, dSize int64) {\n271: \ts.pdMu.Lock()\n272: \tdefer s.pdMu.Unlock()\n273: \n274: \tcancelCh := make(chan struct{})\n275: \ts.pdSizes[key] = &deleteDiff{\n276: \t\tsize:   dSize,\n277: \t\tcancel: cancelCh,\n278: \t}\n279: \n280: \t// Delay cache (file close/removal) deletion,\n281: \t// this is to prevent race conditions with exposed slices,\n282: \t// pending data fetching, or data upload\n283: \tgo (func() {\n284: \t\tselect {\n285: \t\tcase <-ctx.Done():\n286: \t\tcase <-cancelCh:\n287: \t\tcase <-time.After(s.pdDelay):\n288: \t\t\ts.cache.Delete(key)\n289: \t\t}\n290: \t})()",
      "claim": "DiffStore延迟删除以照顾暴露slice/抓取/上传；泛化跨SDK Buffer需显式lease/owner，不把时间延迟当永久借用保证。",
      "legacyChapter": 7
    },
    {
      "id": "F12",
      "title": "迁移工具重复实现应用层分片协议",
      "repo": "KASandbox",
      "commit": "54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7",
      "chapter": 6,
      "path": "migrate-tool/internal/targetstore/mooncake.go",
      "start": 16,
      "end": 37,
      "kind": "code",
      "url": "https://gitcode.com/openeuler/KASandbox/blob/54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7/migrate-tool/internal/targetstore/mooncake.go#L16",
      "excerpt": "16: // mooncakeChunkSize 必须等于 KASandbox 运行时 packages/shared/pkg/storage\n17: // 的 MemoryChunkSize(storage.go,4 MiB)。Mooncake 本身是纯 KV 存储,\n18: // \"大对象按 4 MiB 分片、分片 key 为 <key>#c#<offset>、逻辑 key 存\n19: // size/chunk_size 元数据\"是 E2B 在其上自定的应用层布局,编译在运行时读端\n20: // (storage_mooncake.go)里,没有可在线查询的接口,只能照读端源码对齐。\n21: // 读端虽会从元数据读回 chunk_size,但其缓冲池按 MemoryChunkSize 固定分配,\n22: // 4 MiB 是唯一安全值;写端(本工具)偏离读端会导致导入的对象运行时读不出来。\n23: const mooncakeChunkSize int64 = 4 * 1024 * 1024\n24: \n25: type mooncakeObjectMetadata struct {\n26: \tSize      int64 `json:\"size\"`\n27: \tChunkSize int64 `json:\"chunk_size\"`\n28: }\n29: \n30: // Get returns a view consumed before the next call; implementations must use\n31: // registered memory where the native transport requires it.\n32: type mooncakeClient interface {\n33: \tPut(string, []byte) error\n34: \tExists(string) (bool, error)\n35: \tGet(string, int64) ([]byte, error)\n36: \tClose()\n37: }",
      "claim": "迁移端明确4MiB/#c#协议来自KAS运行时，展示抽共享格式codec/contract的实际复用收益；不是Mooncake native文件接口。",
      "legacyChapter": 7
    },
    {
      "id": "D27",
      "title": "ObjectClient已有全局引用原语",
      "repo": "yuanrong-datasystem",
      "commit": "c0bbb1582e49ecc2d2d925836d1288633d322012",
      "path": "include/datasystem/object_client.h",
      "start": 72,
      "end": 117,
      "kind": "code",
      "chapter": 6,
      "url": "kasandbox-architecture-20261106/datasystem-source-evidence.json#D27",
      "sourceType": "pinned-local-git-blob",
      "excerpt": "72:     /// \\brief Increase the global reference count to objects in the data system.\n73:     ///\n74:     /// \\param[in] objectKeys The object keys to increase, it cannot be empty. ID should not be empty and should only\n75:     ///  alphabetics (a-zA-Z), numbers and ~!@#$%^&*.-_ only. ID length should be no more than 1024.\n76:     /// \\param[out] failedObjectKeys Increase failed object keys.\n77:     /// \\param[in] remoteClientId The remote client id of the client that outside the cloud. Resolve scenarios that ELB\n78:     ///  forwards requests to different gateways, resulting in incorrect increase or decrease in reference counts, and\n79:     ///  system availability after gateway crash.\n80:     ///\n81:     /// \\return K_OK on any object success, the failedObjectKeys indicate the failed list.\n82:     ///         K_RPC_UNAVAILABLE: Disconnect from worker or master.\n83:     ///         K_INVALID: The parameter is invalid.\n84:     Status GIncreaseRef(const std::vector<std::string> &objectKeys, std::vector<std::string> &failedObjectKeys,\n85:                         const std::string &remoteClientId = \"\");\n86: \n87:     /// \\brief Decrease the global reference count to objects in the data system.\n88:     ///\n89:     /// \\param[in] objectKeys The object keys to decrease, it cannot be empty. ID should not be empty and should only\n90:     ///  alphabetics (a-zA-Z), numbers and ~!@#$%^&*.-_ only. ID length should be no more than 1024.\n91:     /// \\param[out] failedObjectKeys Decrease failed object keys.\n92:     /// \\param[in] remoteClientId The remote client id of the client that outside the cloud. Resolve scenarios that ELB\n93:     ///  forwards requests to different gateways, resulting in incorrect increase or decrease in reference counts, and\n94:     ///  system availability after gateway crash.\n95:     ///\n96:     /// \\return K_OK on any object success, the failedObjectKeys indicate the failed list.\n97:     ///         K_RPC_UNAVAILABLE: Disconnect from worker or master.\n98:     ///         K_INVALID: The parameter is invalid.\n99:     Status GDecreaseRef(const std::vector<std::string> &objectKeys, std::vector<std::string> &failedObjectKey,\n100:                         const std::string &remoteClientId = \"\");\n101: \n102:     /// \\brief Release obj Ref of remote client id when remote client that outside the cloud crash.\n103:     ///\n104:     /// \\param[in] remoteClientId The remote client id of the client that outside the cloud.\n105:     ///\n106:     /// \\return K_OK on any object success, the failedObjectKeys indicate the failed list.\n107:     ///         K_RPC_UNAVAILABLE: Disconnect from worker or master.\n108:     ///         K_INVALID: The parameter is invalid.\n109:     Status ReleaseGRefs(const std::string &remoteClientId);\n110: \n111:     /// \\brief Query all objects global references in the cluster (out-cloud reference not included).\n112:     ///\n113:     /// \\param[in] objectKey The specific object key that to query. ID should not be empty and should only contains\n114:     ///  alphabetics (a-zA-Z), numbers and ~!@#$%^&*.-_ only. ID length should be no more than 1024.\n115:     ///\n116:     /// \\return The objects' global reference num; -1 in case of failure.\n117:     int QueryGlobalRefNum(const std::string &objectKey);",
      "claim": "GIncreaseRef/GDecreaseRef/ReleaseGRefs/QueryGlobalRefNum可作为root/ancestor持有机制的复用候选，不等同已完成File版本持久GC/lease。",
      "legacyChapter": 7
    },
    {
      "id": "D28",
      "title": "ObjectClient默认PRAM",
      "repo": "yuanrong-datasystem",
      "commit": "c0bbb1582e49ecc2d2d925836d1288633d322012",
      "path": "include/datasystem/object_client.h",
      "start": 43,
      "end": 46,
      "kind": "code",
      "chapter": 6,
      "url": "kasandbox-architecture-20261106/datasystem-source-evidence.json#D28",
      "sourceType": "pinned-local-git-blob",
      "excerpt": "43: struct CreateParam {\n44:     ConsistencyType consistencyType = ConsistencyType::PRAM;\n45:     CacheType cacheType = CacheType::MEMORY;\n46: };",
      "claim": "ObjectClient CreateParam缺省PRAM；不能未经验证直接混同KV默认CAUSAL与保有策略。",
      "legacyChapter": 7
    },
    {
      "id": "D29",
      "title": "Buffer发布与嵌套依赖",
      "repo": "yuanrong-datasystem",
      "commit": "c0bbb1582e49ecc2d2d925836d1288633d322012",
      "path": "include/datasystem/object/buffer.h",
      "start": 71,
      "end": 88,
      "kind": "code",
      "chapter": 6,
      "url": "kasandbox-architecture-20261106/datasystem-source-evidence.json#D29",
      "sourceType": "pinned-local-git-blob",
      "excerpt": "71:     /// \\brief Get the data size of the buffer.\n72:     ///\n73:     /// \\return The data size of the buffer.\n74:     int64_t GetSize() const;\n75: \n76:     /// \\brief Publish mutable data to the server.\n77:     ///\n78:     /// \\param[in] nestedKeys Object key of the nested object.\n79:     ///\n80:     /// \\return Status of the result.\n81:     Status Publish(const std::unordered_set<std::string> &nestedKeys = {});\n82: \n83:     /// \\brief Publish immutable data to the server.\n84:     ///\n85:     /// \\param[in] nestedKeys Object key of the nested object.\n86:     ///\n87:     /// \\return Status of the result.\n88:     Status Seal(const std::unordered_set<std::string> &nestedKeys = {});",
      "claim": "Buffer.Publish/Seal接受nestedKeys，值得评估复用于manifest依赖；持久性和跨模式语义仍需验证。",
      "legacyChapter": 7
    },
    {
      "id": "D30",
      "title": "ObjectClient嵌套引用写接口",
      "repo": "yuanrong-datasystem",
      "commit": "c0bbb1582e49ecc2d2d925836d1288633d322012",
      "path": "include/datasystem/object_client.h",
      "start": 133,
      "end": 144,
      "kind": "code",
      "chapter": 6,
      "url": "kasandbox-architecture-20261106/datasystem-source-evidence.json#D30",
      "sourceType": "pinned-local-git-blob",
      "excerpt": "133:     /// \\brief Invoke worker client to put an object (publish semantics).\n134:     ///\n135:     /// \\param[in] objectKey The ID of the object to create. ID should not be empty and should only contains english\n136:     ///  alphabetics (a-zA-Z), numbers and ~!@#$%^&*.-_ only. ID length should be no more than 1024.\n137:     /// \\param[in] data The data pointer of the user.\n138:     /// \\param[in] size The size in bytes of object.\n139:     /// \\param[in] param The create parameters.\n140:     /// \\param[in] nestedObjectKeys Objects that depend on objectKey.\n141:     ///\n142:     /// \\return K_OK on success; the error code otherwise.\n143:     Status Put(const std::string &objectKey, const uint8_t *data, uint64_t size, const CreateParam &param,\n144:                const std::unordered_set<std::string> &nestedObjectKeys = {});",
      "claim": "ObjectClient.Put有nestedObjectKeys参数；这是已有原语，不是文件版本/快照GC成品。",
      "legacyChapter": 7
    },
    {
      "id": "D31",
      "title": "L2 PersistenceApi所在层次",
      "repo": "yuanrong-datasystem",
      "commit": "c0bbb1582e49ecc2d2d925836d1288633d322012",
      "path": "src/datasystem/common/l2cache/persistence_api.h",
      "start": 32,
      "end": 116,
      "kind": "code",
      "chapter": 6,
      "url": "kasandbox-architecture-20261106/datasystem-source-evidence.json#D31",
      "sourceType": "pinned-local-git-blob",
      "excerpt": "32: class PersistenceApi {\n33: public:\n34:     virtual ~PersistenceApi() = default;\n35: \n36:     static std::unique_ptr<PersistenceApi> Create();\n37: \n38:     static std::shared_ptr<PersistenceApi> CreateShared();\n39: \n40:     /**\n41:      * @brief init the PersistenceApi\n42:      * @return execute result\n43:      */\n44:     virtual Status Init() = 0;\n45: \n46:     /**\n47:      * @brief save the object to 3rd storage, for example obs\n48:      * @param[in] objectKey the object namespace in datastystem. i.e. <tenantId>/<objectKey>\n49:      * @param[in] version the version of the object\n50:      * @param[in] timeoutMs the connect and request timeout in million second\n51:      * @param[in] body the content of the object\n52:      * @param[in] asyncElapse The time this object being in the async queue\n53:      * @return execute result\n54:      */\n55:     virtual Status Save(const std::string &objectKey, uint64_t version, int64_t timeoutMs,\n56:                         const std::shared_ptr<std::iostream> &body, uint64_t asyncElapse = 0,\n57:                         WriteMode writeMode = WriteMode::NONE_L2_CACHE, uint32_t ttlSecond = 0) = 0;\n58: \n59:     /**\n60:      * @brief get the persistence object with the given version.\n61:      * if the given version is not exist, return the max version exist in persistence.\n62:      *\n63:      * @param[in] objectKey the object key:<TenantId>/<ObjectKey>\n64:      * @param[in] version the object meta version\n65:      * @param[in] timeoutMs the connect and request timeout in million second\n66:      * @param[out] content the string stream byte of the object\n67:      * @return Status of call\n68:      */\n69:     virtual Status Get(const std::string &objectKey, uint64_t version, int64_t timeoutMs,\n70:                        std::shared_ptr<std::stringstream> &content) = 0;\n71: \n72:     /**\n73:      * @brief get the persistence object without any given version.\n74:      * @param[in] objectKey the object key:<TenantId>/<ObjectKey>\n75:      * @param[in] timeoutMs the connect and request timeout in million second\n76:      * @param[in] minVersion the min version for object.\n77:      * @param[out] content the string stream byte of the object\n78:      * @return Status of call\n79:      */\n80:     virtual Status GetWithoutVersion(const std::string &objectKey, int64_t timeoutMs, uint64_t minVersion,\n81:                                      std::shared_ptr<std::stringstream> &content) = 0;\n82: \n83:     /**\n84:      * @brief delete all the satisfied version of the object\n85:      * satisfied version means: version <= maxVerToDelete.\n86:      *\n87:      * two scenarios:\n88:      * 1) deleteAllVersion=false indicate datasystem don't delete the object, but only clear the old version of the\n89:      * object, in this scenarios, invoker need to know that:\n90:      * if existMaxVersion(the max version exist persistence) <= maxVerToDelete, we must not delete the existMaxVersion,\n91:      * the purpose is that we need keep a version of object in cloud storage, finally we will delete the version\n92:      * satisfied: version <= existMaxVersion - 1\n93:      *\n94:      * 2) deleteAllVersion=true, datasystem delete the object, it means clear all the version of the object,\n95:      * in this scenarios, invoker need to know that:\n96:      * if the maxVerToDelete is not found in persistence(i.e. maybe the maxVerToDelete version is in upload process),\n97:      * we do not consider the deletion is complete, even though all other version success to delete.\n98:      *\n99:      * @param[in] objectKey the object path in persistence\n100:      * @param[in] maxVerToDelete the max version can be delete\n101:      * @param[in] deleteAllVersion true if the datasystem delete the object, otherwise false\n102:      * @param[in] asyncElapse The time this object being in the async queue\n103:      * @param[in] objectVersion The object version.\n104:      * @param[in] listIncompleteVersions whether to list those incomplete versions. Usually they are partially uploaded.\n105:      * @return Status of call\n106:      */\n107:     virtual Status Del(const std::string &objectKey, uint64_t maxVerToDelete, bool deleteAllVersion,\n108:                        uint64_t asyncElapse = 0, const uint64_t *const objectVersion = nullptr,\n109:                        bool listIncompleteVersions = false) = 0;\n110: \n111:     virtual Status PreloadSlot(const std::string &sourceWorkerAddress, uint32_t slotId,\n112:                                const SlotPreloadCallback &callback = SlotPreloadCallback{}) = 0;\n113: \n114:     virtual Status MergeSlot(const std::string &sourceWorkerAddress, uint32_t slotId) = 0;\n115: \n116:     virtual Status CleanupLocalSlots() = 0;",
      "claim": "PersistenceApi处理单对象L2保存/版本/删除和slot维护；拟议File跨KV布局与extent映射应在上层SDK，不直接塞入L2接口。",
      "legacyChapter": 7
    },
    {
      "id": "D32",
      "title": "C ABI共享库构建入口",
      "repo": "yuanrong-datasystem",
      "commit": "c0bbb1582e49ecc2d2d925836d1288633d322012",
      "path": "src/datasystem/c_api/CMakeLists.txt",
      "start": 1,
      "end": 12,
      "kind": "code",
      "chapter": 6,
      "url": "kasandbox-architecture-20261106/datasystem-source-evidence.json#D32",
      "sourceType": "pinned-local-git-blob",
      "excerpt": "1: file(GLOB CLIENT_C_API_SRC ./*.cpp)\n2: set(CLIENT_C_DEPEND_LIBS\n3:         datasystem_static\n4:         ds_spdlog::spdlog\n5:         CURL::libcurl)\n6: \n7: add_library(datasystem_c SHARED ${CLIENT_C_API_SRC})\n8: target_link_libraries(datasystem_c PRIVATE \"${CLIENT_C_DEPEND_LIBS}\")\n9: \n10: # just for ut\n11: add_library(datasystem_c_static STATIC ${CLIENT_C_API_SRC})\n12: target_link_libraries(datasystem_c_static PRIVATE \"${CLIENT_C_DEPEND_LIBS}\")",
      "claim": "现有C API生成datasystem_c；新增File opaque handle需纳入构建、包装及SDK打包，尚未实施。",
      "legacyChapter": 7
    },
    {
      "id": "D33",
      "title": "ObjectClient Put 的默认写入路径",
      "repo": "yuanrong-datasystem",
      "commit": "c0bbb1582e49ecc2d2d925836d1288633d322012",
      "chapter": 6,
      "path": "src/datasystem/client/object_cache/object_client.cpp",
      "start": 135,
      "end": 145,
      "kind": "code",
      "sourceType": "pinned-local-git-blob",
      "url": "kasandbox-architecture-20261106/datasystem-source-evidence.json#D33",
      "excerpt": "135: Status ObjectClient::Put(const std::string &objectKey, const uint8_t *data, uint64_t size, const CreateParam &param,\n136:                          const std::unordered_set<std::string> &nestedObjectKeys)\n137: {\n138:     TraceGuard traceGuard = Trace::Instance().SetRequestTraceUUID();\n139:     object_cache::FullParam innerParam;\n140:     innerParam.writeMode = WriteMode::NONE_L2_CACHE;\n141:     innerParam.consistencyType = param.consistencyType;\n142:     innerParam.cacheType = param.cacheType;\n143:     auto access = AccessRecorder::Object(AccessRecorderKey::DS_OBJECT_CLIENT_PUT);\n144:     Status rc = impl_->Put(objectKey, data, size, innerParam, nestedObjectKeys);\n145:     access.ObjectKeyRef(objectKey).WriteMode(static_cast<int>(innerParam.writeMode))",
      "claim": "ObjectClient::Put 将 writeMode 设为 NONE_L2_CACHE；不能直接换API就继承原KV所选持久化策略。",
      "legacyChapter": 7
    }
  ],
  "baselines": {
    "KASandbox": "54a49bc74e2d1dc7e393ce1d61fe4ea7cc592af7",
    "yuanrong-datasystem": "c0bbb1582e49ecc2d2d925836d1288633d322012"
  }
}
