Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions RELEASE-NOTES.txt
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
* [*] Notifications: Comment and like notifications from private sites you can't access now show their content instead of an error [#26432]
* [*] Support: The chat keyboard's return key no longer looks like a send button [#26451]
* [*] Support: A conversation now has a title in the navigation bar, and its subject reads above the status instead of below it
* [*] Stats: Fix a crash when opening Tags and Categories, Clicks, Authors or Referrers details that list the same entry twice


27.5
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
import Foundation
import Testing
import UIKit
import WordPressKit
import WordPressSharedObjC
@testable import WordPress

/// Covers detail tables where the Stats API lists the same top-level entry twice, with the
/// same name, count and link.
@MainActor
struct SiteStatsDetailsDuplicateRowsTests {

@Test func categoryListedTwiceShowsBothCopies() throws {
let table = DetailsTable(section: .insightsTagsAndCategories)
table.setTags(travelViews: [4, 4])

#expect(rowNames(in: try table.snapshot()) == ["Recipes", "Travel", "Travel", "Garden"])
}

@Test func linkListedTwiceInClicksShowsBothCopies() throws {
let table = DetailsTable(section: .periodClicks)
let link = ["name": "example.com/same/", "url": "https://example.com/same/", "views": 5] as [String: Any]
table.periodStore.state.topClicks = StatsTopClicksTimeIntervalData(
date: Date(),
period: .week,
jsonDictionary: [
"days": [
"2026-11-23": [
"clicks": [
["name": "example.com/top/", "views": 20], link, link,
["name": "example.com/end/", "views": 1]
],
"total_clicks": 30,
"other_clicks": 0
]
]
] as [String: AnyObject]
)
table.periodStore.state.topClicksStatus = .success

#expect(
rowNames(in: try table.snapshot()) == [
"example.com/top/", "example.com/same/", "example.com/same/", "example.com/end/"
]
)
}

@Test func newCountForOneCopyKeepsTheOtherCopy() throws {
let table = DetailsTable(section: .insightsTagsAndCategories)
table.setTags(travelViews: [4, 4])
let before = rowItems(in: try table.snapshot())

table.setTags(travelViews: [4, 5])
let after = try table.snapshot()

#expect(rowNames(in: after) == ["Recipes", "Travel", "Travel", "Garden"])
// The diffable data source replaces an item only when it no longer finds an equal one.
#expect(before.map { after.indexOfItem($0) != nil } == [true, true, false, true])
}
}

// MARK: - Helpers

private extension SiteStatsDetailsDuplicateRowsTests {
func rowItems(in snapshot: ImmuTableDiffableDataSourceSnapshot) -> [AnyHashableImmuTableRow] {
snapshot.itemIdentifiers.filter { $0.immuTableRow is DetailExpandableRow }
}

func rowNames(in snapshot: ImmuTableDiffableDataSourceSnapshot) -> [String] {
rowItems(in: snapshot).compactMap { ($0.immuTableRow as? DetailExpandableRow)?.rowData.name }
}
}

/// A stats detail table backed by real stores.
///
/// Each test creates its own instance and releases it on the main actor: the stores'
/// `Dispatcher` asserts when their receipts are released on another thread.
@MainActor
private final class DetailsTable {
let insightsStore = StatsInsightsStore()
let periodStore = StatsPeriodStore()
private let viewModel: SiteStatsDetailsViewModel
// Strong references: the view model keeps its delegates weak.
private let detailsHandler = MockDetailsDelegate()
private let referrerHandler = MockReferrerDelegate()

/// Set the store state after `init`: `fetchDataFor` can mark the section as loading.
init(section: StatSection) {
viewModel = SiteStatsDetailsViewModel(
detailsDelegate: detailsHandler,
referrerDelegate: referrerHandler,
insightsStore: insightsStore,
periodStore: periodStore
)
viewModel.fetchDataFor(statSection: section, selectedDate: Date(), selectedPeriod: .week)
}

/// Single-category groups, as in the crash reports: "Recipes", "Travel" once per count,
/// then "Garden". The last row draws a different separator, so the copies sit before it.
func setTags(travelViews: [Int]) {
let category = { (name: String, views: Int) in
[
"views": views,
"tags": [
["name": name, "type": "category", "link": "https://example.com/?taxonomy=category&term=\(name)"]
]
] as [String: Any]
}
insightsStore.state.allTagsAndCategories = StatsTagsAndCategoriesInsight(jsonDictionary: [
"tags": ([category("Recipes", 30)] + travelViews.map { category("Travel", $0) } + [category("Garden", 1)])
as AnyObject
])
insightsStore.state.allTagsAndCategoriesStatus = .success
}

/// Returns the view model's snapshot.
///
/// UIKit raises `NSInternalInconsistencyException` for equal snapshot items. Catching it
/// fails the test instead of ending the test process.
func snapshot() throws -> ImmuTableDiffableDataSourceSnapshot {
var snapshot = ImmuTableDiffableDataSourceSnapshot()
try WPException.objcTry {
snapshot = self.viewModel.tableViewSnapshot()
}
return snapshot
}

private final class MockDetailsDelegate: SiteStatsDetailsDelegate {}

private final class MockReferrerDelegate: SiteStatsReferrerDelegate {
func showReferrerDetails(_ data: StatsTotalRowData) {}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -903,6 +903,8 @@ private extension SiteStatsDetailsViewModel {

func expandableDataRowsFor(_ rowsData: [StatsTotalRowData], status: StoreFetchingStatus = .idle) -> [any HashableImmutableRow] {
var detailDataRows = [any HashableImmutableRow]()
// Earlier top-level rows by name, to number the copies of an entry the API lists twice.
var earlierRowsByName = [String: [StatsTotalRowData]]()

for (idx, rowData) in rowsData.enumerated() {

Expand All @@ -926,10 +928,13 @@ private extension SiteStatsDetailsViewModel {
let hideIndentedSeparator = expanded ? (expanded || isLastRow) : (nextExpanded || isLastRow)

// Add top level parent row
detailDataRows.append(parentRow(rowData: rowData,
hideIndentedSeparator: hideIndentedSeparator,
hideFullSeparator: !isLastRow,
expanded: expanded))
var row = parentRow(rowData: rowData,
hideIndentedSeparator: hideIndentedSeparator,
hideFullSeparator: !isLastRow,
expanded: expanded)
row.copyIndex = earlierRowsByName[rowData.name, default: []].count { $0 == rowData }

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.

Blocker: Expanding a repeated entry that has two or more children still crashes. rowExpanded looks up the row's name, so tapping either copy expands both. Each copy then appends the same DetailExpandableChildRows (and nested parentRow(rowData: childRowData…) rows), and those have no copyIndex. With two or more children the first ones match exactly, and the snapshot hits the same duplicate-identifier exception.

On trunk this data crashed when the list opened, so nobody is worse off. But the tap crash is only reachable with this PR, so the release note's "Fix a crash when opening … details that list the same entry twice" holds only until the user taps.

Evidence:

  • App: in the build from the summary, tapping either "Travel, Food" row aborts with NSInternalInconsistencyException in -[__UIDiffableDataSourceSnapshot appendItemsWithIdentifiers:intoSectionWithIdentifier:], via StatsTotalRow.didTapDisclosureButton → SiteStatsDetailTableViewController.toggleChildRowsForRow → SiteStatsDetailsViewModel.tableViewSnapshot.
  • Unit test: using the same table setup as SiteStatsDetailsDuplicateRowsTests, a repeated two-tag group loads collapsed. After StatsDataHelper.expandedRowLabelsDetails[.insightsTagsAndCategories] = ["Travel, Food"], tableViewSnapshot() throws NSInternalInconsistencyException (_UIDiffableDataSourceUpdate.m:81).

The same code is in SiteStatsInsightsDetailsViewModel at line 1196. A small fix that doesn't need #26462: pass the parent's copyIndex to the child and nested parent rows it appends, and add copyIndex to DetailExpandableChildRow's ==. Then the two expanded copies stay distinct, even though both still expand together.

earlierRowsByName[rowData.name, default: []].append(rowData)
detailDataRows.append(row)

// Continue to next parent if not expanded.
guard expanded, let childRowsData = rowData.childRows else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1164,6 +1164,8 @@ private extension SiteStatsInsightsDetailsViewModel {

func expandableDataRowsFor(_ rowsData: [StatsTotalRowData], status: StoreFetchingStatus = .idle) -> [any HashableImmutableRow] {
var detailDataRows = [any HashableImmutableRow]()
// Earlier top-level rows by name, to number the copies of an entry the API lists twice.
var earlierRowsByName = [String: [StatsTotalRowData]]()

for (idx, rowData) in rowsData.enumerated() {

Expand All @@ -1187,10 +1189,13 @@ private extension SiteStatsInsightsDetailsViewModel {
let hideIndentedSeparator = expanded ? (expanded || isLastRow) : (nextExpanded || isLastRow)

// Add top level parent row
detailDataRows.append(parentRow(rowData: rowData,
var row = parentRow(rowData: rowData,
hideIndentedSeparator: hideIndentedSeparator,
hideFullSeparator: !isLastRow,
expanded: expanded))
expanded: expanded)
row.copyIndex = earlierRowsByName[rowData.name, default: []].count { $0 == rowData }
earlierRowsByName[rowData.name, default: []].append(rowData)
detailDataRows.append(row)

// Continue to next parent if not expanded.
guard expanded, let childRowsData = rowData.childRows else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -785,6 +785,9 @@ struct DetailExpandableRow: HashableImmutableRow {
let hideIndentedSeparator: Bool
let hideFullSeparator: Bool
let expanded: Bool
/// How many earlier rows in the same list have equal `rowData`. The Stats API can list
/// the same entry twice, and the diffable table rejects equal rows.
var copyIndex = 0
let action: ImmuTableAction? = nil

func configureCell(_ cell: UITableViewCell) {
Expand All @@ -805,7 +808,8 @@ struct DetailExpandableRow: HashableImmutableRow {
return lhs.rowData == rhs.rowData &&
lhs.hideIndentedSeparator == rhs.hideIndentedSeparator &&
lhs.hideFullSeparator == rhs.hideFullSeparator &&
lhs.expanded == rhs.expanded
lhs.expanded == rhs.expanded &&
lhs.copyIndex == rhs.copyIndex
}
}

Expand Down