Debugging Performance
Tracing
To help you debug performance issues, Valdi provides a cross-platform tracing API. You can insert your own traces in your TypeScript code to understand how long your call is taking. The framework also traces some key events by default, which are covered in the section below Framework events.
Recording traces
Using the Valdi Debugger
With a hot reloader connected to the application, run valdi debugger, attach
to a native target, and open Performance. The UI Performance card can
start and stop a renderer trace or capture a bounded interval of up to 15
seconds. Enable Renderer events to include component onRender() spans and
ViewModel-change triggers. Exported captures use Chrome Trace JSON and can be
opened in Perfetto UI. Native trace recording is
process-wide; the selected context is recorded as the capture target used to
reach the runtime, not as the origin of each trace event.
To keep debugger responses bounded before serialization, the native recorder retains at most 10,000 events, 2 KiB per trace name, and 1 MiB of aggregate trace-name data per active recording window. Capture results report how many events were dropped by those limits. Automatically stopped and recently completed results remain available for retry for one minute before they are discarded.
The debugger proxies these operations through /api/performance/trace/status,
start, stop, and capture; the application keeps ownership of the recorder,
so captures continue to work across the loopback debugger HTTP connection.
Web preview traces
When valdi debugger is attached to an exact loopback web preview, the
integrated DevTools Performance panel can sample navigation, resource, heap,
and main-thread metrics. It can also record one global Chromium trace at a
time. The timeline filters are Valdi, Browser, and All. Enabling
Valdi renderer events reloads the inspected page with the explicit tracing
query parameters; browser events remain available without that reload.
Web capture operations use the separate
/api/devtools/performance/trace/status, start, stop, capture, and
enable routes. They do not replace the daemon-backed /api/performance/*
routes described above. Every web request is bound to the exact inspected
sessionId, inspectedUrl, and per-tab targetNonce; a changed or incomplete
identity fails closed.
One-shot web captures run for their requested duration from 100 milliseconds through 15 seconds. Manually started recordings automatically stop after a 15-second watchdog. Normalization happens as CDP events arrive, retaining at most 10,000 events with trace names no larger than 2 KiB. The complete JSON response is limited to 4 MiB, and an automatically completed result remains retrievable for one minute. Responses contain the bounded normalized trace list and export metadata, not a second raw or Perfetto event list. The panel constructs Chrome Trace JSON only when you choose Export trace.
Please make sure to add //src/valdi_modules/src/valdi/benchmarking to the deps attribute of the valdi_module() call in your module's BUILD.bazel.
recordTracesWithTimeout()
This method works on iOS, Android and Desktop, and requires the hot reloader to be connected. You will need to insert a call to recordTracesWithTimeout() from TraceRecorder.ts at the appropriate time, which depends on what you are trying to debug. This call will make the runtime starts collecting traces, and store the result as a Chrome Trace file on your local machine that you can open using Perfetto UI.
For instance, if you wanted to understand what is happening during the creation of your root component, you could insert a recordTracesWithTimeout() as follow:
export class MyRootComponent extends Component {
onCreate() {
recordTracesWithTimeout(10000, '~/mytrace');
}
}
After 10 seconds, you should see a message in the console like Saved traces to ~/mytrace.trace. You can then open the file using Perfetto UI.
Using Android Systrace
This method works on Android only, and does not require the hot reloader to be connected. Valdi traces on Android are also emitted as Android systraces, which means you can use Android's scripts to start recording traces. You can find this script On Snapchat Android at snapchat/scripts/trace/start_trace.sh. The script will store the result as a html file on your local machine, which you can open using Perfetto.
Adding your own traces
All the following functions are from Trace.ts in the valdi_core module.
trace()
This function allows to trace a specific section of your code and pass an arbitrary string to identify it. Example:
function fn() {
trace('BuildSection', () => {
// Do some expensive work there
});
}
instantTrace()
This function records an instant event at the current time. Use it for point-in-time causes such as "this property scheduled a component render", where there is no duration to measure. On runtimes without instant events, it records a zero-length trace instead. Example:
function updateTitle() {
instantTrace('TitleChanged');
}
instantTraceWithArgs() attaches arguments, passed as alternating string keys and values: instantTraceWithArgs('TitleChanged', ['length', title.length]). Runtimes that don't support arguments drop them.
Tracing on Valdi Web
Tracing is disabled by default on Valdi Web. Configure a tracing implementation before creating the
ValdiWebRenderer to include the renderer's detailed trace events.
To show Valdi events on a dedicated track in the Chrome DevTools Performance panel:
import { createBrowserChromeDevToolsTracing } from 'web_renderer/src/tracing/ChromeDevToolsTracing';
import { setValdiWebTracing } from 'web_renderer/src/tracing/ValdiWebTracing';
setValdiWebTracing(createBrowserChromeDevToolsTracing());
In development you can skip the code: loading the page with ?valdiDevTools=1&valdiTrace=chrome makes
ValdiWebRenderer install the same tracer. This is how the Valdi debugger enables renderer events.
Enable Show custom tracks in the Chrome DevTools Performance panel capture settings before recording.
This implementation uses Chrome's extended console.timeStamp() API and does not retain entries when the
Performance panel is not recording.
For standard browser Performance Timeline entries, use PerformanceTimelineTracing instead:
import { PerformanceTimelineTracing } from 'web_renderer/src/tracing/PerformanceTimelineTracing';
import { setValdiWebTracing } from 'web_renderer/src/tracing/ValdiWebTracing';
setValdiWebTracing(new PerformanceTimelineTracing());
Performance Timeline entries are retained until they are explicitly cleared or the page is unloaded. Disable
future Valdi Web traces by calling setValdiWebTracing(undefined).
You can provide your own implementation by implementing the ValdiWebTracing interface and passing it to
setValdiWebTracing().
@Trace annotation
This annotation can be put on a TypeScript class, and will make all its methods automatically traced. Traced methods using the annotation have lower overhead than the trace() function, and they can be thus put on hot code paths.
Example:
@Trace
class MyClass {
// This method will be traced automatically as MyClass.aMethod when called
aMethod() {
// Do some work here
}
}
@TraceMethod annotation
This annotation can be put on a single method in a TypeScript class. It is similar to @Trace, but is meant to trace a single function instead of all the functions of a class.
Example:
class MyClass {
// This method will be traced as MyClass.aMethod when called
@TraceMethod
aMethod() { }
}
installTraceProxy()
The function takes a TypeScript class as its parameter, and will make all its methods automatically traced. It is used by the @Trace annotation under the hood. You can use this to inject traces in classes that already exist or are defined in files on which you don't have control on. If you wanted to trace the Renderer calls, as to see what is happening during rendering, you could do this:
// Will make all the methods of Renderer to be be shown in tracing
installTraceProxy(Renderer);
Framework events
The Valdi runtime traces some default important events that happens during the lifecycle of your component. This section explains some of them:
Valdi.processRenderRequest: TypeScript rendering has completed, and the framework is now processing the request to update the nodes. Every time a render happens at the TypeScript level, if the render has made any changes, a render request will be emitted that will end up being processed by the runtime. This is where the Valdi C++ runtime syncs its internal state with the state of the nodes in TypeScript.
The Valdi runtime uses Source Maps to symbolicate stack traces in the JavaScript engine. This ensures that performance traces and error reports provide meaningful information about your TypeScript code, even when running minified or compiled bytecode.
Valdi.updateViewTree: The framework is going through the nodes and updating the view hierarchy to reflect the changes. This is where the backing views of the nodes are created/destroyed/recycled. This pass might happen after processing a render request, or when scrolling.Valdi.setUserDefinedViewport: The framework is reacting to a scroll change.Valdi.updateVisibility: The framework is resolving the viewports for the nodes. It is finding out which nodes are visible and which nodes are not visible on the screen.Valdi.calculateLayout: The framework is calculating the frames (rectangles) for the nodes. This can happen because nodes have been inserted/removed, because a layout attribute has changed (likepadding), or because the available space for the root component has changed (for instance if the window has been resized). This can be an expensive operation. Because of this, you should avoid triggering changes in the elements that will cause a layout pass to happen when scrolling. If you need to move elements or show/hide them when scrolling, prefer using thetranslationX/translationYattributes oropacitywhich are not layout attributes and don't trigger layout passes when they change.