Skip to content

fix(geo): emit ISO alpha-3 for device.geo.country - #1022

Merged
YuriyVelichkoPI merged 5 commits into
prebid:masterfrom
nsp37:fix/geo-country-alpha3
Nov 29, 2026
Merged

YuriyVelichkoPI merged 5 commits into
prebid:masterfrom
nsp37:fix/geo-country-alpha3

Conversation

@nsp37

@nsp37 nsp37 commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Summary

device.geo.country is populated from the OS sources — telephony (getSimCountryIso() / getNetworkCountryIso()) and the Geocoder (Address.getCountryCode()) — in ISO-3166-1 alpha-2 (e.g. US), while OpenRTB device.geo.country requires alpha-3 (e.g. USA). Only the Locale.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:

  • New GeoCountryFormat enum (ALPHA2 / ALPHA3).
  • PrebidMobile.setGeoCountryFormat(...) / getGeoCountryFormat() — default ALPHA2 (today's behavior).
  • GeoLocationParameterBuilder normalizes device.geo.country to alpha-3 (via Locale.getISO3Country(), full ISO coverage) only when ALPHA3 is selected.
  • Default is planned to flip to ALPHA3 in 4.0 (noted in the Javadoc).

Test plan

  • GeoLocationParameterBuilderTest.testToAlpha3_convertsAlpha2AndPassesThroughAlpha3 covers the conversion helper.
  • Follow-up from review: add a test exercising the flag (ALPHA2 vs ALPHA3 output), and address the inline edge-case notes (null/unmappable → omit, ISO-3 validation, locale-safe upper-casing).

Closes #872

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.
@mdanylov-sigma

Copy link
Copy Markdown
Collaborator

Hey @nsp37! Could you check comments in the issue #872 and align your implementation with new requirements ?

)

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 mdanylov-sigma left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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 ALPHA2 mode the SDK can still send alpha-3 (from the locale fallback), so the flag doesn't control the format yet.
  • In ALPHA3 mode 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:

  1. PR description: it still describes an unconditional alpha-3 conversion. Could you update it to cover the GeoCountryFormat opt-in, the alpha-2 default and the 4.0 plan, and add Closes #872?

  2. 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() prefers getSimCountryIso() over getNetworkCountryIso() (L137-L141). For a roaming user that gives the SIM's home country, not the country the device is in, so it can contradict lat/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) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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 : "";

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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 null from Address.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)?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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().

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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() {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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(...) and shadowOf(telephonyManager).setSimCountryIso("us"), then asserts "US" by default and "USA" with ALPHA3;
  • an @After that resets PrebidMobile.setGeoCountryFormat(GeoCountryFormat.ALPHA2), since the static state otherwise leaks into other tests;
  • a default/null case for the new setter in PrebidMobileTest.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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 {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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?

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.

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();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in 429aebe — @Nullable on the setter param and @NonNull on the getter, matching the neighbouring config API.

@nsp37

nsp37 commented Sep 21, 2026

Copy link
Copy Markdown
Contributor Author

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 ALPHA2 should normalize to alpha-2 vs. remain legacy passthrough, and the network-country-first / validation cleanups) once you and @YuriyVelichkoPI settle on the intended semantics.

…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.
@YuriyVelichkoPI

Copy link
Copy Markdown
Contributor

@mdanylov-sigma let's address the ALPHA2 normalisation and sources order in a separate issue

@YuriyVelichkoPI YuriyVelichkoPI 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.

LGTM

@nsp37

nsp37 commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

@YuriyVelichkoPI thanks for the approval. This has no conflicts with master. Could you or another maintainer merge it when you get a chance? The ALPHA2 normalisation and source order will go in a separate issue, as you suggested.

@YuriyVelichkoPI
YuriyVelichkoPI merged commit e55b00d into prebid:master Nov 29, 2026
6 checks passed
@YuriyVelichkoPI YuriyVelichkoPI added this to the 3.5.0 milestone Nov 29, 2026
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.

device.geo.country is being sent in iso alpha-2 format

3 participants