TITLE: Complement of open set is finite in Zariski topology
QUESTION [7 upvotes]: This problem has two parts: 
a) Let $M$ be a finitely generated module over a Noetherian ring $A$. Prove that $S=\{ P \in\operatorname{Spec}(A) : M_P \mbox{ is a free }A_P\mbox{-module} \}$ is an open subset of $\operatorname{Spec}(A)$. 
b) If $M \subset A^r$ and $A=K[X,Y]$ (where $K$ is a field), prove that the complement of $S$ (as defined above) is a finite set. 
I did the first part. I proved that for a prime ideal $P \in\operatorname{Spec}(A)$, if $M_P \mbox{ is a free }A_P\mbox{-module}$, then there exists $f_P \notin P$ and an $n \in \mathbb{N}$ such that $M_{f_P} \cong A_{f_P}^n$. If $D(f)=i^{*}(\operatorname{Spec}(A_f))$ (which are open in Zariski topology), then we can prove that $S= \cup_{P \in S} D(f_P)$ , hence $S$ is open. 
I cannot solve part two. It is weird, since to prove that the complement of an open set in $\operatorname{Spec}(K[X])$ is always a finite set, since it is a PID. But $K[X,Y]$ is not, so we need to use the structure of $S$. Unfortunately I do not know how. Thank you.

REPLY [3 votes]: Let $A$ be a noetherian ring which is regular in codimension $1$. That means $A_P$ is a discrete valuation ring for all $P$ with $\mathrm{height}\, P = 1$.
The ring $A'=k[X,Y]$ fulfills this condition. In fact every prime of height one is principal $P=(f)$ with $f$ irreducible and the valuation of $P$ is given by the exponent of $f$ in the prime factor decomposition of an element $g$ of $Q(K[X,Y])$.
Now let $A$ be a general codimension $1$ regular noetherian ring and $M \subseteq A^r$ a finitely generated $A$-module. Then by exactness of localization we have
$$M_P \subseteq A_P^r$$
Now for $P$ of height $1$ the ring $A_P$ is a DVR by assumption, especially it is a PID. Now for every PID $R$ it is a standard fact that a submodule $N \subseteq R^l$ of a free module is free itself (unfortunately I can not cite a source with proof for this, but it can be seen easily. For $R$ a DVR it is even easier: For $N \subseteq R^l$ the sequence $0 \to R \xrightarrow{\cdot t} R \to R/tR = k \to 0$ (where $t$ is a generator of the maximal ideal of $R$)
remains exact upon $- \otimes_R N$. This proves $\mathrm{Tor}^R_1(N,k) = 0$ and therefore $N$ is flat and therefore free).
Coming back to the main argument, this proves that every $P$ of height $1$ in $A$ belongs to the set $S$.
So again in $A'=K[X,Y]$ the complement of the set $S$ can contain only prime ideals of height $\geqslant 2$, which form a closed set of maximal ideals, and so are only finitely many.