Q:

Analyzing a signal that contains frequency content at Fs/2 doesn't seem to work unless there is a phase shift

I am trying to write a basic program that samples a 4 kHz sinewave at a sampling rate of 8 kHz and takes the FFT of the signal and plots it.
From everything I have read, as long as the signal you are sampling has frequency content that is less than or equal to Fs/2 no aliasing will occur and the results will be accurate. However writing a simple example seems to be more complicated than I thought.
Using Python I wrote up a basic example:
import matplotlib.pyplot as plt
import numpy as np

Fs = 8000.0
Ts = 1/Fs
N = 8
t = np.arange(0, N*Ts, Ts)

# 4 kHz sinewave
y = np.sin(2*np.pi*4000*t)

# Bandwidth of the signal (Hz)
BW = Fs/2

# Spectral Lines (number of frequency samples)
SL = round(N/2 + 1)

# Frequency scale
f = np.linspace(0, BW, SL)

Y = np.fft.fft(y)*2/N
Y = Y[:SL]

fig, ax = plt.subplots(2, 1)

ax[0].stem(t, y, use_line_collection=True)
ax[0].set_xlabel('Time')
ax[0].set_ylabel('Amplitude')

ax[1].stem(f, abs(Y), use_line_collection=True)
ax[1].set_xlabel('Freq (Hz)')
ax[1].set_ylabel('|Y(freq)|')

plt.show()

Looking at the output you can see that this does not properly capture the frequency content at 4 kHz in the FFT plot.

But if I simply add a phase shift to the signal by changing this line
y = np.sin(2*np.pi*4000*t)

to
y = np.sin(2*np.pi*4000*t + np.pi/2)

I end up with much better results...

My question is, how come this doesn't work without a phase shift? It makes me wonder how anyone can be confident in the result of an FFT when the signal being sampled has some frequency content that is at the frequency Fs/2. How do you ensure that the signal you are analyzing is at a phase alignment that will not cause issues?

A:

the discrete function $$x_q[n]=\sin(\pi n)$$ is always zero for all of the integers $n$.
the discrete function $$x_i[n]=\cos(\pi n)$$ is always $(-1)^n$ for integer $n$.
so this general sinusoid at Nyquist that has a phase term:
$$\begin{align}
x[n] &= A \cos(\pi n + \theta) \\
     &= A \big( \cos(\pi n) \cos(\theta) - \sin(\pi n) \sin(\theta) \big) \\
     &= \big(A\cos(\theta)\big) \cos(\pi n)  +  \big(-A\sin(\theta)\big) \sin(\pi n) \\
     &= \big(A\cos(\theta)\big) (-1)^n  +  \big(-A\sin(\theta)\big) \cdot 0 \\
     &= B (-1)^n \\
\end{align}$$
So now, how do you tell the difference between a sampled sinusoid that had amplitude $A$ and a phase angle $\theta$ and another sampled sinusoid that has amplitude $B \triangleq\big(A\cos(\theta)\big)$ and no phase shift from the cosine?

