Avoid heap allocations when serializing sampling profile (#51028)

Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/51028

# Changelog: [Internal]

There is a way to implement the trie without allocating `ProfileTreeNode` on the heap. The serialization logic (`RuntimeSamplingProfilerTraceEventSerializer.cpp`) remained mostly the same, the only new limitation is that we can only use pointer to `ProfileTreeNode` until the next push into a `children` container, when all pointers are invalidated. Not sure if we can avoid this invalidation, since we don't know the potential size of `children` vector, it has to be dynamically allocated.

Main changes are in `ProfileTreeNode`:
- Instead of receving already created instane that will be check if it should be added as a child, it will expose predicate to check if such node already exists - `getIfAlreadyExists`. If not, then caller can use `addChild` to register it and receive a pointer.

Reviewed By: huntie

Differential Revision: D73213284

fbshipit-source-id: 385be884bcc5feb61b3a8cbd0ff36402e3b20c6c
This commit is contained in:
Ruslan Lesiutin authored and Facebook GitHub Bot committed 2025-05-01 00:22:44 -07:00
1 parent c09340e73e
commit a5f2acde20
4 files changed
+119 -154

No files matched your search

@@ -7,7 +7,6 @@
#pragma once
#include <memory>
#include <utility>
#include <jsinspector-modern/tracing/RuntimeSamplingProfile.h>
@@ -28,14 +27,16 @@ class ProfileTreeNode {
Other,
};
static constexpr uint32_t NO_PARENT = UINT32_MAX;
ProfileTreeNode(
uint32_t id,
CodeType codeType,
std::shared_ptr<ProfileTreeNode> parent,
RuntimeSamplingProfile::SampleCallStackFrame callFrame)
RuntimeSamplingProfile::SampleCallStackFrame callFrame,
uint32_t parentId = NO_PARENT)
: id_(id),
codeType_(codeType),
parent_(parent),
parentId_(parentId),
callFrame_(std::move(callFrame)) {}
uint32_t getId() const {
@@ -46,11 +47,12 @@ class ProfileTreeNode {
return codeType_;
}
/**
* \return pointer to the parent node, nullptr if this is the root node.
*/
ProfileTreeNode* getParent() const {
return parent_.get();
inline bool hasParent() const {
return parentId_ != NO_PARENT;
}
uint32_t getParentId() const {
return parentId_;
}
/**
@@ -61,36 +63,37 @@ class ProfileTreeNode {
}
/**
* Will only add unique child node.
* \return shared pointer to the already existing child node, nullptr if the
* added child node is unique.
* \return a pointer if the node already contains a child with the same
* codeType and callFrame, nullptr otherwise.
*/
std::shared_ptr<ProfileTreeNode> addChild(
std::shared_ptr<ProfileTreeNode> child) {
for (const auto& existingChild : children_) {
if (*existingChild == child.get()) {
return existingChild;
ProfileTreeNode* getIfAlreadyExists(
CodeType childCodeType,
const RuntimeSamplingProfile::SampleCallStackFrame& childCallFrame) {
for (auto& existingChild : children_) {
if (existingChild.getCodeType() == childCodeType &&
existingChild.getCallFrame() == childCallFrame) {
return &existingChild;
}
}
children_.push_back(child);
return nullptr;
}
bool operator==(const ProfileTreeNode* rhs) const {
if (this->parent_ != rhs->parent_) {
return false;
}
if (this->codeType_ != rhs->codeType_) {
return false;
}
return this->getCallFrame() == rhs->getCallFrame();
/**
* Creates a ProfileTreeNode and links it as a child to this node.
* \return a pointer to the child node.
*/
ProfileTreeNode* addChild(
uint32_t childId,
CodeType childCodeType,
RuntimeSamplingProfile::SampleCallStackFrame childCallFrame) {
return &children_.emplace_back(
childId, childCodeType, std::move(childCallFrame), id_);
}
private:
/**
* Unique id of the node.
* Unique id of the node.
*/
uint32_t id_;
/**
@@ -99,13 +102,14 @@ class ProfileTreeNode {
*/
CodeType codeType_;
/**
* Shared pointer to the parent node. Can be nullptr only for root node.
* Unique id of the parent node. NO_PARENT if this is root node.
*/
std::shared_ptr<ProfileTreeNode> parent_;
uint32_t parentId_;
/**
* Lst of shared pointers to children nodes.
* List of children nodes, should be unique by codeType and callFrame among
* each other.
*/
std::vector<std::shared_ptr<ProfileTreeNode>> children_;
std::vector<ProfileTreeNode> children_;
/**
* Information about the corresponding call frame that is represented by this
* node.
@@ -14,12 +14,12 @@ namespace {
// Right now we only emit single Profile. We might revisit this decision in the
// future, once we support multiple VMs being sampled at the same time.
const uint16_t PROFILE_ID = 1;
constexpr uint16_t PROFILE_ID = 1;
/// Fallback script ID for artificial call frames, such as (root), (idle) or
/// (program). Required for emulating the payload in a format that is expected
/// by Chrome DevTools.
const uint32_t FALLBACK_SCRIPT_ID = 0;
constexpr uint32_t FALLBACK_SCRIPT_ID = 0;
uint64_t formatTimePointToUnixTimestamp(
std::chrono::steady_clock::time_point timestamp) {
@@ -29,15 +29,13 @@ uint64_t formatTimePointToUnixTimestamp(
}
TraceEventProfileChunk::CPUProfile::Node convertToTraceEventProfileNode(
std::shared_ptr<ProfileTreeNode> node) {
ProfileTreeNode* nodeParent = node->getParent();
const ProfileTreeNode& node) {
const RuntimeSamplingProfile::SampleCallStackFrame& callFrame =
node->getCallFrame();
node.getCallFrame();
auto traceEventCallFrame =
TraceEventProfileChunk::CPUProfile::Node::CallFrame{
node->getCodeType() == ProfileTreeNode::CodeType::JavaScript
? "JS"
: "other",
node.getCodeType() == ProfileTreeNode::CodeType::JavaScript ? "JS"
: "other",
callFrame.getScriptId(),
callFrame.getFunctionName(),
callFrame.hasUrl() ? std::optional<std::string>(callFrame.getUrl())
@@ -50,10 +48,10 @@ TraceEventProfileChunk::CPUProfile::Node convertToTraceEventProfileNode(
: std::nullopt};
return TraceEventProfileChunk::CPUProfile::Node{
node->getId(),
node.getId(),
traceEventCallFrame,
nodeParent != nullptr ? std::optional<uint32_t>(nodeParent->getId())
: std::nullopt};
node.hasParent() ? std::optional<uint32_t>(node.getParentId())
: std::nullopt};
}
RuntimeSamplingProfile::SampleCallStackFrame createArtificialCallFrame(
@@ -71,42 +69,14 @@ RuntimeSamplingProfile::SampleCallStackFrame createGarbageCollectorCallFrame() {
"(garbage collector)"};
};
std::shared_ptr<ProfileTreeNode> createNode(
NodeIdGenerator& nodeIdGenerator,
ProfileTreeNode::CodeType codeType,
std::shared_ptr<ProfileTreeNode> parent,
const RuntimeSamplingProfile::SampleCallStackFrame& callFrame) {
return std::make_shared<ProfileTreeNode>(
nodeIdGenerator.getNext(), codeType, parent, callFrame);
}
std::shared_ptr<ProfileTreeNode> createArtificialNode(
NodeIdGenerator& nodeIdGenerator,
std::shared_ptr<ProfileTreeNode> parent,
std::string callFrameName) {
RuntimeSamplingProfile::SampleCallStackFrame callFrame =
createArtificialCallFrame(std::move(callFrameName));
return createNode(
nodeIdGenerator, ProfileTreeNode::CodeType::Other, parent, callFrame);
}
std::shared_ptr<ProfileTreeNode> createRootNode(
NodeIdGenerator& nodeIdGenerator) {
return createArtificialNode(nodeIdGenerator, nullptr, "(root)");
}
std::shared_ptr<ProfileTreeNode> createProgramNode(
NodeIdGenerator& nodeIdGenerator,
std::shared_ptr<ProfileTreeNode> rootNode) {
return createArtificialNode(nodeIdGenerator, rootNode, "(program)");
}
std::shared_ptr<ProfileTreeNode> createIdleNode(
NodeIdGenerator& nodeIdGenerator,
std::shared_ptr<ProfileTreeNode> rootNode) {
return createArtificialNode(nodeIdGenerator, rootNode, "(idle)");
}
class ProfileTreeRootNode : public ProfileTreeNode {
public:
explicit ProfileTreeRootNode(uint32_t id)
: ProfileTreeNode(
id,
CodeType::Other,
createArtificialCallFrame("(root)")) {}
};
} // namespace
@@ -159,36 +129,37 @@ void RuntimeSamplingProfileTraceEventSerializer::bufferProfileChunkTraceEvent(
void RuntimeSamplingProfileTraceEventSerializer::processCallStack(
const std::vector<RuntimeSamplingProfile::SampleCallStackFrame>& callStack,
ProfileChunk& chunk,
std::shared_ptr<ProfileTreeNode> rootNode,
std::shared_ptr<ProfileTreeNode> idleNode,
ProfileTreeNode& rootNode,
uint32_t idleNodeId,
long long samplesTimeDelta,
NodeIdGenerator& nodeIdGenerator) {
if (callStack.empty()) {
chunkEmptySample(chunk, idleNode->getId(), samplesTimeDelta);
chunkEmptySample(chunk, idleNodeId, samplesTimeDelta);
return;
}
auto previousNode = rootNode;
ProfileTreeNode* previousNode = &rootNode;
for (auto it = callStack.rbegin(); it != callStack.rend(); ++it) {
const RuntimeSamplingProfile::SampleCallStackFrame& callFrame = *it;
bool isGarbageCollectorFrame = callFrame.getKind() ==
RuntimeSamplingProfile::SampleCallStackFrame::Kind::GarbageCollector;
ProfileTreeNode::CodeType childCodeType = isGarbageCollectorFrame
? ProfileTreeNode::CodeType::Other
: ProfileTreeNode::CodeType::JavaScript;
// We don't need real garbage collector call frame, we change it to
// what Chrome DevTools expects.
auto currentNode = createNode(
nodeIdGenerator,
isGarbageCollectorFrame ? ProfileTreeNode::CodeType::Other
: ProfileTreeNode::CodeType::JavaScript,
previousNode,
isGarbageCollectorFrame ? createGarbageCollectorCallFrame()
: callFrame);
RuntimeSamplingProfile::SampleCallStackFrame childCallFrame =
isGarbageCollectorFrame ? createGarbageCollectorCallFrame() : callFrame;
auto alreadyExistingNode = previousNode->addChild(currentNode);
if (alreadyExistingNode != nullptr) {
previousNode = alreadyExistingNode;
ProfileTreeNode* maybeExistingChild =
previousNode->getIfAlreadyExists(childCodeType, childCallFrame);
if (maybeExistingChild != nullptr) {
previousNode = maybeExistingChild;
} else {
chunk.nodes.push_back(currentNode);
previousNode = currentNode;
previousNode = previousNode->addChild(
nodeIdGenerator.getNext(), childCodeType, childCallFrame);
chunk.nodes.push_back(*previousNode);
}
}
@@ -220,20 +191,28 @@ void RuntimeSamplingProfileTraceEventSerializer::serializeAndNotify(
sendProfileTraceEvent(
firstChunkThreadId, PROFILE_ID, tracingStartUnixTimestamp);
NodeIdGenerator nodeIdGenerator{};
auto rootNode = createRootNode(nodeIdGenerator);
auto programNode = createProgramNode(nodeIdGenerator, rootNode);
auto idleNode = createIdleNode(nodeIdGenerator, rootNode);
rootNode->addChild(programNode);
rootNode->addChild(idleNode);
// There could be any number of new nodes in this chunk. Empty if all nodes
// are already emitted in previous chunks.
ProfileChunk chunk{
profileChunkSize_, firstChunkThreadId, currentChunkUnixTimestamp};
NodeIdGenerator nodeIdGenerator{};
ProfileTreeRootNode rootNode(nodeIdGenerator.getNext());
chunk.nodes.push_back(rootNode);
chunk.nodes.push_back(programNode);
chunk.nodes.push_back(idleNode);
ProfileTreeNode* programNode = rootNode.addChild(
nodeIdGenerator.getNext(),
ProfileTreeNode::CodeType::Other,
createArtificialCallFrame("(program)"));
chunk.nodes.push_back(*programNode);
ProfileTreeNode* idleNode = rootNode.addChild(
nodeIdGenerator.getNext(),
ProfileTreeNode::CodeType::Other,
createArtificialCallFrame("(idle)"));
chunk.nodes.push_back(*idleNode);
uint32_t idleNodeId = idleNode->getId();
for (const auto& sample : samples) {
uint64_t currentSampleThreadId = sample.getThreadId();
@@ -257,7 +236,7 @@ void RuntimeSamplingProfileTraceEventSerializer::serializeAndNotify(
sample.getCallStack(),
chunk,
rootNode,
idleNode,
idleNodeId,
currentSampleUnixTimestamp - previousSampleUnixTimestamp,
nodeIdGenerator);
@@ -50,7 +50,7 @@ class RuntimeSamplingProfileTraceEventSerializer {
return samples.empty();
}
std::vector<std::shared_ptr<ProfileTreeNode>> nodes;
std::vector<ProfileTreeNode> nodes;
std::vector<uint32_t> samples;
std::vector<long long> timeDeltas;
uint16_t size;
@@ -128,11 +128,10 @@ class RuntimeSamplingProfileTraceEventSerializer {
* \param callStack The call stack that will be processed.
* \param chunk The profile chunk, which will buffer the sample with the
* provided call stack.
* \param rootNode Shared pointer to the (root) node. Will be the parent node
* of the corresponding profile tree branch.
* \param idleNode Shared pointer to the (idle) node. Will be the only node
* that is used for the corresponding profile tree branch, in case of an empty
* call stack.
* \param rootNode The (root) node. Will be the parent node of the
* corresponding profile tree branch.
* \param idleNodeId Id of the (idle) node. Will be the only node that is used
* for the corresponding profile tree branch, in case of an empty call stack.
* \param samplesTimeDelta Delta between the current sample and the previous
* one.
* \param nodeIdGenerator NodeIdGenerator instance that will be used for
@@ -142,8 +141,8 @@ class RuntimeSamplingProfileTraceEventSerializer {
const std::vector<RuntimeSamplingProfile::SampleCallStackFrame>&
callStack,
ProfileChunk& chunk,
std::shared_ptr<ProfileTreeNode> rootNode,
std::shared_ptr<ProfileTreeNode> idleNode,
ProfileTreeNode& rootNode,
uint32_t idleNodeId,
long long samplesTimeDelta,
NodeIdGenerator& nodeIdGenerator);
@@ -12,56 +12,39 @@
namespace facebook::react::jsinspector_modern::tracing {
TEST(ProfileTreeNodeTest, EqualityOperator) {
auto callFrame = RuntimeSamplingProfile::SampleCallStackFrame{
TEST(ProfileTreeNodeTest, OnlyAddsUniqueChildren) {
auto fooCallFrame = RuntimeSamplingProfile::SampleCallStackFrame{
RuntimeSamplingProfile::SampleCallStackFrame::Kind::JSFunction, 0, "foo"};
ProfileTreeNode* node1;
ProfileTreeNode* node2;
auto barCallFrame = RuntimeSamplingProfile::SampleCallStackFrame{
RuntimeSamplingProfile::SampleCallStackFrame::Kind::JSFunction, 0, "bar"};
node1 = new ProfileTreeNode(
1, ProfileTreeNode::CodeType::JavaScript, nullptr, callFrame);
node2 = new ProfileTreeNode(
2, ProfileTreeNode::CodeType::JavaScript, nullptr, callFrame);
EXPECT_EQ(*node1 == node2, true);
ProfileTreeNode parent(
1, ProfileTreeNode::CodeType::JavaScript, fooCallFrame);
ProfileTreeNode* child =
parent.addChild(2, ProfileTreeNode::CodeType::JavaScript, barCallFrame);
node1 = new ProfileTreeNode(
3,
ProfileTreeNode::CodeType::JavaScript,
std::shared_ptr<ProfileTreeNode>(node1),
callFrame);
node2 = new ProfileTreeNode(
4, ProfileTreeNode::CodeType::JavaScript, nullptr, callFrame);
EXPECT_EQ(*node1 == node2, false);
auto maybeAlreadyExistingChild = parent.getIfAlreadyExists(
ProfileTreeNode::CodeType::JavaScript, barCallFrame);
EXPECT_NE(maybeAlreadyExistingChild, nullptr);
node1 = new ProfileTreeNode(
5,
ProfileTreeNode::CodeType::JavaScript,
std::shared_ptr<ProfileTreeNode>(node2),
callFrame);
node2 = new ProfileTreeNode(
6,
ProfileTreeNode::CodeType::JavaScript,
std::shared_ptr<ProfileTreeNode>(node2),
callFrame);
EXPECT_EQ(*node1 == node2, true);
auto maybeExistingChildOfChild = child->getIfAlreadyExists(
ProfileTreeNode::CodeType::JavaScript, barCallFrame);
EXPECT_EQ(maybeExistingChildOfChild, nullptr);
}
TEST(ProfileTreeNodeTest, OnlyAddsUniqueChildren) {
auto callFrame = RuntimeSamplingProfile::SampleCallStackFrame{
TEST(ProfileTreeNodeTest, ConsidersCodeTypeOfChild) {
auto parentCallFrame = RuntimeSamplingProfile::SampleCallStackFrame{
RuntimeSamplingProfile::SampleCallStackFrame::Kind::JSFunction, 0, "foo"};
auto parent = std::make_shared<ProfileTreeNode>(
1, ProfileTreeNode::CodeType::JavaScript, nullptr, callFrame);
auto existingChild = std::make_shared<ProfileTreeNode>(
2, ProfileTreeNode::CodeType::JavaScript, parent, callFrame);
auto childCallFrame = RuntimeSamplingProfile::SampleCallStackFrame{
RuntimeSamplingProfile::SampleCallStackFrame::Kind::JSFunction, 0, "bar"};
auto maybeAlreadyExistingChild = parent->addChild(existingChild);
EXPECT_EQ(maybeAlreadyExistingChild, nullptr);
ProfileTreeNode parent(
1, ProfileTreeNode::CodeType::JavaScript, parentCallFrame);
parent.addChild(2, ProfileTreeNode::CodeType::JavaScript, childCallFrame);
auto copyOfExistingChild = std::make_shared<ProfileTreeNode>(
3, ProfileTreeNode::CodeType::JavaScript, parent, callFrame);
maybeAlreadyExistingChild = parent->addChild(copyOfExistingChild);
EXPECT_EQ(maybeAlreadyExistingChild, existingChild);
auto maybeExistingChild = parent.getIfAlreadyExists(
ProfileTreeNode::CodeType::Other, childCallFrame);
EXPECT_EQ(maybeExistingChild, nullptr);
}
} // namespace facebook::react::jsinspector_modern::tracing