The pact between USSR and Nazi Germany was signed in 1939, after the fist Germany (09.01.1939) invaded Poland, and was later (09.17) joined by Soviet Union.
Later during WWII USSR joined the allies and was invaded by Germany, which lost and was forced to retreat by the Red Army. Eventually, Soviets moved West, forcing Hitler's army our of Eastern Poland.