The ending time for magrib is different according to the different madhabs.
According to the Hanafis, Hanbalis and, one group of the Shafi'is and some of the Malikis: its time ends when twilight disappears (and this twilight is interpreted by the majority of them as the redness in the sky), based on the hadith:
ووقت صلاة المغرب ما لم يغب الشفق
The time for the Maghrib prayer is so long as the twilight has not yet disappeared.
— Muslim
According to the later opinion of Imam Shafi'i and the mashur view of the Malikis: the time for maghrib is fixed and restricted. It ends when a period of time passes after sunset in which a person can become purified and offer the rakahs of maghrib. This is based on the fact that in the hadith of Gabriel, maghrib was offered at the same time on both days.
أمني جبريل عليه السلام ... وصلى بي - يعني المغرب - حين أفطر الصائم ... فلما كان الغد ... صلى بي المغرب حين أفطر الصائم ... والوقت ما بين هذين الوقتين
Gabriel (ﷺ) led me in prayer ... he prayed the sunset prayer with me when one who is fasting breaks the fast ... On the following day ... he prayed the sunset prayer at the time when one who is fasting breaks the fast ... the time is anywhere between two times.
Note that it is agreed upon that it is at least recommended to perform maghrib early, right after sunset.
Ref: Islamic Jurisprudence According To The Four Sunni Schools and Fiqh al-Islami wa Adillatuhu and Risala ibn Abi Zaid and Reliance of the traveller and Bidayat al-Mujtahid and Minhaj al-Talibin