Skip to content

feat(react): add element template alog diagnostics#2633

Merged
HuJean merged 2 commits into
lynx-family:mainfrom
Yradex:wt/et-alog-debug
May 14, 2026
Merged

feat(react): add element template alog diagnostics#2633
HuJean merged 2 commits into
lynx-family:mainfrom
Yradex:wt/et-alog-debug

Conversation

@Yradex
Copy link
Copy Markdown
Collaborator

@Yradex Yradex commented May 14, 2026

Summary by CodeRabbit

  • New Features

    • Enhanced debug logging and profiling for element-template APIs, with optional runtime enablement via a flag.
    • Event handling now emits structured debug output (when enabled) including event metadata and handler info.
  • Tests

    • Added robust tests covering profiling on/off, missing-API scenarios, error propagation, and event-logging behavior.
  • Chores

    • Updated event payload typing to improve runtime consistency.

Review Change Stack

Overview

Adds Element Template-only diagnostic logging behind the existing ALog flags so native PAPI calls and background event dispatch can be inspected without adding a private debug publish hook or touching Snapshot wiring.

Key Points

  • REACT_ALOG_ELEMENT_API installs an ET native PAPI wrapper from the ET native entry, covering create/set/insert/remove/serialize calls with readable template ref labels.
  • REACT_ALOG logs background event dispatch metadata after handler lookup: eventValue, event type, resolved handler name, and whether a handler exists.
  • The change keeps Snapshot untouched and does not expose __etDebugPublishEvent or new public runtime exports.

Checklist

  • Tests updated (or not required).
  • Documentation updated (or not required).
  • Changeset added, and when a BREAKING CHANGE occurs, it needs to be clearly marked (or not required).

@changeset-bot
Copy link
Copy Markdown

changeset-bot Bot commented May 14, 2026

⚠️ No Changeset found

Latest commit: 64a00d9

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 14, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: a1ac4160-9894-496c-a6ee-a3ddcbc2ffe0

📥 Commits

Reviewing files that changed from the base of the PR and between f3ec203 and 64a00d9.

📒 Files selected for processing (3)
  • packages/react/runtime/__test__/element-template/debug/elementPAPICall.test.ts
  • packages/react/runtime/src/element-template/debug/elementPAPICall.ts
  • packages/react/runtime/src/element-template/prop-adapters/event.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/react/runtime/src/element-template/debug/elementPAPICall.ts

📝 Walkthrough

Walkthrough

Adds an ALOG wrapper for ElementTemplate PAPI calls (with optional profiling and formatted logging), gates it in native init via __ALOG_ELEMENT_API__, and adds guarded event-dispatch logging and typings (EventDataType). Tests cover normal, missing-API, and error scenarios.

Changes

ElementTemplate and Event ALOG Debug Logging

Layer / File(s) Summary
ElementTemplate PAPI wrapper and formatter
packages/react/runtime/src/element-template/debug/elementPAPICall.ts, packages/react/runtime/__test__/element-template/debug/elementPAPICall.test.ts
initElementTemplatePAPICallAlog wraps ElementTemplate PAPI functions on a provided global-like object, optionally starts/ends profiling, maps __CreateElementTemplate return objects to identifiers, and logs calls/results via console.alog. Adds formatValue for safe log serialization. Tests validate forwarding, formatted logs, profiling counts, missing-API behavior, and exception cleanup.
PAPI logging integration into native initialization
packages/react/runtime/src/element-template/native/index.ts, packages/react/runtime/__test__/element-template/native/index.test.ts
Native init() conditionally calls initElementTemplatePAPICallAlog() when __ALOG_ELEMENT_API__ is truthy. Tests manage globalThis.__ALOG_ELEMENT_API__, mock the debug initializer, and assert it is invoked once during main-thread wiring.
Event dispatch logging and typing
packages/react/runtime/src/element-template/prop-adapters/event.ts, packages/react/runtime/__test__/element-template/runtime/prop-adapters/event.test.ts
Event handler type signatures changed to use EventDataType; dispatchEvent emits guarded console.alog with event diagnostics when __ALOG__ is enabled. Tests added for logging-on and logging-off scenarios while ensuring handlers still receive events.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

framework:React

Suggested reviewers

  • hzy
  • HuJean

Poem

🐰 I peeked at PAPI calls tonight,
Wrapping args so logs look right.
Templates named, events in tow,
Profiles start and profiles go—
A tiny rabbit hums: debug delight.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat(react): add element template alog diagnostics' accurately reflects the main change: introducing ALog diagnostic logging capabilities for Element Template PAPI calls and event dispatch.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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 and usage tips.

@codecov
Copy link
Copy Markdown

codecov Bot commented May 14, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ All tests successful. No failed tests found.

📢 Thoughts on this report? Let us know!

@Yradex Yradex marked this pull request as ready for review May 14, 2026 07:17
@Yradex Yradex requested review from HuJean and hzy as code owners May 14, 2026 07:17
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
packages/react/runtime/src/element-template/debug/elementPAPICall.ts (1)

15-17: Consider memory implications of unbounded template map growth.

The elementTemplateMap (line 17) grows without bounds as templates are created. For long-running debug sessions with frequent template creation, this could accumulate significant memory. Since this is debug-only code gated behind __ALOG_ELEMENT_API__, the impact is limited to development environments, but it's worth noting for operational awareness.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/react/runtime/src/element-template/debug/elementPAPICall.ts` around
lines 15 - 17, The elementTemplateMap in initElementTemplatePAPICallAlog can
grow unbounded; switch to a memory-safe structure or cap its size: either
replace the Map<unknown,string> with a WeakMap<object,string> (use when template
keys are objects so entries can be GC'd) or add a bounded cache/eviction (LRU or
simple maxEntries prune) in the initElementTemplatePAPICallAlog function to
prevent unbounded growth while preserving existing lookup behavior.
packages/react/runtime/src/element-template/prop-adapters/event.ts (1)

14-29: ⚡ Quick win

Consider adding error handling around JSON.stringify.

If data contains circular references or non-serializable values, JSON.stringify will throw and prevent the event from dispatching. While this is debug-only code, it could disrupt testing or debugging sessions.

🛡️ Defensive coding suggestion
   if (typeof __ALOG__ !== 'undefined' && __ALOG__) {
-    console.alog?.(
-      `[ReactLynxDebug] ElementTemplate BTS received event:\n${
-        JSON.stringify(
-          {
-            eventValue,
-            type: (data as { type?: unknown } | null)?.type,
-            jsFunctionName: typeof handler === 'function' ? handler.name : '',
-            hasHandler: typeof handler === 'function',
-          },
-          null,
-          2,
-        )
-      }`,
-    );
+    try {
+      console.alog?.(
+        `[ReactLynxDebug] ElementTemplate BTS received event:\n${
+          JSON.stringify(
+            {
+              eventValue,
+              type: (data as { type?: unknown } | null)?.type,
+              jsFunctionName: typeof handler === 'function' ? handler.name : '',
+              hasHandler: typeof handler === 'function',
+            },
+            null,
+            2,
+          )
+        }`,
+      );
+    } catch {
+      console.alog?.(`[ReactLynxDebug] ElementTemplate BTS received event (stringify failed): ${eventValue}`);
+    }
   }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/react/runtime/src/element-template/prop-adapters/event.ts` around
lines 14 - 29, Wrap the debug JSON.stringify call in a try/catch so circular or
non-serializable data in eventValue/data doesn't throw and block dispatch;
inside the catch build a safe fallback string (include a short message and the
error.message) and still call console.alog. Update the block that checks
__ALOG__ and calls console.alog to use the safe-serialized payload for
eventValue, type ((data as { type?: unknown } | null)?.type),
jsFunctionName/hasHandler (handler) so the logger always runs even if
JSON.stringify fails.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/react/runtime/src/element-template/debug/elementPAPICall.ts`:
- Around line 26-53: The profiler may be left open if callElementTemplatePAPI
throws; wrap the call to callElementTemplatePAPI(...) and subsequent profiling
logic in a try/finally so that profileEnd() is always invoked when
profileStart(...) ran; specifically, in the
globalWithIndex[elementTemplatePAPIName] handler, call profileStart(...) before
invoking callElementTemplatePAPI, assign the result inside the try block, and
call profileEnd() in the finally block (still only when __PROFILE__ is enabled)
so that profileEnd is executed even on exceptions while preserving existing
behavior for elementTemplateMap, console.alog, and the returned result.

---

Nitpick comments:
In `@packages/react/runtime/src/element-template/debug/elementPAPICall.ts`:
- Around line 15-17: The elementTemplateMap in initElementTemplatePAPICallAlog
can grow unbounded; switch to a memory-safe structure or cap its size: either
replace the Map<unknown,string> with a WeakMap<object,string> (use when template
keys are objects so entries can be GC'd) or add a bounded cache/eviction (LRU or
simple maxEntries prune) in the initElementTemplatePAPICallAlog function to
prevent unbounded growth while preserving existing lookup behavior.

In `@packages/react/runtime/src/element-template/prop-adapters/event.ts`:
- Around line 14-29: Wrap the debug JSON.stringify call in a try/catch so
circular or non-serializable data in eventValue/data doesn't throw and block
dispatch; inside the catch build a safe fallback string (include a short message
and the error.message) and still call console.alog. Update the block that checks
__ALOG__ and calls console.alog to use the safe-serialized payload for
eventValue, type ((data as { type?: unknown } | null)?.type),
jsFunctionName/hasHandler (handler) so the logger always runs even if
JSON.stringify fails.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: d26f7009-afa5-41e1-9fcf-16f6e7942982

📥 Commits

Reviewing files that changed from the base of the PR and between 13a0776 and f3ec203.

📒 Files selected for processing (6)
  • packages/react/runtime/__test__/element-template/debug/elementPAPICall.test.ts
  • packages/react/runtime/__test__/element-template/native/index.test.ts
  • packages/react/runtime/__test__/element-template/runtime/prop-adapters/event.test.ts
  • packages/react/runtime/src/element-template/debug/elementPAPICall.ts
  • packages/react/runtime/src/element-template/native/index.ts
  • packages/react/runtime/src/element-template/prop-adapters/event.ts

upupming
upupming previously approved these changes May 14, 2026
Comment thread packages/react/runtime/src/element-template/prop-adapters/event.ts Outdated
Comment thread packages/react/runtime/src/element-template/prop-adapters/event.ts Outdated
@codspeed-hq
Copy link
Copy Markdown

codspeed-hq Bot commented May 14, 2026

Merging this PR will improve performance by ×4.2

⚠️ Different runtime environments detected

Some benchmarks with significant performance changes were compared across different runtime environments,
which may affect the accuracy of the results.

Open the report in CodSpeed to investigate

⚡ 1 improved benchmark
✅ 80 untouched benchmarks
⏩ 26 skipped benchmarks1

Performance Changes

Benchmark BASE HEAD Efficiency
basic-performance-large-css 68.5 ms 16.1 ms ×4.2

Tip

Curious why this is faster? Comment @codspeedbot explain why this is faster on this PR, or directly use the CodSpeed MCP with your agent.


Comparing Yradex:wt/et-alog-debug (64a00d9) with main (a973c54)

Open in CodSpeed

Footnotes

  1. 26 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports.

@relativeci
Copy link
Copy Markdown

relativeci Bot commented May 14, 2026

React External

#1315 Bundle Size — 693.04KiB (0%).

64a00d9(current) vs 66f6ecf main#1314(baseline)

Bundle metrics  no changes
                 Current
#1315
     Baseline
#1314
No change  Initial JS 0B 0B
No change  Initial CSS 0B 0B
No change  Cache Invalidation 0% 0%
No change  Chunks 0 0
No change  Assets 3 3
No change  Modules 17 17
No change  Duplicate Modules 5 5
No change  Duplicate Code 8.59% 8.59%
No change  Packages 0 0
No change  Duplicate Packages 0 0
Bundle size by type  no changes
                 Current
#1315
     Baseline
#1314
No change  Other 693.04KiB 693.04KiB

Bundle analysis reportBranch Yradex:wt/et-alog-debugProject dashboard


Generated by RelativeCIDocumentationReport issue

@relativeci
Copy link
Copy Markdown

relativeci Bot commented May 14, 2026

React MTF Example

#1334 Bundle Size — 207.46KiB (0%).

64a00d9(current) vs 66f6ecf main#1333(baseline)

Bundle metrics  no changes
                 Current
#1334
     Baseline
#1333
No change  Initial JS 0B 0B
No change  Initial CSS 0B 0B
No change  Cache Invalidation 0% 0%
No change  Chunks 0 0
No change  Assets 3 3
No change  Modules 192 192
No change  Duplicate Modules 77 77
No change  Duplicate Code 44.38% 44.38%
No change  Packages 2 2
No change  Duplicate Packages 0 0
Bundle size by type  no changes
                 Current
#1334
     Baseline
#1333
No change  IMG 111.23KiB 111.23KiB
No change  Other 96.23KiB 96.23KiB

Bundle analysis reportBranch Yradex:wt/et-alog-debugProject dashboard


Generated by RelativeCIDocumentationReport issue

@relativeci
Copy link
Copy Markdown

relativeci Bot commented May 14, 2026

React Example

#8201 Bundle Size — 236.51KiB (0%).

64a00d9(current) vs 66f6ecf main#8200(baseline)

Bundle metrics  no changes
                 Current
#8201
     Baseline
#8200
No change  Initial JS 0B 0B
No change  Initial CSS 0B 0B
No change  Cache Invalidation 0% 0%
No change  Chunks 0 0
No change  Assets 4 4
No change  Modules 197 197
No change  Duplicate Modules 80 80
No change  Duplicate Code 44.87% 44.87%
No change  Packages 2 2
No change  Duplicate Packages 0 0
Bundle size by type  no changes
                 Current
#8201
     Baseline
#8200
No change  IMG 145.76KiB 145.76KiB
No change  Other 90.75KiB 90.75KiB

Bundle analysis reportBranch Yradex:wt/et-alog-debugProject dashboard


Generated by RelativeCIDocumentationReport issue

@relativeci
Copy link
Copy Markdown

relativeci Bot commented May 14, 2026

Web Explorer

#9775 Bundle Size — 901.38KiB (0%).

64a00d9(current) vs a973c54 main#9764(baseline)

Bundle metrics  Change 2 changes
                 Current
#9775
     Baseline
#9764
No change  Initial JS 45.06KiB 45.06KiB
No change  Initial CSS 2.22KiB 2.22KiB
No change  Cache Invalidation 0% 0%
No change  Chunks 9 9
No change  Assets 11 11
Change  Modules 230(+0.44%) 229
No change  Duplicate Modules 11 11
Change  Duplicate Code 27.21%(-0.04%) 27.22%
No change  Packages 10 10
No change  Duplicate Packages 0 0
Bundle size by type  no changes
                 Current
#9775
     Baseline
#9764
No change  JS 497.1KiB 497.1KiB
No change  Other 402.06KiB 402.06KiB
No change  CSS 2.22KiB 2.22KiB

Bundle analysis reportBranch Yradex:wt/et-alog-debugProject dashboard


Generated by RelativeCIDocumentationReport issue

@relativeci
Copy link
Copy Markdown

relativeci Bot commented May 14, 2026

React Example with Element Template

#467 Bundle Size — 199.83KiB (0%).

64a00d9(current) vs 66f6ecf main#466(baseline)

Bundle metrics  Change 3 changes Regression 1 regression
                 Current
#467
     Baseline
#466
No change  Initial JS 0B 0B
No change  Initial CSS 0B 0B
No change  Cache Invalidation 0% 0%
No change  Chunks 0 0
No change  Assets 4 4
Change  Modules 88(+3.53%) 85
Regression  Duplicate Modules 26(+4%) 25
Change  Duplicate Code 40.03%(+0.15%) 39.97%
No change  Packages 2 2
No change  Duplicate Packages 0 0
Bundle size by type  no changes
                 Current
#467
     Baseline
#466
No change  IMG 145.76KiB 145.76KiB
No change  Other 54.08KiB 54.08KiB

Bundle analysis reportBranch Yradex:wt/et-alog-debugProject dashboard


Generated by RelativeCIDocumentationReport issue

@HuJean HuJean merged commit c516ac8 into lynx-family:main May 14, 2026
103 of 108 checks passed
@Yradex Yradex deleted the wt/et-alog-debug branch May 14, 2026 13:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants