Skip to content

fix(extractor): recognize DP old→new subscription rotation as paired (Closes #218)#230

Merged
PhysShell merged 3 commits into
mainfrom
claude/dp-rotation-218
Jul 11, 2026
Merged

fix(extractor): recognize DP old→new subscription rotation as paired (Closes #218)#230
PhysShell merged 3 commits into
mainfrom
claude/dp-rotation-218

Conversation

@PhysShell

Copy link
Copy Markdown
Owner

Что и зачем

Property-changed callback, который отвязывает ТОТ ЖЕ handler от старого значения и привязывает к новому при смене значения, ложно флагался как OWN001-утечка: экстрактор пара́ит -=/+= по переменной-источнику, поэтому += на new-половине (newCommand) выглядел непарным, хотя -= на old-половине (oldCommand) строкой выше — тот же rotation-slot. Живой подписки максимум одна. Самый подтверждённый FP-класс sweep'а #201: 3 репозитория, 6+ точек (MahApps CommandTriggerAction, MaterialDesign SmartHint, AvalonEdit margins).

Фикс — только в экстракторе, без изменений OwnIR: третий дизъюнкт releasedIsRotationPairedRelease — помечает += на new-половине как released, когда в ТОМ ЖЕ методе есть -= на old-половине с тем же event-member и handler, а (oldRecv, newRecv) — old/new-половины одного изменения. Ядро видит сбалансированный acquire/release и молчит. Новый факт не нужен, OWNIR_VERSION не бампается (переиспользую существующее поле released).

Тип изменения

  • fix — исправление бага (precision / FP)

Как проверено

  • python tests/run_tests.py — exit 0 (test_ownir 271/271)
  • ruff check . и mypy --strict на ownlang/ — clean / Success
  • локально через настоящий экстрактор (.NET 8 в env):
BEFORE (baseline, current main): DpRotationSample.cs -> 5 findings (все флагнуты — это FP)
AFTER  (с фиксом):               DpRotationSample.cs -> 3 findings
  silent : CommandTriggerAction (form 1, e.OldValue/e.NewValue), AbstractMargin (form 2, OnXChanged(old,new))
  flagged: MismatchedHandlerRotation (a), UnrelatedPairRotation (b), TwoFieldsRotation (c)
regression: diff старого и нового экстрактора по всем 32 существующим сэмплам — БАЙТ-В-БАЙТ идентичен (0 регрессий)

Две распознаваемые формы

  1. DP-callbackoldRecv/newRecv привязаны из DependencyPropertyChangedEventArgs e.OldValue/e.NewValue: напрямую, или через e.OldValue is T old / (T)e.OldValue / var old = e.OldValue.
  2. Виртуальный override OnXChanged(T old, T new) — два параметра одного типа, old перед new (матч по паре параметров, НЕ по имени метода).

Не перерасширяет (обязательные негативные контроли — остаются флагнутыми)

  • (a) += с хендлером, ОТЛИЧНЫМ от -= → реальная непарная подписка.
  • (b) пара на двух параметрах РАЗНОГО типа (не old/new-половины одного значения).
  • (c) -= на одном поле класса, += на другом → две независимые подписки.

Существующий paired-случай (-=/+= на ОДНОМ источнике) не затронут — он идёт через прежний per-variable unsub-матч.

Связанные issue

Closes #218. Найден sweep'ом #201 (docs/notes/oracle-sweep-2026-07-10.md), каталогизирован как field-notes-patterns.md запись 11 (помечена shipped).

План валидации на живых репозиториях (после мержа — отдельной задачей)

Фикс запинен на синтетическом сэмпле; подтверждение на реальном коде — перегнать oracle-sweep по трём репо-первоисточникам и показать дельту FP:

  • MahApps.MetroActions/CommandTriggerAction.cs:102-117 (OnCommandChanged, CanExecuteChanged old→new) должен уйти из own-only.
  • MaterialDesignInXamlToolkitSmartHint.cs:189-209 (4 находки: IsVisibleChanged/ContentChanged/Loaded/FocusedChanged) должны уйти.
  • AvalonEditAbstractMargin.cs:92-101, LineNumberMargin.cs:105-118, Folding/FoldingMargin.cs (виртуальный OnTextViewChanged(old,new)) должны уйти.
  • Ожидаемая дельта: −6+ FP в own-only, при этом ни одна ранее-подтверждённая настоящая находка не исчезает (проверить, что общий leak-count по репо падает ровно на число rotation-точек). Сама перегонка — вне этого PR (нужен клон репозиториев в sweep-окружении).

Чеклист

  • изменение покрыто тестом/сэмплом + CI-ассертами в обе стороны (silent + flagged)
  • README/docs обновлены (field-notes-patterns.md запись 11 → shipped)
  • коммиты в conventional-commit стиле (fix:)

🤖 Generated with Claude Code


Generated by Claude Code

…218)

A property-changed callback that detaches the SAME handler from the OLD value
and re-attaches it to the NEW one across a value change was false-flagged as an
OWN001 leak: the extractor pairs `-=`/`+=` per source VARIABLE, so the `+=` on
the new half (`newCommand`) looked unpaired even though the `-=` on the old half
(`oldCommand`) a few lines up is the same rotation slot — at most one
subscription is ever live. Confirmed FP in 3 real repos, 6+ call sites (MahApps
CommandTriggerAction, MaterialDesign SmartHint, AvalonEdit margins); the single
most-corroborated false-positive class from the issue #201 oracle sweep.

Fix (extractor-only, no OwnIR change): a third `released` disjunct,
IsRotationPairedRelease, stamps the `+=` on the new half as released when the
same method holds a `-=` on the old half with the same event member and handler,
and (oldRecv, newRecv) are the old/new halves of one change — either bound from a
DependencyPropertyChangedEventArgs OldValue/NewValue (directly or via
`is`-pattern / cast / assignment), or two same-type parameters of the enclosing
method with old before new (the OnXChanged(old, new) override, matched by the
param-pair shape, not the method name). The core then sees a balanced
acquire/release and stays silent. No new fact, no OWNIR_VERSION bump — it reuses
the existing `released` field.

Precision-first, does not over-widen — three negative controls stay flagged:
(a) a `+=` with a different handler than the `-=`; (b) a pair on two
differently-typed params (not old/new halves); (c) a pair across two class fields.

Sample DpRotationSample.cs pins both forms silent and all three controls flagged,
wired into the wpf-extractor CI job. field-notes entry 11 marked shipped.

Verified locally with the real extractor (.NET 8): the sample goes 5 findings ->
3 (2 rotations silenced, 3 controls flagged); a full-sample-set diff of old vs
new extractor output is byte-identical (zero regression on existing findings).
Gates: run_tests.py exit 0, test_ownir 271/271, ruff clean, mypy --strict green.

Closes #218

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cg6DVXahkyY68Ruu7f76rG
if (e.OldValue is ICommand oldCommand)
oldCommand.CanExecuteChanged -= self.HandlerA; // unsub OLD with HandlerA
if (e.NewValue is ICommand newCommand)
newCommand.CanExecuteChanged += self.HandlerB; // sub NEW with HandlerB (different!) -> LEAK
private void Wire(ICommand primary, IOtherCommand secondary)
{
primary.CanExecuteChanged -= Handler; // unsub on primary (ICommand)
secondary.CanExecuteChanged += Handler; // sub on secondary (IOtherCommand — different type) -> LEAK
private void Swap()
{
_a.CanExecuteChanged -= Handler; // unsub on field _a
_b.CanExecuteChanged += Handler; // sub on field _b (not an old/new pair) -> LEAK
@coderabbitai

coderabbitai Bot commented Jul 11, 2026

Copy link
Copy Markdown

Warning

Review limit reached

@PhysShell, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 36 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: a8413c6c-d596-4d65-b70f-e1952d836584

📥 Commits

Reviewing files that changed from the base of the PR and between 53c3299 and 2ad7dc9.

📒 Files selected for processing (4)
  • .github/workflows/ci.yml
  • docs/notes/field-notes-patterns.md
  • frontend/roslyn/OwnSharp.Extractor/Program.cs
  • frontend/roslyn/samples/DpRotationSample.cs
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/dp-rotation-218

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 28b7ea0747

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +527 to +528
if (IsDpValueAccess(oldRecv, "OldValue") && IsDpValueAccess(newRecv, "NewValue"))
return true;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Strip casts before recognizing direct DP receivers

When the callback subscribes directly on a cast DP value, e.g. ((ICommand)e.NewValue).CanExecuteChanged += ... paired with ((ICommand)e.OldValue)... -= ..., the receiver passed here is a parenthesized/cast expression rather than the e.NewValue member access, so IsDpValueAccess returns false and the new rotation exemption is not applied. Since DependencyPropertyChangedEventArgs.OldValue/NewValue are object-typed, this direct-cast form is a common way to write the exact old→new rotation this change is meant to silence; use the existing StripCasts before this direct check so those balanced callbacks do not keep reporting OWN001.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Good catch — fixed in e942b95. You're right that this was a real gap: OldValue/NewValue are object-typed, so the inline form must cast, and the direct-check receiver was a parenthesized cast that IsDpValueAccess rejected. (My sample only covered the is-pattern form, which resolves via BoundFromDpValue, so the direct path was untested.)

StripCasts is now applied to both receivers before the direct check, and it also peels the null-forgiving !, so ((ICommand)e.NewValue!).CanExecuteChanged += H paired with the OldValue -= is recognised. Pinned by a new InlineCastRotation fixture (silent) wired into the CI silent-rotation assertion; the three negative controls still stay flagged and a full existing-sample diff is byte-identical (zero regression).


Generated by Claude Code

…eck (#218)

Codex review catch. The direct old/new form matched a bare `e.OldValue`/`e.NewValue`
member-access receiver, but DependencyPropertyChangedEventArgs.OldValue/NewValue are
object-typed, so the inline form MUST cast: `((ICommand)e.NewValue!).CanExecuteChanged
+= H`. There the `+=` receiver is a parenthesized cast, so IsDpValueAccess returned
false and the rotation stayed wrongly flagged. StripCasts (now also peeling the
null-forgiving `!`) is applied before the direct check, so the inline-cast rotation —
a common way to write this idiom — is recognised. The `is`-pattern / local-binding
forms already worked via BoundFromDpValue.

Pinned by a new InlineCastRotation class in DpRotationSample.cs (silent), added to the
CI silent-rotation assertion. Verified locally: the sample's three rotation forms
(pattern-cast, inline-cast, virtual-override) are all silent; the three controls stay
flagged; a full existing-sample diff is byte-identical (zero regression).

Refs #218

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cg6DVXahkyY68Ruu7f76rG
@github-actions

Copy link
Copy Markdown

@coderabbitai review

Both sides appended to the same wpf-extractor job tail: main's #215
[OwnIgnore] block (sample, assertions, SARIF rc-capture step) and this
branch's #218 rotation block (sample, silent + three flagged controls).
Kept both, single merged OK line. Program.cs auto-merged (additive).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LsWw4Ay8KLTHFom1HvRu3U
@PhysShell
PhysShell merged commit 0748800 into main Jul 11, 2026
37 checks passed
PhysShell pushed a commit that referenced this pull request Jul 12, 2026
Lines starting with "#201)" / "#230/#231" after a soft wrap read as
malformed ATX headings to markdownlint. No content change.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01D6Naf8CcezjCbikueKdeYv
PhysShell added a commit that referenced this pull request Jul 12, 2026
docs: verify #230/#231 precision-gap fixes against 2026-07-10 oracle sweep
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.

Precision gap: DependencyProperty/property-changed old→new subscription rotation flagged as a leak

3 participants