Skip to content
Merged
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 changelog.d/1760.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
**The facts frame now drops an extensible-enumeration fact repeated with different whitespace.** One member set filed once with spaces and once with line breaks stayed as two rows, because duplicates were compared as raw strings. Enumeration values now compare with whitespace collapsed, while `value` is still returned as filed; row counts across the 47 bundled XBRL fixtures (94,996 facts) are unchanged.
41 changes: 37 additions & 4 deletions edgar/xbrl/facts.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@
# by_statement_type() to test against (gh #1242); they are list-valued, and the
# frame's schema is declared rather than inferred (edgartools-rsyt), so they
# stay off it rather than widening the contract with two list cells.
_SKIP_COLUMNS = frozenset({'fact_key', 'original_label',
_SKIP_COLUMNS = frozenset({'fact_key', 'original_label', 'dedup_value',
'statement_types', 'statement_roles'})


Expand All @@ -118,7 +118,26 @@
# `is_nil` is in it because a filed nil item and an empty non-nil element share
# every other identity field; without it the frame kept whichever came first
# (GH #1254). Two nil items, or two empty ones, still collapse.
_DEDUP_OPTIONAL = ('unit_ref', 'is_nil')
# `dedup_value` stands in for `value` where it is set (see `_dedup_value`).
_DEDUP_OPTIONAL = ('unit_ref', 'is_nil', 'dedup_value')

# Extensible-enumeration values are xs:token lists (Extensible Enumerations 2.0
# section 6.2.2): whitespace between members is not significant, so two facts
# naming the same members, one with a space and one with a line break, are
# duplicates (section 6.2.3, GH #1760). Matched on the local type name, whatever
# prefix the schema binds to the enum2 namespace.
_ENUMERATION_TYPES = ('enumerationItemType', 'enumerationSetItemType')


def _dedup_value(data_type: Optional[str], value: Any) -> Optional[str]:
"""The value an enumeration fact is compared by, or None for any other fact.

`value` itself is never rewritten: the kept row reports its value exactly
as filed. Only the de-duplication identity collapses the whitespace.
"""
if isinstance(value, str) and data_type and data_type.endswith(_ENUMERATION_TYPES):
return ' '.join(value.split())
return None


def _source_column_presence(results: List[Dict[str, Any]], names) -> set:
Expand Down Expand Up @@ -168,8 +187,15 @@ def _deduplicate_facts(df: pd.DataFrame) -> pd.DataFrame:
dedup_cols = list(_DEDUP_REQUIRED)
if all(col in df.columns for col in dedup_cols):
# Repeated tags of one fact still collapse (gh #769): they share a unit.
dedup_cols.extend(col for col in _DEDUP_OPTIONAL if col in df.columns)
df = df.drop_duplicates(subset=dedup_cols, keep='first')
optional = [col for col in _DEDUP_OPTIONAL if col in df.columns]
if 'dedup_value' in optional:
# Compare the collapsed enumeration value in place of `value`.
key = df['dedup_value'].where(df['dedup_value'].notna(), df['value'])
subset = ['_dedup_key' if col == 'value' else col for col in dedup_cols]
subset += [col for col in optional if col != 'dedup_value']
df = df.loc[~df.assign(_dedup_key=key).duplicated(subset=subset, keep='first')]
else:
df = df.drop_duplicates(subset=dedup_cols + optional, keep='first')
return df


Expand Down Expand Up @@ -1660,6 +1686,11 @@ def get_facts(self) -> List[Dict[str, Any]]:
from edgar.xbrl.parsers.concepts import resolve_balance
fact_dict['balance'] = resolve_balance(element.balance, fact.element_id) # "debit", "credit", or None

# GH #1760: enumeration members compare without their whitespace.
dedup_value = _dedup_value(element.data_type, fact_dict.get('value'))
if dedup_value is not None:
fact_dict['dedup_value'] = dedup_value

# Add preferred_sign from presentation linkbase (Issue #463)
# Convert preferredLabel to a numeric sign multiplier for display
# -1 means "negate for display", 1 means "use as-is", None means "not specified"
Expand Down Expand Up @@ -1735,6 +1766,8 @@ def to_dataframe(self) -> pd.DataFrame:
facts = self.get_facts()
df = pd.DataFrame(facts)
df = _deduplicate_facts(df)
if 'dedup_value' in df.columns:
df = df.drop(columns=['dedup_value'])
self._facts_df_cache = df
return df

Expand Down
97 changes: 97 additions & 0 deletions tests/issues/regression/test_issue_1760.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
"""Regression: duplicate removal compared enumeration values with their whitespace.

GitHub Issue: https://github.com/dgunning/edgartools/issues/1760

An extensible-enumeration value is an xs:token list of members, so the
whitespace between members is not significant (Extensible Enumerations 2.0
section 6.2.2) and duplicate detection compares the collapsed value (section
6.2.3). The facts frame compared the raw string, so one member set filed once
with a space and once with a line break stayed as two rows.

`value` itself is still returned exactly as filed; only the de-duplication
key collapses whitespace, and only for enumeration-typed concepts.
"""

import pytest

from edgar.xbrl import XBRL

SCHEMA = '''<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:link="http://www.xbrl.org/2003/linkbase" xmlns:xbrli="http://www.xbrl.org/2003/instance" xmlns:enum2="http://xbrl.org/2020/extensible-enumerations-2.0" targetNamespace="http://example.com" xmlns:ex="http://example.com" elementFormDefault="qualified">
<xs:element name="Selection" id="ex_Selection" type="enum2:enumerationSetItemType" substitutionGroup="xbrli:item" xbrli:periodType="instant" enum2:domain="ex:Domain" enum2:linkrole="http://example.com/role/enumeration" enum2:headUsable="false"/>
<xs:element name="Note" id="ex_Note" type="xbrli:stringItemType" substitutionGroup="xbrli:item" xbrli:periodType="instant"/>
</xs:schema>'''


def facts_frame(selections=(), notes=(), columns=()):
facts = "".join(f'<ex:Selection id="s{i}" contextRef="c">{v}</ex:Selection>' for i, v in enumerate(selections))
facts += "".join(f'<ex:Note id="n{i}" contextRef="c">{v}</ex:Note>' for i, v in enumerate(notes))
xbrl = XBRL()
xbrl.parser.parse_schema_content(SCHEMA)
xbrl.parser.parse_instance_content(
'<xbrl xmlns="http://www.xbrl.org/2003/instance" xmlns:ex="http://example.com">'
'<context id="c"><entity><identifier scheme="http://www.sec.gov/CIK">1</identifier></entity>'
f'<period><instant>2025-12-31</instant></period></context>{facts}</xbrl>')
if columns:
return xbrl.facts.query().to_dataframe(*columns)
return xbrl.facts.to_dataframe()


SPACED = "http://example.com#A http://example.com#B"
BROKEN = "http://example.com#A\nhttp://example.com#B"


@pytest.mark.fast
def test_same_members_with_different_whitespace_are_one_fact():
df = facts_frame([SPACED, BROKEN])
assert len(df) == 1
# The kept row is the first occurrence, as filed.
assert df["value"].tolist() == [SPACED]
df = facts_frame([BROKEN, SPACED])
assert df["value"].tolist() == [BROKEN]


@pytest.mark.fast
def test_different_members_stay_two_facts():
df = facts_frame([SPACED, "http://example.com#A"])
assert sorted(df["value"]) == sorted([SPACED, "http://example.com#A"])


@pytest.mark.fast
def test_whitespace_still_counts_for_a_plain_string():
# xs:string preserves whitespace: these are two different values.
df = facts_frame(notes=["one two", "one\ntwo"])
assert len(df) == 2


@pytest.mark.fast
def test_projected_frame_drops_the_same_duplicate():
# The early projection must keep dedup_value long enough to de-duplicate,
# and not return it when it was not asked for.
df = facts_frame([SPACED, BROKEN], columns=("concept", "value"))
assert df.to_dict("records") == [{"concept": "ex:Selection", "value": SPACED}]


@pytest.mark.fast
def test_hidden_key_is_not_a_default_column():
# Like fact_key and original_label, it appears only when asked for by name.
for df in (facts_frame([SPACED, BROKEN]), facts_frame([SPACED, BROKEN], columns=("value",))):
assert "dedup_value" not in df.columns


@pytest.mark.network
def test_cracker_barrel_state_sets_keep_their_three_periods():
"""Cracker Barrel 10-K, accession 0001104659-26-110772: the state-and-local
tax-rate reconciliation enumeration names IL, KY, TN and TX for each of three
fiscal years, filed with line breaks between members. The three are
different periods, not duplicates, and each value is kept as filed."""
from edgar import find

concept = ("EffectiveIncomeTaxRateReconciliationStateAndLocalJurisdiction"
"ContributionGreaterThan50PercentTaxEffectExtensibleEnumeration")
xbrl = find("0001104659-26-110772").xbrl()
df = xbrl.facts.query().by_concept(concept).to_dataframe()

assert sorted(df["period_end"].astype(str)) == ["2024-08-02", "2025-08-01", "2026-07-31"]
for value in df["value"]:
assert "\n" in value
assert [m.name for m in xbrl.enumeration_members(value)] == ["IL", "KY", "TN", "TX"]