Skip to content

fix(insert-sync): fix reuse ub insert sync bug#935

Open
jimmychou0 wants to merge 2 commits into
hw-native-sys:mainfrom
jimmychou0:fix/issue-934-planmemory-sync
Open

fix(insert-sync): fix reuse ub insert sync bug#935
jimmychou0 wants to merge 2 commits into
hw-native-sys:mainfrom
jimmychou0:fix/issue-934-planmemory-sync

Conversation

@jimmychou0

@jimmychou0 jimmychou0 commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

问题根因

--pto-level=level2 下,PlanMemory 会将不同的本地分配物化为不同的 pto.pointer_cast。旧 InsertSync 对单地址 pointer_cast 主要依赖地址 SSA 的 root 身份判断别名,无法识别不同 root 对应的物理 UB 区间重叠。

Issue #934 的根因是:PlanMemory 复用了 UB 物理内存,但 InsertSync 仍按 SSA 指针身份判断是否别名,导致漏掉同步。
具体过程:
PlanMemory 后:

stored = pointer_cast(1280) // 占用 [1280, 9472)
reused = pointer_cast(8192) // 占用 [8192, 16384)
两个区间在 [8192, 9472) 重叠。stored 在 tstore 之后,SSA 层面已经不再使用,因此 PlanMemory 认为其 UB 可复用给 reused。但 tstore 实际由 MTE3 异步执行,仍在从 stored 对应的 UB 区域读取数据。
随后 V pipe 的 tmuls 写入 reused,就可能提前覆盖 MTE3 尚未读完的 stored 数据:
TSTORE(stored -> GM) // MTE3 异步读 UB
TMULS(... -> reused) // V pipe 写入重叠的 UB 区间
旧 InsertSync 对单地址 pointer_cast 只记录相对偏移 {0},并要求两侧的 rootBuffer 是同一个 SSA 值才继续做区间判断。pointer_cast(1280) 和 pointer_cast(8192) 的常量 SSA 不同,因此被误判为“不别名”,没有插入:
set_flag(PIPE_MTE3, PIPE_V, ...)
wait_flag(PIPE_MTE3, PIPE_V, ...)
结果是 MTE3 与 V pipe 存在数据竞争,表现为 tstore 输出偶发错误或被后续计算覆盖。

修复方案

  1. 为 InsertSync 的内存信息增加 hasKnownPhysicalAddresses 标记,标识可静态解析且对应 local UB 物理地址的 pto.pointer_cast
  2. 静态 local pto.pointer_cast 保留真实起始字节地址,不只保留相对偏移。
  3. 两侧都是已知物理地址的 local buffer 时,按真实内存区间是否重叠判断别名,不依赖 SSA root 是否相同。
  4. 若 tstore 的 MTE3 异步读与后续 V pipe 写入重叠,插入 MTE3 -> V 的 set_flag/wait_flag。
  5. 动态地址、GM 地址与原有基于相同 SSA root 的分析路径保持不变。

验证

  • ninja -C /private/tmp/ptoas-issue934-pr-build ptoas
  • llvm-lit 聚焦回归:
    • plan_memory_reused_tstore_sync.pto
    • multi_tile_const_slot_disjoint_sync.pto
    • issue870_identity_tmov_pruning.pto
  • 使用完整 level2 复现输入验证生成代码中 k 路径已变为:
    TSTORE -> set_flag(MTE3, V) -> wait_flag(MTE3, V) -> TMUL

Fixes #934

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@reedhecre

reedhecre commented Jul 14, 2026

Copy link
Copy Markdown

Codex Review

该评论由 review 机器人自动更新。

  • PR: fix(insert-sync): fix reuse ub insert sync bug #935 fix(insert-sync): fix reuse ub insert sync bug
  • Author: jimmychou0
  • Base/Head: main / fix/issue-934-planmemory-sync
  • Head SHA: 328c22ae8623
  • Trigger: PR 有新提交
  • Generated At: 2026-07-14T09:40:51Z
  • Previous Head SHA: 89b4d4ce4716
  • Status: failed at codex-review (exit=1)

Summary

Review failed at stage codex-review: exit=1

Findings

未生成结构化 findings,因为 review 过程提前失败。

Log Tail

git clone --branch 'main' --depth 50 'https://github.com/hw-native-sys/PTOAS.git' '/tmp/ptoas-pr-review-monitor/runs/20260714_174031_pr935/repo'
cd '/tmp/ptoas-pr-review-monitor/runs/20260714_174031_pr935/repo'
git fetch origin 'refs/pull/935/head:pr-935' --depth 50
git fetch origin 'main' --depth 50 || true
git checkout -f 'pr-935'
git rev-parse HEAD
git diff --stat 'origin/main...HEAD' || true
Cloning into '/tmp/ptoas-pr-review-monitor/runs/20260714_174031_pr935/repo'...
From https://github.com/hw-native-sys/PTOAS
 * [new ref]           refs/pull/935/head -> pr-935
From https://github.com/hw-native-sys/PTOAS
 * branch              main       -> FETCH_HEAD
Switched to branch 'pr-935'
328c22ae8623c9c84eff1a84c653ad81d03942a9
 include/PTO/Transforms/InsertSync/SyncCommon.h     | 19 +++--
 .../InsertSync/MemoryDependentAnalyzer.cpp         | 15 +++-
 lib/PTO/Transforms/InsertSync/PTOIRTranslator.cpp  | 60 +++++++++------
 test/lit/pto/alloc_tile_physical_overlap_sync.pto  | 51 +++++++++++++
 test/lit/pto/plan_memory_reused_tstore_sync.pto    | 53 +++++++++++++
 .../pto/plan_memory_reused_tstore_sync_level2.pto  | 88 ++++++++++++++++++++++
 6 files changed, 257 insertions(+), 29 deletions(-)
===== END STAGE clone rc=0 @ 2026-07-14 17:40:41 =====

===== STAGE codex-review @ 2026-07-14 17:40:41 =====
set -euo pipefail
cd '/tmp/ptoas-pr-review-monitor/runs/20260714_174031_pr935/repo'
'codex' exec -C '/tmp/ptoas-pr-review-monitor/runs/20260714_174031_pr935/repo' -s read-only -c 'model_provider="codereview"' -c 'model="gpt-5.4"' -c 'model_reasoning_effort="xhigh"' --output-schema '/tmp/ptoas-pr-review-monitor/runs/20260714_174031_pr935/review_schema.json' -o '/tmp/ptoas-pr-review-monitor/runs/20260714_174031_pr935/codex_last_message.json' --color never - < '/tmp/ptoas-pr-review-monitor/runs/20260714_174031_pr935/review_prompt.txt'
[monitor] stage timeout: 1800s
OpenAI Codex v0.115.0 (research preview)
--------
workdir: /tmp/ptoas-pr-review-monitor/runs/20260714_174031_pr935/repo
model: gpt-5.4
provider: codereview
approval: never
sandbox: read-only
reasoning effort: xhigh
reasoning summaries: none
session id: 019f6000-0a46-7261-ad44-900c751fd3e7
--------
user
你现在在审查 GitHub PR。

仓库:hw-native-sys/PTOAS
PR:#935 fix(insert-sync): fix reuse ub insert sync bug
作者:jimmychou0
base branch:origin/main
head branch:HEAD(当前已 checkout 到 PR head)

要求:
1. 只审查这个 PR 相对 origin/main 的改动,必要时可以看上下文文件。
2. 重点找真实的 correctness / regression / contract mismatch / CI / runtime / compatibility 问题。
3. 不要提纯风格建议,不要提低价值猜测。
4. 严格按优先级输出:
   - P1:高概率会导致错误结果、编译/运行失败、严重回归、发布阻断
   - P2:重要缺陷、行为回归、遗漏校验/测试、较大兼容性问题
   - P3:次要但明确可改的问题
5. 如果没有问题,summary 直接写:未检查到 PR #935 存在问题,并返回 findings=[]。
6. 如果有问题,summary 简洁概括,findings 里每条都要给出:
   - severity
   - title
   - body(说明为什么是问题,尽量具体)
   - file(尽量给相对路径)
   - line(能确定就填整数,否则 null)

建议先查看:
- git status --short
- git diff --stat origin/main...HEAD
- git diff --unified=80 origin/main...HEAD

最终输出必须严格匹配 JSON schema。

mcp startup: no servers
Reconnecting... 1/5 (unexpected status 403 Forbidden: {"code":"INSUFFICIENT_BALANCE","message":"Insufficient account balance"}, url: https://codex.0u0o.com/responses, cf-ray: a1af914d4c432a98-LAX, request id: f2678ef4-177d-4ef9-82eb-e71fc7f5fb4b)
Reconnecting... 2/5 (unexpected status 403 Forbidden: {"code":"INSUFFICIENT_BALANCE","message":"Insufficient account balance"}, url: https://codex.0u0o.com/responses, cf-ray: a1af91507cc4984e-LAX, request id: b0f74300-9c8b-4dae-b2c5-c895155de5bc)
Reconnecting... 3/5 (unexpected status 403 Forbidden: {"code":"INSUFFICIENT_BALANCE","message":"Insufficient account balance"}, url: https://codex.0u0o.com/responses, cf-ray: a1af91544c274896-LAX, request id: e131c8df-9ddb-451f-a834-d8aaed63eba7)
Reconnecting... 4/5 (unexpected status 403 Forbidden: {"code":"INSUFFICIENT_BALANCE","message":"Insufficient account balance"}, url: https://codex.0u0o.com/responses, cf-ray: a1af915b0d84d904-LAS, request id: 40aa96dd-57e5-4419-80ed-ea1b57aeceb8)
Reconnecting... 5/5 (unexpected status 403 Forbidden: {"code":"INSUFFICIENT_BALANCE","message":"Insufficient account balance"}, url: https://codex.0u0o.com/responses, cf-ray: a1af9165be950d83-LAX, request id: a3ebde42-6b43-493d-9772-2eaffd11eeae)
ERROR: unexpected status 403 Forbidden: {"code":"INSUFFICIENT_BALANCE","message":"Insufficient account balance"}, url: https://codex.0u0o.com/responses, cf-ray: a1af91799eb23efd-LAX, request id: d878a77c-3767-4e02-af93-70e60bf4ee6c
Warning: no last agent message; wrote empty content to /tmp/ptoas-pr-review-monitor/runs/20260714_174031_pr935/codex_last_message.json
===== END STAGE codex-review rc=1 @ 2026-07-14 17:40:51 =====

@jimmychou0 jimmychou0 changed the title fix(insert-sync): 修复复用本地内存的存储同步 fix(insert-sync): fix reuse ub insert sync bug Jul 14, 2026
@jimmychou0 jimmychou0 marked this pull request as ready for review July 14, 2026 06:48
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@jimmychou0

Copy link
Copy Markdown
Contributor Author

/run a3

@reedhecre

Copy link
Copy Markdown

已接收 /run a3,A3 板测器会处理这条请求。

页面会自动刷新,可以直接看当前阶段、排队情况和最近结果。

@zhangstevenunity zhangstevenunity left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review: correctness-focused. No blocking issues.

This is a sound, well-scoped fix for the #934 class of bug: PlanMemory (level2) reuses a UB physical range across two distinct pto.pointer_cast roots, and the old MemAlias gated cross-root aliasing on i64 address-SSA identity (via GetRealRoot). So a TSTORE's async MTE3 read of stored and a later V-pipe write to the reused range were judged non-aliasing and no MTE3 -> V handshake was inserted.

Why it's safe. The change is monotonic: it only adds alias edges.

  • For same-root inputs the new hasKnownPhysicalAddresses branch computes exactly the same isBufferAddressRangeOverlap the old same-root path did (adding the physical base to both sides is translation-invariant for the maxStart < minEnd overlap test), so results are identical.
  • The only behavioral delta is for different-root known-physical local pairs, where the old code always returned false (roots are distinct constant SSA -> GetRealRoot mismatch) and the new branch now returns a real range-overlap test.

So no previously-inserted sync is dropped, and the previously-missed cross-root overlaps are now caught. Placing the new branch before the rootBuffer == check is correct and necessary for the different-root case.

Fix reaches the real flow, not just the hand-written test. I traced the level2 lowering: AllocToPointerCast (in PTOPlanMemory) turns each memref.alloc into a single-address pto.pointer_cast whose operand is an arith.ConstantIntOp(_, 64) in vec space -- exactly the shape getKnownPhysicalAddress + isLocalAddressSpace recognize, so hasKnownPhysicalAddresses is set on the actual #934 buffers.

Regression test is valid. Without the fix, %stored(@1280, [1280,9472)) and %reused(@8192, [8192,16384)) have distinct constant roots -> old MemAlias returns false -> the set_flag/wait_flag(MTE3, V) lines are absent -> the CHECK-NEXT block fails. CI build-and-test (full lit) is green, so it passes with the fix and the existing suite is unaffected -- including multi_tile_const_slot_disjoint_sync.pto, whose disjoint slots stay disjoint under physical-range comparison (that test now passes for the right reason: range-disjointness rather than root-mismatch).

Note: I could not build/run locally to independently confirm the "fails without the fix" half -- the repo now requires LLVM 21 (post-PR796) and only an LLVM 19 prebuilt is available here -- so that half rests on the static reasoning above plus green CI.


Non-blocking observations

2. Coverage. The committed test deliberately hand-models the lowered form at --pto-level=level3 to preserve the explicit addresses (PlanMemory would otherwise reassign them). There is no end-to-end level2 test that lets PlanMemory actually create the reuse, and vpto-sim-validation / remote-npu-validation are skipped, so the real #934 numeric fix rests on the manual check quoted in the PR body ("k path becomes TSTORE -> set_flag(MTE3,V) -> wait_flag -> TMUL"). A level2 repro-derived test would harden this against future changes to PlanMemory's lowering shape.

4. Nit. BaseMemInfo::operator== (SyncCommon.h:116) was not extended with the new field. It is inert today -- the flag is a deterministic function of scope + baseAddresses, both already compared, so two infos cannot differ only in the flag -- but it is a latent footgun if the flag's derivation ever diverges from those inputs.

Overall: correct, minimal, and in the safe direction. LGTM modulo the optional symmetry/coverage items (see inline comments for 1 and 3).

return static_cast<uint64_t>(address);
}

static bool isLocalAddressSpace(pto::AddressSpace space) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Asymmetric coverage: alloc_tile(addr) never gets hasKnownPhysicalAddresses.

These two helpers are only wired into the pointer_cast path. But UpdateAllocTileOpMemInfo (line ~461) already extracts the constant address into baseAddresses (baseAddr), yet constructs its BaseMemInfo with the default hasKnownPhysicalAddresses = false.

At --pto-level=level3 PlanMemory is skipped and every pto.alloc_tile must carry an explicit addr (enforced in ptoas.cpp), and those ops survive to InsertSync -- lowerAllocTileOps in PTOViewToMemref.cpp:942 is [[maybe_unused]] and never called, and the translator has a live AllocTileOp handler. So two distinct level3 alloc_tiles that share or overlap a physical UB range would still miss exactly the cross-root MTE3 -> V handshake this PR adds for pointer_cast.

This is pre-existing and not a regression -- but for symmetry consider routing the same getKnownPhysicalAddress / isLocalAddressSpace treatment through UpdateAllocTileOpMemInfo so the reuse-race class is closed for both local-alloc materializations.

llvm::errs() << " -> Comparing known physical local ranges.\n";
if (a->baseAddresses.empty() || b->baseAddresses.empty())
return true;
if (a->allocateSize == 0 || b->allocateSize == 0)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

allocateSize == 0 now over-approximates cross-root.

When a known-physical local pto.pointer_cast has a dynamic shape, sizeInBytes stays 0, so allocateSize == 0 and this guard returns true -- meaning it aliases every known-physical buffer in the same address space, across roots. The old root-identity path returned false for such a buffer against a different root.

Direction is safe (more syncs, never fewer), but it is coarser than the previous behavior and, under event-id pressure, can turn into extra PIPE_ALL barriers. Low priority; flagging so it is a conscious tradeoff rather than an accident.

@reedhecre

Copy link
Copy Markdown

A3 板测完成(有跳过)

  • 触发方式:manual
  • 源码提交:3a564233a185
  • 结果汇总:OK 221 / FAIL 0 / SKIP 2
  • 日志:/home/zhongxuan/ptoas-board-monitor/runtime/logs/20260713_235911_manual_pr935.log
  • 结果 TSV:/home/zhongxuan/ptoas-board-monitor/runtime/logs/20260713_235911_manual_pr935.tsv
  • 手动指令:/run a3
  • 触发人:jimmychou0
  • 触发评论:fix(insert-sync): fix reuse ub insert sync bug #935 (comment)

@jimmychou0 jimmychou0 marked this pull request as draft July 14, 2026 09:36
@jimmychou0 jimmychou0 marked this pull request as ready for review July 14, 2026 09:36
@jimmychou0

Copy link
Copy Markdown
Contributor Author

/run a3

@reedhecre

Copy link
Copy Markdown

已接收 /run a3,A3 板测器会处理这条请求。

页面会自动刷新,可以直接看当前阶段、排队情况和最近结果。

@reedhecre

Copy link
Copy Markdown

A3 板测完成(有跳过)

  • 触发方式:manual
  • 源码提交:77166d99ca9a
  • 结果汇总:OK 221 / FAIL 0 / SKIP 2
  • 日志:/home/zhongxuan/ptoas-board-monitor/runtime/logs/20260714_233707_manual_pr935.log
  • 结果 TSV:/home/zhongxuan/ptoas-board-monitor/runtime/logs/20260714_233707_manual_pr935.tsv
  • 手动指令:/run a3
  • 触发人:jimmychou0
  • 触发评论:fix(insert-sync): fix reuse ub insert sync bug #935 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] PlanMemory (level2) reuses a live tile's UB range for a row_sum tmp without a store→vector sync → data race corrupts the output

3 participants