Different rental URLs can still put the same building in your training corpus and your test set.
If you deduplicate listingUrl and then shuffle the rows, a unit listing can land across the split from its building page. Your evaluation may reward familiar building descriptions when you meant to test retrieval on unfamiliar properties. An awkward detail to discover after presenting the score.
Lab note 145: can we keep useful unit-level documents without letting their buildings cross evaluation partitions? The catch comes early: missing building identity means unresolved membership. We'd rather quarantine those records than invent a relationship from a familiar name.
Canonical pages solve only record duplication
Our rental Actor's details mode accepts listing URLs, apartment-building URLs, and numeric listing IDs. Its output distinguishes the canonical listingUrl from inputUrl, which records a supplied URL when it differs.
That gives us useful provenance. It doesn't make the canonical page a building boundary.
Canonical listing identity removes alternate references to a record; building identity keeps related records in the same evaluation partition.
This helper creates identity aliases from published identifiers and canonical pages, leaving the supplied URL out of the identity decision:
import hashlib
import json
import os
import tiktoken
from apify_client import ApifyClient
def scalar(row, field):
value = row.get(field)
return str(value).strip() if value is not None else ""
def record_aliases(row):
kind = scalar(row, "recordType")
if kind not in {"listing", "building"}:
return []
id_field = "listingId" if kind == "listing" else "buildingId"
aliases = []
if identity := scalar(row, id_field):
aliases.append(f"zumper:{kind}:id:{identity}")
if canonical := scalar(row, "listingUrl"):
aliases.append(f"zumper:{kind}:url:{canonical}")
return aliases
The record type scopes each alias. A building page and a unit listing remain separate documents even when their descriptions overlap.
Exact canonical strings are intentional here. Removing arbitrary path segments or query parameters would introduce another identity rule we'd need to justify.
A corpus row needs identity and ancestry
For retrieval, we'd embed a listing as a document and retain its building as metadata. A building page can remain its own document, with the same group membership.
The exported fields have separate jobs:
| Corpus field | Job |
|---|---|
record_key |
Identify the deduplicated listing or building record |
building_group_key |
Keep related documents in the same partition |
record_type |
Distinguish unit listings from building pages |
source_url |
Retain a canonical page for attribution |
observations |
Preserve input URLs, scrape timestamps, and search context |
text |
Hold the searchable content |
token_count |
Make the embedding budget inspectable |
partition |
Record the evaluation assignment |
Search context belongs in provenance. A search's searchCity isn't a substitute for the property's address, so we don't quietly turn it into a location claim inside the embedding text.
These helpers preserve observation metadata and label unit amenities separately from shared amenities:
def observation(row):
return {
"source_url": scalar(row, "listingUrl") or None,
"input_url": scalar(row, "inputUrl") or None,
"observed_at": scalar(row, "scrapedAt") or None,
"search_city": scalar(row, "searchCity") or None,
"search_state": scalar(row, "searchState") or None,
}
def corpus_text(row):
sections = []
description = " ".join(scalar(row, "description").split())
if description:
sections.append(f"Description: {description}")
for field, label in (
("amenities", "Unit amenities"),
("buildingAmenities", "Building amenities"),
):
values = row.get(field)
if isinstance(values, list):
names = sorted({
" ".join(value.split())
for value in values
if isinstance(value, str) and value.strip()
})
if names:
sections.append(f"{label}: {'; '.join(names)}")
return "\n\n".join(sections)
We normalize whitespace and amenity ordering. We don't lowercase the description, strip numbers, or remove unit-specific phrases merely because they look repetitive.
Those details may be the reason a rental matches a query.
Keep unit text attached to its building
The relationship we want is easier to see than to describe:
supplied URL ──┐
numeric ID ────┴──> canonical listing record ──┐
├──> building group ──> partition
canonical building page ─────────────────────┘
This is entity grouping, not text deduplication.
Identical amenity lists can belong to different units. Removing every document with repeated text can erase legitimate inventory differences while leaving the actual evaluation problem unresolved.
For labeling, record_key identifies the document receiving a label. building_group_key controls where that document may appear. Keep both when you create relevance judgments.
If you later chunk long descriptions, every child chunk must inherit the parent record key, building group, source, and partition. Splitting chunks independently would reopen the same hole with smaller documents. Very efficient sabotage.
Collapse aliases before choosing partitions
Example input: this cell fetches listing and building details, then leaves the returned records available for corpus construction.
run_input = {
"mode": "listingDetails",
"listingUrls": [
"https://www.zumper.com/listings/5710732p/1-bedroom-south-beach-san-francisco-ca",
"https://www.zumper.com/apartment-buildings/p208324/one-henry-adams-potrero-hill-san-francisco-ca",
],
}
client = ApifyClient(os.environ["APIFY_TOKEN"])
run = client.actor(
"vexaloom-labs/zumper-us-and-canada-rental-listings-finder"
).call(run_input=run_input)
if run["status"] != "SUCCEEDED":
raise RuntimeError(f"Actor ended with {run['status']}")
items = client.dataset(run["defaultDatasetId"]).list_items().items
A fallback expression such as “ID, otherwise URL” misses an alias problem: a record with an ID and canonical URL should connect to another observation that has only that canonical URL.
We connect all available aliases before selecting a record key. Input order shouldn't decide which alternate references get noticed.
This cell groups connected aliases and sends records without usable identity to the audit collection:
parents = {}
identified = []
audit = []
def root(key):
parents.setdefault(key, key)
while parents[key] != key:
parents[key] = parents[parents[key]]
key = parents[key]
return key
for item in items:
aliases = record_aliases(item)
if not aliases:
audit.append({
"reason": "unresolved_record_identity",
"record_type": scalar(item, "recordType") or None,
"observation": observation(item),
})
continue
leader = root(aliases[0])
for alias in aliases[1:]:
parents[root(alias)] = leader
identified.append((item, aliases))
components = {}
for item, aliases in identified:
components.setdefault(root(aliases[0]), []).append((item, aliases))
That type check also prevents market_stats records from becoming rental documents. A city rent summary answers a different question from a property description.
Unresolved buildings stay out of the evaluation
A missing buildingId isn't permission to group by buildingName. Names can be reused, abbreviated, or changed. An incorrect merge hides uncertainty behind a tidy key.
We also quarantine conflicting identifiers and differing text observations within a deduplicated record. This intentionally avoids choosing a snapshot policy by accident.
The next cell builds documents, applies a token budget without truncating descriptions, and assigns each resolved building group deterministically:
encoder = tiktoken.get_encoding("cl100k_base")
token_budget = 800
split_buckets = 5
documents = []
for members in components.values():
record_key = min(
alias for _, aliases in members for alias in aliases
)
kind = scalar(members[0][0], "recordType")
id_field = "listingId" if kind == "listing" else "buildingId"
identities = {
scalar(row, id_field)
for row, _ in members if scalar(row, id_field)
}
buildings = {
scalar(row, "buildingId")
for row, _ in members if scalar(row, "buildingId")
}
texts = {corpus_text(row) for row, _ in members}
texts.discard("")
observations = [observation(row) for row, _ in members]
reason = (
"conflicting_record_ids" if len(identities) > 1 else
"conflicting_building_ids" if len(buildings) > 1 else
"unresolved_building" if not buildings else
"missing_searchable_text" if not texts else
"conflicting_text_or_snapshots" if len(texts) > 1 else
None
)
if reason:
audit.append({
"record_key": record_key,
"reason": reason,
"observations": observations,
})
continue
text = next(iter(texts))
token_count = len(encoder.encode(text, disallowed_special=()))
if token_count > token_budget:
audit.append({
"record_key": record_key,
"reason": "token_budget",
"token_count": token_count,
"observations": observations,
})
continue
group_key = f"zumper:building:{next(iter(buildings))}"
digest = hashlib.sha256(group_key.encode("utf-8")).hexdigest()
partition = (
"test" if int(digest, 16) % split_buckets == 0 else "train"
)
sources = sorted({
obs["source_url"] for obs in observations if obs["source_url"]
})
documents.append({
"record_key": record_key,
"building_group_key": group_key,
"record_type": kind,
"source_url": sources[0] if sources else None,
"observations": observations,
"text": text,
"token_count": token_count,
"partition": partition,
})
The token filter makes exclusions inspectable. Blind truncation could discard the unit-specific sentence at the end while retaining a generous helping of shared building copy.
Before reporting retrieval quality, inspect audit reasons and partition composition. A hash gives reproducible membership, not balanced geography, property coverage, or relevance difficulty.
What still leaks through?
buildingId is a grouping candidate, not evidence of permanent identity across relistings or source changes. An unseen-building claim needs a check that the identifiers actually track buildings across the observations you collect.
Repeated snapshots need a temporal policy too. The code quarantines differing searchable text; identical text doesn't prove identical observation time or rental availability.
For a historical evaluation, apply a timestamp cutoff before this pipeline and define how repeated observations are selected. Otherwise, future information can enter the corpus without changing a single building assignment.
Privacy has a similar catch. The text allowlist excludes the dedicated phone and agentName fields, but descriptions can still contain contact details. Review or redact free text before embedding it, and keep provenance URLs in an access-controlled store if they expose addresses.
The worked source is Zumper US & Canada Rental Listings Finder. Its published fields give us the ingredients for these decisions; they don't settle the evaluation design.
Write files that preserve the evaluation claim
Our verdict: listing deduplication and building grouping belong in separate fields.
The claim this pipeline can support is narrower than “leakage-free rental data”: documents sharing a resolved building identifier receive the same partition. Unknown membership, identifier churn, and temporal leakage remain explicit review work.
These files preserve accepted documents and rejected cases separately, without dumping raw contact fields into either collection:
for filename, records in (
("rental-corpus.jsonl", documents),
("rental-audit.jsonl", audit),
):
with open(filename, "w", encoding="utf-8") as handle:
for record in records:
handle.write(json.dumps(record, ensure_ascii=False) + "\n")
Freeze the export and partition rule with your evaluation. For incremental ingestion, persist the alias registry too: newly discovered aliases can change the chosen record key even when the underlying listing hasn't changed.
Build the files from a details lookup
- Set
APIFY_TOKENin your environment and installapify-clientandtiktoken. - Run the Python cells in order.
- Inspect the audit file before treating the corpus as evaluation-ready.
- Replace the source references with your evaluation inventory while retaining the same partition policy.
Example input: use this exact JSON for the details lookup shown above.
{
"mode": "listingDetails",
"listingUrls": [
"https://www.zumper.com/listings/5710732p/1-bedroom-south-beach-san-francisco-ca",
"https://www.zumper.com/apartment-buildings/p208324/one-henry-adams-potrero-hill-san-francisco-ca"
]
}
Drafted with AI assistance and reviewed for accuracy.
Top comments (0)