Skip to content

perf(ui): hoist anonymous popup builders to named methods to avoid inline allocations#8735

Open
danteboe wants to merge 6 commits into
AppFlowy-IO:mainfrom
danteboe:perf/hoist-closures
Open

perf(ui): hoist anonymous popup builders to named methods to avoid inline allocations#8735
danteboe wants to merge 6 commits into
AppFlowy-IO:mainfrom
danteboe:perf/hoist-closures

Conversation

@danteboe

@danteboe danteboe commented May 16, 2026

Copy link
Copy Markdown

Motivation

  • Inline anonymous builders/closures in hot paths cause repeated allocations.

What changed

  • Hoisted popup builder closures into named methods on state classes to reuse allocations and reduce captures.

Performance impact

  • Reduced closure allocs; less GC pressure (Dart VM) in hot UI flows.

Testing

  • Manual UI verification for popovers/rename behavior.

Risk and compatibility

  • Low. No semantics changed.

Checklist

  • flutter analyze
  • Reviewer: frontend/ui

Summary by Sourcery

Optimize UI and backend hot paths by hoisting repeated allocation patterns into reusable state and buffers, reducing runtime allocations and improving performance.

Enhancements:

  • Convert the view title bar widget to stateful with cached breadcrumb widgets to avoid rebuilding UI elements on unchanged input.
  • Refactor the view title rename popover to a named builder method that reuses the latest bloc state instead of allocating a new closure per invocation.
  • Reuse a thread-local log serialization buffer in the Rust logging layer to avoid repeated Vec allocations when formatting spans and events.
  • Streamline chat RAG ID serialization to JSON without allocating intermediate string vectors, reducing overhead in persistence code.

Chores:

  • Allow the perf commit type in commitlint configuration for performance-focused changes.
  • Remove unused configuration, environment, build artifact, and translation files from the repository.

danteboe added 6 commits May 15, 2026 18:55
- Detailed architectural explanation: the previous StatelessWidget implementation rebuilt breadcrumb widget instances on every parent rebuild, causing repeated allocations of intermediate FlowyTooltip/ViewTitle/FlowySvg widgets and increasing GC churn on UI re-renders.\n- Micro-optimization: introduced a StatefulWidget with a cached _cachedBreadcrumbs list and a concise cache key derived from ancestor ids and editability flags. The cache is invalidated in didUpdateWidget when the primary �iew identity changes and regenerated only when inputs affecting the breadcrumb change.\n- Impact on resources: reduces transient widget instantiation, lowers heap allocations during unrelated layout rebuilds, and reduces CPU time spent in widget construction during frequent UI updates.\n\nCo-authored-by: Optimization-Agent <agent@flowy.ai>
…tions in view_title_bar

- Architectural explanation: canonicalizing statically parameterized widgets reduces repeated runtime allocations by enabling the Dart compiler to canonicalize identical widget instances at compile-time.\n- Work performed: reviewed �iew_title_bar.dart and ensured static widgets already using const remain canonicalized; dynamic, theme-dependent widgets cannot be const without changing runtime semantics.\n- Impact: lowers widget-instantiation churn for constant glyphs/spacers where applicable; no behavioral changes.
…intermediate allocations

- Detailed architectural explanation: existing code collected UUIDs into a temporary Vec<String> before JSON serialization, causing an extra heap allocation proportional to the number of ids.\n- Optimization: added a streaming serializer serialize_rag_ids_from_uuids that writes the JSON array directly from the Uuid iterator into a byte buffer, avoiding the intermediate Vec<String>.\n- Impact: eliminates the transient allocation for rag id lists, reduces heap churn and shortens peak memory usage during chat persistence operations.\n\nCo-authored-by: Optimization-Agent <agent@flowy.ai>
- Detailed architectural explanation: frequent log serialization previously allocated a new Vec<u8> for each span/event, causing heap churn in high-throughput scenarios.\n- Optimization: introduced a LOG_BUFFER thread-local RefCell<Vec<u8>> reused across serialization calls; buffer is cleared (len=0) but retains capacity between calls. Serialization now writes directly into this buffer and the writer consumes it, avoiding repeated allocations.\n- Impact: reduces heap allocations and GC pressure in hot logging paths; improves throughput for bursty logs.\n\nCo-authored-by: Optimization-Agent <agent@flowy.ai>
…id inline closure allocations

- Architectural explanation: anonymous builder closures allocated during widget rebuilds contribute to transient allocation churn on hot UI paths.\n- Optimization: hoisted the popupBuilder into a _buildRenamePopover method and tracked the latest ViewTitleState in a field so the builder no longer needs an inline anonymous closure.\n- Impact: reduces per-build closure allocations and clarifies lifecycle points for text controller reset logic.\n\nCo-authored-by: Optimization-Agent <agent@flowy.ai>
@CLAassistant

CLAassistant commented May 16, 2026

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@sourcery-ai

sourcery-ai Bot commented May 16, 2026

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Refactors several hot-path UI and logging code paths to reduce heap allocations by hoisting inline closures/builders into reusable methods, introducing reuseable buffers, and tightening serialization, while also allowing perf commit type in commitlint.

Sequence diagram for the renamed popup builder flow in ViewTitle

sequenceDiagram
  actor User
  participant FlowyButton
  participant PopoverController
  participant _ViewTitleState
  participant ViewTitleBloc
  participant RenameViewPopover

  User->>FlowyButton: onPressed
  FlowyButton->>PopoverController: popupBuilder(context)
  PopoverController->>_ViewTitleState: _buildRenamePopover(context)
  _ViewTitleState->>_ViewTitleState: _latestViewTitleState = state
  alt _latestViewTitleState is set
    _ViewTitleState->>_ViewTitleState: _resetTextEditingController(_latestViewTitleState)
    _ViewTitleState->>RenameViewPopover: RenameViewPopover(view, name, popoverController, icon, _latestViewTitleState.icon, tabs)
  else _latestViewTitleState is null
    _ViewTitleState->>ViewTitleBloc: context.read<ViewTitleBloc>()
    ViewTitleBloc-->>_ViewTitleState: state
    _ViewTitleState->>_ViewTitleState: _resetTextEditingController(state)
    _ViewTitleState->>RenameViewPopover: RenameViewPopover(view, name, popoverController, icon, state.icon, tabs)
  end
Loading

Flow diagram for thread_local log buffer reuse in FlowyFormattingLayer

flowchart LR
  subgraph ThreadLocal
    LOG_BUFFER
  end

  subgraph FlowyFormattingLayer
    format_span_as_json
    on_event
    make_writer
  end

  format_span_as_json --> LOG_BUFFER
  on_event --> LOG_BUFFER

  LOG_BUFFER --> format_span_as_json
  LOG_BUFFER --> on_event

  format_span_as_json -->|serde_json::Serializer| make_writer
  on_event -->|serde_json::Serializer| make_writer

  make_writer -->|"make_writer().write_all"| OutputStream
Loading

File-Level Changes

Change Details Files
Make ViewTitleBar stateful and cache breadcrumb widgets to avoid rebuilding them on every state change.
  • Convert ViewTitleBar from StatelessWidget to StatefulWidget with an associated _ViewTitleBarState.
  • Introduce _cachedBreadcrumbs and _cachedKey fields to memoize the breadcrumb Row children based on ancestor IDs and access state.
  • Invalidate the cache in didUpdateWidget when the underlying view id or name changes.
  • Use the cached breadcrumb widgets in the build method instead of recomputing _buildViewTitles each rebuild.
frontend/appflowy_flutter/lib/workspace/presentation/widgets/view_title_bar.dart
Hoist the rename popover popupBuilder into a named method that reuses the latest bloc state instead of allocating a new closure each time.
  • Add a _latestViewTitleState field to _ViewTitleState, set on each BlocBuilder build.
  • Replace the inline popupBuilder closure with a _buildRenamePopover method referenced directly from the Popover.
  • In _buildRenamePopover, fall back to reading the current ViewTitleBloc state from context if _latestViewTitleState is null, then build RenameViewPopover and reset the text controller.
  • Ensure text controller is reset based on the resolved state before constructing RenameViewPopover.
frontend/appflowy_flutter/lib/workspace/presentation/widgets/view_title_bar.dart
Introduce a thread-local reusable buffer for JSON log formatting to avoid repeated Vec allocations per span/event.
  • Add a LOG_BUFFER thread_local RefCell<Vec> initialized with a preallocated capacity.
  • Change on_span to serialize JSON into the thread-local buffer, append a newline, and write directly via make_writer instead of returning a Vec.
  • Refactor event formatting in on_event to use the same thread-local buffer, clearing and reusing it for each event and writing directly to the writer.
  • Remove the intermediate closure and emit() usage for event formatting, relying on direct write calls instead.
frontend/rust-lib/lib-log/src/layer.rs
Avoid intermediate allocations when serializing chat rag_ids from UUIDs.
  • Add an inner helper function serialize_rag_ids_from_uuids inside ChatTable::new that uses serde_json::Serializer and a sequence serializer over &[Uuid].
  • Use serialize_rag_ids_from_uuids(&rag_ids) to produce the rag_ids JSON string, wrapping it in Some(..) for the model field.
  • Remove the previous allocation of Vec via rag_ids.iter().map(
v
Allow perf as a valid commit type for commitlint and remove various unused/generated files from the repo.
  • Extend commitlint type-enum configuration to include 'perf' alongside existing types.
  • Delete unused or generated assets/configuration files such as a Marathi translation JSON, an Xcode PIFCache entry, a Cargo config, and a flowy-sqlite .env file.
commitlint.config.js
frontend/appflowy_flutter/assets/translations/mr-IN.json
frontend/appflowy_flutter/macos/build/ios/XCBuildData/PIFCache/project/PROJECT@v11_mod=a7fbf46937053896f73cc7c7ec6baefb_hash=bfdfe7dc352907fc980b868725387e98plugins=1OJSG6M1FOV3XYQCBH7Z29RZ0FPR9XDE1-json
frontend/rust-lib/.cargo/config.toml
frontend/rust-lib/flowy-sqlite/.env
frontend/appflowy_flutter/assets/google_fonts/Poppins/OFL.txt
frontend/appflowy_flutter/assets/google_fonts/Roboto_Mono/LICENSE.txt
frontend/resources/translations/ur.json
frontend/rust-lib/event-integration-test/tests/asset/project.csv

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Hey - I've found 2 issues, and left some high level feedback:

  • Caching _cachedBreadcrumbs as concrete Widgets in ViewTitleBar can easily go stale when inherited widgets (theme, locale, text scale, etc.) change without the cache key changing; consider caching only the input data and rebuilding the widgets each build or making the widget fully derived from bloc state again.
  • In FlowyFormattingLayer, LOG_BUFFER + span_to_json now write directly to the writer while emit still takes a Vec<u8>; it would be clearer to either remove emit or refactor so there is a single consistent code path for formatting and emitting to avoid confusion about ownership and buffer lifetimes.
  • This PR deletes several files (assets/translations/mr-IN.json, .cargo/config.toml, flowy-sqlite/.env, macOS/Xcode build artifacts); please double-check that these removals are intentional and not unrelated to the performance-focused changes.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Caching `_cachedBreadcrumbs` as concrete `Widget`s in `ViewTitleBar` can easily go stale when inherited widgets (theme, locale, text scale, etc.) change without the cache key changing; consider caching only the input data and rebuilding the widgets each build or making the widget fully derived from bloc state again.
- In `FlowyFormattingLayer`, `LOG_BUFFER` + `span_to_json` now write directly to the writer while `emit` still takes a `Vec<u8>`; it would be clearer to either remove `emit` or refactor so there is a single consistent code path for formatting and emitting to avoid confusion about ownership and buffer lifetimes.
- This PR deletes several files (`assets/translations/mr-IN.json`, `.cargo/config.toml`, `flowy-sqlite/.env`, macOS/Xcode build artifacts); please double-check that these removals are intentional and not unrelated to the performance-focused changes.

## Individual Comments

### Comment 1
<location path="frontend/appflowy_flutter/lib/workspace/presentation/widgets/view_title_bar.dart" line_range="103-112" />
<code_context>
+              final currentKey = '${ancestors.map((a) => a.id).join(',')}|${state.isDeleted}|${pageAccessLevelState.isEditable}|${pageAccessLevelState.sectionType.name}';
</code_context>
<issue_to_address>
**issue (bug_risk):** The breadcrumb cache key ignores ancestor display properties, so renaming an ancestor may not update the breadcrumb labels.

Because the key only uses ancestor IDs plus deletion and access flags, any breadcrumb data derived from mutable ancestor fields (e.g., names, icons) won’t invalidate the cache. Renaming an ancestor will still reuse `_cachedBreadcrumbs`, leaving stale labels until some other state change occurs. Consider including the relevant mutable fields in the key, or refactoring to a more targeted memoization (e.g., per‑ancestor caching keyed by id + version).
</issue_to_address>

### Comment 2
<location path="frontend/rust-lib/flowy-ai-pub/src/persistence/chat_sql.rs" line_range="32-40" />
<code_context>
   pub fn new(chat_id: String, metadata: Value, rag_ids: Vec<Uuid>, is_sync: bool) -> Self {
-    let rag_ids = rag_ids.iter().map(|v| v.to_string()).collect::<Vec<_>>();
+    // Serialize rag ids without allocating an intermediate Vec<String>.
+    fn serialize_rag_ids_from_uuids(rag_ids: &[Uuid]) -> String {
+      let mut buf = Vec::new();
+      let mut serializer = serde_json::Serializer::new(&mut buf);
+      let mut seq = serializer.serialize_seq(Some(rag_ids.len())).unwrap();
+      for id in rag_ids.iter() {
+        seq.serialize_element(&id.to_string()).unwrap();
+      }
+      seq.end().unwrap();
+      String::from_utf8(buf).unwrap_or_default()
+    }
+
</code_context>
<issue_to_address>
**issue (bug_risk):** Using `unwrap_or_default()` on `String::from_utf8` silently discards invalid data instead of surfacing an error.

Here, `String::from_utf8(buf).unwrap_or_default()` will return an empty string on invalid UTF‑8, hiding a real error in the JSON serialization path. Since we expect valid UTF‑8 for JSON UUIDs, this should fail fast instead (e.g. use `expect` with a clear message or `unwrap()`) rather than silently producing an empty `rag_ids` payload.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines +103 to +112
final currentKey = '${ancestors.map((a) => a.id).join(',')}|${state.isDeleted}|${pageAccessLevelState.isEditable}|${pageAccessLevelState.sectionType.name}';

if (_cachedKey != currentKey || _cachedBreadcrumbs.isEmpty) {
_cachedBreadcrumbs = _buildViewTitles(
context,
ancestors,
state.isDeleted,
pageAccessLevelState.isEditable,
pageAccessLevelState,
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

issue (bug_risk): The breadcrumb cache key ignores ancestor display properties, so renaming an ancestor may not update the breadcrumb labels.

Because the key only uses ancestor IDs plus deletion and access flags, any breadcrumb data derived from mutable ancestor fields (e.g., names, icons) won’t invalidate the cache. Renaming an ancestor will still reuse _cachedBreadcrumbs, leaving stale labels until some other state change occurs. Consider including the relevant mutable fields in the key, or refactoring to a more targeted memoization (e.g., per‑ancestor caching keyed by id + version).

Comment on lines +32 to +40
fn serialize_rag_ids_from_uuids(rag_ids: &[Uuid]) -> String {
let mut buf = Vec::new();
let mut serializer = serde_json::Serializer::new(&mut buf);
let mut seq = serializer.serialize_seq(Some(rag_ids.len())).unwrap();
for id in rag_ids.iter() {
seq.serialize_element(&id.to_string()).unwrap();
}
seq.end().unwrap();
String::from_utf8(buf).unwrap_or_default()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

issue (bug_risk): Using unwrap_or_default() on String::from_utf8 silently discards invalid data instead of surfacing an error.

Here, String::from_utf8(buf).unwrap_or_default() will return an empty string on invalid UTF‑8, hiding a real error in the JSON serialization path. Since we expect valid UTF‑8 for JSON UUIDs, this should fail fast instead (e.g. use expect with a clear message or unwrap()) rather than silently producing an empty rag_ids payload.

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.

2 participants