Blog · 2026-12-01 · 8 min read · by Saoud Tamimi

KSeF FA(3) for developers: the XSD gotchas that reject your invoices

Poland's National e-Invoicing System (KSeF) became mandatory in 2026: from 1 February 2026 for the largest taxpayers (and every business must be able to receive through KSeF from that date), from 1 April 2026 for most other businesses, and from 1 January 2027 for the smallest ones. The official timeline and details are on ksef.podatki.gov.pl. Every invoice is an XML document in the FA(3) structure, and KSeF checks it against the published XSD when you submit it. If the schema check fails, the invoice doesn't exist.

The XSD error messages are accurate but not friendly, especially when your team doesn't read Polish field names every day. Below are the mistakes I see most often, each reproduced with the official schema and real lxml output, so you can recognise them in your logs. At the end is a small pre-flight script for two things the XSD cannot check.

Setup: get the official schema (gotcha 0)

The FA(3) schema lives at https://crd.gov.pl/wzor/2025/06/25/13775/schemat.xsd. It imports shared type definitions by absolute http:// URLs, and when I tested, the http:// variant of that host returned HTTP 500 while https:// worked. A validator that tries to resolve imports at runtime will fail in CI for reasons that have nothing to do with your invoice. Download everything once, rewrite the imports to local files, and commit the result (or cache it):

"""fetch_fa3_xsd.py: download the FA(3) schema and its imports; point imports at local copies."""
import pathlib, re, urllib.request

ROOT = "https://crd.gov.pl/xml/schematy/dziedzinowe/mf/2022/01/05/eD/DefinicjeTypy/"
FILES = {
    "schemat.xsd": "https://crd.gov.pl/wzor/2025/06/25/13775/schemat.xsd",
    "StrukturyDanych_v10-0E.xsd": ROOT + "StrukturyDanych_v10-0E.xsd",
    "ElementarneTypyDanych_v10-0E.xsd": ROOT + "ElementarneTypyDanych_v10-0E.xsd",
    "KodyKrajow_v10-0E.xsd": ROOT + "KodyKrajow_v10-0E.xsd",
}
out = pathlib.Path("xsd"); out.mkdir(exist_ok=True)
for name, url in FILES.items():
    text = urllib.request.urlopen(url, timeout=30).read().decode("utf-8")
    text = re.sub(r'schemaLocation="[^"]*/([^"/]+\.xsd)"', r'schemaLocation="\1"', text)
    (out / name).write_text(text, encoding="utf-8")
    print("saved", out / name)

Then a validator that prints every error with its line number and exits non-zero for CI:

"""check_fa3.py: validate KSeF FA(3) XML files against the official XSD."""
import sys
from lxml import etree

schema = etree.XMLSchema(etree.parse("xsd/schemat.xsd"))
parser = etree.XMLParser(resolve_entities=False, no_network=True)

def check(path):
    doc = etree.parse(path, parser)
    if schema.validate(doc):
        return []
    return [f"line {e.line}: {e.message}" for e in schema.error_log]

if __name__ == "__main__":
    failed = 0
    for path in sys.argv[1:]:
        errors = check(path)
        print(("OK   " if not errors else "FAIL ") + path)
        for e in errors:
            print("     " + e)
        failed += bool(errors)
    sys.exit(1 if failed else 0)

no_network=True and resolve_entities=False are deliberate: an invoice should never make your validator fetch anything.

Each gotcha below starts from a valid FA(3) invoice and changes one thing. The error lines are the real lxml output (namespace shortened to {…13775/} for readability).

1. The FA(2) namespace

Copying an older example is the fastest way to get this one:

<Faktura xmlns="http://crd.gov.pl/wzor/2023/06/29/12648/">   <!-- FA(2) -->
Element '{http://crd.gov.pl/wzor/2023/06/29/12648/}Faktura': No matching global declaration available for the validation root.

FA(3) is http://crd.gov.pl/wzor/2025/06/25/13775/. "No matching global declaration" almost always means a wrong namespace, not a wrong element.

2. kodSystemowy has a space in it

The header is fixed, and the fixed value contains a space:

<KodFormularza kodSystemowy="FA (3)" wersjaSchemy="1-0E">FA</KodFormularza>
<WariantFormularza>3</WariantFormularza>

Write FA(3) and you get:

attribute 'kodSystemowy': The value 'FA(3)' does not match the fixed value constraint 'FA (3)'.

Treat these three values as constants in code, not configuration.

3. DataWytworzeniaFa is a timestamp, with limits

The creation timestamp is an xsd:dateTime restricted to 2025-09-01T00:00:00Z … 2050-01-01T23:59:59Z. Python's str(datetime) gives a space instead of a T:

Element '{…13775/}DataWytworzeniaFa': '2026-11-30 06:52:26' is not a valid value of the local atomic type.

Use datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z"). Test fixtures with a date before September 2025 also fail on the lower bound.

4. Decimal commas and decimal places

Polish UIs show 575,00, but the XML needs a dot:

Element '{…13775/}P_14_1': '575,00' is not a valid value of the atomic type '{…13775/}TKwotowy'.

Amounts (TKwotowy) allow at most two decimals:

Element '{…13775/}P_15': [facet 'pattern'] The value '3261.900' is not accepted by the pattern '-?([1-9]\d{0,15}|0)(\.\d{1,2})?'.

Not every number is an amount, though. Quantities (P_8B, type TIlosci) allow six decimals and unit prices (P_9A, TKwotowy2) allow eight. A single "format money" helper applied everywhere either rejects valid quantities or rounds unit prices you were supposed to keep. Use Decimal and quantize per field type.

5. NIP: digits only

The NIP pattern is [1-9]((\d[1-9])|([1-9]\d))\d{7}: ten digits, no separators, no country prefix.

Element '{…13775/}NIP': [facet 'pattern'] The value '777-000-11-11' is not accepted by the pattern …
Element '{…13775/}NIP': [facet 'pattern'] The value 'PL7770001111' is not accepted by the pattern …

PL7770001111 is how a Polish VAT number appears in VIES and on many EU invoices, so normalise on input. Foreign buyers don't go in NIP at all: they use KodUE plus NrVatUE, or NrID.

6. VAT rates are an enumeration, not a number

P_12 on each line must be one of:

'23', '22', '8', '7', '5', '4', '3', '0 KR', '0 WDT', '0 EX', 'zw', 'oo', 'np I', 'np II'

So 5% fails and so does plain 0:

Element '{…13775/}P_12': [facet 'enumeration'] The value '0' is not an element of the set {…}.

Zero-rated supplies must say why: 0 KR (domestic), 0 WDT (intra-EU supply), 0 EX (export). zw is exempt, oo is domestic reverse charge, and np I / np II are outside Polish VAT. Map your internal tax codes explicitly; never str(rate).

The header totals also have fixed slots: P_13_1/P_14_1 hold net and VAT for the basic rate (23 or 22), P_13_2/P_14_2 the first reduced rate (8 or 7), and P_13_3/P_14_3 the second reduced rate (5).

7. Element order matters

FA(3) is built from xsd:sequence, so order is part of the schema. Move P_15 (total due) after RodzajFaktury and the error points somewhere else entirely:

Element '{…13775/}Adnotacje': This element is not expected. Expected is one of ( {…13775/}P_14_3W, {…13775/}P_13_4, … ).

If you build XML from a dict or a JSON object, make sure your serialiser keeps the schema order. The safest approach is to write the elements in the order the XSD lists them, in one function, with a test that round-trips a full invoice.

8. Podmiot2 needs JST and GV

New in FA(3): the buyer block must state whether the invoice concerns a subordinate unit of a local-government body (JST) and whether the buyer is a VAT group member (GV), each as 1 (yes) or 2 (no). Leave them out and the error lists what could come next instead:

Element '{…13775/}Podmiot2': Missing child element(s). Expected is one of ( {…13775/}DaneKontaktowe, {…13775/}NrKlienta, {…13775/}IDNabywcy, …

9. Adnotacje is all-or-nothing

The annotations block is mandatory and every flag must be present, even when the answer is "no". This is the minimal "nothing special" block:

<Adnotacje>
  <P_16>2</P_16>                                   <!-- cash accounting: no -->
  <P_17>2</P_17>                                   <!-- self-billing: no -->
  <P_18>2</P_18>                                   <!-- reverse charge: no -->
  <P_18A>2</P_18A>                                 <!-- split payment: no -->
  <Zwolnienie><P_19N>1</P_19N></Zwolnienie>         <!-- no exemption -->
  <NoweSrodkiTransportu><P_22N>1</P_22N></NoweSrodkiTransportu>
  <P_23>2</P_23>                                   <!-- simplified triangular: no -->
  <PMarzy><P_PMarzyN>1</P_PMarzyN></PMarzy>         <!-- no margin scheme -->
</Adnotacje>

Drop the last one and:

Element '{…13775/}Adnotacje': Missing child element(s). Expected is ( {…13775/}PMarzy ).

Note the two encodings: 2 means "no" for P_16…P_23, but the …N elements use 1 to mean "this does not apply".

10. Currency codes are case-sensitive

KodWaluty is an enumeration of ISO 4217 codes in upper case. pln fails with a very long error that lists every currency. Also note that RodzajFaktury (VAT, KOR, ZAL, ROZ, UPR, KOR_ZAL, KOR_ROZ) is an enumeration too; corrections (KOR) need extra elements that a plain VAT invoice doesn't.

What the XSD will not catch

A file can be schema-valid and still be wrong. Two checks are cheap enough to run on every invoice before submission: the NIP check digit (the pattern accepts a typo) and the totals.

"""fa3_preflight.py: checks the FA(3) XSD cannot do: NIP check digit and invoice totals."""
import sys
from decimal import Decimal
from lxml import etree

NS = {"fa": "http://crd.gov.pl/wzor/2025/06/25/13775/"}
BUCKET = {"23": "1", "22": "1", "8": "2", "7": "2", "5": "3"}   # rate -> P_13_x / P_14_x

def nip_ok(nip: str) -> bool:
    w = (6, 5, 7, 2, 3, 4, 5, 6, 7)
    d = [int(c) for c in nip]
    return len(d) == 10 and sum(a * b for a, b in zip(w, d)) % 11 == d[9]

def preflight(path):
    doc = etree.parse(path)
    problems = []
    for nip in doc.iterfind(".//fa:DaneIdentyfikacyjne/fa:NIP", NS):
        if not nip_ok(nip.text):
            problems.append(f"NIP {nip.text}: wrong check digit")
    fa = doc.find("fa:Fa", NS)
    nets = {}
    for row in fa.iterfind("fa:FaWiersz", NS):
        b = BUCKET.get(row.findtext("fa:P_12", namespaces=NS))
        if b:
            nets[b] = nets.get(b, Decimal("0")) + Decimal(row.findtext("fa:P_11", namespaces=NS))
    for b, net in nets.items():
        stated = Decimal(fa.findtext(f"fa:P_13_{b}", "0", namespaces=NS))
        if stated != net:
            problems.append(f"P_13_{b} is {stated}, rows add up to {net}")
    total = sum(Decimal(e.text) for e in fa
                if etree.QName(e).localname.startswith(("P_13_", "P_14_"))
                and not etree.QName(e).localname.endswith("W"))
    if Decimal(fa.findtext("fa:P_15", namespaces=NS)) != total:
        problems.append(f"P_15 is {fa.findtext('fa:P_15', namespaces=NS)}, P_13_x + P_14_x = {total}")
    return problems

if __name__ == "__main__":
    bad = 0
    for p in sys.argv[1:]:
        found = preflight(p)
        print(("OK   " if not found else "FAIL ") + p)
        for f in found:
            print("     " + f)
        bad += bool(found)
    sys.exit(1 if bad else 0)

On an invoice with one mistyped buyer NIP and a wrong total, the XSD says OK and the pre-flight says:

FAIL typo.xml
     NIP 7770001112: wrong check digit
     P_15 is 3261.99, P_13_x + P_14_x = 3261.90

It's deliberately simple. It assumes net-based line amounts (P_11) and the standard rate slots, so extend it for gross-based invoices, advance invoices and corrections.

Running it in CI

Put both scripts in your test job and point them at invoices generated by your code from fixture orders:

python fetch_fa3_xsd.py          # or commit xsd/ and skip this
python check_fa3.py out/ksef/*.xml && python fa3_preflight.py out/ksef/*.xml

If you'd rather not maintain the scripts, the open-source valifakt-cli bundles the same official FA(3) XSD and checks it fully offline (valifakt check out/ksef/*.xml), and the validate-einvoice GitHub Action wraps it for pull requests.

Remember that the XSD is only the first gate. KSeF applies further checks on submission, and the Ministry of Finance documents the API and structures in CIRFMF/ksef-docs. Use the KSeF test environment before production.

For a browser-based check of a single file, there is a free KSeF FA(3) validator (in Polish) that runs the same official schema.

Disclosure: I build Valifakt, which makes the CLI and validator linked above. This article was drafted with AI assistance; every error message was reproduced by me against the official FA(3) XSD before publishing.

Guides on valifakt.com

More from the blog