Repository navigation
fix(geo): emit ISO alpha-3 for device.geo.country - #1022
Conversation
GeoLocationParameterBuilder populates device.geo.country from getSimCountryIso()/
getNetworkCountryIso() (telephony) and Geocoder Address.getCountryCode(), all of
which return ISO-3166-1 alpha-2 (e.g. "US"). Only the Locale.getISO3Country()
fallback is alpha-3. OpenRTB device.geo.country is defined as alpha-3, so
location-enabled requests send a malformed alpha-2 value that buyers mis-bucket.
Normalize the resolved country to alpha-3 via the JDK's own ISO tables
(new Locale("", cc).getISO3Country()) — full coverage. Idempotent for values
already alpha-3; empty/unknown -> "" so no malformed country is emitted.
Adds a unit test for the conversion.
) Per the prebid#872 discussion (align with PMC guidance): don't hardcode the alpha-3 conversion — that would silently change existing behavior. Gate it behind an SDK-level config flag, defaulting to alpha-2 (today's behavior). Publishers opt in to the spec-compliant alpha-3 via PrebidMobile.setGeoCountryFormat(ALPHA3); the default is planned to flip to ALPHA3 in 4.0. Adds GeoCountryFormat enum + PrebidMobile.get/setGeoCountryFormat; the GeoLocationParameterBuilder only normalizes device.geo.country to alpha-3 when ALPHA3 is selected.
mdanylov-sigma
left a comment
There was a problem hiding this comment.
Thanks for adding the config flag so quickly, @nsp37! I checked the update against the requirements @YuriyVelichkoPI set in #872 (comment). The overall shape matches: the conversion is opt-in, the default is alpha-2, and the Javadoc mentions the 4.0 flip. The inline comments cover a few gaps. The main ones:
- In the default
ALPHA2mode the SDK can still send alpha-3 (from the locale fallback), so the flag doesn't control the format yet. - In
ALPHA3mode a few inputs still produce values that aren't alpha-3 ("","419", codes from Turkish-locale devices). - The tests don't exercise the flag itself.
Two things outside the diff:
-
PR description: it still describes an unconditional alpha-3 conversion. Could you update it to cover the
GeoCountryFormatopt-in, the alpha-2 default and the 4.0 plan, and addCloses #872? -
How reliable the country signal is (existing code, so not blocking this PR, but it bears on Yuriy's question in #872 about whether carrier data is accurate):
getTelephonyCountry()prefersgetSimCountryIso()overgetNetworkCountryIso()(L137-L141). For a roaming user that gives the SIM's home country, not the country the device is in, so it can contradictlat/lon. Checking the network country first would fix that.- The locale fallback (L77-L80) reports the region of the UI language, not the device's location. For example, an en-US tablet in Germany sends
USA.
Probably a follow-up rather than part of this PR, but worth agreeing on.
| // Opt-in via PrebidMobile.setGeoCountryFormat(ALPHA3) so we don't | ||
| // silently change existing behavior; defaults to alpha-2 (planned | ||
| // to default to alpha-3 in 4.0). Idempotent for values already alpha-3. | ||
| if (PrebidMobile.getGeoCountryFormat() == GeoCountryFormat.ALPHA3) { |
There was a problem hiding this comment.
In the default ALPHA2 mode this block doesn't run, so whatever the fallbacks produced is sent as-is, and the locale fallback (L78-L79) already returns alpha-3. For example, a Wi-Fi-only tablet with no SIM and an en-US locale sends "country":"USA" while the flag says alpha-2.
#872 asked for a flag telling which format will be used, so I think ALPHA2 should normalize to alpha-2 as well (e.g. a toAlpha2() counterpart in an else branch). If the intent is to keep today's mixed output, ALPHA2 should be renamed or documented as the legacy, non-normalized behavior instead.
@YuriyVelichkoPI, which one did you have in mind? Normalizing would change what the locale path sends today (USA → US).
| } | ||
| try { | ||
| String iso3 = new Locale("", c).getISO3Country(); | ||
| return iso3 != null ? iso3 : ""; |
There was a problem hiding this comment.
Returning "" doesn't omit the field: Geo.getJsonObject() uses putOpt, which only skips null, so the request carries "country":"".
In ALPHA3 mode that's a small regression:
- a
nullfromAddress.getCountryCode()used to omit the field and now sends""; - a code the tables can't map, such as Kosovo (
XK), used to be sent as"XK"and now goes out as"".
Could toAlpha3 return null for anything it can't convert (with the test switched to assertNull)?
There was a problem hiding this comment.
Fixed in b0dfc0b — toAlpha3 now returns null (not "") for empty/unknown/unconvertible input, so putOpt omits the field. Covers a null Address.getCountryCode() and unmappable codes like Kosovo XK.
| return ""; | ||
| } | ||
| String c = country.trim().toUpperCase(Locale.ROOT); | ||
| if (c.length() == 3) { |
There was a problem hiding this comment.
This accepts any 3-character string as alpha-3. On Android, Locale.getISO3Country() returns a 3-character region unchanged. So on a device with an es-419 (Latin American Spanish) locale and no SIM country, the locale fallback should produce "419", a UN M.49 code, and ALPHA3 mode passes it straight through.
I haven't reproduced this on a device, and the Robolectric test can't catch it because the JVM's Locale throws for 419 instead of returning it.
Suggestion: validate against the real ISO-3 set, e.g. a static Set<String> built from Locale.getISOCountries() mapped through new Locale("", cc).getISO3Country().
There was a problem hiding this comment.
Fixed in b0dfc0b — 3-char inputs are now validated against the real ISO-3 set (built once from Locale.getISOCountries() mapped via getISO3Country()), so a UN M.49 code like 419 is rejected (→ null/omitted) instead of passed through as "alpha-3".
| if (country == null) { | ||
| return ""; | ||
| } | ||
| String c = country.trim().toUpperCase(Locale.ROOT); |
There was a problem hiding this comment.
Locale.ROOT is right here, but the value can already be broken by the time it arrives: getTelephonyCountry() (L134-L135) calls toUpperCase() without a locale.
On a device whose default locale is Turkish (or Azerbaijani), "it" becomes "İT" (dotted İ). ALPHA2 then sends "İT" and ALPHA3 sends "". The same happens for IN, ID, IE, IL, IR, IQ, IS, FI and others.
Could you switch those two calls to toUpperCase(Locale.ROOT) while you're in this file?
There was a problem hiding this comment.
Fixed in b0dfc0b — getTelephonyCountry() now upper-cases with Locale.ROOT, so Turkish/Azerbaijani-locale devices no longer corrupt IT/IN/ID/IE/IL/....
| } | ||
|
|
||
| @Test | ||
| public void testToAlpha3_convertsAlpha2AndPassesThroughAlpha3() { |
There was a problem hiding this comment.
This covers the helper, but nothing tests the flag itself: removing or inverting the if on L95 of the builder keeps the whole suite green.
The existing tests in this class never reach the country code either. They don't set PrebidContextHolder or a SIM country, so country stays null in all of them (the expected JSON has no country). Could you add:
- a builder test that sets
PrebidContextHolder.setContext(...)andshadowOf(telephonyManager).setSimCountryIso("us"), then asserts"US"by default and"USA"withALPHA3; - an
@Afterthat resetsPrebidMobile.setGeoCountryFormat(GeoCountryFormat.ALPHA2), since the static state otherwise leaks into other tests; - a default/
nullcase for the new setter inPrebidMobileTest.
There was a problem hiding this comment.
Added a flag set/get test (incl. null → default ALPHA2) in b0dfc0b. A test that the builder honors the flag needs telephony/geocoder mocking to force a country source — happy to add it, likely alongside the ALPHA2-normalize decision above since that changes what the ALPHA2 branch should assert.
There was a problem hiding this comment.
Added builder-level tests in 68b126d that set PrebidContextHolder and a shadowed SIM/network country of us: the default format sends "US" and ALPHA3 sends "USA", so inverting or removing the gate now fails. The empty-country case (e.g. an unmappable locale throwing in getISO3Country()) now omits the field instead of sending "country":"".
| * Format used for the auto-detected {@code device.geo.country} in the bid | ||
| * request. See {@link PrebidMobile#setGeoCountryFormat(GeoCountryFormat)}. | ||
| */ | ||
| public enum GeoCountryFormat { |
There was a problem hiding this comment.
A timing question before this becomes public API. In #872 Yuriy also asked whether the SDK should have a toggle to not send country at all, and that's still unanswered.
If the answer is yes, it would land either as a third value here (e.g. NONE) or as a separate flag next to setGeoCountryFormat. Reshaping or renaming a public enum after release is a breaking change.
@YuriyVelichkoPI @justadreamer, is it worth settling this before merge?
There was a problem hiding this comment.
Let's move forward without a toggle so far
| @@ -84,12 +85,48 @@ private void setLocation(AdRequestInput adRequestInput, LocationInfoManager loca | |||
| geo.country = list.get(0).getCountryCode(); | |||
There was a problem hiding this comment.
Not blocking, and this is existing code: Geocoder.getFromLocation (L83-L84) is a synchronous network call. This builder runs from Requester.makeAdRequest() → URLBuilder.buildUrl() on the caller's thread, which is usually the main thread via fetchDemand.
It's rarely reached today because the locale fallback almost always fills the value first. I'm only flagging it in case reverse geocoding moves earlier (the source the #872 reporter preferred). It would then need the async GeocodeListener API (API 33+) or to run off the main thread.
| * set {@link GeoCountryFormat#ALPHA3} to send the spec-compliant format. The | ||
| * default is planned to change to {@code ALPHA3} in Prebid SDK 4.0. | ||
| */ | ||
| public static void setGeoCountryFormat(GeoCountryFormat format) { |
There was a problem hiding this comment.
nit: could you add @Nullable to the parameter and @NonNull to the getter, like the neighbouring API (setCustomHeaders(@Nullable ...))? Also worth a line in the Javadoc that null resets the value to ALPHA2.
There was a problem hiding this comment.
Done in 429aebe — @Nullable on the setter param and @NonNull on the getter, matching the neighbouring config API.
|
I'll get the hang of these eventually — thanks for the guidance so far! On the reliability question: we don't have access to this on iOS, but I lean toward trusting the carrier/network data here. Now that alpha-3 is in place, being able to derive the country for publishers is a meaningful feature and a nice end-engineer simplification — as long as it isn't violating Prebid's desired rules. In our own implementation/fork we also check a set of remote CDN headers to try to fill this; I left that out of these PRs. Happy to align on the open items (e.g. whether |
…fe upcase Per review on prebid#1022: - toAlpha3 returns null (not "") for empty/unknown/unconvertible input so the field is omitted rather than sent as "country":"" (Geo uses putOpt, which only skips null). Covers null Geocoder codes and unmappable codes like Kosovo "XK". - Validate 3-char inputs against the real ISO-3 set (from Locale.getISOCountries) so a UN M.49 code like "419" from a Latin-American-Spanish locale isn't passed through as alpha-3. - getTelephonyCountry() upper-cases with Locale.ROOT so Turkish/Azerbaijani-locale devices don't corrupt codes ("it" -> "İT"), which affected IT/IN/ID/IE/IL/... . - Tests: toAlpha3 now asserts null for the omit cases (incl. "419","XK"); add a flag set/get test (incl. null -> default alpha-2). Deferred (need maintainer agreement, tracked in the PR thread): normalizing ALPHA2 down to alpha-2 (pending the intended semantics), and preferring getNetworkCountryIso() over getSimCountryIso() for roaming.
…rmat Match the neighbouring config API annotations (per review).
- An unmappable locale made getISO3Country() throw MissingResourceException, which skipped the Geocoder fallback and toAlpha3 and left geo.country = "". Catch it around the Locale fallback so the remaining steps still run, and normalize an empty country to null so the field is omitted. - Add builder-level tests (per review): with a shadowed SIM/network country of "us", the default format sends "US" and ALPHA3 sends "USA", so an inverted flag gate fails. The shadowed TelephonyManager comes from the same context set on PrebidContextHolder; context and format are reset in finally.
|
@mdanylov-sigma let's address the ALPHA2 normalisation and sources order in a separate issue |
|
@YuriyVelichkoPI thanks for the approval. This has no conflicts with |
Summary
device.geo.countryis populated from the OS sources — telephony (getSimCountryIso()/getNetworkCountryIso()) and the Geocoder (Address.getCountryCode()) — in ISO-3166-1 alpha-2 (e.g.US), while OpenRTBdevice.geo.countryrequires alpha-3 (e.g.USA). Only theLocale.getISO3Country()fallback was already alpha-3.Per the discussion in #872, the alpha-3 conversion is made opt-in so existing behavior isn't silently changed:
GeoCountryFormatenum (ALPHA2/ALPHA3).PrebidMobile.setGeoCountryFormat(...)/getGeoCountryFormat()— defaultALPHA2(today's behavior).GeoLocationParameterBuildernormalizesdevice.geo.countryto alpha-3 (viaLocale.getISO3Country(), full ISO coverage) only whenALPHA3is selected.ALPHA3in 4.0 (noted in the Javadoc).Test plan
GeoLocationParameterBuilderTest.testToAlpha3_convertsAlpha2AndPassesThroughAlpha3covers the conversion helper.Closes #872